diff --git a/README.md b/README.md index 37dbefb..746e890 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ The complete code of the "Hello World" example is shown below
- + + ``` - UNPKG ```html - + ``` - In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. ```html - + ``` However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. @@ -245,9 +245,9 @@ The simplest way to include the SDK is to use either the [jsDelivr](https://jsde - In frameworks like React and Vue, you may want to add the package as a dependency. ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.2001 -E + npm i dynamsoft-barcode-reader-bundle@10.4.2002 -E # or - yarn add dynamsoft-barcode-reader-bundle@10.4.2001 -E + yarn add dynamsoft-barcode-reader-bundle@10.4.2002 -E ``` NOTE that in frameworks, you need to [specify the engineResourcePaths](#specify-the-location-of-the-engine-files-optional). @@ -265,13 +265,13 @@ There are two options for downloading the SDK, and the usage for each is slightl The resources are located at path `dynamsoft/distributables/@`, you can typically include it like this: ```html - + ``` - npm ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.2001 -E + npm i dynamsoft-barcode-reader-bundle@10.4.2002 -E # Compared with using CDN, you need to set up more resources. npm i dynamsoft-capture-vision-std@1.4.10 -E npm i dynamsoft-image-processing@2.4.20 -E @@ -592,7 +592,7 @@ await cvRouter.startCapturing("ReadSingleBarcode"); The preset templates have many more settings that can be customized to suit your use case best. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under -* "/dynamsoft-barcode-reader-js-10.4.2001/dynamsoft/templates/" +* "/dynamsoft-barcode-reader-js-10.4.2002/dynamsoft/templates/" Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. @@ -674,7 +674,7 @@ The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on ho ## API Documentation You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.2001](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.2001). +[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.2002](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.2002). ## System Requirements @@ -716,7 +716,7 @@ Apart from the browsers, the operating systems may impose some limitations of th ## How to Upgrade -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.4.2001&utm_source=github). +If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.4.2002&utm_source=github). ## Release Notes @@ -728,4 +728,4 @@ Now that you have got the SDK integrated, you can choose to move forward in the 1. Learn how to [Use in Framework](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-in-framework.html) 2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.4.20) -3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.4.2001) +3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.4.2002) diff --git a/dist/dbr.bundle.js b/dist/dbr.bundle.js index af2071c..58144fe 100644 --- a/dist/dbr.bundle.js +++ b/dist/dbr.bundle.js @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft -* @version 10.4.2001 +* @version 10.4.2002 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{})}(this,(function(t){"use strict";function e(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function i(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}var r,n,s;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(r||(r={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(n||(n={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(s||(s={}));const o="undefined"==typeof self,a=(()=>{if(!o&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),h=t=>{if(null==t&&(t="./"),o);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},l=t=>Object.prototype.toString.call(t),c=t=>Array.isArray?Array.isArray(t):"[object Array]"===l(t),u=t=>"[object Boolean]"===l(t),d=t=>"number"==typeof t&&!Number.isNaN(t),f=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),g=t=>!(!f(t)||!d(t.x)||!d(t.y)||!d(t.radius)||t.radius<0||!d(t.startAngle)||!d(t.endAngle)),m=t=>!!f(t)&&!!c(t.points)&&0!=t.points.length&&!t.points.some((t=>!w(t))),p=t=>!(!f(t)||!(t.bytes instanceof Uint8Array)||!d(t.width)||t.width<=0||!d(t.height)||t.height<=0||!d(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!v(t.tag)),_=t=>!(!f(t)||!d(t.left)||t.left<0||!d(t.top)||t.top<0||!d(t.right)||t.right<0||!d(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!u(t.isMeasuredInPercentage)),v=t=>!!f(t)&&!!d(t.imageId)&&"type"in t,y=t=>!(!f(t)||!w(t.startPoint)||!w(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),w=t=>!!f(t)&&!!d(t.x)&&!!d(t.y),C=t=>!!f(t)&&!!c(t.points)&&0!=t.points.length&&!t.points.some((t=>!w(t))),E=t=>!!f(t)&&!!c(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!w(t))),b=t=>!(!f(t)||!d(t.x)||!d(t.y)||!d(t.width)||t.width<0||!d(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!u(t.isMeasuredInPercentage));async function T(t,e){return await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(t+" "+n.status):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}}))}const S=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t{const i={};for(let r in e){const n=r;let s=t[n];s&&"string"!=typeof s&&s.path&&(s=s.path),t.rootDirectory&&!t.rootDirectory.endsWith("/")&&(t.rootDirectory=t.rootDirectory+"/"),void 0===s?t.rootDirectory?s=`${t.rootDirectory}${x[n]}@${e[n].version}/dist/`:(s=e[n].path,s||(s=e[n])):s.startsWith("@engineRootDirectory/")&&(s=s.replace("@engineRootDirectory/",t.rootDirectory)),i[n]=h(s)}return i},x={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer"},A=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await R(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),O=t=>{p(t)&&(t=L(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},R=async(t,e)=>{p(e)&&(e=L(e));const i=O(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},L=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===s.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===s.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r=e(this,F,"f"))switch(e(this,P,"f")){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:if(e(this,M,"f").push(t),f(e(this,B,"f"))&&d(e(this,B,"f").imageId)&&1==e(this,B,"f").keepInBuffer)for(;e(this,M,"f").length>e(this,F,"f");){const t=e(this,M,"f").findIndex((t=>{var i;return(null===(i=t.tag)||void 0===i?void 0:i.imageId)!==e(this,B,"f").imageId}));e(this,M,"f").splice(t,1)}else e(this,M,"f").splice(0,e(this,M,"f").length-e(this,F,"f"))}else e(this,M,"f").push(t)}getImage(){if(0===e(this,M,"f").length)return null;let i;if(e(this,B,"f")&&d(e(this,B,"f").imageId)){const t=e(this,D,"m",j).call(this,e(this,B,"f").imageId);if(t<0)throw new Error(`Image with id ${e(this,B,"f").imageId} doesn't exist.`);i=e(this,M,"f").slice(t,t+1)[0]}else i=e(this,M,"f").pop();if([s.IPF_RGB_565,s.IPF_RGB_555,s.IPF_RGB_888,s.IPF_ARGB_8888,s.IPF_RGB_161616,s.IPF_ARGB_16161616,s.IPF_ABGR_8888,s.IPF_ABGR_16161616,s.IPF_BGR_888].includes(i.format)){if(e(this,N,"f")===n.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const e=new Uint8Array(i.width*i.height);for(let t=0;t0!==t.length&&t.every((t=>d(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!u(e))throw new TypeError("Invalid 'keepInBuffer'.");i(this,B,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){i(this,B,null,"f")}hasImage(t){return e(this,D,"m",j).call(this,t)>=0}startFetching(){i(this,k,!0,"f")}stopFetching(){i(this,k,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(i(this,F,t,"f");e(this,M,"f")&&e(this,M,"f").length>t;)e(this,M,"f").shift()}getMaxImageCount(){return e(this,F,"f")}getImageCount(){return e(this,M,"f").length}clearBuffer(){e(this,M,"f").length=0}isBufferEmpty(){return 0===e(this,M,"f").length}setBufferOverflowProtectionMode(t){i(this,P,t,"f")}getBufferOverflowProtectionMode(){return e(this,P,"f")}setColourChannelUsageType(t){i(this,N,t,"f")}getColourChannelUsageType(){return e(this,N,"f")}};M=new WeakMap,F=new WeakMap,P=new WeakMap,k=new WeakMap,B=new WeakMap,N=new WeakMap,D=new WeakSet,j=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return e(this,M,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))};const G=t=>t&&"object"==typeof t&&"function"==typeof t.then;let V,W,Y,H,X,z=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,G(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(G(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};"undefined"!=typeof navigator&&(V=navigator,W=V.userAgent,Y=V.platform,H=V.mediaDevices),function(){if(!o){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:V.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Y,search:"Win"},Mac:{str:Y},Linux:{str:Y}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||W,o=n.search||e,a=n.verStr||W,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||W,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=W.indexOf("Windows NT")&&(n="HarmonyOS"),X={browser:i,version:r,OS:n}}o&&(X={browser:"ssr",version:0,OS:"ssr"})}();const Z="undefined"!=typeof WebAssembly&&W&&!(/Safari/.test(W)&&!/Chrome/.test(W)&&/\(.+\s11_2_([2-6]).*\)/.test(W)),K=!("undefined"==typeof Worker),q=!(!H||!H.getUserMedia),J=async()=>{let t=!1;if(q)try{(await H.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===X.browser&&X.version>66||"Safari"===X.browser&&X.version>13||"OPR"===X.browser&&X.version>43||"Edge"===X.browser&&X.version;const Q={},$=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Q[t]=Q[t]||new z);await Promise.all(i)},tt=async(t,e)=>{let i,r="string"==typeof t?[t]:t,n=[];for(let t of r){let r;n.push(r=Q[t]=Q[t]||new z(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(n)};let et,it=0;const rt=()=>it++,nt={};let st;const ot=t=>{st=t,et&&et.postMessage({type:"setBLog",body:{value:!!t}})};let at=!1;const ht=t=>{at=t,et&&et.postMessage({type:"setBDebug",body:{value:!!t}})},lt={},ct={},ut={std:{version:"1.4.10",path:h(a+"../../dynamsoft-capture-vision-std@1.4.10/dist/")},core:{version:"3.4.20",path:a}},dt={dip:{wasm:!0}},ft={},gt=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=Q.core;e=!i||i.isEmpty;let r=new Map;const n=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!dt[t])throw Error("The '"+t+"' module cannot be found.");let e=dt[t].deps;if(null==e?void 0:e.length)for(let t of e)n(t);let i=Q[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)n(e);let s=[];e&&s.push("core"),s.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await tt(s,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await $(o);const i=I(ft,ut),n={};for(let e of t)n[e]=dt[e];const s={engineResourcePaths:i,autoResources:n,names:t};let a=new z;if(e){s.needLoadCore=!0;let t=i.core+mt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),et=new Worker(t),et.onerror=t=>{let e=new Error(t.message);a.reject(e)},et.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":st&&st(e.message);break;case"task":try{nt[r](n),delete nt[r]}catch(t){throw delete nt[r],t}break;case"event":try{nt[r](n)}catch(t){throw t}break;default:console.log(t)}})),s.bLog=!!st,s.bd=at,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await $("core");let h=it++;nt[h]=t=>{if(t.success)Object.assign(lt,t.versions),"{}"!==JSON.stringify(t.versions)&&(mt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},et.postMessage({type:"loadWasm",body:s,id:h}),await a}))};class mt{static get engineResourcePaths(){return ft}static set engineResourcePaths(t){Object.assign(ft,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return st}static set _onLog(t){ot(t)}static get _bDebug(){return at}static set _bDebug(t){ht(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Q[t]&&Q[t].isFulfilled}static async loadWasm(t){return await gt(t)}static async detectEnvironment(){return await(async()=>({wasm:Z,worker:K,getUserMedia:q,camera:await J(),browser:X.browser,version:X.version,OS:X.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.20(Worker: ${lt.core&<.core.worker||"Not Loaded"}, Wasm: ${lt.core&<.core.wasm||"Not Loaded"})`}static enableLogging(){U._onLog=console.log,mt._onLog=console.log}static disableLogging(){U._onLog=null,mt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var pt,_t,vt,yt,wt,Ct,Et,bt;mt._bSupportDce4Module=-1,mt._bSupportIRTModule=-1,mt._versions=null,mt._workerName="core.worker.js",mt.browserInfo=X,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(pt||(pt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(_t||(_t={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(vt||(vt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(yt||(yt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(wt||(wt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(Ct||(Ct={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Et||(Et={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(bt||(bt={}));const Tt={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var St,It;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(St||(St={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(It||(It={}));var xt=Object.freeze({__proto__:null,CoreModule:mt,get EnumBufferOverflowProtectionMode(){return r},get EnumCapturedResultItemType(){return pt},get EnumColourChannelUsageType(){return n},get EnumCornerType(){return _t},get EnumErrorCode(){return vt},get EnumGrayscaleEnhancementMode(){return yt},get EnumGrayscaleTransformationMode(){return wt},get EnumImagePixelFormat(){return s},get EnumImageTagType(){return Ct},EnumIntermediateResultUnitType:Tt,get EnumPDFReadingMode(){return Et},get EnumRasterDataSource(){return bt},get EnumRegionObjectElementType(){return St},get EnumSectionType(){return It},ImageSourceAdapter:U,_getNorImageData:L,_isArc:g,_isContour:m,_isDSImageData:p,_isDSRect:_,_isImageTag:v,_isLineSegment:y,_isPoint:w,_isPolygon:C,_isQuad:E,_isRect:b,_saveToFile:A,_toBlob:R,_toCanvas:O,_toImage:(t,e)=>{p(e)&&(e=L(e));const i=O(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r},autoDiscoveryPaths:ut,get bDebug(){return at},checkIsLink:function(t){return/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t)},compareVersion:S,doOrWaitAsyncDependency:tt,getNextTaskID:rt,handleEngineResourcePaths:I,innerVersions:lt,isArc:g,isContour:m,isDSImageData:p,isDSRect:_,isImageTag:v,isLineSegment:y,isObject:f,isPoint:w,isPolygon:C,isQuad:E,isRect:b,loadWasm:gt,mapAsyncDependency:Q,mapPackageRegister:ct,mapTaskCallBack:nt,get onLog(){return st},requestResource:T,setBDebug:ht,setOnLog:ot,waitAsyncDependency:$,get worker(){return et},workerAutoResources:dt});let At="./";if(document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}At=t.substring(0,t.lastIndexOf("/")+1)}mt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(At+"../../")};const Ot="undefined"==typeof self,Rt=Ot?{}:self,Lt=(()=>{if(!Ot&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),Dt=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Mt=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Dt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Dt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ft=" is not allowed to change after `createInstance` or `loadWasm` is called.",Pt=!Ot&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",kt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ft);i._license=e}};!Ot&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Bt=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Bt(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ft);i._licenseServer=e}},jt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ft);i._deviceFriendlyName=e}};let Ut,Gt,Vt,Wt,Yt;"undefined"!=typeof navigator&&(Ut=navigator,Gt=Ut.userAgent,Vt=Ut.platform,Wt=Ut.mediaDevices),function(){if(!Ot){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ut.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Vt,search:"Win"},Mac:{str:Vt},Linux:{str:Vt}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Gt,o=n.search||e,a=n.verStr||Gt,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Gt,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Gt.indexOf("Windows NT")&&(n="HarmonyOS"),Yt={browser:i,version:r,OS:n}}Ot&&(Yt={browser:"ssr",version:0,OS:"ssr"})}(),Wt&&Wt.getUserMedia,"Chrome"===Yt.browser&&Yt.version>66||"Safari"===Yt.browser&&Yt.version>13||"OPR"===Yt.browser&&Yt.version>43||"Edge"===Yt.browser&&Yt.version;const Ht=()=>(gt("license"),tt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Bt(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Rt.crypto||(s="Please upgrade your browser to support online key."),Rt.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==l)throw new Error(s);l=0,console.warn(s),i._lastErrorCode=-1,i._lastErrorString=s}return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Ft)})(zt),o=new Mt;zt._pLoad.task=o,(async()=>{try{await zt._pLoad}catch(t){}})();let a=rt();nt[a]=e=>{if(e.message&&zt._onAuthMessage){let t=zt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(st&&st("init license success"),e.message&&console.warn(e.message),mt._bSupportIRTModule=e.bSupportIRTModule,mt._bSupportDce4Module=e.bSupportDce4Module,zt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){const t=I(mt.engineResourcePaths,ut);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:zt._bNeverShowDialog,engineResourcePath:t.license,_onLog:st},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await $("core"),et.postMessage({type:"license_dynamsoft",body:{v:"3.4.21",brtk:!!t,bptk:1===t,l:e,os:Yt,fn:zt.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),zt.bCallInitLicense=!0,await o})));let Xt;ct.license={},ct.license.dynamsoft=Ht,ct.license.getAR=async()=>{{let t=Q.dynamsoft_inited;t&&t.isRejected&&await t}return et?new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){delete i.success;{let t=zt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},et.postMessage({type:"license_getAR",id:i})})):null};let zt=class t{static setLicenseServer(e){Nt(t,e)}static get license(){return this._license}static set license(e){kt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Nt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){jt(t,e)}static initLicense(e,i){if(kt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Ht()}static setDeviceFriendlyName(e){jt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await tt("dynamsoft_uuid",(async()=>{await gt();let t=new Mt,e=rt();nt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},et.postMessage({type:"license_getDeviceUUID",id:e}),Xt=await t})),Xt))()}};zt._pLoad=new Mt,zt.bPassValidation=!1,zt.bCallInitLicense=!1,zt._license=Pt,zt._licenseServer=[],zt._deviceFriendlyName="",ut.license={version:"3.4.21",path:Lt},dt.license={wasm:!0,js:!0},ct.license.LicenseManager=zt;const Zt="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,Zt)<0&&(ut.std={version:Zt,path:(t=>{if(null==t&&(t="./"),Ot);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Lt+`../../dynamsoft-capture-vision-std@${Zt}/dist/`)});var Kt=Object.freeze({__proto__:null,LicenseManager:zt,LicenseModule:class{static getVersion(){return`3.4.21(Worker: ${lt.license&<.license.worker||"Not Loaded"}, Wasm: ${lt.license&<.license.wasm||"Not Loaded"})`}}});function qt(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Jt(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Qt=t=>t&&"object"==typeof t&&"function"==typeof t.then;class $t extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Qt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Qt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class te{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ee={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1};const ie=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class re{constructor(t){this._irrRegistryState=ee,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ie(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=rt();nt[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ie(this),await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const ne="undefined"==typeof self,se=(()=>{if(!ne&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),oe=t=>{if(null==t&&(t="./"),ne);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ae;ut.cvr={version:"2.4.21",path:se},dt.cvr={js:!0,wasm:!0,deps:["license","dip"]},ct.cvr={};const he="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,he)<0&&(ut.std={version:he,path:oe(se+`../../dynamsoft-capture-vision-std@${he}/dist/`)});const le="2.4.20";(!ut.dip||"string"!=typeof ut.dip&&S(ut.dip.version,le)<0)&&(ut.dip={version:le,path:oe(se+`../../dynamsoft-image-processing@${le}/dist/`)});class ce{static getVersion(){return this._version}}var ue,de,fe,ge,me,pe,_e,ve,ye,we,Ce,Ee,be;function Te(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Te(t.referencedItem,e)}}function Se(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}ce._version=`2.4.21(Worker: ${null===(ae=lt.cvr)||void 0===ae?void 0:ae.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ue||(ue={})),BigInt(0),BigInt(1),BigInt(2),BigInt(4),BigInt(8),BigInt(16),BigInt(32),BigInt(64),BigInt(128),BigInt(256),BigInt(512),BigInt(1024),BigInt(2048),BigInt(4096),BigInt(8192),BigInt(16384),BigInt(32768),BigInt(65536),BigInt(1<<17),BigInt(1<<18),BigInt(1<<19),BigInt(1<<20),BigInt(1<<21),BigInt(1<<22),BigInt(1<<23),BigInt(1<<24),BigInt(1<<25),BigInt(1<<26),BigInt(1<<27),BigInt(1<<28),BigInt("0xFFFFFFFFFFFFFFFF");const Ie={onTaskResultsReceived:()=>{},isFilter:!0};class xe{constructor(){this.maxCvsSideLength=["iPhone","Android","HarmonyOS"].includes(mt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,de.set(this,null),fe.set(this,null),ge.set(this,null),me.set(this,null),pe.set(this,null),_e.set(this,new Set),ve.set(this,new Set),ye.set(this,new Set),we.set(this,0),Ce.set(this,!1),Ee.set(this,!1),be.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return qt(this,be,"f")}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await gt(["cvr"]);const t=new xe,e=new $t;let i=rt();return nt[i]=async i=>{var r;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(i.outputSettings),ce._version=`2.4.21(Worker: ${null===(r=lt.cvr)||void 0===r?void 0:r.worker}, Wasm: ${i.version})`,Jt(t,Ee,!0,"f"),Jt(t,me,t.getIntermediateResultManager(),"f"),Jt(t,Ee,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},et.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of qt(this,_e,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of qt(this,_e,"f"))t.isDce&&t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of qt(this,_e,"f"))if(e.onDecodedBarcodesReceived&&i.barcodeResultItems&&e.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems})),e.onRecognizedTextLinesReceived&&i.textLineResultItems&&e.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems})),e.onDetectedQuadsReceived&&i.detectedQuadResultItems&&e.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems})),e.onNormalizedImagesReceived&&i.normalizedImageResultItems&&e.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems})),e.onParsedResultsReceived&&i.parsedResultItems&&e.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems})),e.onCapturedResultReceived&&!e.isDce){if(this._isOutputOriginalImage){const e=i.items.findIndex((t=>1===t.type));-1!==e&&(i.items[e].imageData=t)}e.onCapturedResultReceived(i)}}setInput(t){if(Se(this),t){if(Jt(this,de,t,"f"),t.isCameraEnhancer){qt(this,me,"f")&&(qt(this,de,"f")._intermediateResultReceiver.isDce=!0,qt(this,me,"f").addResultReceiver(qt(this,de,"f")._intermediateResultReceiver));const t=qt(this,de,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,qt(this,_e,"f").add(e)}}}else Jt(this,de,null,"f")}getInput(){return qt(this,de,"f")}addImageSourceStateListener(t){if(Se(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&qt(this,ve,"f").add(t)}removeImageSourceStateListener(t){return Se(this),qt(this,ve,"f").delete(t)}addResultReceiver(t){if(Se(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(qt(this,_e,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Se(this),qt(this,_e,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of qt(this,_e,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new $t;let i=rt();return nt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},et.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Se(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");qt(this,ye,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Se(this),qt(this,ye,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(qt(this,me,"f").removeResultReceiver(Ie),0===qt(this,ye,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1},e={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1};return await Ae(this,t),void await Oe(this,e)}for(let t of qt(this,ye,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(pt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(pt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(pt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(pt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(pt.CRIT_BARCODE)){[...qt(this,me,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||qt(this,me,"f").addResultReceiver(Ie)}await Ae(this,t.verificationEnabled),await Oe(this,t.duplicateFilterEnabled),await Re(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Se(this),!this._isPauseScan)return;if(!qt(this,de,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const r=await this.containsTask(t);await gt(r);for(let t of qt(this,ye,"f"))await this.addResultFilter(t);if(r.includes("dlr")&&!(null===(e=ct.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=I(mt.engineResourcePaths,ut);await(null===(i=ct.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(qt(this,de,"f").isCameraEnhancer&&(r.includes("ddn")?qt(this,de,"f").setPixelFormat(s.IPF_ABGR_8888):qt(this,de,"f").setPixelFormat(s.IPF_GRAYSCALED)),void 0!==qt(this,de,"f").singleFrameMode&&"disabled"!==qt(this,de,"f").singleFrameMode)return this._templateName=t,void qt(this,de,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return qt(this,de,"f").getColourChannelUsageType()===n.CCUT_AUTO&&qt(this,de,"f").setColourChannelUsageType(r.includes("ddn")?n.CCUT_FULL_CHANNEL:n.CCUT_Y_CHANNEL_ONLY),qt(this,ge,"f")&&qt(this,ge,"f").isPending?qt(this,ge,"f"):(Jt(this,ge,new $t(((e,i)=>{if(this.disposed)return;let r=rt();nt[r]=async r=>{if(qt(this,ge,"f")&&!qt(this,ge,"f").isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=r.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&qt(this,de,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},et.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await qt(this,ge,"f"))}stopCapturing(){Se(this),qt(this,de,"f")&&(qt(this,de,"f").isCameraEnhancer&&void 0!==qt(this,de,"f").singleFrameMode&&"disabled"!==qt(this,de,"f").singleFrameMode?qt(this,de,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=rt();const i=new $t;nt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},et.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),qt(this,de,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Jt(this,ge,null,"f"),qt(this,de,"f").setColourChannelUsageType(n.CCUT_AUTO)))}async containsTask(t){return Se(this),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Jt(this,Ce,!0,"f"),qt(this,de,"f").isBufferEmpty())if(qt(this,de,"f").hasNextImageToFetch())for(let t of qt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_BUFFER_EMPTY);else if(!qt(this,de,"f").hasNextImageToFetch())for(let t of qt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||qt(this,de,"f").isBufferEmpty())try{qt(this,de,"f").isBufferEmpty()&&xe._onLog&&xe._onLog("buffer is empty so fetch image"),xe._onLog&&xe._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=qt(this,de,"f").fetchImage(),xe._onLog&&xe._onLog(`DCE: finish fetching a frame: ${Date.now()}`),qt(this,de,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(qt(this,de,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=qt(this,de,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of qt(this,_e,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(xe._onLog&&xe._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of qt(this,_e,"f")){if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),xe._onLog){const t=Date.now()-e;t>10&&xe._onLog(`draw result time: ${t}`)}}t.onDecodedBarcodesReceived&&i.barcodeResultItems&&t.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems.filter((t=>!t.isFilter))})),t.onRecognizedTextLinesReceived&&i.textLineResultItems&&t.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems.filter((t=>!t.isFilter))})),t.onDetectedQuadsReceived&&i.detectedQuadResultItems&&t.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems.filter((t=>!t.isFilter))})),t.onNormalizedImagesReceived&&i.normalizedImageResultItems&&t.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems.filter((t=>!t.isFilter))})),t.onParsedResultsReceived&&i.parsedResultItems&&t.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems.filter((t=>!t.isFilter))})),t.onCapturedResultReceived&&!t.isDce&&(i.items=i.items.filter((t=>!t.isFilter)),i.barcodeResultItems&&(i.barcodeResultItems=i.barcodeResultItems.filter((t=>!t.isFilter))),i.textLineResultItems&&(i.textLineResultItems=i.textLineResultItems.filter((t=>!t.isFilter))),i.detectedQuadResultItems&&(i.detectedQuadResultItems=i.detectedQuadResultItems.filter((t=>!t.isFilter))),i.normalizedImageResultItems&&(i.normalizedImageResultItems=i.normalizedImageResultItems.filter((t=>!t.isFilter))),i.parsedResultItems&&(i.parsedResultItems=i.parsedResultItems.filter((t=>!t.isFilter))),t.onCapturedResultReceived(i))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,xe._onLog&&(xe._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),xe._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),xe._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),xe._onLog(`averageTime: ${this._averageTime}`))),xe._onLog){const t=Date.now()-n;t>10&&xe._onLog(`fetch image calculate time: ${t}`)}xe._onLog&&xe._onLog(`time finish decode: ${Date.now()}`),xe._onLog&&xe._onLog("main time: "+(Date.now()-e)),xe._onLog&&xe._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{qt(this,de,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{qt(this,de,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;Se(this),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const n=await this.containsTask(e);if(await gt(n),n.includes("dlr")&&!(null===(i=ct.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=I(mt.engineResourcePaths,ut);await(null===(r=ct.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Jt(this,Ce,!1,"f"),p(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await T(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,e){let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*qt(this,we,"f")),r=Math.round(s*qt(this,we,"f"))):(i=n,r=s),qt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=qt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*qt(this,we,"f")),r=Math.round(s*qt(this,we,"f"))):(i=n,r=s),qt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=qt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:r,height:n,stride:s,format:o}=t;let a=rt();const h=new $t;return nt[a]=async e=>{var i,r;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const n=Date.now();xe._onLog&&(xe._onLog(`get result time from worker: ${n}`),xe._onLog("worker to main time consume: "+(n-e.workerReturnMsgTime)));try{const n=e.captureResult;if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of n.items)0!==qt(this,we,"f")&&Te(e,qt(this,we,"f")),e.type===pt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===pt.CRIT_NORMALIZED_IMAGE?null===(i=ct.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===pt.CRIT_PARSED_RESULT&&(null===(r=ct.dcp)||void 0===r||r.handleParsedResultItem(e));if(qt(this,Ce,"f"))for(let t of qt(this,ye,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onDetectedQuadsReceived(n),t.onNormalizedImagesReceived(n);const s=function(t){const e={barcodeResultItems:[],textLineResultItems:[],detectedQuadResultItems:[],normalizedImageResultItems:[],parsedResultItems:[]};return t.items.forEach((t=>{t.type===pt.CRIT_BARCODE?e.barcodeResultItems.push(t):t.type===pt.CRIT_TEXT_LINE?e.textLineResultItems.push(t):t.type===pt.CRIT_DETECTED_QUAD?e.detectedQuadResultItems.push(t):t.type===pt.CRIT_NORMALIZED_IMAGE?e.normalizedImageResultItems.push(t):t.type===pt.CRIT_PARSED_RESULT&&e.parsedResultItems.push(t)})),e}(n);if(s.barcodeResultItems.length&&(n.barcodeResultItems=s.barcodeResultItems),s.textLineResultItems.length&&(n.textLineResultItems=s.textLineResultItems),s.detectedQuadResultItems.length&&(n.detectedQuadResultItems=s.detectedQuadResultItems),s.normalizedImageResultItems.length&&(n.normalizedImageResultItems=s.normalizedImageResultItems),s.parsedResultItems.length&&(n.parsedResultItems=s.parsedResultItems),!this._isPauseScan||!qt(this,Ce,"f")){const e=n.intermediateResult;if(e){let i=0;for(let r of qt(this,me,"f")._intermediateResultReceiverSet){i++;for(let n of e){if("onTaskResultsReceived"===n.info.callbackName){for(let e of n.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);i===qt(this,me,"f")._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}}return n&&n.hasOwnProperty("intermediateResult")&&delete n.intermediateResult,Jt(this,we,0,"f"),h.resolve(n)}catch(t){return h.reject(t)}}},xe._onLog&&xe._onLog(`send buffer to worker: ${Date.now()}`),et.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:r,height:n,stride:s,format:o,templateName:e||"",isScanner:qt(this,Ce,"f")}},[i.buffer]),h}async initSettings(t){return Se(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?(t.startsWith("{")||(t=await T(t,"text")),this._currentSettings=JSON.parse(t)):"object"==typeof t&&(this._currentSettings=t,t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=rt();nt[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.exception){let t=new Error(n.description?n.description:"Init Settings Failed.");return t.errorCode=n.exception,i(t)}let s=[],o=JSON.parse(t).CaptureVisionTemplates;for(let t=0;t{let r=rt();nt[r]=async t=>{if(t.success){const r=JSON.parse(t.settings);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return delete r.errorCode,delete r.errorString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getSimplifiedSettings(t){Se(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await gt(e),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success){const r=JSON.parse(t.settings,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));if(r.minImageCaptureInterval=this._minImageCaptureInterval,0!==r.code){let t=new Error(r.codeString);return t.errorCode=r.errorCode,i(t)}return delete r.code,delete r.codeString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Se(this);const i=await this.containsTask(t);return await gt(i),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==n.exception){let t=new Error(n.description?n.description:"Update Settings Failed.");return t.errorCode=n.exception,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Se(this),await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.exception){let t=new Error(r.description?r.description:"Reset Settings Failed.");return t.errorCode=r.exception,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return qt(this,pe,"f")||Jt(this,pe,new te(this),"f"),qt(this,pe,"f")}getIntermediateResultManager(){if(Se(this),!qt(this,Ee,"f")&&0!==mt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return qt(this,me,"f")||Jt(this,me,new re(this),"f"),qt(this,me,"f")}async parseRequiredResources(t){return Se(this),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Se(this),qt(this,ge,"f")&&this.stopCapturing(),Jt(this,de,null,"f"),qt(this,_e,"f").clear(),qt(this,ve,"f").clear(),qt(this,ye,"f").clear(),qt(this,me,"f")._intermediateResultReceiverSet.clear(),Jt(this,be,!0,"f");let t=rt();nt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:qt(this,de,"f"),promiseStartScan:qt(this,ge,"f"),intermediateResultManager:qt(this,me,"f"),bufferdItemsManager:qt(this,pe,"f"),resultReceiverSet:qt(this,_e,"f"),isaStateListenerSet:qt(this,ve,"f"),resultFilterSet:qt(this,ye,"f"),compressRate:qt(this,we,"f"),canvas:qt(this,fe,"f"),isScanner:qt(this,Ce,"f"),innerUseTag:qt(this,Ee,"f"),isDestroyed:qt(this,be,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Ae(t,e){return Se(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function Oe(t,e){return Se(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Re(t,e){return Se(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,be=new WeakMap;var Le;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Le||(Le={}));var De=Object.freeze({__proto__:null,CaptureVisionRouter:xe,CaptureVisionRouterModule:ce,CapturedResultReceiver:class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},get EnumImageSourceState(){return ue},get EnumPresetTemplate(){return Le},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=Tt.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const Me="undefined"==typeof self,Fe=(()=>{if(!Me&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();ut.dce={version:"4.1.0",path:Fe},dt.dce={wasm:!1,js:!1},ct.dce={};let Pe,ke,Be,Ne,je;function Ue(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Ge(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Pe=navigator,ke=Pe.userAgent,Be=Pe.platform,Ne=Pe.mediaDevices),function(){if(!Me){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Pe.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Be,search:"Win"},Mac:{str:Be},Linux:{str:Be}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||ke,o=n.search||e,a=n.verStr||ke,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||ke,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=ke.indexOf("Windows NT")&&(n="HarmonyOS"),je={browser:i,version:r,OS:n}}Me&&(je={browser:"ssr",version:0,OS:"ssr"})}();const Ve="undefined"!=typeof WebAssembly&&ke&&!(/Safari/.test(ke)&&!/Chrome/.test(ke)&&/\(.+\s11_2_([2-6]).*\)/.test(ke)),We=!("undefined"==typeof Worker),Ye=!(!Ne||!Ne.getUserMedia),He=async()=>{let t=!1;if(Ye)try{(await Ne.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===je.browser&&je.version>66||"Safari"===je.browser&&je.version>13||"OPR"===je.browser&&je.version>43||"Edge"===je.browser&&je.version;var Xe={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,b,T=T||{version:"5.2.1"};if(e.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var S=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=S.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=S,DOMParser=T.window.DOMParser}function I(t,e){var i=t.canvas,r=e.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:T.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}T.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof T.Gradient||this.set(e,new T.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof T.Pattern?i&&i():this.set(e,new T.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new T.Point(t.x-e.x,t.y-e.y),n=T.util.rotateVector(r,i);return new T.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),r=T.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new T.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new T.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=T.util.createVector(t,e),n=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(r,n),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(r,s),n)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new T.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new T.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(T.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(T.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=T.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new T.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new T.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var b=Math.sqrt(1-C/(_*v));i*=b,s*=b}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var S=E*i*p/s,I=-E*s*m/i,x=d*S-u*I+.5*t,A=u*S+d*I+.5*e,O=n(1,0,(m-S)/i,(p-I)/s),R=n((m-S)/i,(p-I)/s,(-m-S)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var L=Math.ceil(Math.abs(R/l*2)),D=[],M=R/L,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=O+M,k=0;kE)for(var S=1,I=m.length;S2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(T.cachesBoundsOfCurve&&(l=t.call(arguments),T.boundsOfCurveCache[l]))return T.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],b=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var S=0;S<2;++S)if(S>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,A,O=E.length,R=O;O--;)I=(A=1-(f=E[O]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,b[0][O]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,b[1][O]=x;b[0][R]=e,b[1][R]=i,b[0][R+1]=a,b[1][R+1]=h;var L=[{x:y.apply(null,b[0]),y:y.apply(null,b[1])},{x:w.apply(null,b[0]),y:w.apply(null,b[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[l]=L),L},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},T.util.transformPath=function(t,e,i){return i&&(e=T.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),T.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(T.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=T.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=T.document.documentElement,n=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(t,e){var i=T.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=T.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=T.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},T.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},T.util.getById=function(t){return"string"==typeof t?T.document.getElementById(t):t},T.util.toArray=s,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=o,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},T.util.getNodeCanvas=function(t){var e=T.jsdomImplForWrapper(t);return e._canvas||e._image},T.util.cleanUpJsdomNode=function(t){if(T.isLikelyNode){var e=T.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}T.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}T.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},o=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=T.runningAnimations.indexOf(s);return t>-1&&T.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=n,!o){if(!f(w,C,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,n),void a(t));h()}}(l)})),s.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return o.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,r,n){var s=new T.Color(e).getSource(),o=new T.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},T.util.animate(T.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",b=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=n,C.viewBoxHeight=o,y?(C.width=n,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/n,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),b=C.width-n*c,T=C.height-o*c,"Mid"===p.alignX&&(b/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(b=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+b)+" "+(r*u+T)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function m(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function C(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function b(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),b(l,"skewY","scaleY","y",p)}return m}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),b(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,w=m(t,f),E=_(f,y,w),b=e.gestureScale;if(E)return!1;if(b)o=e.scaleX*b,a=e.scaleY*b;else{if(s=C(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),S=e.original,I=T/(Math.abs(h.x*S.scaleX/f.scaleX)+Math.abs(h.y*S.scaleY/f.scaleY));o=S.scaleX*I,a=S.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=w("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),E(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(T))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=C(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),E(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(S))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=w,n.getLocalPoint=C,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new T.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new T.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=m/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=T.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,m=-i.top),new T.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=T.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var t=T.util.object.extend,e=T.util.getElementOffset,i=T.util.removeFromArray,r=T.util.toFixed,n=T.util.transformPoint,s=T.util.invertTransform,o=T.util.getNodeCanvas,a=T.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=T.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?T.util.loadImage(e,(function(e,n){if(e){var s=new T.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=T.util.getById(t)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?T.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=T.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(T.StaticCanvas.prototype,T.Observable),t(T.StaticCanvas.prototype,T.Collection),t(T.StaticCanvas.prototype,T.DataURLExporter),t(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new T.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new T.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new T.Point(r.x,r.y),n=new T.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=T.util.invertTransform(i),n=this.restorePointerVpt(e);return T.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,T.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):T.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new T.Point(e.ex,e.ey),r=T.util.transformPoint(i,this.viewportTransform),n=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof T.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return T.util.transformPoint(t,T.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;T.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,T.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e:e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:e,selected:n}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),T.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==r&&(T.Canvas[r]=T.StaticCanvas[r])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(T.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(T.document,t+"up",this._onMouseUp),e(T.document,"touchend",this._onTouchEnd,i),e(T.document,t+"move",this._onMouseMove,i),e(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e:e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new T.Point(v(r,s),v(n,o)),h=new T.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return T.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):T.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=T.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new T.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof n?n=E[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new T.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new T.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),n=new T.Point(t.x,t.y),this.angle&&(n=T.util.rotatePoint(n,s,-w(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=w(this.angle),n=this.getScaledWidth(),s=T.util.cos(r)*n,o=T.util.sin(r)*n;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=T.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===T.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+T.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=T.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=T.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=T.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?T.util.animateColor(h.startValue,h.endValue,h.duration,h):T.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return T.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);T.filterBackend||(T.filterBackend=T.initFilterBackend());var o=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,T.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=T.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(T.util.getById(t),e),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(t,e){var i=T.util.object.clone(t);T.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],T.util.enlivenObjectEnlivables(i,i,(function(){var r=new T.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,r){e&&e(new T.Image(t,i),r)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(t,i,r){var n=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(n["xlink:href"],i,e(r?T.util.object.clone(r):{},n))})}(e),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(e){if(T.isLikelyNode)return!1;e=e||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){T.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=n,n},T.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}T.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=T.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(t,e){var i=new T.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,b||(n+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=r,E[s+3]=b?m[s+3]:n}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){D=r(1e3*s(T-C.x)),w[D]||(w[D]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-C.y)),w[D][M]||(w[D][M]=f(n(i(D*p,2)+i(M*_,2))/1e3)),(S=w[D][M])>0&&(x+=S,A+=S*c[I=4*(F*e+T)],O+=S*c[I+1],R+=S*c[I+2],L+=S*c[I+3]))}d[I=4*(b*a+h)]=A/x,d[I+1]=O/x,d[I+2]=R/x,d[I+3]=L/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(S+=y*f[3+(D=4*(L+x*e))],C+=y,f[D+3]<255&&(y=y*f[D+3]/250),E+=y*f[D],b+=y*f[D+1],T+=y*f[D+2],w+=y)}m[v]=E/w,m[v+1]=b/w,m[v+2]=T/w,m[v+3]=S/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),T.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);T.Object._fromObject("IText",e,i,"text")}}(),b=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],T.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=T.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=T.util.transformPoint(h,a),(h=T.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=b(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:b(r[i-1])}:n?this.styles[t+i]={0:b(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?b(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=b(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=b(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=T.util.toFixed,e=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},ze={};function Ze(t){var e=ze[t];if(void 0!==e)return e.exports;var i=ze[t]={exports:{}};return Xe[t](i,i.exports,Ze),i.exports}Ze.d=(t,e)=>{for(var i in e)Ze.o(e,i)&&!Ze.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},Ze.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ke={};(()=>{let t;Ze.d(Ke,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?Ze(653).fabric:{version:"5.2.1"}})();var qe,Je,Qe,$e,ti=Ke.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(qe||(qe={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(Je||(Je={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(Qe||(Qe={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}($e||($e={}));const ei=t=>"number"==typeof t&&!Number.isNaN(t),ii=t=>"string"==typeof t;var ri,ni,si,oi,ai,hi;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(ai||(ai={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(hi||(hi={}));class li{get mediaType(){return new Map([["rect",qe.DIMT_RECTANGLE],["quad",qe.DIMT_QUADRILATERAL],["text",qe.DIMT_TEXT],["arc",qe.DIMT_ARC],["image",qe.DIMT_IMAGE],["polygon",qe.DIMT_POLYGON],["line",qe.DIMT_LINE],["group",qe.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ue(this,ni,"f")){case Je.DIS_DEFAULT:return"default";case Je.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Ue(this,si,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ue(this,si,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ge(this,si,t,"f")}get coordinateBase(){return Ue(this,si,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(ri.add(this),ni.set(this,void 0),si.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!ei(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(Je.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(Je.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(Je.DIS_SELECTED):this.setState(Je.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ge(this,ni,t,"f")}getState(){return Ue(this,ni,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)unull!==t&&"object"==typeof t&&!Array.isArray(t),ui=t=>!!ii(t)&&""!==t,di=p,fi=_,gi=y,mi=C,pi=w,_i=E,vi=b,yi=t=>!(!ci(t)||"id"in t&&!ei(t.id)||"lineWidth"in t&&!ei(t.lineWidth)||"fillStyle"in t&&!ui(t.fillStyle)||"strokeStyle"in t&&!ui(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!ui(t.fontFamily)||"fontSize"in t&&!ei(t.fontSize));class wi{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(vi(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!fi(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Ci,Ei;class bi{constructor(){Ci.set(this,new Map),Ei.set(this,!1)}get disposed(){return Ue(this,Ei,"f")}on(t,e){t=t.toLowerCase();const i=Ue(this,Ci,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ue(this,Ci,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ue(this,Ci,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=Ue(this,Ci,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=Ue(this,Ci,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Ge(this,Ei,!0,"f")}}function Ti(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Si(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Ii(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}Ci=new WeakMap,Ei=new WeakMap;const xi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");if(r.insertAdjacentHTML("beforeend",i),1===r.childElementCount&&r.firstChild instanceof HTMLTemplateElement)return r.firstChild.content;const n=new DocumentFragment;for(let t of r.children)n.append(t);return n};var Ai,Oi,Ri,Li,Di;class Mi extends li{constructor(t,e){if(super(null,e),Ai.set(this,void 0),!vi(t))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new ti.Rect({left:t.x,top:t.y,width:t.width,height:t.height})),Ge(this,Ai,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="rect"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth"))),this.set("height",this.convertPropFromViewToImage(this.get("scaledHeight")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth"))),this.set("height",this.convertPropFromImageToView(this.get("scaledHeight")))}setPosition(t){this.setRect(t)}getPosition(){return this.getRect()}updatePosition(){Ue(this,Ai,"f")&&this.setRect(Ue(this,Ai,"f"))}setRect(t){if(!vi(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width)),this.set("height",this.convertPropFromViewToImage(t.height));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width),this.set("height",t.height)}this._drawingLayer.renderAll()}else Ge(this,Ai,JSON.parse(JSON.stringify(t)),"f")}getRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Ai,"f")?JSON.parse(JSON.stringify(Ue(this,Ai,"f"))):null}}function Fi(t,e,i){let r=i.points[this.pointIndex].x-i.pathOffset.x,n=i.points[this.pointIndex].y-i.pathOffset.y;return ti.util.transformPoint({x:r,y:n},i.calcTransformMatrix())}function Pi(t){let e=new ti.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new ti.Point(t.width+e.x,t.height+e.y)}function ki(t,e,i,r){let n=e.target,s=n.controls[n.__corner],o=n.toLocalPoint(new ti.Point(i,r),"center","center"),a=Pi(n),h=n._getTransformedDimensions(0,0),l={x:o.x*a.x/h.x+n.pathOffset.x,y:o.y*a.y/h.y+n.pathOffset.y};return n.points[s.pointIndex]=l,ti.controlsUtils.fireEvent("scaling",{e:t,transform:e,pointer:{x:i,y:r}}),!0}function Bi(t,e){return function(i,r,n,s){let o=r.target,a=ti.util.transformPoint({x:o.points[t].x-o.pathOffset.x,y:o.points[t].y-o.pathOffset.y},o.calcTransformMatrix()),h=e(i,r,n,s);o._setPositionDimensions({});let l=Pi(o),c=(o.points[t].x-o.pathOffset.x)/l.x,u=(o.points[t].y-o.pathOffset.y)/l.y;return o.setPositionByOrigin(a,c+.5,u+.5),h}}Ai=new WeakMap;class Ni extends li{constructor(t,e){if(super(null,e),Oi.set(this,void 0),!mi(t))throw new TypeError("Invalid 'polygon'.");this._setFabricObject(new ti.Polygon(t.points,{objectCaching:!1}));const i=this._fabricObject;let r=i.points.length-1;i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ti.Control({positionHandler:Fi,actionHandler:Bi(i>0?i-1:r,ki),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Ge(this,Oi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new ti.Control({positionHandler:Fi,actionHandler:Bi(r>0?r-1:i,ki),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=ti.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Ue(this,Oi,"f")&&this.setPolygon(Ue(this,Oi,"f"))}setPolygon(t){if(!mi(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ge(this,Oi,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Oi,"f")?JSON.parse(JSON.stringify(Ue(this,Oi,"f"))):null}}Oi=new WeakMap;Ri=new WeakMap,Li=new WeakMap;const ji=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ge(this,Vi,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Vi,"f")?JSON.parse(JSON.stringify(Ue(this,Vi,"f"))):null}}Vi=new WeakMap;class Tr extends li{constructor(t){super(new ti.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(Je.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(Je.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}class Sr{static createDrawingStyle(t){if(!yi(t))throw new Error("Invalid style definition.");let e,i=Sr.USER_START_STYLE_ID;for(;Ue(Sr,Wi,"f",Yi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in Ue(Sr,Wi,"f",Hi))r.hasOwnProperty(t)||(r[t]=Ue(Sr,Wi,"f",Hi)[t]);return Ue(Sr,Wi,"f",Yi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ue(Sr,Wi,"f",Yi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Ue(Sr,Wi,"f",Yi).values())))}static _updateDrawingStyle(t,e){if(!yi(e))throw new Error("Invalid style definition.");const i=Ue(Sr,Wi,"f",Yi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Wi=Sr,Sr.STYLE_BLUE_STROKE=1,Sr.STYLE_GREEN_STROKE=2,Sr.STYLE_ORANGE_STROKE=3,Sr.STYLE_YELLOW_STROKE=4,Sr.STYLE_BLUE_STROKE_FILL=5,Sr.STYLE_GREEN_STROKE_FILL=6,Sr.STYLE_ORANGE_STROKE_FILL=7,Sr.STYLE_YELLOW_STROKE_FILL=8,Sr.STYLE_BLUE_STROKE_TRANSPARENT=9,Sr.STYLE_GREEN_STROKE_TRANSPARENT=10,Sr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Sr.USER_START_STYLE_ID=1024,Yi={value:new Map([[Sr.STYLE_BLUE_STROKE,{id:Sr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE,{id:Sr.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE,{id:Sr.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_YELLOW_STROKE,{id:Sr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_BLUE_STROKE_FILL,{id:Sr.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE_FILL,{id:Sr.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE_FILL,{id:Sr.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_YELLOW_STROKE_FILL,{id:Sr.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Sr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Sr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Sr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Hi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ti.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ti.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ti.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ti.Object.prototype.transparentCorners=!1,ti.Object.prototype.cornerSize=20,ti.Object.prototype.touchCornerSize=100,ti.Object.prototype.cornerColor="rgb(254,142,20)",ti.Object.prototype.cornerStyle="circle",ti.Object.prototype.strokeUniform=!0,ti.Object.prototype.hasBorders=!1,ti.Canvas.prototype.containerClass="",ti.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=ti.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},ti.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();ti.util.addListener(ti.document,"touchend",this._onTouchEnd,{passive:!1}),ti.util.addListener(ti.document,"touchmove",this._onMouseMove,{passive:!1}),ti.util.removeListener(i,r+"down",this._onMouseDown)},ti.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?ti.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class Ir{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ti.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case Ir.DDN_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_BLUE_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_BLUE_STROKE_FILL);break;case Ir.DBR_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_ORANGE_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_ORANGE_STROKE_FILL);break;case Ir.DLR_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_GREEN_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_GREEN_STROKE_FILL);break;default:r=Sr.getDrawingStyle(Sr.STYLE_YELLOW_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_YELLOW_STROKE_FILL)}for(let t of li.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Sr.getDrawingStyle(t.styleId);return Sr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=Sr.getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildDrawingItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Sr.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=Sr.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof li))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildDrawingItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of li.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Sr.getDrawingStyle(t.styleId);else{s=Sr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of li.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Sr.getDrawingStyle(t.styleId);else{s=Sr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=li.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=li.arrStyleSelectors;const r=Sr.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&qe.DIMT_RECTANGLE&&r.push("rect"),i&qe.DIMT_QUADRILATERAL&&r.push("quad"),i&qe.DIMT_TEXT&&r.push("text"),i&qe.DIMT_ARC&&r.push("arc"),i&qe.DIMT_IMAGE&&r.push("image"),i&qe.DIMT_POLYGON&&r.push("polygon"),i&qe.DIMT_LINE&&r.push("line");const n=[];e&Je.DIS_DEFAULT&&n.push("default"),e&Je.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Ir.DDN_LAYER_ID=1,Ir.DBR_LAYER_ID=2,Ir.DLR_LAYER_ID=3,Ir.USER_DEFINED_LAYER_BASE_ID=100,Ir.TIP_LAYER_ID=999;class xr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Ir(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Ar extends Ui{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),Xi.set(this,void 0),zi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ge(this,zi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Ue(this,Xi,"f")),"f")}getDuration(){return Ue(this,Xi,"f")}}Xi=new WeakMap,zi=new WeakMap;class Or{constructor(){Zi.add(this),Ki.set(this,void 0),qi.set(this,void 0),Ji.set(this,void 0),Qi.set(this,!0),this._drawingLayerManager=new xr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=Ir.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Ir.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Ir.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(ci(e=t)&&pi(e.topLeftPoint)&&ei(e.width))||e.width<=0||!ei(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ge(this,Ki,JSON.parse(JSON.stringify(t)),"f"),Ue(this,Ki,"f").coordinateBase||(Ue(this,Ki,"f").coordinateBase="view"),Ge(this,Ji,t.duration,"f"),Ue(this,Zi,"m",ir).call(this)}getTipConfig(){return Ue(this,Ki,"f")?Ue(this,Ki,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ge(this,Qi,t,"f")}isTipVisible(){return Ue(this,Qi,"f")}updateTipMessage(t){if(!Ue(this,Ki,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Sr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Ir.TIP_LAYER_ID)||this._createDrawingLayer(Ir.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ue(this,Zi,"m",$i).call(this,t,Ue(this,Ki,"f").topLeftPoint.x,Ue(this,Ki,"f").topLeftPoint.y,Ue(this,Ki,"f").width,Ue(this,Ki,"f").coordinateBase,this._tipStyleId),Ue(this,Zi,"m",tr).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ue(this,Qi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ue(this,qi,"f")&&clearTimeout(Ue(this,qi,"f")),Ue(this,Ji,"f")>=0&&Ge(this,qi,setTimeout((()=>{Ue(this,Zi,"m",er).call(this)}),Ue(this,Ji,"f")),"f")}}Ki=new WeakMap,qi=new WeakMap,Ji=new WeakMap,Qi=new WeakMap,Zi=new WeakSet,$i=function(t,e,i,r,n,s){const o=new Ar(t,e,i,r,s);return o.coordinateBase=n,o},tr=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},er=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},ir=function(){if(!this._tip)return;const t=Ue(this,Ki,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Rr extends HTMLElement{constructor(){super(),rr.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ge(this,rr,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Ue(this,rr,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}rr=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Rr);class Lr extends Or{static get engineResourcePath(){return I(mt.engineResourcePaths,ut).dce}static set defaultUIElementURL(t){Lr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Lr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Lr.engineResourcePath)}static async createInstance(t){const e=new Lr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Lr.engineResourcePath)),await e.setUIElement(t||Lr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ue(this,fr,"f")){if(Ge(this,fr,t,"f"),Ue(this,nr,"m",pr).call(this))Ge(this,hr,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Ue(this,hr,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ge(this,hr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ue(this,nr,"m",pr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Ue(this,fr,"f")}get disposed(){return Ue(this,mr,"f")}constructor(){super(),nr.add(this),sr.set(this,void 0),or.set(this,void 0),ar.set(this,void 0),this.containerClassName="dce-video-container",hr.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,lr.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,cr.set(this,!1),ur.set(this,!1),dr.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ue(this,nr,"m",Cr).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Ue(this,nr,"m",wr).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Lr._onLog&&Lr._onLog("window resize event triggered."),Ue(this,dr,"f").width===document.documentElement.clientWidth&&Ue(this,dr,"f").height===document.documentElement.clientHeight||(Ue(this,dr,"f").width=document.documentElement.clientWidth,Ue(this,dr,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},fr.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ue(this,nr,"m",pr).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},gr.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>Lr._transformCoordinates(t,i,r,n,s,o,a)));const c=new br({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ue(this,gr,"f").push(c)};let m,p;for(let t of a)switch(t.type){case pt.CRIT_ORIGINAL_IMAGE:break;case pt.CRIT_BARCODE:m=this.getDrawingLayer(Ir.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Sr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case pt.CRIT_TEXT_LINE:m=this.getDrawingLayer(Ir.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Sr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case pt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Ir.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Sr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case pt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Ir.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Sr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case pt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},mr.set(this,!1),this.eventHandler=new bi,this.eventHandler.on("content:updated",(()=>{Ue(this,sr,"f")&&clearTimeout(Ue(this,sr,"f")),Ge(this,sr,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Ue(this,or,"f")&&clearTimeout(Ue(this,or,"f")),Ge(this,or,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await xi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let r=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!r)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=new Rr,r.appendChild(this._innerComponent),Ue(this,nr,"m",pr).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ge(this,hr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Ue(this,nr,"m",pr).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ue(this,nr,"m",pr).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ue(this,nr,"m",Cr).call(this),Ue(this,nr,"m",pr).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ue(this,nr,"m",pr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Lr._onLog&&Lr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Ue(this,dr,"f").width=document.documentElement.clientWidth,Ue(this,dr,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;Ue(this,nr,"m",pr).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ue(this,nr,"m",Cr).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ge(this,hr,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),r=Math.min(t.width,t.height);e=r<=1080?r+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Ue(this,hr,"f")}isVideoLoaded(){return!(!Ue(this,hr,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ue(this,hr,"f"))return;if(Ue(this,hr,"f").style.objectFit=t,Ue(this,nr,"m",pr).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ue(this,nr,"m",Er).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(Ue(this,nr,"m",pr).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=Ue(this,hr,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ue(this,hr,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=wi.convert(this.scanRegion,t.width,t.height);Ge(this,lr,e,"f"),Ue(this,ar,"f")&&clearTimeout(Ue(this,ar,"f")),Ge(this,ar,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ue(this,nr,"m",_r).call(this,t,e),Ue(this,nr,"m",Er).call(this,t,e)}),0),"f")}getConvertedRegion(){return Ue(this,lr,"f")}setScanRegion(t){if(null!=t&&!fi(t)&&!vi(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ue(this,hr,"f").videoWidth,i=Ue(this,hr,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=Ue(this,hr,"f").videoWidth,e=Ue(this,hr,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),Ue(this,gr,"f").length=0}dispose(){this._unbindUI(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}function Dr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Mr(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,nr=new WeakSet,pr=function(){return"disabled"!==this._singleFrameMode},_r=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},vr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},yr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},wr=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Cr=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Er=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===jr.browser&&jr.version>13||"OPR"===jr.browser&&jr.version>43||"Edge"===jr.browser&&jr.version,"function"==typeof SuppressedError&&SuppressedError;let Vr=class t{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,i,r){return t.multiply(e,[1,0,0,0,1,0,i,r,1])}static rotate(e,i){var r=Math.cos(i),n=Math.sin(i);return t.multiply(e,[r,-n,0,n,r,0,0,0,1])}static scale(e,i,r){return t.multiply(e,[i,0,0,0,r,0,0,0,1])}};var Wr,Yr,Hr,Xr,zr,Zr,Kr,qr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,bn,Tn,Sn,In,xn,An,On,Rn,Ln,Dn,Mn,Fn,Pn,kn,Bn,Nn,jn,Un,Gn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Wr||(Wr={}));class Vn{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Gr(Vn,Yr,!1,"f",Hr),!1):(Gr(Vn,Yr,!0,"f",Hr),!0)}get disposed(){return Ur(this,Jr,"f")}constructor(){Xr.set(this,Wr.RGBA),zr.set(this,null),Zr.set(this,null),Kr.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,qr.set(this,null),Jr.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Ur(Vn,Yr,"f",Hr)&&Vn.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Ur(Vn,Yr,"f",Hr))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Vn._onLog&&(o=Date.now(),Vn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=Wr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Ur(Vn,Yr,"f",Hr)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Vn._onLog&&Vn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Gr(this,Zr,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Gr(this,Kr,e(t),"f"),Gr(this,zr,i(t),"f"),Gr(this,Xr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Wr.GREY,Wr.GREY32].includes(p)?1:0);let m,_,v=Vr.translate(Vr.identity(),-1,-1);v=Vr.scale(v,2,2),v=Vr.scale(v,1/t.canvas.width,1/t.canvas.height),m=Vr.translate(v,u,d),m=Vr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Vr.translate(Vr.identity(),a/i,h/r),_=Vr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Ur(this,zr,"f"),e),v(t,Ur(this,Zr,"f"),Ur(this,Kr,"f"),Ur(this,zr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Vn._onLog&&Vn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Vn._onLog&&Vn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Wr.GREY?Wr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Vn._onLog&&Vn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Vn._onLog&&(n=Date.now(),Vn._onLog("transformPixelFormat(), START: "+n)),e===i)return Vn._onLog&&Vn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[Wr.RGBA,Wr.RBGA,Wr.GRBA,Wr.GBRA,Wr.BRGA,Wr.BGRA];if(o.includes(e))if(i===Wr.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Vn._onLog&&(s=Date.now(),Vn._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=Wr.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Ur(Vn,Yr,"f",Hr)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Vn._onLog&&Vn._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===Wr.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Mr(this,$r,!0,"f")}}Qr=new WeakMap,$r=new WeakMap;const Yn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class Hn{static get version(){return"2.0.13"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(jr.OS))return Hn.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(jr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{t.src&&await t.load(),await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a){await m;try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Dr(this,gn,"f"))return"closed";if("pending"===Dr(this,gn,"f"))return"opening";if("fulfilled"===Dr(this,gn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Hn.isStorageAvailable("localStorage")?Mr(this,cn,!0,"f"):(Mr(this,cn,!1,"f"),console.warn("Local storage is unavailable")):Mr(this,cn,!1,"f")}get ifSaveLastUsedCamera(){return Dr(this,cn,"f")}get isVideoPlaying(){return!(!Dr(this,rn,"f")||Dr(this,rn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Dr(this,wn,"f"))||void 0===e||e.removeEventListener("click",Dr(this,yn,"f")),null===(i=Dr(this,wn,"f"))||void 0===i||i.removeEventListener("touchend",Dr(this,yn,"f")),null===(r=Dr(this,wn,"f"))||void 0===r||r.removeEventListener("touchmove",Dr(this,vn,"f")),Mr(this,wn,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(jr.OS)?(t.addEventListener("touchend",Dr(this,yn,"f")),t.addEventListener("touchmove",Dr(this,vn,"f"))):t.addEventListener("click",Dr(this,yn,"f")))}get tapFocusEventBoundEl(){return Dr(this,wn,"f")}get disposed(){return Dr(this,On,"f")}constructor(t){var e,i;en.add(this),rn.set(this,null),nn.set(this,void 0),sn.set(this,(()=>{"opened"===this.state&&Dr(this,Tn,"f").fire("resumed",null,{target:this,async:!1})})),on.set(this,(()=>{Dr(this,Tn,"f").fire("paused",null,{target:this,async:!1})})),an.set(this,void 0),hn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],ln.set(this,void 0),cn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,un.set(this,void 0),dn.set(this,!0),fn.set(this,void 0),gn.set(this,void 0),mn.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},pn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(Dr(this,rn,"f")).objectFit,s=this.getResolution(),o=Dr(this,rn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Dr(this,rn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},_n.set(this,!1),vn.set(this,(()=>{Mr(this,_n,!0,"f")})),yn.set(this,(async t=>{var e;if(Dr(this,_n,"f"))return void Mr(this,_n,!1,"f");if(!Dr(this,pn,"f"))return;if(!this.isVideoPlaying)return;if(!Dr(this,nn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Hn._onLog&&(c=Date.now());try{await Dr(this,en,"m",jn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Hn._onLog)throw Hn._onLog(t),t}Hn._onLog&&Hn._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Hn._onLog&&Hn._onLog("Back to continuous focus."),null===(t=Dr(this,nn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Dr(this,Tn,"f").fire("tapfocus",null,{target:this,async:!1})})),wn.set(this,null),Cn.set(this,1),En.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Dr(this,rn,"f"))return;const t=Dr(this,Cn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Dr(this,rn,"f").style.transform="";else{const e=window.getComputedStyle(Dr(this,rn,"f")).objectFit,i=Dr(this,rn,"f").videoWidth,r=Dr(this,rn,"f").videoHeight,{width:n,height:s}=Dr(this,rn,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-Dr(this,En,"f").x),c=h*(1-1/t)*(r/2-Dr(this,En,"f").y);Dr(this,rn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},bn.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Wr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Hn._onLog&&Hn._onLog("document visible. video paused: "+(null===(t=Dr(this,rn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Hn._onLog&&Hn._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Hn._onLog&&Hn._onLog("document visible. 1st resume video failed, try open instead.")}e||await Dr(this,en,"m",Fn).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Hn._onLog&&Hn._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Hn._onLog&&Hn._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Dr(this,en,"m",Fn).call(this)}}}else"hidden"===document.visibilityState&&(Hn._onLog&&Hn._onLog("document hidden. video paused: "+(null===(e=Dr(this,rn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),On.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Hn.onWarning&&Hn.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Mr(this,Tn,new Wn,"f"),this.imageDataGetter=new Vn,document.addEventListener("visibilitychange",Dr(this,An,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Dr(this,sn,"f")),t.addEventListener("pause",Dr(this,on,"f")),Mr(this,rn,t,"f")}getVideoEl(){return Dr(this,rn,"f")}releaseVideoEl(){var t,e;null===(t=Dr(this,rn,"f"))||void 0===t||t.removeEventListener("play",Dr(this,sn,"f")),null===(e=Dr(this,rn,"f"))||void 0===e||e.removeEventListener("pause",Dr(this,on,"f")),Mr(this,rn,null,"f")}isVideoLoaded(){return!!Dr(this,rn,"f")&&4==Dr(this,rn,"f").readyState}async open(){if(Dr(this,fn,"f")&&!Dr(this,dn,"f")){if("pending"===Dr(this,gn,"f"))return Dr(this,fn,"f");if("fulfilled"===Dr(this,gn,"f"))return}Dr(this,Tn,"f").fire("before:open",null,{target:this}),await Dr(this,en,"m",Fn).call(this),Dr(this,Tn,"f").fire("played",null,{target:this,async:!1}),Dr(this,Tn,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Dr(this,Tn,"f").fire("before:close",null,{target:this});const t=Dr(this,fn,"f");if(Dr(this,en,"m",kn).call(this),t&&"pending"===Dr(this,gn,"f")){try{await t}catch(t){}if(!1===Dr(this,dn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Mr(this,fn,null,"f"),Mr(this,gn,null,"f"),Dr(this,Tn,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Dr(this,rn,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Dr(this,rn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Dr(this,an,"f").video&&(Dr(this,an,"f").video={}),delete Dr(this,an,"f").video.facingMode,Dr(this,an,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,dn,"f"))){Dr(this,Tn,"f").fire("before:camera:change",[],{target:this,async:!1}),await Dr(this,en,"m",Pn).call(this);try{this.resetSoftwareScale()}catch(t){}return Dr(this,hn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Dr(this,an,"f").video&&(Dr(this,an,"f").video={}),(null==t?void 0:t.resolution)&&(Dr(this,an,"f").video.width={ideal:t.resolution.width},Dr(this,an,"f").video.height={ideal:t.resolution.height}),delete Dr(this,an,"f").video.deviceId,Dr(this,an,"f").video.facingMode={exact:"user"},Mr(this,ln,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,dn,"f"))){Dr(this,Tn,"f").fire("before:camera:change",[],{target:this,async:!1}),Dr(this,en,"m",Pn).call(this);try{this.resetSoftwareScale()}catch(t){}return Dr(this,hn,"f")}}getCamera(){var t;if(Dr(this,hn,"f"))return Dr(this,hn,"f");{let e=(null===(t=Dr(this,an,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Dr(this,an,"f").video&&(Dr(this,an,"f").video={}),i?(Dr(this,an,"f").video.width={exact:t},Dr(this,an,"f").video.height={exact:e}):(Dr(this,an,"f").video.width={ideal:t},Dr(this,an,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,dn,"f"))return null;Dr(this,Tn,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Dr(this,en,"m",Pn).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Dr(this,rn,"f"))return{width:Dr(this,rn,"f").videoWidth,height:Dr(this,rn,"f").videoHeight};if(Dr(this,nn,"f")){const t=Dr(this,nn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Dr(this,rn,"f").videoWidth,height:Dr(this,rn,"f").videoHeight};{const t={width:0,height:0};let e=Dr(this,an,"f").video.width||0,i=Dr(this,an,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Dr(this,In,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Dr(this,hn,"f"))||void 0===u?void 0:u.deviceId;let e=Dr(this,In,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Dr(this,In,"f").set(d,e),Mr(this,mn,!0,"f");try{for(let t of this.detectedResolutions){await Dr(this,nn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Dr(this,en,"m",Ln).call(this);const i=Dr(this,nn,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw Dr(this,en,"m",kn).call(this),Mr(this,mn,!1,"f"),t}try{await Dr(this,en,"m",Fn).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Mr(this,mn,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(n=null===(r=Dr(this,an,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Dr(this,an,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Dr(this,an,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Dr(this,In,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Dr(this,In,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Mr(this,an,JSON.parse(JSON.stringify(t)),"f"),Mr(this,ln,null,"f"),e&&Dr(this,en,"m",Pn).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Dr(this,an,"f")))}resetMediaStreamConstraints(){Mr(this,an,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Dr(this,nn,"f").getCapabilities?Dr(this,nn,"f").getCapabilities():{}}getCameraSettings(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Dr(this,nn,"f").getSettings()}async turnOnTorch(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Dr(this,nn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Dr(this,nn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Yn(t,r.min,r.step,r.max)),await Dr(this,nn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Yn(t,r.min,r.step,r.max)),await Dr(this,nn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await Dr(this,nn,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=Yn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await Dr(this,nn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await Dr(this,en,"m",jn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await Dr(this,nn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Mr(this,pn,!0,"f")}disableTapToFocus(){Mr(this,pn,!1,"f")}isTapToFocusEnabled(){return Dr(this,pn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Dr(this,en,"m",Un).call(this,t.centerPoint):this.resetScaleCenter();try{if(Dr(this,en,"m",Gn).call(this,Dr(this,En,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Dr(this,Cn,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Yn(t,r.min,r.step,r.max)),await Dr(this,nn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Dr(this,en,"m",Un).call(this,e),Mr(this,Cn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Dr(this,Cn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Mr(this,En,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Dr(this,mn,"f"))return null;const e=Date.now();Hn._onLog&&Hn._onLog("getFrameData() START: "+e);const i=Dr(this,rn,"f").videoWidth,r=Dr(this,rn,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=Wr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Dr(this,Cn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Dr(this,En,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(Dr(this,rn,"f"),i,r,n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return Hn._onLog&&Hn._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Dr(this,bn,"f")}}on(t,e){if(!Dr(this,Sn,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Dr(this,Tn,"f").on(t,e)}off(t,e){Dr(this,Tn,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Dr(this,Tn,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Dr(this,An,"f")),Mr(this,On,!0,"f")}}var Xn,zn,Zn,Kn,qn,Jn,Qn,$n,ts,es,is,rs,ns,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,bs,Ts,Ss,Is;rn=new WeakMap,nn=new WeakMap,sn=new WeakMap,on=new WeakMap,an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,bn=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,In=new WeakMap,xn=new WeakMap,An=new WeakMap,On=new WeakMap,en=new WeakSet,Rn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Dr(this,ln,"f"))delete t.video.facingMode,t.video.deviceId={exact:Dr(this,ln,"f")};else if(this.ifSaveLastUsedCamera&&Hn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(jr.OS)?(await this._getCameras(!1),Dr(this,en,"m",Ln).call(this),e=Hn.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(jr.OS)||(await this._getCameras(!1),Dr(this,en,"m",Ln).call(this),e=Hn.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},Ln=function(){if(Dr(this,dn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Dn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{Hn._onLog&&Hn._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),Dr(this,en,"m",Ln).call(this));try{Hn._onLog&&Hn._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),Dr(this,en,"m",Ln).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Hn._onLog&&Hn._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Mn=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Mr(this,nn,null,"f")},Fn=async function(){Mr(this,dn,!1,"f");const t=Mr(this,un,Symbol(),"f");if(Dr(this,fn,"f")&&"pending"===Dr(this,gn,"f")){try{await Dr(this,fn,"f")}catch(t){}Dr(this,en,"m",Ln).call(this)}if(t!==Dr(this,un,"f"))return;const e=Mr(this,fn,(async()=>{Mr(this,gn,"pending","f");try{if(this.videoSrc){if(!Dr(this,rn,"f"))throw new Error("'videoEl' should be set.");await Hn.playVideo(Dr(this,rn,"f"),this.videoSrc,this.cameraOpenTimeout),Dr(this,en,"m",Ln).call(this)}else{let t=await Dr(this,en,"m",Rn).call(this);Dr(this,en,"m",Mn).call(this);let e=await Dr(this,en,"m",Dn).call(this,t);await this._getCameras(!1),Dr(this,en,"m",Ln).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=Dr(this,an,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(Dr(this,ln,"f")||this.ifSaveLastUsedCamera&&Hn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=Hn.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Dr(this,en,"m",Dn).call(this,t),Dr(this,en,"m",Ln).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(Mr(this,ln,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&Hn.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Dr(this,ln,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Dr(this,rn,"f")&&(await Hn.playVideo(Dr(this,rn,"f"),e,this.cameraOpenTimeout),Dr(this,en,"m",Ln).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Mr(this,nn,s[0],"f"),Mr(this,hn,n,"f")}}catch(t){throw Dr(this,en,"m",kn).call(this),Mr(this,gn,null,"f"),t}Mr(this,gn,"fulfilled","f")})(),"f");return e},Pn=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Dr(this,hn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Dr(this,en,"m",Fn).call(this);const r=this.getResolution();e&&e!==Dr(this,hn,"f").deviceId&&Dr(this,Tn,"f").fire("camera:changed",[Dr(this,hn,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||Dr(this,Tn,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),Dr(this,Tn,"f").fire("played",null,{target:this,async:!1})},kn=function(){Dr(this,en,"m",Mn).call(this),Mr(this,hn,null,"f"),Dr(this,rn,"f")&&(Dr(this,rn,"f").srcObject=null,this.videoSrc&&(Dr(this,rn,"f").pause(),Dr(this,rn,"f").currentTime=0)),Mr(this,dn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Bn=async function t(e,i){const r=t=>{if(!Dr(this,nn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Dr(this,nn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=Yn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Dr(this,nn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Dr(this,rn,"f"),l.width,l.height,{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:Wr.RGBA,bufferContainer:d}))return Dr(this,en,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await Dr(this,en,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await Dr(this,en,"m",Bn).call(this,e,c);if(a>h)return await Dr(this,en,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await Dr(this,en,"m",t).call(this,e,o,a,c,h);let u=await Dr(this,en,"m",Bn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Dr(this,Cn,"f")){const t=Dr(this,Cn,"f"),e=Dr(this,En,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=Yn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=Yn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Yn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Dr(this,en,"m",Bn).call(this,t,s),a=await Dr(this,en,"m",Bn).call(this,t,n),h=await Dr(this,en,"m",Bn).call(this,t,r);if(a>h&&ho&&a>o){let e=await Dr(this,en,"m",Bn).call(this,t,i);const n=await Dr(this,en,"m",Nn).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await Dr(this,en,"m",Nn).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},Un=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");Mr(this,En,{x:i,y:r},"f")},Gn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Hn.browserInfo=jr,Hn.onWarning=null===(tn=null===window||void 0===window?void 0:window.console)||void 0===tn?void 0:tn.warn;class xs{constructor(t){Xn.add(this),zn.set(this,void 0),Zn.set(this,0),Kn.set(this,void 0),qn.set(this,0),Jn.set(this,!1),Ge(this,zn,t,"f")}startCharging(){Ue(this,Jn,"f")||(xs._onLog&&xs._onLog("start charging."),Ue(this,Xn,"m",$n).call(this),Ge(this,Jn,!0,"f"))}stopCharging(){Ue(this,Kn,"f")&&clearTimeout(Ue(this,Kn,"f")),Ue(this,Jn,"f")&&(xs._onLog&&xs._onLog("stop charging."),Ge(this,Zn,Date.now()-Ue(this,qn,"f"),"f"),Ge(this,Jn,!1,"f"))}}zn=new WeakMap,Zn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Xn=new WeakSet,Qn=function(){mt.cfd(1),xs._onLog&&xs._onLog("charge 1.")},$n=function t(){0==Ue(this,Zn,"f")&&Ue(this,Xn,"m",Qn).call(this),Ge(this,qn,Date.now(),"f"),Ue(this,Kn,"f")&&clearTimeout(Ue(this,Kn,"f")),Ge(this,Kn,setTimeout((()=>{Ge(this,Zn,0,"f"),Ue(this,Xn,"m",t).call(this)}),Ue(this,zn,"f")-Ue(this,Zn,"f")),"f")};class As{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ue(this,ts,"f",rs)<100)){if(Ge(this,ts,e,"f",rs),Ue(this,ts,"f",es).size&&(t=Ue(this,ts,"f",es).values().next().value,this.beepSoundSource==t.src?(Ue(this,ts,"f",es).delete(t),t.play()):t=null),!t)if(Ue(this,ts,"f",is).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Ue(this,ts,"f",is).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ue(this,ts,"f",is).delete(t),Ue(this,ts,"f",es).add(t)}))}else Ue(this,ts,"f",ns)||(Ge(this,ts,!0,"f",ns),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ue(this,ts,"f",is).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(As.vibrateDuration)}}}ts=As,es={value:new Set},is={value:new Set},rs={value:0},ns={value:!1},As.allowBeep=!0,As.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",As.allowVibrate=!0,As.vibrateDuration=300;const Os=new Map([[s.IPF_GRAYSCALED,Wr.GREY],[s.IPF_ABGR_8888,Wr.RGBA],[s.IPF_ARGB_8888,Wr.BGRA]]),Rs=new Map([[Wr.GREY,s.IPF_GRAYSCALED],[Wr.RGBA,s.IPF_ABGR_8888],[Wr.BGRA,s.IPF_ARGB_8888]]),Ls="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Ds extends U{static set _onLog(t){Ge(Ds,os,t,"f",as),Hn._onLog=t,xs._onLog=t}static get _onLog(){return Ue(Ds,os,"f",as)}static async detectEnvironment(){return await(async()=>({wasm:Ve,worker:We,getUserMedia:Ye,camera:await He(),browser:je.browser,version:je.version,OS:je.OS}))()}static async testCameraAccess(){const t=await Hn.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Lr))throw new TypeError("Invalid view.");if(null===(e=ct.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ct.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await mt.loadWasm(["license"]),await ct.license.dynamsoft()}const r=new Ds(t);return Ds.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Ds.onWarning&&Ds.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Ds.onWarning&&Ds.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ge(this,cs,t,"f")}get singleFrameMode(){return Ue(this,cs,"f")}get _isFetchingStarted(){return Ue(this,ps,"f")}get disposed(){return Ue(this,Cs,"f")}constructor(t){if(super(),ss.add(this),hs.set(this,"closed"),ls.set(this,void 0),this.isTorchOn=void 0,cs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},us.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,e,i,s,{pixelFormat:Os.get(this.getPixelFormat())});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===Wr.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:Rs.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Ct.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:Ue(this,ds,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():wi.convert(Ue(this,gs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ue(this,us,"f").call(this,t,t.width,t.height,e);Ue(this,ls,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ds.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===s.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(je.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Ue(this,ws,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Ue(this,ws,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Ue(this,vs,"f").tapToFocus&&Ue(this,ws,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(Ue(this,ss,"m",Es).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;Ds._onLog&&(Ds._onLog("intermediateResultUnits:"),Ds._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Tt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Tt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Ds._onLog&&(Ds._onLog("hasLocalizedBarcodes:"),Ds._onLog(h)),Ue(this,vs,"f").autoZoom||Ue(this,vs,"f").enhancedFocus)if(a)Ue(this,ys,"f").autoZoomInFrameArray.length=0,Ue(this,ys,"f").autoZoomOutFrameCount=0,Ue(this,ys,"f").frameArrayInIdealZoom.length=0,Ue(this,ys,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ue(this,vs,"f").autoZoom&&Ue(this,ws,"f").startCharging()},a=async t=>{await this.setFocus(t),Ue(this,vs,"f").enhancedFocus&&Ue(this,ws,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-Ue(this,ys,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ue(this,ys,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-Ue(this,ys,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ue(this,ys,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}Ds._onLog&&(Ds._onLog("detectionArea:"),Ds._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=Si(a.y-i)>0&&Si(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(Ii([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Ii([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Ii([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Ii([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Lr._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(Ds._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Sr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new Ni({points:i},e);t.addDrawingItems([n])}}}if(Ds._onLog&&(Ds._onLog("intersectedResults:"),Ds._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==Ls.BF_QR_CODE||t.possibleFormats==Ls.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Ls.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Ue(this,ys,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Ue(this,ys,"f").autoZoomInFrameLimit[1]){Ue(this,ys,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Ue(this,ys,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ue(this,ys,"f").autoZoomInMaxTimes),Ue(this,ys,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ue(this,ys,"f").minValue,u),u=Math.min(Ue(this,ys,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ue(this,ys,"f").autoZoomInFrameArray.length=0,Ue(this,ys,"f").frameArrayInIdealZoom.push(!0),Ue(this,ys,"f").frameArrayInIdealZoom.splice(0,Ue(this,ys,"f").frameArrayInIdealZoom.length-Ue(this,ys,"f").frameLimitInIdealZoom[0]),Ue(this,ys,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Ue(this,ys,"f").frameLimitInIdealZoom[1]&&(Ue(this,ys,"f").frameArrayInIdealZoom.length=0,Ue(this,vs,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Ue(this,vs,"f").autoZoom&&Ue(this,vs,"f").enhancedFocus&&(Ue(this,ys,"f").autoFocusFrameArray.push(!0),Ue(this,ys,"f").autoFocusFrameArray.splice(0,Ue(this,ys,"f").autoFocusFrameArray.length-Ue(this,ys,"f").autoFocusFrameLimit[0]),Ue(this,ys,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Ue(this,ys,"f").autoFocusFrameLimit[1])){Ue(this,ys,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Ue(this,vs,"f").autoZoom){if(Ue(this,ys,"f").autoZoomInFrameArray.push(!1),Ue(this,ys,"f").autoZoomInFrameArray.splice(0,Ue(this,ys,"f").autoZoomInFrameArray.length-Ue(this,ys,"f").autoZoomInFrameLimit[0]),Ue(this,ys,"f").autoZoomOutFrameCount++,Ue(this,ys,"f").frameArrayInIdealZoom.push(!1),Ue(this,ys,"f").frameArrayInIdealZoom.splice(0,Ue(this,ys,"f").frameArrayInIdealZoom.length-Ue(this,ys,"f").frameLimitInIdealZoom[0]),Ue(this,ys,"f").autoZoomOutFrameCount>=Ue(this,ys,"f").autoZoomOutFrameLimit){Ue(this,ys,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*Ue(this,ys,"f").autoZoomOutStepRate,Ue(this,ys,"f").autoZoomOutMinStep);r=Math.max(Ue(this,ys,"f").minValue,r),r=Math.min(Ue(this,ys,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ue(this,vs,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Ue(this,vs,"f").autoZoom&&Ue(this,vs,"f").enhancedFocus&&(Ue(this,ys,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},Ge(this,ws,new xs(1e4),"f")}setCameraView(t){if(!(t instanceof Lr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Ue(this,ss,"m",Es).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Ue(this,ss,"m",Es).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Ue(this,ss,"m",Es).call(this)?Ue(this,hs,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Ue(this,ss,"m",Es).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Ue(this,ss,"m",Es).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,r=t.getUIElement();if(r=r.shadowRoot||r,i=r.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=r.elTorchAuto=r.querySelector(".dce-mn-torch-auto"),e=r.elTorchOn=r.querySelector(".dce-mn-torch-on"),n=r.elTorchOff=r.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),n&&(n.style.display=0==this.isTorchOn?"":"none");let s=r.elBeepOn=r.querySelector(".dce-mn-beep-on"),o=r.elBeepOff=r.querySelector(".dce-mn-beep-off");s&&(s.style.display=As.allowBeep?"":"none"),o&&(o.style.display=As.allowBeep?"none":"");let a=r.elVibrateOn=r.querySelector(".dce-mn-vibrate-on"),h=r.elVibrateOff=r.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=As.allowVibrate?"":"none"),h&&(h.style.display=As.allowVibrate?"none":""),r.elResolutionBox=r.querySelector(".dce-mn-resolution-box");let l,c=r.elZoom=r.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=r.elZoomSpan=c.querySelector("span"));let u=r.elToast=r.querySelector(".dce-mn-toast"),d=r.elCameraClose=r.querySelector(".dce-mn-camera-close"),f=r.elTakePhoto=r.querySelector(".dce-mn-take-photo"),g=r.elCameraSwitch=r.querySelector(".dce-mn-camera-switch"),m=r.elCameraAndResolutionSettings=r.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=r.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==n||n.addEventListener("pointerdown",y);const w=()=>{As.allowBeep=!As.allowBeep,s&&(s.style.display=As.allowBeep?"":"none"),o&&(o.style.display=As.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{As.allowVibrate=!As.allowVibrate,a&&(a.style.display=As.allowVibrate?"":"none"),h&&(h.style.display=As.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),r=parseInt(e.getAttribute("data-height")),n=await this.setResolution({width:i,height:r});{let e=Math.max(n.width,n.height),i=Math.min(n.width,n.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&S(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};r.addEventListener("click",E);let b=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout((()=>{c.style.display="none",b=null}),e))};let T=null,S=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const A=()=>{var t,e;let i,r=this.getVideoSettings(),n=r.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==n?void 0:n.ideal)||(null==n?void 0:n.exact)||n)),r.video.facingMode={ideal:i?"environment":"user"},delete r.video.deviceId,this.updateVideoSettings(r)};null==g||g.addEventListener("pointerdown",A);let O=-1/0,R=1;const L=t=>{let e=Date.now();e-O>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),O=e};i.addEventListener("wheel",L);const D=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],r=t.touches[1],n=D.get(i.identifier),s=D.get(r.identifier);if(!n||!s)break;let o=Math.pow(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-r.clientX,2)+Math.pow(i.clientY-r.clientY,2),.5),h=Date.now();if(M||h-O<100)return;h-O>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==je?void 0:je.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&S("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,O=Date.now();break}D.clear();for(let e of t.touches)D.set(e.identifier,{x:e.clientX,y:e.clientY})};r.addEventListener("touchstart",F),r.addEventListener("touchmove",F),r.addEventListener("touchend",F),r.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==n||n.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);r.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",A),i.removeEventListener("wheel",L),r.removeEventListener("touchstart",F),r.removeEventListener("touchmove",F),r.removeEventListener("touchend",F),r.removeEventListener("touchcancel",F),delete r.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const n=this.getResolution();e.width=n.width,e.height=n.height,e.deviceId=this.getSelectedCamera().deviceId}return Ge(this,hs,"open","f"),t&&(t._innerComponent.style.display="",Ue(this,ss,"m",Es).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Ue(this,ls,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Ue(this,ss,"m",Es).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Ge(this,hs,"closed","f"),Ue(this,ws,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ue(this,ss,"m",Es).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ue(this,ls,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ue(this,ss,"m",Es).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ue(this,ss,"m",Es).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ue(this,ss,"m",Es).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),r=this.cameraView;return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ue(this,ls,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ue(this,ls,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Ue(this,ss,"m",Es).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,n;if(e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(s.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){console.log(`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(t=null==e?void 0:e.dceMnFs)||void 0===t||t.funcShowToast("Torch Auto On")}catch(t){console.error(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(n=null==i?void 0:i.dceMnFs)||void 0===n||n.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(n,t),this.isTorchOn=void 0,n();let o=this.cameraView.getUIElement();o=o.shadowRoot||o,o.elTorchAuto&&(o.elTorchAuto.style.display=""),o.elTorchOn&&(o.elTorchOn.style.display="none"),o.elTorchOff&&(o.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ue(this,ss,"m",Es).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,r;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(r=null==e?void 0:e.dceMnFs)||void 0===r||r.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Ue(this,ss,"m",Es).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Ue(this,ys,"f").minValue=t.min,Ue(this,ys,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ue(this,ys,"f").minValue,max:Ue(this,ys,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ct.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==mt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&Qe.EF_ENHANCED_FOCUS&&(Ue(this,vs,"f").enhancedFocus=!0),t&Qe.EF_AUTO_ZOOM&&(Ue(this,vs,"f").autoZoom=!0),t&Qe.EF_TAP_TO_FOCUS&&(Ue(this,vs,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&Qe.EF_ENHANCED_FOCUS&&(Ue(this,vs,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&Qe.EF_AUTO_ZOOM&&(Ue(this,vs,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&Qe.EF_TAP_TO_FOCUS&&(Ue(this,vs,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ue(this,ss,"m",Ts).call(this)&&Ue(this,ss,"m",bs).call(this)||Ue(this,ws,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!fi(t)&&!vi(t))throw TypeError("Invalid 'region'.");Ge(this,gs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Ue(this,gs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ge(this,fs,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ue(this,ss,"m",Es).call(this))}startFetching(){if(Ue(this,ss,"m",Es).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ue(this,ps,"f")||(Ge(this,ps,!0,"f"),Ue(this,ss,"m",Ss).call(this))}stopFetching(){Ue(this,ps,"f")&&(Ds._onLog&&Ds._onLog("DCE: stop fetching loop: "+Date.now()),Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),Ge(this,ps,!1,"f"))}fetchImage(){if(Ue(this,ss,"m",Es).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=wi.convert(Ue(this,gs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=this.cameraManager.getFrameData({position:i,pixelFormat:Os.get(this.getPixelFormat())});if(!n)return null;let s;s=n.pixelFormat===Wr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:Rs.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Ct.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:Ue(this,ds,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ue(this,ps,"f")&&(Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),Ge(this,_s,setTimeout((()=>{this.disposed||Ue(this,ss,"m",Ss).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ge(this,ms,t,"f")}getPixelFormat(){return Ue(this,ms,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ue(this,ss,"m",Es).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=wi.convert(Ue(this,gs,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=Ue(this,us,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ue(this,ss,"m",Is).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ue(this,ss,"m",Is).call(this,t);return{x:e.clientX,y:e.clientY}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}function Ms(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Fs(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}os=Ds,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,ss=new WeakSet,Es=function(){return"disabled"!==this.singleFrameMode},bs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Ts=function(){for(let t in Ue(this,vs,"f"))if(1==Ue(this,vs,"f")[t])return!0;return!1},Ss=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ue(this,ps,"f"))return Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),void Ge(this,_s,setTimeout((()=>{this.disposed||Ue(this,ss,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;Ds._onLog&&Ds._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Ue(this,fs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Ue(this,fs,"f"))||void 0===t||t.onErrorReceived(vt.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Ds._onLog&&Ds._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ue(this,ls,"f").fire("frameAddedToBuffer",null,{async:!1})):Ds._onLog&&Ds._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:e()}else e();Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),Ge(this,_s,setTimeout((()=>{this.disposed||Ue(this,ss,"m",t).call(this)}),this.fetchInterval),"f")},Is=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ue(this,ss,"m",Es).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ue(this,ss,"m",Es).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ue(this,ss,"m",Es).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)ut+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Ps.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return Ps.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return Ps.multiply(t,[e,0,0,0,i,0,0,0,1])}}var ks,Bs,Ns,js,Us,Gs,Vs,Ws,Ys,Hs,Xs,zs,Zs,Ks,qs,Js,Qs,$s;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ks||(ks={}));class to{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Fs(to,Bs,!1,"f",Ns),!1):(Fs(to,Bs,!0,"f",Ns),!0)}get disposed(){return Ms(this,Ys,"f")}constructor(){js.set(this,ks.RGBA),Us.set(this,null),Gs.set(this,null),Vs.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Ws.set(this,null),Ys.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Ms(to,Bs,"f",Ns)&&to.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Ms(to,Bs,"f",Ns))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;to._onLog&&(o=Date.now(),to._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=ks.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Ms(to,Bs,"f",Ns)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){to._onLog&&to._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Fs(this,Gs,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Fs(this,Vs,e(t),"f"),Fs(this,Us,i(t),"f"),Fs(this,js,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[ks.GREY,ks.GREY32].includes(p)?1:0);let m,_,v=Ps.translate(Ps.identity(),-1,-1);v=Ps.scale(v,2,2),v=Ps.scale(v,1/t.canvas.width,1/t.canvas.height),m=Ps.translate(v,u,d),m=Ps.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Ps.translate(Ps.identity(),a/i,h/r),_=Ps.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Ms(this,Us,"f"),e),v(t,Ms(this,Gs,"f"),Ms(this,Vs,"f"),Ms(this,Us,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){to._onLog&&to._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return to._onLog&&to._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===ks.GREY?ks.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return to._onLog&&to._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(to._onLog&&(n=Date.now(),to._onLog("transformPixelFormat(), START: "+n)),e===i)return to._onLog&&to._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[ks.RGBA,ks.RBGA,ks.GRBA,ks.GBRA,ks.BRGA,ks.BGRA];if(o.includes(e))if(i===ks.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;to._onLog&&(s=Date.now(),to._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=ks.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Ms(to,Bs,"f",Ns)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){to._onLog&&to._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===ks.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{var e;if(!this.isUseMagnifier)return;if(Ue(this,Ks,"f")||Ge(this,Ks,new eo,"f"),!Ue(this,Ks,"f").magnifierCanvas)return;document.body.contains(Ue(this,Ks,"f").magnifierCanvas)||(Ue(this,Ks,"f").magnifierCanvas.style.position="fixed",Ue(this,Ks,"f").magnifierCanvas.style.boxSizing="content-box",Ue(this,Ks,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ue(this,Ks,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Ue(this,Js,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];Ue(this,Ks,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Ue(this,Ks,"f").magnifierCanvas.style.left="auto",Ue(this,Ks,"f").magnifierCanvas.style.top="0",Ue(this,Ks,"f").magnifierCanvas.style.right="0"):(Ue(this,Ks,"f").magnifierCanvas.style.left="0",Ue(this,Ks,"f").magnifierCanvas.style.top="0",Ue(this,Ks,"f").magnifierCanvas.style.right="auto")}Ue(this,Ks,"f").show()})),Js.set(this,(()=>{Ue(this,Ks,"f")&&Ue(this,Ks,"f").hide()})),Qs.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await xi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=new Rr,e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(di(t)){Ge(this,Zs,t,"f");const{width:e,height:i,bytes:r,format:n}=Object.assign({},t);let o;if(n===s.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ti.Control({positionHandler:Fi,actionHandler:Bi(i>0?i-1:r,ki),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=ti.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Ue(this,Gi,"f")&&this.setLine(Ue(this,Gi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!gi(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ge(this,Gi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Gi,"f")?JSON.parse(JSON.stringify(Ue(this,Gi,"f"))):null}},QuadDrawingItem:br,RectDrawingItem:Mi,TextDrawingItem:Ui});const no="undefined"==typeof self,so=(()=>{if(!no&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),oo=t=>{if(null==t&&(t="./"),no);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};ut.dbr={version:"10.4.20",path:so},dt.dbr={js:!1,wasm:!0,deps:["license","dip"]},ct.dbr={};const ao="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,ao)<0&&(ut.std={version:ao,path:oo(so+`../../dynamsoft-capture-vision-std@${ao}/dist/`)});const ho="2.4.20";(!ut.dip||"string"!=typeof ut.dip&&S(ut.dip.version,ho)<0)&&(ut.dip={version:ho,path:oo(so+`../../dynamsoft-image-processing@${ho}/dist/`)});const lo={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var co,uo,fo,go;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(co||(co={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(uo||(uo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP"}(fo||(fo={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(go||(go={}));var mo=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=lt.dbr&<.dbr.wasm;return`10.4.20(Worker: ${lt.dbr&<.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:lo,get EnumDeblurMode(){return go},get EnumExtendedBarcodeResultType(){return co},get EnumLocalizationMode(){return fo},get EnumQRCodeErrorCorrectionLevel(){return uo}});const po=async t=>{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const _o="undefined"==typeof self,vo=(()=>{if(!_o&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),yo=t=>{if(null==t&&(t="./"),_o);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};ut.utility={version:"1.4.20",path:vo},dt.utility={js:!0,wasm:!0};const wo="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,wo)<0&&(ut.std={version:wo,path:yo(vo+`../../dynamsoft-capture-vision-std@${wo}/dist/`)});const Co="2.4.20";(!ut.dip||"string"!=typeof ut.dip&&S(ut.dip.version,Co)<0)&&(ut.dip={version:Co,path:yo(vo+`../../dynamsoft-image-processing@${Co}/dist/`)});function Eo(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}var bo,To,So;"function"==typeof SuppressedError&&SuppressedError;const Io={barcode:2,text_line:4,detected_quad:8,normalized_image:16},xo=t=>Object.values(Io).includes(t)||Io.hasOwnProperty(t),Ao=(t,e)=>"string"==typeof t?e[Io[t]]:e[t],Oo=(t,e,i)=>{"string"==typeof t?e[Io[t]]=i:e[t]=i},Ro=(t,e,i)=>{if(t.isResultCrossVerificationEnabled(i))for(let t=0;t{let h=rt();nt[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},et.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}},MultiFrameResultCrossFilter:class{constructor(){this.verificationEnabled={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!0,[pt.CRIT_DETECTED_QUAD]:!0,[pt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateFilterEnabled={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateForgetTime={[pt.CRIT_BARCODE]:3e3,[pt.CRIT_TEXT_LINE]:3e3,[pt.CRIT_DETECTED_QUAD]:3e3,[pt.CRIT_NORMALIZED_IMAGE]:3e3},this.latestOverlappingEnabled={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1},bo.set(this,new Map),To.set(this,new Map),So.set(this,new Map)}_dynamsoft(){Eo(this,bo,"f").forEach(((t,e)=>{Oo(e,this.verificationEnabled,t)})),Eo(this,To,"f").forEach(((t,e)=>{Oo(e,this.duplicateFilterEnabled,t)})),Eo(this,So,"f").forEach(((t,e)=>{Oo(e,this.duplicateForgetTime,t)}))}enableResultCrossVerification(t,e){xo(t)&&Eo(this,bo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!xo(t)&&Ao(t,this.verificationEnabled)}enableResultDeduplication(t,e){xo(t)&&Eo(this,To,"f").set(t,e)}isResultDeduplicationEnabled(t){return!!xo(t)&&Ao(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){xo(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Eo(this,So,"f").set(t,e))}getDuplicateForgetTime(t){return xo(t)?Ao(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){}getMaxOverlappingFrames(t){}enableLatestOverlapping(t,e){xo(t)&&Oo(t,this.latestOverlappingEnabled,e)}isLatestOverlappingEnabled(t){return!!xo(t)&&Ao(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[pt.CRIT_BARCODE,pt.CRIT_TEXT_LINE,pt.CRIT_DETECTED_QUAD,pt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(!o&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),h=t=>{if(null==t&&(t="./"),o);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},l=t=>Object.prototype.toString.call(t),c=t=>Array.isArray?Array.isArray(t):"[object Array]"===l(t),u=t=>"[object Boolean]"===l(t),d=t=>"number"==typeof t&&!Number.isNaN(t),f=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),g=t=>!(!f(t)||!d(t.x)||!d(t.y)||!d(t.radius)||t.radius<0||!d(t.startAngle)||!d(t.endAngle)),m=t=>!!f(t)&&!!c(t.points)&&0!=t.points.length&&!t.points.some((t=>!w(t))),p=t=>!(!f(t)||!(t.bytes instanceof Uint8Array)||!d(t.width)||t.width<=0||!d(t.height)||t.height<=0||!d(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!v(t.tag)),_=t=>!(!f(t)||!d(t.left)||t.left<0||!d(t.top)||t.top<0||!d(t.right)||t.right<0||!d(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!u(t.isMeasuredInPercentage)),v=t=>!!f(t)&&!!d(t.imageId)&&"type"in t,y=t=>!(!f(t)||!w(t.startPoint)||!w(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),w=t=>!!f(t)&&!!d(t.x)&&!!d(t.y),C=t=>!!f(t)&&!!c(t.points)&&0!=t.points.length&&!t.points.some((t=>!w(t))),E=t=>!!f(t)&&!!c(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!w(t))),b=t=>!(!f(t)||!d(t.x)||!d(t.y)||!d(t.width)||t.width<0||!d(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!u(t.isMeasuredInPercentage));async function T(t,e){return await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(t+" "+n.status):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}}))}const S=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t{const i={};for(let r in e){const n=r;let s=t[n];s&&"string"!=typeof s&&s.path&&(s=s.path),t.rootDirectory&&!t.rootDirectory.endsWith("/")&&(t.rootDirectory=t.rootDirectory+"/"),void 0===s?t.rootDirectory?s=`${t.rootDirectory}${x[n]}@${e[n].version}/dist/`:(s=e[n].path,s||(s=e[n])):s.startsWith("@engineRootDirectory/")&&(s=s.replace("@engineRootDirectory/",t.rootDirectory)),i[n]=h(s)}return i},x={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer"},A=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await R(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),O=t=>{p(t)&&(t=L(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},R=async(t,e)=>{p(e)&&(e=L(e));const i=O(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},L=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===s.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===s.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r=e(this,F,"f"))switch(e(this,P,"f")){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:if(e(this,M,"f").push(t),f(e(this,B,"f"))&&d(e(this,B,"f").imageId)&&1==e(this,B,"f").keepInBuffer)for(;e(this,M,"f").length>e(this,F,"f");){const t=e(this,M,"f").findIndex((t=>{var i;return(null===(i=t.tag)||void 0===i?void 0:i.imageId)!==e(this,B,"f").imageId}));e(this,M,"f").splice(t,1)}else e(this,M,"f").splice(0,e(this,M,"f").length-e(this,F,"f"))}else e(this,M,"f").push(t)}getImage(){if(0===e(this,M,"f").length)return null;let i;if(e(this,B,"f")&&d(e(this,B,"f").imageId)){const t=e(this,D,"m",j).call(this,e(this,B,"f").imageId);if(t<0)throw new Error(`Image with id ${e(this,B,"f").imageId} doesn't exist.`);i=e(this,M,"f").slice(t,t+1)[0]}else i=e(this,M,"f").pop();if([s.IPF_RGB_565,s.IPF_RGB_555,s.IPF_RGB_888,s.IPF_ARGB_8888,s.IPF_RGB_161616,s.IPF_ARGB_16161616,s.IPF_ABGR_8888,s.IPF_ABGR_16161616,s.IPF_BGR_888].includes(i.format)){if(e(this,N,"f")===n.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const e=new Uint8Array(i.width*i.height);for(let t=0;t0!==t.length&&t.every((t=>d(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!u(e))throw new TypeError("Invalid 'keepInBuffer'.");i(this,B,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){i(this,B,null,"f")}hasImage(t){return e(this,D,"m",j).call(this,t)>=0}startFetching(){i(this,k,!0,"f")}stopFetching(){i(this,k,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(i(this,F,t,"f");e(this,M,"f")&&e(this,M,"f").length>t;)e(this,M,"f").shift()}getMaxImageCount(){return e(this,F,"f")}getImageCount(){return e(this,M,"f").length}clearBuffer(){e(this,M,"f").length=0}isBufferEmpty(){return 0===e(this,M,"f").length}setBufferOverflowProtectionMode(t){i(this,P,t,"f")}getBufferOverflowProtectionMode(){return e(this,P,"f")}setColourChannelUsageType(t){i(this,N,t,"f")}getColourChannelUsageType(){return e(this,N,"f")}};M=new WeakMap,F=new WeakMap,P=new WeakMap,k=new WeakMap,B=new WeakMap,N=new WeakMap,D=new WeakSet,j=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return e(this,M,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))};const G=t=>t&&"object"==typeof t&&"function"==typeof t.then;let V,W,Y,H,X,z=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,G(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(G(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};"undefined"!=typeof navigator&&(V=navigator,W=V.userAgent,Y=V.platform,H=V.mediaDevices),function(){if(!o){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:V.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Y,search:"Win"},Mac:{str:Y},Linux:{str:Y}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||W,o=n.search||e,a=n.verStr||W,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||W,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=W.indexOf("Windows NT")&&(n="HarmonyOS"),X={browser:i,version:r,OS:n}}o&&(X={browser:"ssr",version:0,OS:"ssr"})}();const Z="undefined"!=typeof WebAssembly&&W&&!(/Safari/.test(W)&&!/Chrome/.test(W)&&/\(.+\s11_2_([2-6]).*\)/.test(W)),q=!("undefined"==typeof Worker),K=!(!H||!H.getUserMedia),J=async()=>{let t=!1;if(K)try{(await H.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===X.browser&&X.version>66||"Safari"===X.browser&&X.version>13||"OPR"===X.browser&&X.version>43||"Edge"===X.browser&&X.version;const Q={},$=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Q[t]=Q[t]||new z);await Promise.all(i)},tt=async(t,e)=>{let i,r="string"==typeof t?[t]:t,n=[];for(let t of r){let r;n.push(r=Q[t]=Q[t]||new z(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(n)};let et,it=0;const rt=()=>it++,nt={};let st;const ot=t=>{st=t,et&&et.postMessage({type:"setBLog",body:{value:!!t}})};let at=!1;const ht=t=>{at=t,et&&et.postMessage({type:"setBDebug",body:{value:!!t}})},lt={},ct={},ut={std:{version:"1.4.10",path:h(a+"../../dynamsoft-capture-vision-std@1.4.10/dist/")},core:{version:"3.4.21",path:a}},dt={dip:{wasm:!0}},ft={},gt=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=Q.core;e=!i||i.isEmpty;let r=new Map;const n=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!dt[t])throw Error("The '"+t+"' module cannot be found.");let e=dt[t].deps;if(null==e?void 0:e.length)for(let t of e)n(t);let i=Q[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)n(e);let s=[];e&&s.push("core"),s.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await tt(s,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await $(o);const i=I(ft,ut),n={};for(let e of t)n[e]=dt[e];const s={engineResourcePaths:i,autoResources:n,names:t};let a=new z;if(e){s.needLoadCore=!0;let t=i.core+mt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),et=new Worker(t),et.onerror=t=>{let e=new Error(t.message);a.reject(e)},et.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":st&&st(e.message);break;case"task":try{nt[r](n),delete nt[r]}catch(t){throw delete nt[r],t}break;case"event":try{nt[r](n)}catch(t){throw t}break;default:console.log(t)}})),s.bLog=!!st,s.bd=at,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await $("core");let h=it++;nt[h]=t=>{if(t.success)Object.assign(lt,t.versions),"{}"!==JSON.stringify(t.versions)&&(mt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},et.postMessage({type:"loadWasm",body:s,id:h}),await a}))};class mt{static get engineResourcePaths(){return ft}static set engineResourcePaths(t){Object.assign(ft,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return st}static set _onLog(t){ot(t)}static get _bDebug(){return at}static set _bDebug(t){ht(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Q[t]&&Q[t].isFulfilled}static async loadWasm(t){return await gt(t)}static async detectEnvironment(){return await(async()=>({wasm:Z,worker:q,getUserMedia:K,camera:await J(),browser:X.browser,version:X.version,OS:X.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.21(Worker: ${lt.core&<.core.worker||"Not Loaded"}, Wasm: ${lt.core&<.core.wasm||"Not Loaded"})`}static enableLogging(){U._onLog=console.log,mt._onLog=console.log}static disableLogging(){U._onLog=null,mt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var pt,_t,vt,yt,wt,Ct,Et,bt;mt._bSupportDce4Module=-1,mt._bSupportIRTModule=-1,mt._versions=null,mt._workerName="core.worker.js",mt.browserInfo=X,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(pt||(pt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(_t||(_t={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(vt||(vt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(yt||(yt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(wt||(wt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(Ct||(Ct={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Et||(Et={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(bt||(bt={}));const Tt={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var St,It;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(St||(St={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(It||(It={}));var xt=Object.freeze({__proto__:null,CoreModule:mt,get EnumBufferOverflowProtectionMode(){return r},get EnumCapturedResultItemType(){return pt},get EnumColourChannelUsageType(){return n},get EnumCornerType(){return _t},get EnumErrorCode(){return vt},get EnumGrayscaleEnhancementMode(){return yt},get EnumGrayscaleTransformationMode(){return wt},get EnumImagePixelFormat(){return s},get EnumImageTagType(){return Ct},EnumIntermediateResultUnitType:Tt,get EnumPDFReadingMode(){return Et},get EnumRasterDataSource(){return bt},get EnumRegionObjectElementType(){return St},get EnumSectionType(){return It},ImageSourceAdapter:U,_getNorImageData:L,_isArc:g,_isContour:m,_isDSImageData:p,_isDSRect:_,_isImageTag:v,_isLineSegment:y,_isPoint:w,_isPolygon:C,_isQuad:E,_isRect:b,_saveToFile:A,_toBlob:R,_toCanvas:O,_toImage:(t,e)=>{p(e)&&(e=L(e));const i=O(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r},autoDiscoveryPaths:ut,get bDebug(){return at},checkIsLink:function(t){return/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t)},compareVersion:S,doOrWaitAsyncDependency:tt,getNextTaskID:rt,handleEngineResourcePaths:I,innerVersions:lt,isArc:g,isContour:m,isDSImageData:p,isDSRect:_,isImageTag:v,isLineSegment:y,isObject:f,isPoint:w,isPolygon:C,isQuad:E,isRect:b,loadWasm:gt,mapAsyncDependency:Q,mapPackageRegister:ct,mapTaskCallBack:nt,get onLog(){return st},requestResource:T,setBDebug:ht,setOnLog:ot,waitAsyncDependency:$,get worker(){return et},workerAutoResources:dt});let At="./";if(document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}At=t.substring(0,t.lastIndexOf("/")+1)}mt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(At+"../../")};const Ot="undefined"==typeof self,Rt=Ot?{}:self,Lt=(()=>{if(!Ot&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),Dt=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Mt=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Dt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Dt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ft=" is not allowed to change after `createInstance` or `loadWasm` is called.",Pt=!Ot&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",kt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ft);i._license=e}};!Ot&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Bt=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Bt(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ft);i._licenseServer=e}},jt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ft);i._deviceFriendlyName=e}};let Ut,Gt,Vt,Wt,Yt;"undefined"!=typeof navigator&&(Ut=navigator,Gt=Ut.userAgent,Vt=Ut.platform,Wt=Ut.mediaDevices),function(){if(!Ot){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ut.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Vt,search:"Win"},Mac:{str:Vt},Linux:{str:Vt}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Gt,o=n.search||e,a=n.verStr||Gt,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Gt,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Gt.indexOf("Windows NT")&&(n="HarmonyOS"),Yt={browser:i,version:r,OS:n}}Ot&&(Yt={browser:"ssr",version:0,OS:"ssr"})}(),Wt&&Wt.getUserMedia,"Chrome"===Yt.browser&&Yt.version>66||"Safari"===Yt.browser&&Yt.version>13||"OPR"===Yt.browser&&Yt.version>43||"Edge"===Yt.browser&&Yt.version;const Ht=()=>(gt("license"),tt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Bt(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Rt.crypto||(s="Please upgrade your browser to support online key."),Rt.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==l)throw new Error(s);l=0,console.warn(s),i._lastErrorCode=-1,i._lastErrorString=s}return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Ft)})(zt),o=new Mt;zt._pLoad.task=o,(async()=>{try{await zt._pLoad}catch(t){}})();let a=rt();nt[a]=e=>{if(e.message&&zt._onAuthMessage){let t=zt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(st&&st("init license success"),e.message&&console.warn(e.message),mt._bSupportIRTModule=e.bSupportIRTModule,mt._bSupportDce4Module=e.bSupportDce4Module,zt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){const t=I(mt.engineResourcePaths,ut);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:zt._bNeverShowDialog,engineResourcePath:t.license,_onLog:st},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await $("core"),et.postMessage({type:"license_dynamsoft",body:{v:"3.4.21",brtk:!!t,bptk:1===t,l:e,os:Yt,fn:zt.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),zt.bCallInitLicense=!0,await o})));let Xt;ct.license={},ct.license.dynamsoft=Ht,ct.license.getAR=async()=>{{let t=Q.dynamsoft_inited;t&&t.isRejected&&await t}return et?new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){delete i.success;{let t=zt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},et.postMessage({type:"license_getAR",id:i})})):null};let zt=class t{static setLicenseServer(e){Nt(t,e)}static get license(){return this._license}static set license(e){kt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Nt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){jt(t,e)}static initLicense(e,i){if(kt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Ht()}static setDeviceFriendlyName(e){jt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await tt("dynamsoft_uuid",(async()=>{await gt();let t=new Mt,e=rt();nt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},et.postMessage({type:"license_getDeviceUUID",id:e}),Xt=await t})),Xt))()}};zt._pLoad=new Mt,zt.bPassValidation=!1,zt.bCallInitLicense=!1,zt._license=Pt,zt._licenseServer=[],zt._deviceFriendlyName="",ut.license={version:"3.4.21",path:Lt},dt.license={wasm:!0,js:!0},ct.license.LicenseManager=zt;const Zt="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,Zt)<0&&(ut.std={version:Zt,path:(t=>{if(null==t&&(t="./"),Ot);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Lt+`../../dynamsoft-capture-vision-std@${Zt}/dist/`)});var qt=Object.freeze({__proto__:null,LicenseManager:zt,LicenseModule:class{static getVersion(){return`3.4.21(Worker: ${lt.license&<.license.worker||"Not Loaded"}, Wasm: ${lt.license&<.license.wasm||"Not Loaded"})`}}});function Kt(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Jt(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Qt=t=>t&&"object"==typeof t&&"function"==typeof t.then;class $t extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Qt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Qt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class te{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ee={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1};const ie=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class re{constructor(t){this._irrRegistryState=ee,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ie(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=rt();nt[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ie(this),await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const ne="undefined"==typeof self,se=(()=>{if(!ne&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),oe=t=>{if(null==t&&(t="./"),ne);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ae;ut.cvr={version:"2.4.22",path:se},dt.cvr={js:!0,wasm:!0,deps:["license","dip"]},ct.cvr={};const he="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,he)<0&&(ut.std={version:he,path:oe(se+`../../dynamsoft-capture-vision-std@${he}/dist/`)});const le="2.4.20";(!ut.dip||"string"!=typeof ut.dip&&S(ut.dip.version,le)<0)&&(ut.dip={version:le,path:oe(se+`../../dynamsoft-image-processing@${le}/dist/`)});class ce{static getVersion(){return this._version}}var ue,de,fe,ge,me,pe,_e,ve,ye,we,Ce,Ee,be;function Te(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Te(t.referencedItem,e)}}function Se(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}ce._version=`2.4.22(Worker: ${null===(ae=lt.cvr)||void 0===ae?void 0:ae.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ue||(ue={})),BigInt(0),BigInt(1),BigInt(2),BigInt(4),BigInt(8),BigInt(16),BigInt(32),BigInt(64),BigInt(128),BigInt(256),BigInt(512),BigInt(1024),BigInt(2048),BigInt(4096),BigInt(8192),BigInt(16384),BigInt(32768),BigInt(65536),BigInt(1<<17),BigInt(1<<18),BigInt(1<<19),BigInt(1<<20),BigInt(1<<21),BigInt(1<<22),BigInt(1<<23),BigInt(1<<24),BigInt(1<<25),BigInt(1<<26),BigInt(1<<27),BigInt(1<<28),BigInt("0xFFFFFFFFFFFFFFFF");const Ie={onTaskResultsReceived:()=>{},isFilter:!0};class xe{constructor(){this.maxCvsSideLength=["iPhone","Android","HarmonyOS"].includes(mt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,de.set(this,null),fe.set(this,null),ge.set(this,null),me.set(this,null),pe.set(this,null),_e.set(this,new Set),ve.set(this,new Set),ye.set(this,new Set),we.set(this,0),Ce.set(this,!1),Ee.set(this,!1),be.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Kt(this,be,"f")}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await gt(["cvr"]);const t=new xe,e=new $t;let i=rt();return nt[i]=async i=>{var r;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(i.outputSettings),ce._version=`2.4.22(Worker: ${null===(r=lt.cvr)||void 0===r?void 0:r.worker}, Wasm: ${i.version})`,Jt(t,Ee,!0,"f"),Jt(t,me,t.getIntermediateResultManager(),"f"),Jt(t,Ee,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},et.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of Kt(this,_e,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of Kt(this,_e,"f"))t.isDce&&t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of Kt(this,_e,"f"))if(e.onDecodedBarcodesReceived&&i.barcodeResultItems&&e.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems})),e.onRecognizedTextLinesReceived&&i.textLineResultItems&&e.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems})),e.onDetectedQuadsReceived&&i.detectedQuadResultItems&&e.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems})),e.onNormalizedImagesReceived&&i.normalizedImageResultItems&&e.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems})),e.onParsedResultsReceived&&i.parsedResultItems&&e.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems})),e.onCapturedResultReceived&&!e.isDce){if(this._isOutputOriginalImage){const e=i.items.findIndex((t=>1===t.type));-1!==e&&(i.items[e].imageData=t)}e.onCapturedResultReceived(i)}}setInput(t){if(Se(this),t){if(Jt(this,de,t,"f"),t.isCameraEnhancer){Kt(this,me,"f")&&(Kt(this,de,"f")._intermediateResultReceiver.isDce=!0,Kt(this,me,"f").addResultReceiver(Kt(this,de,"f")._intermediateResultReceiver));const t=Kt(this,de,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Kt(this,_e,"f").add(e)}}}else Jt(this,de,null,"f")}getInput(){return Kt(this,de,"f")}addImageSourceStateListener(t){if(Se(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Kt(this,ve,"f").add(t)}removeImageSourceStateListener(t){return Se(this),Kt(this,ve,"f").delete(t)}addResultReceiver(t){if(Se(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Kt(this,_e,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Se(this),Kt(this,_e,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of Kt(this,_e,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new $t;let i=rt();return nt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},et.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Se(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Kt(this,ye,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Se(this),Kt(this,ye,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Kt(this,me,"f").removeResultReceiver(Ie),0===Kt(this,ye,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1},e={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1};return await Ae(this,t),void await Oe(this,e)}for(let t of Kt(this,ye,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(pt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(pt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(pt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(pt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(pt.CRIT_BARCODE)){[...Kt(this,me,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||Kt(this,me,"f").addResultReceiver(Ie)}await Ae(this,t.verificationEnabled),await Oe(this,t.duplicateFilterEnabled),await Re(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Se(this),!this._isPauseScan)return;if(!Kt(this,de,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const r=await this.containsTask(t);await gt(r);for(let t of Kt(this,ye,"f"))await this.addResultFilter(t);if(r.includes("dlr")&&!(null===(e=ct.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=I(mt.engineResourcePaths,ut);await(null===(i=ct.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(Kt(this,de,"f").isCameraEnhancer&&(r.includes("ddn")?Kt(this,de,"f").setPixelFormat(s.IPF_ABGR_8888):Kt(this,de,"f").setPixelFormat(s.IPF_GRAYSCALED)),void 0!==Kt(this,de,"f").singleFrameMode&&"disabled"!==Kt(this,de,"f").singleFrameMode)return this._templateName=t,void Kt(this,de,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return Kt(this,de,"f").getColourChannelUsageType()===n.CCUT_AUTO&&Kt(this,de,"f").setColourChannelUsageType(r.includes("ddn")?n.CCUT_FULL_CHANNEL:n.CCUT_Y_CHANNEL_ONLY),Kt(this,ge,"f")&&Kt(this,ge,"f").isPending?Kt(this,ge,"f"):(Jt(this,ge,new $t(((e,i)=>{if(this.disposed)return;let r=rt();nt[r]=async r=>{if(Kt(this,ge,"f")&&!Kt(this,ge,"f").isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=r.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&Kt(this,de,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},et.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await Kt(this,ge,"f"))}stopCapturing(){Se(this),Kt(this,de,"f")&&(Kt(this,de,"f").isCameraEnhancer&&void 0!==Kt(this,de,"f").singleFrameMode&&"disabled"!==Kt(this,de,"f").singleFrameMode?Kt(this,de,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=rt();const i=new $t;nt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},et.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),Kt(this,de,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Jt(this,ge,null,"f"),Kt(this,de,"f").setColourChannelUsageType(n.CCUT_AUTO)))}async containsTask(t){return Se(this),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Jt(this,Ce,!0,"f"),Kt(this,de,"f").isBufferEmpty())if(Kt(this,de,"f").hasNextImageToFetch())for(let t of Kt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_BUFFER_EMPTY);else if(!Kt(this,de,"f").hasNextImageToFetch())for(let t of Kt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Kt(this,de,"f").isBufferEmpty())try{Kt(this,de,"f").isBufferEmpty()&&xe._onLog&&xe._onLog("buffer is empty so fetch image"),xe._onLog&&xe._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Kt(this,de,"f").fetchImage(),xe._onLog&&xe._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Kt(this,de,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(Kt(this,de,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Kt(this,de,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of Kt(this,_e,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(xe._onLog&&xe._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Kt(this,_e,"f")){if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),xe._onLog){const t=Date.now()-e;t>10&&xe._onLog(`draw result time: ${t}`)}}t.onDecodedBarcodesReceived&&i.barcodeResultItems&&t.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems.filter((t=>!t.isFilter))})),t.onRecognizedTextLinesReceived&&i.textLineResultItems&&t.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems.filter((t=>!t.isFilter))})),t.onDetectedQuadsReceived&&i.detectedQuadResultItems&&t.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems.filter((t=>!t.isFilter))})),t.onNormalizedImagesReceived&&i.normalizedImageResultItems&&t.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems.filter((t=>!t.isFilter))})),t.onParsedResultsReceived&&i.parsedResultItems&&t.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems.filter((t=>!t.isFilter))})),t.onCapturedResultReceived&&!t.isDce&&(i.items=i.items.filter((t=>!t.isFilter)),i.barcodeResultItems&&(i.barcodeResultItems=i.barcodeResultItems.filter((t=>!t.isFilter))),i.textLineResultItems&&(i.textLineResultItems=i.textLineResultItems.filter((t=>!t.isFilter))),i.detectedQuadResultItems&&(i.detectedQuadResultItems=i.detectedQuadResultItems.filter((t=>!t.isFilter))),i.normalizedImageResultItems&&(i.normalizedImageResultItems=i.normalizedImageResultItems.filter((t=>!t.isFilter))),i.parsedResultItems&&(i.parsedResultItems=i.parsedResultItems.filter((t=>!t.isFilter))),t.onCapturedResultReceived(i))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,xe._onLog&&(xe._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),xe._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),xe._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),xe._onLog(`averageTime: ${this._averageTime}`))),xe._onLog){const t=Date.now()-n;t>10&&xe._onLog(`fetch image calculate time: ${t}`)}xe._onLog&&xe._onLog(`time finish decode: ${Date.now()}`),xe._onLog&&xe._onLog("main time: "+(Date.now()-e)),xe._onLog&&xe._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{Kt(this,de,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{Kt(this,de,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;Se(this),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const n=await this.containsTask(e);if(await gt(n),n.includes("dlr")&&!(null===(i=ct.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=I(mt.engineResourcePaths,ut);await(null===(r=ct.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Jt(this,Ce,!1,"f"),p(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await T(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,e){let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*Kt(this,we,"f")),r=Math.round(s*Kt(this,we,"f"))):(i=n,r=s),Kt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=Kt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*Kt(this,we,"f")),r=Math.round(s*Kt(this,we,"f"))):(i=n,r=s),Kt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=Kt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:r,height:n,stride:s,format:o}=t;let a=rt();const h=new $t;return nt[a]=async e=>{var i,r;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const n=Date.now();xe._onLog&&(xe._onLog(`get result time from worker: ${n}`),xe._onLog("worker to main time consume: "+(n-e.workerReturnMsgTime)));try{const n=e.captureResult;if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of n.items)0!==Kt(this,we,"f")&&Te(e,Kt(this,we,"f")),e.type===pt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===pt.CRIT_NORMALIZED_IMAGE?null===(i=ct.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===pt.CRIT_PARSED_RESULT&&(null===(r=ct.dcp)||void 0===r||r.handleParsedResultItem(e));if(Kt(this,Ce,"f"))for(let t of Kt(this,ye,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onDetectedQuadsReceived(n),t.onNormalizedImagesReceived(n);const s=function(t){const e={barcodeResultItems:[],textLineResultItems:[],detectedQuadResultItems:[],normalizedImageResultItems:[],parsedResultItems:[]};return t.items.forEach((t=>{t.type===pt.CRIT_BARCODE?e.barcodeResultItems.push(t):t.type===pt.CRIT_TEXT_LINE?e.textLineResultItems.push(t):t.type===pt.CRIT_DETECTED_QUAD?e.detectedQuadResultItems.push(t):t.type===pt.CRIT_NORMALIZED_IMAGE?e.normalizedImageResultItems.push(t):t.type===pt.CRIT_PARSED_RESULT&&e.parsedResultItems.push(t)})),e}(n);if(s.barcodeResultItems.length&&(n.barcodeResultItems=s.barcodeResultItems),s.textLineResultItems.length&&(n.textLineResultItems=s.textLineResultItems),s.detectedQuadResultItems.length&&(n.detectedQuadResultItems=s.detectedQuadResultItems),s.normalizedImageResultItems.length&&(n.normalizedImageResultItems=s.normalizedImageResultItems),s.parsedResultItems.length&&(n.parsedResultItems=s.parsedResultItems),!this._isPauseScan||!Kt(this,Ce,"f")){const e=n.intermediateResult;if(e){let i=0;for(let r of Kt(this,me,"f")._intermediateResultReceiverSet){i++;for(let n of e){if("onTaskResultsReceived"===n.info.callbackName){for(let e of n.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);i===Kt(this,me,"f")._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}}return n&&n.hasOwnProperty("intermediateResult")&&delete n.intermediateResult,Jt(this,we,0,"f"),h.resolve(n)}catch(t){return h.reject(t)}}},xe._onLog&&xe._onLog(`send buffer to worker: ${Date.now()}`),et.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:r,height:n,stride:s,format:o,templateName:e||"",isScanner:Kt(this,Ce,"f")}},[i.buffer]),h}async initSettings(t){return Se(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?(t.startsWith("{")||(t=await T(t,"text")),this._currentSettings=JSON.parse(t)):"object"==typeof t&&(this._currentSettings=t,t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=rt();nt[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.exception){let t=new Error(n.description?n.description:"Init Settings Failed.");return t.errorCode=n.exception,i(t)}let s=[],o=JSON.parse(t).CaptureVisionTemplates;for(let t=0;t{let r=rt();nt[r]=async t=>{if(t.success){const r=JSON.parse(t.settings);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return delete r.errorCode,delete r.errorString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getSimplifiedSettings(t){Se(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await gt(e),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success){const r=JSON.parse(t.settings,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));if(r.minImageCaptureInterval=this._minImageCaptureInterval,0!==r.code){let t=new Error(r.codeString);return t.errorCode=r.errorCode,i(t)}return delete r.code,delete r.codeString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Se(this);const i=await this.containsTask(t);return await gt(i),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==n.exception){let t=new Error(n.description?n.description:"Update Settings Failed.");return t.errorCode=n.exception,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Se(this),await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.exception){let t=new Error(r.description?r.description:"Reset Settings Failed.");return t.errorCode=r.exception,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return Kt(this,pe,"f")||Jt(this,pe,new te(this),"f"),Kt(this,pe,"f")}getIntermediateResultManager(){if(Se(this),!Kt(this,Ee,"f")&&0!==mt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Kt(this,me,"f")||Jt(this,me,new re(this),"f"),Kt(this,me,"f")}async parseRequiredResources(t){return Se(this),await new Promise(((e,i)=>{let r=rt();nt[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Se(this),Kt(this,ge,"f")&&this.stopCapturing(),Jt(this,de,null,"f"),Kt(this,_e,"f").clear(),Kt(this,ve,"f").clear(),Kt(this,ye,"f").clear(),Kt(this,me,"f")._intermediateResultReceiverSet.clear(),Jt(this,be,!0,"f");let t=rt();nt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Kt(this,de,"f"),promiseStartScan:Kt(this,ge,"f"),intermediateResultManager:Kt(this,me,"f"),bufferdItemsManager:Kt(this,pe,"f"),resultReceiverSet:Kt(this,_e,"f"),isaStateListenerSet:Kt(this,ve,"f"),resultFilterSet:Kt(this,ye,"f"),compressRate:Kt(this,we,"f"),canvas:Kt(this,fe,"f"),isScanner:Kt(this,Ce,"f"),innerUseTag:Kt(this,Ee,"f"),isDestroyed:Kt(this,be,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=rt();nt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Ae(t,e){return Se(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function Oe(t,e){return Se(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Re(t,e){return Se(t),await new Promise(((i,r)=>{let n=rt();nt[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},et.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,be=new WeakMap;var Le;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Le||(Le={}));var De=Object.freeze({__proto__:null,CaptureVisionRouter:xe,CaptureVisionRouterModule:ce,CapturedResultReceiver:class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},get EnumImageSourceState(){return ue},get EnumPresetTemplate(){return Le},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=Tt.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const Me="undefined"==typeof self,Fe=(()=>{if(!Me&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();ut.dce={version:"4.1.0",path:Fe},dt.dce={wasm:!1,js:!1},ct.dce={};let Pe,ke,Be,Ne,je;function Ue(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Ge(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Pe=navigator,ke=Pe.userAgent,Be=Pe.platform,Ne=Pe.mediaDevices),function(){if(!Me){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Pe.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Be,search:"Win"},Mac:{str:Be},Linux:{str:Be}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||ke,o=n.search||e,a=n.verStr||ke,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||ke,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=ke.indexOf("Windows NT")&&(n="HarmonyOS"),je={browser:i,version:r,OS:n}}Me&&(je={browser:"ssr",version:0,OS:"ssr"})}();const Ve="undefined"!=typeof WebAssembly&&ke&&!(/Safari/.test(ke)&&!/Chrome/.test(ke)&&/\(.+\s11_2_([2-6]).*\)/.test(ke)),We=!("undefined"==typeof Worker),Ye=!(!Ne||!Ne.getUserMedia),He=async()=>{let t=!1;if(Ye)try{(await Ne.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===je.browser&&je.version>66||"Safari"===je.browser&&je.version>13||"OPR"===je.browser&&je.version>43||"Edge"===je.browser&&je.version;var Xe={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,b,T=T||{version:"5.2.1"};if(e.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var S=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=S.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=S,DOMParser=T.window.DOMParser}function I(t,e){var i=t.canvas,r=e.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:T.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}T.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof T.Gradient||this.set(e,new T.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof T.Pattern?i&&i():this.set(e,new T.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new T.Point(t.x-e.x,t.y-e.y),n=T.util.rotateVector(r,i);return new T.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),r=T.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new T.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new T.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=T.util.createVector(t,e),n=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(r,n),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(r,s),n)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new T.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new T.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(T.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(T.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=T.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new T.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new T.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var b=Math.sqrt(1-C/(_*v));i*=b,s*=b}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var S=E*i*p/s,I=-E*s*m/i,x=d*S-u*I+.5*t,A=u*S+d*I+.5*e,O=n(1,0,(m-S)/i,(p-I)/s),R=n((m-S)/i,(p-I)/s,(-m-S)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var L=Math.ceil(Math.abs(R/l*2)),D=[],M=R/L,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=O+M,k=0;kE)for(var S=1,I=m.length;S2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(T.cachesBoundsOfCurve&&(l=t.call(arguments),T.boundsOfCurveCache[l]))return T.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],b=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var S=0;S<2;++S)if(S>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,A,O=E.length,R=O;O--;)I=(A=1-(f=E[O]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,b[0][O]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,b[1][O]=x;b[0][R]=e,b[1][R]=i,b[0][R+1]=a,b[1][R+1]=h;var L=[{x:y.apply(null,b[0]),y:y.apply(null,b[1])},{x:w.apply(null,b[0]),y:w.apply(null,b[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[l]=L),L},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},T.util.transformPath=function(t,e,i){return i&&(e=T.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),T.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(T.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=T.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=T.document.documentElement,n=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(t,e){var i=T.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=T.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=T.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},T.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},T.util.getById=function(t){return"string"==typeof t?T.document.getElementById(t):t},T.util.toArray=s,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=o,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},T.util.getNodeCanvas=function(t){var e=T.jsdomImplForWrapper(t);return e._canvas||e._image},T.util.cleanUpJsdomNode=function(t){if(T.isLikelyNode){var e=T.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}T.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}T.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},o=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=T.runningAnimations.indexOf(s);return t>-1&&T.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=n,!o){if(!f(w,C,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,n),void a(t));h()}}(l)})),s.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return o.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,r,n){var s=new T.Color(e).getSource(),o=new T.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},T.util.animate(T.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",b=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=n,C.viewBoxHeight=o,y?(C.width=n,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/n,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),b=C.width-n*c,T=C.height-o*c,"Mid"===p.alignX&&(b/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(b=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+b)+" "+(r*u+T)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function m(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function C(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function b(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),b(l,"skewY","scaleY","y",p)}return m}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),b(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,w=m(t,f),E=_(f,y,w),b=e.gestureScale;if(E)return!1;if(b)o=e.scaleX*b,a=e.scaleY*b;else{if(s=C(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),S=e.original,I=T/(Math.abs(h.x*S.scaleX/f.scaleX)+Math.abs(h.y*S.scaleY/f.scaleY));o=S.scaleX*I,a=S.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=w("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),E(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(T))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=C(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),E(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(S))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=w,n.getLocalPoint=C,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new T.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new T.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=m/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=T.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,m=-i.top),new T.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=T.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var t=T.util.object.extend,e=T.util.getElementOffset,i=T.util.removeFromArray,r=T.util.toFixed,n=T.util.transformPoint,s=T.util.invertTransform,o=T.util.getNodeCanvas,a=T.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=T.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?T.util.loadImage(e,(function(e,n){if(e){var s=new T.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=T.util.getById(t)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?T.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=T.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(T.StaticCanvas.prototype,T.Observable),t(T.StaticCanvas.prototype,T.Collection),t(T.StaticCanvas.prototype,T.DataURLExporter),t(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new T.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new T.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new T.Point(r.x,r.y),n=new T.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=T.util.invertTransform(i),n=this.restorePointerVpt(e);return T.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,T.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):T.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new T.Point(e.ex,e.ey),r=T.util.transformPoint(i,this.viewportTransform),n=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof T.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return T.util.transformPoint(t,T.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;T.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,T.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e:e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:e,selected:n}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),T.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==r&&(T.Canvas[r]=T.StaticCanvas[r])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(T.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(T.document,t+"up",this._onMouseUp),e(T.document,"touchend",this._onTouchEnd,i),e(T.document,t+"move",this._onMouseMove,i),e(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e:e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new T.Point(v(r,s),v(n,o)),h=new T.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return T.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):T.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=T.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new T.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof n?n=E[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new T.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new T.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),n=new T.Point(t.x,t.y),this.angle&&(n=T.util.rotatePoint(n,s,-w(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=w(this.angle),n=this.getScaledWidth(),s=T.util.cos(r)*n,o=T.util.sin(r)*n;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=T.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===T.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+T.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=T.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=T.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=T.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?T.util.animateColor(h.startValue,h.endValue,h.duration,h):T.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return T.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);T.filterBackend||(T.filterBackend=T.initFilterBackend());var o=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,T.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=T.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(T.util.getById(t),e),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(t,e){var i=T.util.object.clone(t);T.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],T.util.enlivenObjectEnlivables(i,i,(function(){var r=new T.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,r){e&&e(new T.Image(t,i),r)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(t,i,r){var n=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(n["xlink:href"],i,e(r?T.util.object.clone(r):{},n))})}(e),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(e){if(T.isLikelyNode)return!1;e=e||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){T.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=n,n},T.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}T.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=T.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(t,e){var i=new T.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,b||(n+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=r,E[s+3]=b?m[s+3]:n}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){D=r(1e3*s(T-C.x)),w[D]||(w[D]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-C.y)),w[D][M]||(w[D][M]=f(n(i(D*p,2)+i(M*_,2))/1e3)),(S=w[D][M])>0&&(x+=S,A+=S*c[I=4*(F*e+T)],O+=S*c[I+1],R+=S*c[I+2],L+=S*c[I+3]))}d[I=4*(b*a+h)]=A/x,d[I+1]=O/x,d[I+2]=R/x,d[I+3]=L/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(S+=y*f[3+(D=4*(L+x*e))],C+=y,f[D+3]<255&&(y=y*f[D+3]/250),E+=y*f[D],b+=y*f[D+1],T+=y*f[D+2],w+=y)}m[v]=E/w,m[v+1]=b/w,m[v+2]=T/w,m[v+3]=S/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),T.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);T.Object._fromObject("IText",e,i,"text")}}(),b=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],T.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=T.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=T.util.transformPoint(h,a),(h=T.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=b(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:b(r[i-1])}:n?this.styles[t+i]={0:b(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?b(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=b(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=b(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=T.util.toFixed,e=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},ze={};function Ze(t){var e=ze[t];if(void 0!==e)return e.exports;var i=ze[t]={exports:{}};return Xe[t](i,i.exports,Ze),i.exports}Ze.d=(t,e)=>{for(var i in e)Ze.o(e,i)&&!Ze.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},Ze.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var qe={};(()=>{let t;Ze.d(qe,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?Ze(653).fabric:{version:"5.2.1"}})();var Ke,Je,Qe,$e,ti=qe.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(Ke||(Ke={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(Je||(Je={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(Qe||(Qe={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}($e||($e={}));const ei=t=>"number"==typeof t&&!Number.isNaN(t),ii=t=>"string"==typeof t;var ri,ni,si,oi,ai,hi;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(ai||(ai={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(hi||(hi={}));let li=class{get mediaType(){return new Map([["rect",Ke.DIMT_RECTANGLE],["quad",Ke.DIMT_QUADRILATERAL],["text",Ke.DIMT_TEXT],["arc",Ke.DIMT_ARC],["image",Ke.DIMT_IMAGE],["polygon",Ke.DIMT_POLYGON],["line",Ke.DIMT_LINE],["group",Ke.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ue(this,ni,"f")){case Je.DIS_DEFAULT:return"default";case Je.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Ue(this,si,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ue(this,si,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ge(this,si,t,"f")}get coordinateBase(){return Ue(this,si,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(ri.add(this),ni.set(this,void 0),si.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!ei(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(Je.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(Je.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(Je.DIS_SELECTED):this.setState(Je.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ge(this,ni,t,"f")}getState(){return Ue(this,ni,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)unull!==t&&"object"==typeof t&&!Array.isArray(t),ui=t=>!!ii(t)&&""!==t,di=p,fi=_,gi=y,mi=C,pi=w,_i=E,vi=b,yi=t=>!(!ci(t)||"id"in t&&!ei(t.id)||"lineWidth"in t&&!ei(t.lineWidth)||"fillStyle"in t&&!ui(t.fillStyle)||"strokeStyle"in t&&!ui(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!ui(t.fontFamily)||"fontSize"in t&&!ei(t.fontSize));class wi{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(vi(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!fi(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Ci,Ei;class bi{constructor(){Ci.set(this,new Map),Ei.set(this,!1)}get disposed(){return Ue(this,Ei,"f")}on(t,e){t=t.toLowerCase();const i=Ue(this,Ci,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ue(this,Ci,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ue(this,Ci,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=Ue(this,Ci,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=Ue(this,Ci,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Ge(this,Ei,!0,"f")}}function Ti(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Si(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Ii(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}Ci=new WeakMap,Ei=new WeakMap;const xi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");if(r.insertAdjacentHTML("beforeend",i),1===r.childElementCount&&r.firstChild instanceof HTMLTemplateElement)return r.firstChild.content;const n=new DocumentFragment;for(let t of r.children)n.append(t);return n};var Ai,Oi,Ri,Li,Di;class Mi extends li{constructor(t,e){if(super(null,e),Ai.set(this,void 0),!vi(t))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new ti.Rect({left:t.x,top:t.y,width:t.width,height:t.height})),Ge(this,Ai,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="rect"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth"))),this.set("height",this.convertPropFromViewToImage(this.get("scaledHeight")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth"))),this.set("height",this.convertPropFromImageToView(this.get("scaledHeight")))}setPosition(t){this.setRect(t)}getPosition(){return this.getRect()}updatePosition(){Ue(this,Ai,"f")&&this.setRect(Ue(this,Ai,"f"))}setRect(t){if(!vi(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width)),this.set("height",this.convertPropFromViewToImage(t.height));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width),this.set("height",t.height)}this._drawingLayer.renderAll()}else Ge(this,Ai,JSON.parse(JSON.stringify(t)),"f")}getRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Ai,"f")?JSON.parse(JSON.stringify(Ue(this,Ai,"f"))):null}}function Fi(t,e,i){let r=i.points[this.pointIndex].x-i.pathOffset.x,n=i.points[this.pointIndex].y-i.pathOffset.y;return ti.util.transformPoint({x:r,y:n},i.calcTransformMatrix())}function Pi(t){let e=new ti.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new ti.Point(t.width+e.x,t.height+e.y)}function ki(t,e,i,r){let n=e.target,s=n.controls[n.__corner],o=n.toLocalPoint(new ti.Point(i,r),"center","center"),a=Pi(n),h=n._getTransformedDimensions(0,0),l={x:o.x*a.x/h.x+n.pathOffset.x,y:o.y*a.y/h.y+n.pathOffset.y};return n.points[s.pointIndex]=l,ti.controlsUtils.fireEvent("scaling",{e:t,transform:e,pointer:{x:i,y:r}}),!0}function Bi(t,e){return function(i,r,n,s){let o=r.target,a=ti.util.transformPoint({x:o.points[t].x-o.pathOffset.x,y:o.points[t].y-o.pathOffset.y},o.calcTransformMatrix()),h=e(i,r,n,s);o._setPositionDimensions({});let l=Pi(o),c=(o.points[t].x-o.pathOffset.x)/l.x,u=(o.points[t].y-o.pathOffset.y)/l.y;return o.setPositionByOrigin(a,c+.5,u+.5),h}}Ai=new WeakMap;class Ni extends li{constructor(t,e){if(super(null,e),Oi.set(this,void 0),!mi(t))throw new TypeError("Invalid 'polygon'.");this._setFabricObject(new ti.Polygon(t.points,{objectCaching:!1}));const i=this._fabricObject;let r=i.points.length-1;i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ti.Control({positionHandler:Fi,actionHandler:Bi(i>0?i-1:r,ki),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Ge(this,Oi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new ti.Control({positionHandler:Fi,actionHandler:Bi(r>0?r-1:i,ki),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=ti.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Ue(this,Oi,"f")&&this.setPolygon(Ue(this,Oi,"f"))}setPolygon(t){if(!mi(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ge(this,Oi,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Oi,"f")?JSON.parse(JSON.stringify(Ue(this,Oi,"f"))):null}}Oi=new WeakMap;Ri=new WeakMap,Li=new WeakMap;const ji=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ge(this,Vi,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Vi,"f")?JSON.parse(JSON.stringify(Ue(this,Vi,"f"))):null}}Vi=new WeakMap;class Tr extends li{constructor(t){super(new ti.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(Je.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(Je.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}class Sr{static createDrawingStyle(t){if(!yi(t))throw new Error("Invalid style definition.");let e,i=Sr.USER_START_STYLE_ID;for(;Ue(Sr,Wi,"f",Yi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in Ue(Sr,Wi,"f",Hi))r.hasOwnProperty(t)||(r[t]=Ue(Sr,Wi,"f",Hi)[t]);return Ue(Sr,Wi,"f",Yi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ue(Sr,Wi,"f",Yi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Ue(Sr,Wi,"f",Yi).values())))}static _updateDrawingStyle(t,e){if(!yi(e))throw new Error("Invalid style definition.");const i=Ue(Sr,Wi,"f",Yi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Wi=Sr,Sr.STYLE_BLUE_STROKE=1,Sr.STYLE_GREEN_STROKE=2,Sr.STYLE_ORANGE_STROKE=3,Sr.STYLE_YELLOW_STROKE=4,Sr.STYLE_BLUE_STROKE_FILL=5,Sr.STYLE_GREEN_STROKE_FILL=6,Sr.STYLE_ORANGE_STROKE_FILL=7,Sr.STYLE_YELLOW_STROKE_FILL=8,Sr.STYLE_BLUE_STROKE_TRANSPARENT=9,Sr.STYLE_GREEN_STROKE_TRANSPARENT=10,Sr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Sr.USER_START_STYLE_ID=1024,Yi={value:new Map([[Sr.STYLE_BLUE_STROKE,{id:Sr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE,{id:Sr.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE,{id:Sr.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_YELLOW_STROKE,{id:Sr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_BLUE_STROKE_FILL,{id:Sr.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE_FILL,{id:Sr.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE_FILL,{id:Sr.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_YELLOW_STROKE_FILL,{id:Sr.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Sr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Sr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Sr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Sr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Hi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ti.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ti.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ti.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ti.Object.prototype.transparentCorners=!1,ti.Object.prototype.cornerSize=20,ti.Object.prototype.touchCornerSize=100,ti.Object.prototype.cornerColor="rgb(254,142,20)",ti.Object.prototype.cornerStyle="circle",ti.Object.prototype.strokeUniform=!0,ti.Object.prototype.hasBorders=!1,ti.Canvas.prototype.containerClass="",ti.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=ti.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},ti.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();ti.util.addListener(ti.document,"touchend",this._onTouchEnd,{passive:!1}),ti.util.addListener(ti.document,"touchmove",this._onMouseMove,{passive:!1}),ti.util.removeListener(i,r+"down",this._onMouseDown)},ti.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?ti.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class Ir{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ti.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case Ir.DDN_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_BLUE_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_BLUE_STROKE_FILL);break;case Ir.DBR_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_ORANGE_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_ORANGE_STROKE_FILL);break;case Ir.DLR_LAYER_ID:r=Sr.getDrawingStyle(Sr.STYLE_GREEN_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_GREEN_STROKE_FILL);break;default:r=Sr.getDrawingStyle(Sr.STYLE_YELLOW_STROKE),n=Sr.getDrawingStyle(Sr.STYLE_YELLOW_STROKE_FILL)}for(let t of li.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Sr.getDrawingStyle(t.styleId);return Sr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=Sr.getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildDrawingItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Sr.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=Sr.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof li))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildDrawingItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of li.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Sr.getDrawingStyle(t.styleId);else{s=Sr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of li.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Sr.getDrawingStyle(t.styleId);else{s=Sr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,Sr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=li.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=li.arrStyleSelectors;const r=Sr.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&Ke.DIMT_RECTANGLE&&r.push("rect"),i&Ke.DIMT_QUADRILATERAL&&r.push("quad"),i&Ke.DIMT_TEXT&&r.push("text"),i&Ke.DIMT_ARC&&r.push("arc"),i&Ke.DIMT_IMAGE&&r.push("image"),i&Ke.DIMT_POLYGON&&r.push("polygon"),i&Ke.DIMT_LINE&&r.push("line");const n=[];e&Je.DIS_DEFAULT&&n.push("default"),e&Je.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Ir.DDN_LAYER_ID=1,Ir.DBR_LAYER_ID=2,Ir.DLR_LAYER_ID=3,Ir.USER_DEFINED_LAYER_BASE_ID=100,Ir.TIP_LAYER_ID=999;class xr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Ir(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Ar extends Ui{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),Xi.set(this,void 0),zi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ge(this,zi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Ue(this,Xi,"f")),"f")}getDuration(){return Ue(this,Xi,"f")}}Xi=new WeakMap,zi=new WeakMap;class Or{constructor(){Zi.add(this),qi.set(this,void 0),Ki.set(this,void 0),Ji.set(this,void 0),Qi.set(this,!0),this._drawingLayerManager=new xr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=Ir.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Ir.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Ir.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(ci(e=t)&&pi(e.topLeftPoint)&&ei(e.width))||e.width<=0||!ei(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ge(this,qi,JSON.parse(JSON.stringify(t)),"f"),Ue(this,qi,"f").coordinateBase||(Ue(this,qi,"f").coordinateBase="view"),Ge(this,Ji,t.duration,"f"),Ue(this,Zi,"m",ir).call(this)}getTipConfig(){return Ue(this,qi,"f")?Ue(this,qi,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ge(this,Qi,t,"f")}isTipVisible(){return Ue(this,Qi,"f")}updateTipMessage(t){if(!Ue(this,qi,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Sr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Ir.TIP_LAYER_ID)||this._createDrawingLayer(Ir.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ue(this,Zi,"m",$i).call(this,t,Ue(this,qi,"f").topLeftPoint.x,Ue(this,qi,"f").topLeftPoint.y,Ue(this,qi,"f").width,Ue(this,qi,"f").coordinateBase,this._tipStyleId),Ue(this,Zi,"m",tr).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ue(this,Qi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ue(this,Ki,"f")&&clearTimeout(Ue(this,Ki,"f")),Ue(this,Ji,"f")>=0&&Ge(this,Ki,setTimeout((()=>{Ue(this,Zi,"m",er).call(this)}),Ue(this,Ji,"f")),"f")}}qi=new WeakMap,Ki=new WeakMap,Ji=new WeakMap,Qi=new WeakMap,Zi=new WeakSet,$i=function(t,e,i,r,n,s){const o=new Ar(t,e,i,r,s);return o.coordinateBase=n,o},tr=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},er=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},ir=function(){if(!this._tip)return;const t=Ue(this,qi,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Rr extends HTMLElement{constructor(){super(),rr.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ge(this,rr,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Ue(this,rr,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}rr=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Rr);class Lr extends Or{static get engineResourcePath(){return I(mt.engineResourcePaths,ut).dce}static set defaultUIElementURL(t){Lr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Lr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Lr.engineResourcePath)}static async createInstance(t){const e=new Lr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Lr.engineResourcePath)),await e.setUIElement(t||Lr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ue(this,fr,"f")){if(Ge(this,fr,t,"f"),Ue(this,nr,"m",pr).call(this))Ge(this,hr,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Ue(this,hr,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ge(this,hr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ue(this,nr,"m",pr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Ue(this,fr,"f")}get disposed(){return Ue(this,mr,"f")}constructor(){super(),nr.add(this),sr.set(this,void 0),or.set(this,void 0),ar.set(this,void 0),this.containerClassName="dce-video-container",hr.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,lr.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,cr.set(this,!1),ur.set(this,!1),dr.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ue(this,nr,"m",Cr).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Ue(this,nr,"m",wr).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Lr._onLog&&Lr._onLog("window resize event triggered."),Ue(this,dr,"f").width===document.documentElement.clientWidth&&Ue(this,dr,"f").height===document.documentElement.clientHeight||(Ue(this,dr,"f").width=document.documentElement.clientWidth,Ue(this,dr,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},fr.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ue(this,nr,"m",pr).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},gr.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>Lr._transformCoordinates(t,i,r,n,s,o,a)));const c=new br({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ue(this,gr,"f").push(c)};let m,p;for(let t of a)switch(t.type){case pt.CRIT_ORIGINAL_IMAGE:break;case pt.CRIT_BARCODE:m=this.getDrawingLayer(Ir.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Sr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case pt.CRIT_TEXT_LINE:m=this.getDrawingLayer(Ir.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Sr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case pt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Ir.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Sr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case pt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Ir.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Sr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case pt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},mr.set(this,!1),this.eventHandler=new bi,this.eventHandler.on("content:updated",(()=>{Ue(this,sr,"f")&&clearTimeout(Ue(this,sr,"f")),Ge(this,sr,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Ue(this,or,"f")&&clearTimeout(Ue(this,or,"f")),Ge(this,or,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await xi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let r=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!r)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=new Rr,r.appendChild(this._innerComponent),Ue(this,nr,"m",pr).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ge(this,hr,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Ue(this,nr,"m",pr).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ue(this,nr,"m",pr).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ue(this,nr,"m",Cr).call(this),Ue(this,nr,"m",pr).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ue(this,nr,"m",pr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Lr._onLog&&Lr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Ue(this,dr,"f").width=document.documentElement.clientWidth,Ue(this,dr,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;Ue(this,nr,"m",pr).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ue(this,nr,"m",Cr).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ge(this,hr,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),r=Math.min(t.width,t.height);e=r<=1080?r+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Ue(this,hr,"f")}isVideoLoaded(){return!(!Ue(this,hr,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ue(this,hr,"f"))return;if(Ue(this,hr,"f").style.objectFit=t,Ue(this,nr,"m",pr).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ue(this,nr,"m",Er).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(Ue(this,nr,"m",pr).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=Ue(this,hr,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ue(this,hr,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=wi.convert(this.scanRegion,t.width,t.height);Ge(this,lr,e,"f"),Ue(this,ar,"f")&&clearTimeout(Ue(this,ar,"f")),Ge(this,ar,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ue(this,nr,"m",_r).call(this,t,e),Ue(this,nr,"m",Er).call(this,t,e)}),0),"f")}getConvertedRegion(){return Ue(this,lr,"f")}setScanRegion(t){if(null!=t&&!fi(t)&&!vi(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ue(this,hr,"f").videoWidth,i=Ue(this,hr,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=Ue(this,hr,"f").videoWidth,e=Ue(this,hr,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),Ue(this,gr,"f").length=0}dispose(){this._unbindUI(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}function Dr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Mr(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,nr=new WeakSet,pr=function(){return"disabled"!==this._singleFrameMode},_r=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},vr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},yr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},wr=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Cr=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Er=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===jr.browser&&jr.version>13||"OPR"===jr.browser&&jr.version>43||"Edge"===jr.browser&&jr.version,"function"==typeof SuppressedError&&SuppressedError;let Vr=class t{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,i,r){return t.multiply(e,[1,0,0,0,1,0,i,r,1])}static rotate(e,i){var r=Math.cos(i),n=Math.sin(i);return t.multiply(e,[r,-n,0,n,r,0,0,0,1])}static scale(e,i,r){return t.multiply(e,[i,0,0,0,r,0,0,0,1])}};var Wr,Yr,Hr,Xr,zr,Zr,qr,Kr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,bn,Tn,Sn,In,xn,An,On,Rn,Ln,Dn,Mn,Fn,Pn,kn,Bn,Nn,jn,Un,Gn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Wr||(Wr={}));class Vn{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Gr(Vn,Yr,!1,"f",Hr),!1):(Gr(Vn,Yr,!0,"f",Hr),!0)}get disposed(){return Ur(this,Jr,"f")}constructor(){Xr.set(this,Wr.RGBA),zr.set(this,null),Zr.set(this,null),qr.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Kr.set(this,null),Jr.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Ur(Vn,Yr,"f",Hr)&&Vn.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Ur(Vn,Yr,"f",Hr))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Vn._onLog&&(o=Date.now(),Vn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=Wr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Ur(Vn,Yr,"f",Hr)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Vn._onLog&&Vn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Gr(this,Zr,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Gr(this,qr,e(t),"f"),Gr(this,zr,i(t),"f"),Gr(this,Xr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Wr.GREY,Wr.GREY32].includes(p)?1:0);let m,_,v=Vr.translate(Vr.identity(),-1,-1);v=Vr.scale(v,2,2),v=Vr.scale(v,1/t.canvas.width,1/t.canvas.height),m=Vr.translate(v,u,d),m=Vr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Vr.translate(Vr.identity(),a/i,h/r),_=Vr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Ur(this,zr,"f"),e),v(t,Ur(this,Zr,"f"),Ur(this,qr,"f"),Ur(this,zr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Vn._onLog&&Vn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Vn._onLog&&Vn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Wr.GREY?Wr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Vn._onLog&&Vn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Vn._onLog&&(n=Date.now(),Vn._onLog("transformPixelFormat(), START: "+n)),e===i)return Vn._onLog&&Vn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[Wr.RGBA,Wr.RBGA,Wr.GRBA,Wr.GBRA,Wr.BRGA,Wr.BGRA];if(o.includes(e))if(i===Wr.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Vn._onLog&&(s=Date.now(),Vn._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=Wr.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Ur(Vn,Yr,"f",Hr)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Vn._onLog&&Vn._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===Wr.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Mr(this,$r,!0,"f")}}Qr=new WeakMap,$r=new WeakMap;const Yn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class Hn{static get version(){return"2.0.13"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(jr.OS))return Hn.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(jr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{t.src&&await t.load(),await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a){await m;try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Dr(this,gn,"f"))return"closed";if("pending"===Dr(this,gn,"f"))return"opening";if("fulfilled"===Dr(this,gn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Hn.isStorageAvailable("localStorage")?Mr(this,cn,!0,"f"):(Mr(this,cn,!1,"f"),console.warn("Local storage is unavailable")):Mr(this,cn,!1,"f")}get ifSaveLastUsedCamera(){return Dr(this,cn,"f")}get isVideoPlaying(){return!(!Dr(this,rn,"f")||Dr(this,rn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Dr(this,wn,"f"))||void 0===e||e.removeEventListener("click",Dr(this,yn,"f")),null===(i=Dr(this,wn,"f"))||void 0===i||i.removeEventListener("touchend",Dr(this,yn,"f")),null===(r=Dr(this,wn,"f"))||void 0===r||r.removeEventListener("touchmove",Dr(this,vn,"f")),Mr(this,wn,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(jr.OS)?(t.addEventListener("touchend",Dr(this,yn,"f")),t.addEventListener("touchmove",Dr(this,vn,"f"))):t.addEventListener("click",Dr(this,yn,"f")))}get tapFocusEventBoundEl(){return Dr(this,wn,"f")}get disposed(){return Dr(this,On,"f")}constructor(t){var e,i;en.add(this),rn.set(this,null),nn.set(this,void 0),sn.set(this,(()=>{"opened"===this.state&&Dr(this,Tn,"f").fire("resumed",null,{target:this,async:!1})})),on.set(this,(()=>{Dr(this,Tn,"f").fire("paused",null,{target:this,async:!1})})),an.set(this,void 0),hn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],ln.set(this,void 0),cn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,un.set(this,void 0),dn.set(this,!0),fn.set(this,void 0),gn.set(this,void 0),mn.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},pn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(Dr(this,rn,"f")).objectFit,s=this.getResolution(),o=Dr(this,rn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Dr(this,rn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},_n.set(this,!1),vn.set(this,(()=>{Mr(this,_n,!0,"f")})),yn.set(this,(async t=>{var e;if(Dr(this,_n,"f"))return void Mr(this,_n,!1,"f");if(!Dr(this,pn,"f"))return;if(!this.isVideoPlaying)return;if(!Dr(this,nn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Hn._onLog&&(c=Date.now());try{await Dr(this,en,"m",jn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Hn._onLog)throw Hn._onLog(t),t}Hn._onLog&&Hn._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Hn._onLog&&Hn._onLog("Back to continuous focus."),null===(t=Dr(this,nn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Dr(this,Tn,"f").fire("tapfocus",null,{target:this,async:!1})})),wn.set(this,null),Cn.set(this,1),En.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Dr(this,rn,"f"))return;const t=Dr(this,Cn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Dr(this,rn,"f").style.transform="";else{const e=window.getComputedStyle(Dr(this,rn,"f")).objectFit,i=Dr(this,rn,"f").videoWidth,r=Dr(this,rn,"f").videoHeight,{width:n,height:s}=Dr(this,rn,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-Dr(this,En,"f").x),c=h*(1-1/t)*(r/2-Dr(this,En,"f").y);Dr(this,rn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},bn.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Wr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Hn._onLog&&Hn._onLog("document visible. video paused: "+(null===(t=Dr(this,rn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Hn._onLog&&Hn._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Hn._onLog&&Hn._onLog("document visible. 1st resume video failed, try open instead.")}e||await Dr(this,en,"m",Fn).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Hn._onLog&&Hn._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Hn._onLog&&Hn._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Dr(this,en,"m",Fn).call(this)}}}else"hidden"===document.visibilityState&&(Hn._onLog&&Hn._onLog("document hidden. video paused: "+(null===(e=Dr(this,rn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),On.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Hn.onWarning&&Hn.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Mr(this,Tn,new Wn,"f"),this.imageDataGetter=new Vn,document.addEventListener("visibilitychange",Dr(this,An,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Dr(this,sn,"f")),t.addEventListener("pause",Dr(this,on,"f")),Mr(this,rn,t,"f")}getVideoEl(){return Dr(this,rn,"f")}releaseVideoEl(){var t,e;null===(t=Dr(this,rn,"f"))||void 0===t||t.removeEventListener("play",Dr(this,sn,"f")),null===(e=Dr(this,rn,"f"))||void 0===e||e.removeEventListener("pause",Dr(this,on,"f")),Mr(this,rn,null,"f")}isVideoLoaded(){return!!Dr(this,rn,"f")&&4==Dr(this,rn,"f").readyState}async open(){if(Dr(this,fn,"f")&&!Dr(this,dn,"f")){if("pending"===Dr(this,gn,"f"))return Dr(this,fn,"f");if("fulfilled"===Dr(this,gn,"f"))return}Dr(this,Tn,"f").fire("before:open",null,{target:this}),await Dr(this,en,"m",Fn).call(this),Dr(this,Tn,"f").fire("played",null,{target:this,async:!1}),Dr(this,Tn,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Dr(this,Tn,"f").fire("before:close",null,{target:this});const t=Dr(this,fn,"f");if(Dr(this,en,"m",kn).call(this),t&&"pending"===Dr(this,gn,"f")){try{await t}catch(t){}if(!1===Dr(this,dn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Mr(this,fn,null,"f"),Mr(this,gn,null,"f"),Dr(this,Tn,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Dr(this,rn,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Dr(this,rn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Dr(this,an,"f").video&&(Dr(this,an,"f").video={}),delete Dr(this,an,"f").video.facingMode,Dr(this,an,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,dn,"f"))){Dr(this,Tn,"f").fire("before:camera:change",[],{target:this,async:!1}),await Dr(this,en,"m",Pn).call(this);try{this.resetSoftwareScale()}catch(t){}return Dr(this,hn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Dr(this,an,"f").video&&(Dr(this,an,"f").video={}),(null==t?void 0:t.resolution)&&(Dr(this,an,"f").video.width={ideal:t.resolution.width},Dr(this,an,"f").video.height={ideal:t.resolution.height}),delete Dr(this,an,"f").video.deviceId,Dr(this,an,"f").video.facingMode={exact:"user"},Mr(this,ln,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,dn,"f"))){Dr(this,Tn,"f").fire("before:camera:change",[],{target:this,async:!1}),Dr(this,en,"m",Pn).call(this);try{this.resetSoftwareScale()}catch(t){}return Dr(this,hn,"f")}}getCamera(){var t;if(Dr(this,hn,"f"))return Dr(this,hn,"f");{let e=(null===(t=Dr(this,an,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Dr(this,an,"f").video&&(Dr(this,an,"f").video={}),i?(Dr(this,an,"f").video.width={exact:t},Dr(this,an,"f").video.height={exact:e}):(Dr(this,an,"f").video.width={ideal:t},Dr(this,an,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Dr(this,dn,"f"))return null;Dr(this,Tn,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Dr(this,en,"m",Pn).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Dr(this,rn,"f"))return{width:Dr(this,rn,"f").videoWidth,height:Dr(this,rn,"f").videoHeight};if(Dr(this,nn,"f")){const t=Dr(this,nn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Dr(this,rn,"f").videoWidth,height:Dr(this,rn,"f").videoHeight};{const t={width:0,height:0};let e=Dr(this,an,"f").video.width||0,i=Dr(this,an,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Dr(this,In,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Dr(this,hn,"f"))||void 0===u?void 0:u.deviceId;let e=Dr(this,In,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Dr(this,In,"f").set(d,e),Mr(this,mn,!0,"f");try{for(let t of this.detectedResolutions){await Dr(this,nn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Dr(this,en,"m",Ln).call(this);const i=Dr(this,nn,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw Dr(this,en,"m",kn).call(this),Mr(this,mn,!1,"f"),t}try{await Dr(this,en,"m",Fn).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Mr(this,mn,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(n=null===(r=Dr(this,an,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Dr(this,an,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Dr(this,an,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Dr(this,In,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Dr(this,In,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Mr(this,an,JSON.parse(JSON.stringify(t)),"f"),Mr(this,ln,null,"f"),e&&Dr(this,en,"m",Pn).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Dr(this,an,"f")))}resetMediaStreamConstraints(){Mr(this,an,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Dr(this,nn,"f").getCapabilities?Dr(this,nn,"f").getCapabilities():{}}getCameraSettings(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Dr(this,nn,"f").getSettings()}async turnOnTorch(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Dr(this,nn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Dr(this,nn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Yn(t,r.min,r.step,r.max)),await Dr(this,nn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Yn(t,r.min,r.step,r.max)),await Dr(this,nn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await Dr(this,nn,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=Yn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await Dr(this,nn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await Dr(this,en,"m",jn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await Dr(this,nn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Mr(this,pn,!0,"f")}disableTapToFocus(){Mr(this,pn,!1,"f")}isTapToFocusEnabled(){return Dr(this,pn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Dr(this,en,"m",Un).call(this,t.centerPoint):this.resetScaleCenter();try{if(Dr(this,en,"m",Gn).call(this,Dr(this,En,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Dr(this,Cn,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Dr(this,nn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Yn(t,r.min,r.step,r.max)),await Dr(this,nn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Dr(this,en,"m",Un).call(this,e),Mr(this,Cn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Dr(this,Cn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Mr(this,En,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Dr(this,mn,"f"))return null;const e=Date.now();Hn._onLog&&Hn._onLog("getFrameData() START: "+e);const i=Dr(this,rn,"f").videoWidth,r=Dr(this,rn,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=Wr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Dr(this,Cn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Dr(this,En,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(Dr(this,rn,"f"),i,r,n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return Hn._onLog&&Hn._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Dr(this,bn,"f")}}on(t,e){if(!Dr(this,Sn,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Dr(this,Tn,"f").on(t,e)}off(t,e){Dr(this,Tn,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Dr(this,Tn,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Dr(this,An,"f")),Mr(this,On,!0,"f")}}var Xn,zn,Zn,qn,Kn,Jn,Qn,$n,ts,es,is,rs,ns,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,bs,Ts,Ss,Is;rn=new WeakMap,nn=new WeakMap,sn=new WeakMap,on=new WeakMap,an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,bn=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,In=new WeakMap,xn=new WeakMap,An=new WeakMap,On=new WeakMap,en=new WeakSet,Rn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Dr(this,ln,"f"))delete t.video.facingMode,t.video.deviceId={exact:Dr(this,ln,"f")};else if(this.ifSaveLastUsedCamera&&Hn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(jr.OS)?(await this._getCameras(!1),Dr(this,en,"m",Ln).call(this),e=Hn.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(jr.OS)||(await this._getCameras(!1),Dr(this,en,"m",Ln).call(this),e=Hn.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},Ln=function(){if(Dr(this,dn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Dn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{Hn._onLog&&Hn._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),Dr(this,en,"m",Ln).call(this));try{Hn._onLog&&Hn._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),Dr(this,en,"m",Ln).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Hn._onLog&&Hn._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Mn=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Mr(this,nn,null,"f")},Fn=async function(){Mr(this,dn,!1,"f");const t=Mr(this,un,Symbol(),"f");if(Dr(this,fn,"f")&&"pending"===Dr(this,gn,"f")){try{await Dr(this,fn,"f")}catch(t){}Dr(this,en,"m",Ln).call(this)}if(t!==Dr(this,un,"f"))return;const e=Mr(this,fn,(async()=>{Mr(this,gn,"pending","f");try{if(this.videoSrc){if(!Dr(this,rn,"f"))throw new Error("'videoEl' should be set.");await Hn.playVideo(Dr(this,rn,"f"),this.videoSrc,this.cameraOpenTimeout),Dr(this,en,"m",Ln).call(this)}else{let t=await Dr(this,en,"m",Rn).call(this);Dr(this,en,"m",Mn).call(this);let e=await Dr(this,en,"m",Dn).call(this,t);await this._getCameras(!1),Dr(this,en,"m",Ln).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=Dr(this,an,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(Dr(this,ln,"f")||this.ifSaveLastUsedCamera&&Hn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=Hn.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Dr(this,en,"m",Dn).call(this,t),Dr(this,en,"m",Ln).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(Mr(this,ln,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&Hn.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Dr(this,ln,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Dr(this,rn,"f")&&(await Hn.playVideo(Dr(this,rn,"f"),e,this.cameraOpenTimeout),Dr(this,en,"m",Ln).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Mr(this,nn,s[0],"f"),Mr(this,hn,n,"f")}}catch(t){throw Dr(this,en,"m",kn).call(this),Mr(this,gn,null,"f"),t}Mr(this,gn,"fulfilled","f")})(),"f");return e},Pn=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Dr(this,hn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Dr(this,en,"m",Fn).call(this);const r=this.getResolution();e&&e!==Dr(this,hn,"f").deviceId&&Dr(this,Tn,"f").fire("camera:changed",[Dr(this,hn,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||Dr(this,Tn,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),Dr(this,Tn,"f").fire("played",null,{target:this,async:!1})},kn=function(){Dr(this,en,"m",Mn).call(this),Mr(this,hn,null,"f"),Dr(this,rn,"f")&&(Dr(this,rn,"f").srcObject=null,this.videoSrc&&(Dr(this,rn,"f").pause(),Dr(this,rn,"f").currentTime=0)),Mr(this,dn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Bn=async function t(e,i){const r=t=>{if(!Dr(this,nn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Dr(this,nn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=Yn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Dr(this,nn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Dr(this,rn,"f"),l.width,l.height,{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:Wr.RGBA,bufferContainer:d}))return Dr(this,en,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await Dr(this,en,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await Dr(this,en,"m",Bn).call(this,e,c);if(a>h)return await Dr(this,en,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await Dr(this,en,"m",t).call(this,e,o,a,c,h);let u=await Dr(this,en,"m",Bn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Dr(this,Cn,"f")){const t=Dr(this,Cn,"f"),e=Dr(this,En,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=Yn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=Yn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Yn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Dr(this,en,"m",Bn).call(this,t,s),a=await Dr(this,en,"m",Bn).call(this,t,n),h=await Dr(this,en,"m",Bn).call(this,t,r);if(a>h&&ho&&a>o){let e=await Dr(this,en,"m",Bn).call(this,t,i);const n=await Dr(this,en,"m",Nn).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await Dr(this,en,"m",Nn).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},Un=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");Mr(this,En,{x:i,y:r},"f")},Gn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Hn.browserInfo=jr,Hn.onWarning=null===(tn=null===window||void 0===window?void 0:window.console)||void 0===tn?void 0:tn.warn;class xs{constructor(t){Xn.add(this),zn.set(this,void 0),Zn.set(this,0),qn.set(this,void 0),Kn.set(this,0),Jn.set(this,!1),Ge(this,zn,t,"f")}startCharging(){Ue(this,Jn,"f")||(xs._onLog&&xs._onLog("start charging."),Ue(this,Xn,"m",$n).call(this),Ge(this,Jn,!0,"f"))}stopCharging(){Ue(this,qn,"f")&&clearTimeout(Ue(this,qn,"f")),Ue(this,Jn,"f")&&(xs._onLog&&xs._onLog("stop charging."),Ge(this,Zn,Date.now()-Ue(this,Kn,"f"),"f"),Ge(this,Jn,!1,"f"))}}zn=new WeakMap,Zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Jn=new WeakMap,Xn=new WeakSet,Qn=function(){mt.cfd(1),xs._onLog&&xs._onLog("charge 1.")},$n=function t(){0==Ue(this,Zn,"f")&&Ue(this,Xn,"m",Qn).call(this),Ge(this,Kn,Date.now(),"f"),Ue(this,qn,"f")&&clearTimeout(Ue(this,qn,"f")),Ge(this,qn,setTimeout((()=>{Ge(this,Zn,0,"f"),Ue(this,Xn,"m",t).call(this)}),Ue(this,zn,"f")-Ue(this,Zn,"f")),"f")};class As{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ue(this,ts,"f",rs)<100)){if(Ge(this,ts,e,"f",rs),Ue(this,ts,"f",es).size&&(t=Ue(this,ts,"f",es).values().next().value,this.beepSoundSource==t.src?(Ue(this,ts,"f",es).delete(t),t.play()):t=null),!t)if(Ue(this,ts,"f",is).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Ue(this,ts,"f",is).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ue(this,ts,"f",is).delete(t),Ue(this,ts,"f",es).add(t)}))}else Ue(this,ts,"f",ns)||(Ge(this,ts,!0,"f",ns),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ue(this,ts,"f",is).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(As.vibrateDuration)}}}ts=As,es={value:new Set},is={value:new Set},rs={value:0},ns={value:!1},As.allowBeep=!0,As.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",As.allowVibrate=!0,As.vibrateDuration=300;const Os=new Map([[s.IPF_GRAYSCALED,Wr.GREY],[s.IPF_ABGR_8888,Wr.RGBA],[s.IPF_ARGB_8888,Wr.BGRA]]),Rs=new Map([[Wr.GREY,s.IPF_GRAYSCALED],[Wr.RGBA,s.IPF_ABGR_8888],[Wr.BGRA,s.IPF_ARGB_8888]]),Ls="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Ds extends U{static set _onLog(t){Ge(Ds,os,t,"f",as),Hn._onLog=t,xs._onLog=t}static get _onLog(){return Ue(Ds,os,"f",as)}static async detectEnvironment(){return await(async()=>({wasm:Ve,worker:We,getUserMedia:Ye,camera:await He(),browser:je.browser,version:je.version,OS:je.OS}))()}static async testCameraAccess(){const t=await Hn.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Lr))throw new TypeError("Invalid view.");if(null===(e=ct.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ct.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await mt.loadWasm(["license"]),await ct.license.dynamsoft()}const r=new Ds(t);return Ds.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Ds.onWarning&&Ds.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Ds.onWarning&&Ds.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ge(this,cs,t,"f")}get singleFrameMode(){return Ue(this,cs,"f")}get _isFetchingStarted(){return Ue(this,ps,"f")}get disposed(){return Ue(this,Cs,"f")}constructor(t){if(super(),ss.add(this),hs.set(this,"closed"),ls.set(this,void 0),this.isTorchOn=void 0,cs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},us.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,e,i,s,{pixelFormat:Os.get(this.getPixelFormat())});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===Wr.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:Rs.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Ct.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:Ue(this,ds,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():wi.convert(Ue(this,gs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ue(this,us,"f").call(this,t,t.width,t.height,e);Ue(this,ls,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ds.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===s.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(je.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Ue(this,ws,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Ue(this,ws,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Ue(this,vs,"f").tapToFocus&&Ue(this,ws,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(Ue(this,ss,"m",Es).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;Ds._onLog&&(Ds._onLog("intermediateResultUnits:"),Ds._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Tt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Tt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Ds._onLog&&(Ds._onLog("hasLocalizedBarcodes:"),Ds._onLog(h)),Ue(this,vs,"f").autoZoom||Ue(this,vs,"f").enhancedFocus)if(a)Ue(this,ys,"f").autoZoomInFrameArray.length=0,Ue(this,ys,"f").autoZoomOutFrameCount=0,Ue(this,ys,"f").frameArrayInIdealZoom.length=0,Ue(this,ys,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ue(this,vs,"f").autoZoom&&Ue(this,ws,"f").startCharging()},a=async t=>{await this.setFocus(t),Ue(this,vs,"f").enhancedFocus&&Ue(this,ws,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-Ue(this,ys,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ue(this,ys,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-Ue(this,ys,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ue(this,ys,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}Ds._onLog&&(Ds._onLog("detectionArea:"),Ds._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=Si(a.y-i)>0&&Si(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(Ii([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Ii([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Ii([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Ii([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Lr._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(Ds._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Sr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new Ni({points:i},e);t.addDrawingItems([n])}}}if(Ds._onLog&&(Ds._onLog("intersectedResults:"),Ds._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==Ls.BF_QR_CODE||t.possibleFormats==Ls.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Ls.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Ue(this,ys,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Ue(this,ys,"f").autoZoomInFrameLimit[1]){Ue(this,ys,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Ue(this,ys,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ue(this,ys,"f").autoZoomInMaxTimes),Ue(this,ys,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ue(this,ys,"f").minValue,u),u=Math.min(Ue(this,ys,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ue(this,ys,"f").autoZoomInFrameArray.length=0,Ue(this,ys,"f").frameArrayInIdealZoom.push(!0),Ue(this,ys,"f").frameArrayInIdealZoom.splice(0,Ue(this,ys,"f").frameArrayInIdealZoom.length-Ue(this,ys,"f").frameLimitInIdealZoom[0]),Ue(this,ys,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Ue(this,ys,"f").frameLimitInIdealZoom[1]&&(Ue(this,ys,"f").frameArrayInIdealZoom.length=0,Ue(this,vs,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Ue(this,vs,"f").autoZoom&&Ue(this,vs,"f").enhancedFocus&&(Ue(this,ys,"f").autoFocusFrameArray.push(!0),Ue(this,ys,"f").autoFocusFrameArray.splice(0,Ue(this,ys,"f").autoFocusFrameArray.length-Ue(this,ys,"f").autoFocusFrameLimit[0]),Ue(this,ys,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Ue(this,ys,"f").autoFocusFrameLimit[1])){Ue(this,ys,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Ue(this,vs,"f").autoZoom){if(Ue(this,ys,"f").autoZoomInFrameArray.push(!1),Ue(this,ys,"f").autoZoomInFrameArray.splice(0,Ue(this,ys,"f").autoZoomInFrameArray.length-Ue(this,ys,"f").autoZoomInFrameLimit[0]),Ue(this,ys,"f").autoZoomOutFrameCount++,Ue(this,ys,"f").frameArrayInIdealZoom.push(!1),Ue(this,ys,"f").frameArrayInIdealZoom.splice(0,Ue(this,ys,"f").frameArrayInIdealZoom.length-Ue(this,ys,"f").frameLimitInIdealZoom[0]),Ue(this,ys,"f").autoZoomOutFrameCount>=Ue(this,ys,"f").autoZoomOutFrameLimit){Ue(this,ys,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*Ue(this,ys,"f").autoZoomOutStepRate,Ue(this,ys,"f").autoZoomOutMinStep);r=Math.max(Ue(this,ys,"f").minValue,r),r=Math.min(Ue(this,ys,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ue(this,vs,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Ue(this,vs,"f").autoZoom&&Ue(this,vs,"f").enhancedFocus&&(Ue(this,ys,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},Ge(this,ws,new xs(1e4),"f")}setCameraView(t){if(!(t instanceof Lr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Ue(this,ss,"m",Es).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Ue(this,ss,"m",Es).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Ue(this,ss,"m",Es).call(this)?Ue(this,hs,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Ue(this,ss,"m",Es).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Ue(this,ss,"m",Es).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,r=t.getUIElement();if(r=r.shadowRoot||r,i=r.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=r.elTorchAuto=r.querySelector(".dce-mn-torch-auto"),e=r.elTorchOn=r.querySelector(".dce-mn-torch-on"),n=r.elTorchOff=r.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),n&&(n.style.display=0==this.isTorchOn?"":"none");let s=r.elBeepOn=r.querySelector(".dce-mn-beep-on"),o=r.elBeepOff=r.querySelector(".dce-mn-beep-off");s&&(s.style.display=As.allowBeep?"":"none"),o&&(o.style.display=As.allowBeep?"none":"");let a=r.elVibrateOn=r.querySelector(".dce-mn-vibrate-on"),h=r.elVibrateOff=r.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=As.allowVibrate?"":"none"),h&&(h.style.display=As.allowVibrate?"none":""),r.elResolutionBox=r.querySelector(".dce-mn-resolution-box");let l,c=r.elZoom=r.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=r.elZoomSpan=c.querySelector("span"));let u=r.elToast=r.querySelector(".dce-mn-toast"),d=r.elCameraClose=r.querySelector(".dce-mn-camera-close"),f=r.elTakePhoto=r.querySelector(".dce-mn-take-photo"),g=r.elCameraSwitch=r.querySelector(".dce-mn-camera-switch"),m=r.elCameraAndResolutionSettings=r.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=r.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==n||n.addEventListener("pointerdown",y);const w=()=>{As.allowBeep=!As.allowBeep,s&&(s.style.display=As.allowBeep?"":"none"),o&&(o.style.display=As.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{As.allowVibrate=!As.allowVibrate,a&&(a.style.display=As.allowVibrate?"":"none"),h&&(h.style.display=As.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),r=parseInt(e.getAttribute("data-height")),n=await this.setResolution({width:i,height:r});{let e=Math.max(n.width,n.height),i=Math.min(n.width,n.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&S(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};r.addEventListener("click",E);let b=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout((()=>{c.style.display="none",b=null}),e))};let T=null,S=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const A=()=>{var t,e;let i,r=this.getVideoSettings(),n=r.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==n?void 0:n.ideal)||(null==n?void 0:n.exact)||n)),r.video.facingMode={ideal:i?"environment":"user"},delete r.video.deviceId,this.updateVideoSettings(r)};null==g||g.addEventListener("pointerdown",A);let O=-1/0,R=1;const L=t=>{let e=Date.now();e-O>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),O=e};i.addEventListener("wheel",L);const D=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],r=t.touches[1],n=D.get(i.identifier),s=D.get(r.identifier);if(!n||!s)break;let o=Math.pow(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-r.clientX,2)+Math.pow(i.clientY-r.clientY,2),.5),h=Date.now();if(M||h-O<100)return;h-O>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==je?void 0:je.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&S("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,O=Date.now();break}D.clear();for(let e of t.touches)D.set(e.identifier,{x:e.clientX,y:e.clientY})};r.addEventListener("touchstart",F),r.addEventListener("touchmove",F),r.addEventListener("touchend",F),r.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==n||n.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);r.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",A),i.removeEventListener("wheel",L),r.removeEventListener("touchstart",F),r.removeEventListener("touchmove",F),r.removeEventListener("touchend",F),r.removeEventListener("touchcancel",F),delete r.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const n=this.getResolution();e.width=n.width,e.height=n.height,e.deviceId=this.getSelectedCamera().deviceId}return Ge(this,hs,"open","f"),t&&(t._innerComponent.style.display="",Ue(this,ss,"m",Es).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Ue(this,ls,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Ue(this,ss,"m",Es).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Ge(this,hs,"closed","f"),Ue(this,ws,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ue(this,ss,"m",Es).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ue(this,ls,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ue(this,ss,"m",Es).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ue(this,ss,"m",Es).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ue(this,ss,"m",Es).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),r=this.cameraView;return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ue(this,ls,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ue(this,ls,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Ue(this,ss,"m",Es).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,n;if(e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(s.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){console.log(`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(t=null==e?void 0:e.dceMnFs)||void 0===t||t.funcShowToast("Torch Auto On")}catch(t){console.error(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(n=null==i?void 0:i.dceMnFs)||void 0===n||n.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(n,t),this.isTorchOn=void 0,n();let o=this.cameraView.getUIElement();o=o.shadowRoot||o,o.elTorchAuto&&(o.elTorchAuto.style.display=""),o.elTorchOn&&(o.elTorchOn.style.display="none"),o.elTorchOff&&(o.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ue(this,ss,"m",Es).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,r;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(r=null==e?void 0:e.dceMnFs)||void 0===r||r.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Ue(this,ss,"m",Es).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Ue(this,ss,"m",Es).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Ue(this,ys,"f").minValue=t.min,Ue(this,ys,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ue(this,ys,"f").minValue,max:Ue(this,ys,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ct.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==mt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&Qe.EF_ENHANCED_FOCUS&&(Ue(this,vs,"f").enhancedFocus=!0),t&Qe.EF_AUTO_ZOOM&&(Ue(this,vs,"f").autoZoom=!0),t&Qe.EF_TAP_TO_FOCUS&&(Ue(this,vs,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&Qe.EF_ENHANCED_FOCUS&&(Ue(this,vs,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&Qe.EF_AUTO_ZOOM&&(Ue(this,vs,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&Qe.EF_TAP_TO_FOCUS&&(Ue(this,vs,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ue(this,ss,"m",Ts).call(this)&&Ue(this,ss,"m",bs).call(this)||Ue(this,ws,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!fi(t)&&!vi(t))throw TypeError("Invalid 'region'.");Ge(this,gs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Ue(this,gs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ge(this,fs,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ue(this,ss,"m",Es).call(this))}startFetching(){if(Ue(this,ss,"m",Es).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ue(this,ps,"f")||(Ge(this,ps,!0,"f"),Ue(this,ss,"m",Ss).call(this))}stopFetching(){Ue(this,ps,"f")&&(Ds._onLog&&Ds._onLog("DCE: stop fetching loop: "+Date.now()),Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),Ge(this,ps,!1,"f"))}fetchImage(){if(Ue(this,ss,"m",Es).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=wi.convert(Ue(this,gs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=this.cameraManager.getFrameData({position:i,pixelFormat:Os.get(this.getPixelFormat())});if(!n)return null;let s;s=n.pixelFormat===Wr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:Rs.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Ct.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:Ue(this,ds,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ue(this,ps,"f")&&(Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),Ge(this,_s,setTimeout((()=>{this.disposed||Ue(this,ss,"m",Ss).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ge(this,ms,t,"f")}getPixelFormat(){return Ue(this,ms,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ue(this,ss,"m",Es).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=wi.convert(Ue(this,gs,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=Ue(this,us,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ue(this,ss,"m",Is).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ue(this,ss,"m",Is).call(this,t);return{x:e.clientX,y:e.clientY}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}function Ms(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Fs(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}os=Ds,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,ss=new WeakSet,Es=function(){return"disabled"!==this.singleFrameMode},bs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Ts=function(){for(let t in Ue(this,vs,"f"))if(1==Ue(this,vs,"f")[t])return!0;return!1},Ss=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ue(this,ps,"f"))return Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),void Ge(this,_s,setTimeout((()=>{this.disposed||Ue(this,ss,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;Ds._onLog&&Ds._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Ue(this,fs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Ue(this,fs,"f"))||void 0===t||t.onErrorReceived(vt.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Ds._onLog&&Ds._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ue(this,ls,"f").fire("frameAddedToBuffer",null,{async:!1})):Ds._onLog&&Ds._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:e()}else e();Ue(this,_s,"f")&&clearTimeout(Ue(this,_s,"f")),Ge(this,_s,setTimeout((()=>{this.disposed||Ue(this,ss,"m",t).call(this)}),this.fetchInterval),"f")},Is=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ue(this,ss,"m",Es).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ue(this,ss,"m",Es).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ue(this,ss,"m",Es).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)ut+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Ps.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return Ps.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return Ps.multiply(t,[e,0,0,0,i,0,0,0,1])}}var ks,Bs,Ns,js,Us,Gs,Vs,Ws,Ys,Hs,Xs,zs,Zs,qs,Ks,Js,Qs,$s;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ks||(ks={}));class to{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Fs(to,Bs,!1,"f",Ns),!1):(Fs(to,Bs,!0,"f",Ns),!0)}get disposed(){return Ms(this,Ys,"f")}constructor(){js.set(this,ks.RGBA),Us.set(this,null),Gs.set(this,null),Vs.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Ws.set(this,null),Ys.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Ms(to,Bs,"f",Ns)&&to.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Ms(to,Bs,"f",Ns))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;to._onLog&&(o=Date.now(),to._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=ks.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Ms(to,Bs,"f",Ns)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){to._onLog&&to._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Fs(this,Gs,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Fs(this,Vs,e(t),"f"),Fs(this,Us,i(t),"f"),Fs(this,js,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[ks.GREY,ks.GREY32].includes(p)?1:0);let m,_,v=Ps.translate(Ps.identity(),-1,-1);v=Ps.scale(v,2,2),v=Ps.scale(v,1/t.canvas.width,1/t.canvas.height),m=Ps.translate(v,u,d),m=Ps.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Ps.translate(Ps.identity(),a/i,h/r),_=Ps.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Ms(this,Us,"f"),e),v(t,Ms(this,Gs,"f"),Ms(this,Vs,"f"),Ms(this,Us,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){to._onLog&&to._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return to._onLog&&to._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===ks.GREY?ks.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return to._onLog&&to._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(to._onLog&&(n=Date.now(),to._onLog("transformPixelFormat(), START: "+n)),e===i)return to._onLog&&to._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[ks.RGBA,ks.RBGA,ks.GRBA,ks.GBRA,ks.BRGA,ks.BGRA];if(o.includes(e))if(i===ks.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;to._onLog&&(s=Date.now(),to._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=ks.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Ms(to,Bs,"f",Ns)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){to._onLog&&to._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===ks.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{var e;if(!this.isUseMagnifier)return;if(Ue(this,qs,"f")||Ge(this,qs,new eo,"f"),!Ue(this,qs,"f").magnifierCanvas)return;document.body.contains(Ue(this,qs,"f").magnifierCanvas)||(Ue(this,qs,"f").magnifierCanvas.style.position="fixed",Ue(this,qs,"f").magnifierCanvas.style.boxSizing="content-box",Ue(this,qs,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ue(this,qs,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Ue(this,Js,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];Ue(this,qs,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Ue(this,qs,"f").magnifierCanvas.style.left="auto",Ue(this,qs,"f").magnifierCanvas.style.top="0",Ue(this,qs,"f").magnifierCanvas.style.right="0"):(Ue(this,qs,"f").magnifierCanvas.style.left="0",Ue(this,qs,"f").magnifierCanvas.style.top="0",Ue(this,qs,"f").magnifierCanvas.style.right="auto")}Ue(this,qs,"f").show()})),Js.set(this,(()=>{Ue(this,qs,"f")&&Ue(this,qs,"f").hide()})),Qs.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await xi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=new Rr,e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(di(t)){Ge(this,Zs,t,"f");const{width:e,height:i,bytes:r,format:n}=Object.assign({},t);let o;if(n===s.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ti.Control({positionHandler:Fi,actionHandler:Bi(i>0?i-1:r,ki),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=ti.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Ue(this,Gi,"f")&&this.setLine(Ue(this,Gi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!gi(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ge(this,Gi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Ue(this,Gi,"f")?JSON.parse(JSON.stringify(Ue(this,Gi,"f"))):null}},QuadDrawingItem:br,RectDrawingItem:Mi,TextDrawingItem:Ui});const no="undefined"==typeof self,so=(()=>{if(!no&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),oo=t=>{if(null==t&&(t="./"),no);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};ut.dbr={version:"10.4.20",path:so},dt.dbr={js:!1,wasm:!0,deps:["license","dip"]},ct.dbr={};const ao="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,ao)<0&&(ut.std={version:ao,path:oo(so+`../../dynamsoft-capture-vision-std@${ao}/dist/`)});const ho="2.4.20";(!ut.dip||"string"!=typeof ut.dip&&S(ut.dip.version,ho)<0)&&(ut.dip={version:ho,path:oo(so+`../../dynamsoft-image-processing@${ho}/dist/`)});const lo={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var co,uo,fo,go;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(co||(co={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(uo||(uo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP"}(fo||(fo={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(go||(go={}));var mo=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=lt.dbr&<.dbr.wasm;return`10.4.20(Worker: ${lt.dbr&<.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:lo,get EnumDeblurMode(){return go},get EnumExtendedBarcodeResultType(){return co},get EnumLocalizationMode(){return fo},get EnumQRCodeErrorCorrectionLevel(){return uo}});const po=async t=>{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const _o="undefined"==typeof self,vo=(()=>{if(!_o&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),yo=t=>{if(null==t&&(t="./"),_o);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};ut.utility={version:"1.4.21",path:vo},dt.utility={js:!0,wasm:!0};const wo="1.4.10";"string"!=typeof ut.std&&S(ut.std.version,wo)<0&&(ut.std={version:wo,path:yo(vo+`../../dynamsoft-capture-vision-std@${wo}/dist/`)});const Co="2.4.20";(!ut.dip||"string"!=typeof ut.dip&&S(ut.dip.version,Co)<0)&&(ut.dip={version:Co,path:yo(vo+`../../dynamsoft-image-processing@${Co}/dist/`)});function Eo(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}var bo,To,So,Io,xo;function Ao(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=n+u*(o-n),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function Lo(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*n,y:t.y+l*s}:null}function Fo(t){let e=0;for(let i=0;i0}function ko(t,e){for(let i=0;i<4;i++)if(!Po(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function Bo(t,e,i,r){const n=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=Lo(n)[3],h=Lo(n)[1],l=Lo(s)[3],c=Lo(s)[1];let u,d=0;if(u=Math.max(Math.abs(Ro(a,e.points[0])),Math.abs(Ro(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Ro(h,e.points[1])),Math.abs(Ro(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Ro(l,t.points[0])),Math.abs(Ro(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Ro(c,t.points[1])),Math.abs(Ro(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=Do(Lo(n)[0]),g=Do(Lo(n)[2]),m=Do(Lo(s)[0]),p=Do(Lo(s)[2]),_=Oo(f,p),v=Oo(m,g),y=_>v,w=Math.min(_,v),C=Oo(f,g),E=Oo(m,p);let b=12*i;return b=Math.max(b,5),b=Math.min(b,C),b=Math.min(b,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,r=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-r.area)>.4*i.area)return!1;let n=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)n[t]=Math.round(100*(r.points[t].x-i.points[t].x))/100,o+=n[t],s[t]=Math.round(100*(r.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(n[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(ko(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(ko(this.location,e))return!0}else{for(let e=0;e<4;e++)if(ko(t,this.location.points[e]))return!0;if(ko(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const r=[this.location.points[0],this.location.points[3]],n=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?r:n;if(Math.abs(Ro(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const r=t.location.points[i],n=this.location.points[i];if(!(Math.abs(n.x+e.x-r.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const r=Object.assign({},t.location);for(let t=0;t<4;t++)r.points[t].x-=e.x,r.points[t].y-=e.y;if(!this.isLocationOverlap(r,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let r=0;r<4;r++)for(let n=0;n<4;n++){const s=Mo(t[r],t[(r+1)%4],e[n],e[(n+1)%4]);s&&i.push(s)}return t.forEach((t=>{Ao(e,t)&&i.push(t)})),e.forEach((e=>{Ao(t,e)&&i.push(e)})),Fo(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],r.points)>this.locationArea*t}return!0}}const jo={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},Uo={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Go=t=>Object.values(Uo).includes(t)||Uo.hasOwnProperty(t),Vo=(t,e)=>"string"==typeof t?e[Uo[t]]:e[t],Wo=(t,e,i)=>{"string"==typeof t?e[Uo[t]]=i:e[t]=i},Yo=(t,e,i)=>{if(t.isResultCrossVerificationEnabled(i))for(let t=0;t{let h=rt();nt[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},et.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}},MultiFrameResultCrossFilter:class{constructor(){this.verificationEnabled={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!0,[pt.CRIT_DETECTED_QUAD]:!0,[pt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateFilterEnabled={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateForgetTime={[pt.CRIT_BARCODE]:3e3,[pt.CRIT_TEXT_LINE]:3e3,[pt.CRIT_DETECTED_QUAD]:3e3,[pt.CRIT_NORMALIZED_IMAGE]:3e3},this.latestOverlappingEnabled={[pt.CRIT_BARCODE]:!1,[pt.CRIT_TEXT_LINE]:!1,[pt.CRIT_DETECTED_QUAD]:!1,[pt.CRIT_NORMALIZED_IMAGE]:!1},this.maxOverlappingFrames={[pt.CRIT_BARCODE]:5,[pt.CRIT_TEXT_LINE]:5,[pt.CRIT_DETECTED_QUAD]:5,[pt.CRIT_NORMALIZED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,bo.set(this,new Map),To.set(this,new Map),So.set(this,new Map),Io.set(this,new Map),xo.set(this,new Map)}_dynamsoft(){Eo(this,bo,"f").forEach(((t,e)=>{Wo(e,this.verificationEnabled,t)})),Eo(this,To,"f").forEach(((t,e)=>{Wo(e,this.duplicateFilterEnabled,t)})),Eo(this,So,"f").forEach(((t,e)=>{Wo(e,this.duplicateForgetTime,t)})),Eo(this,Io,"f").forEach(((t,e)=>{Wo(e,this.latestOverlappingEnabled,t)})),Eo(this,xo,"f").forEach(((t,e)=>{Wo(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){Go(t)&&Eo(this,bo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Go(t)&&Vo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Go(t)&&(e&&this.enableLatestOverlapping(t,!1),Eo(this,To,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Go(t)&&Vo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Go(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Eo(this,So,"f").set(t,e))}getDuplicateForgetTime(t){return Go(t)?Vo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Go(t)&&Eo(this,xo,"f").set(t,e)}getMaxOverlappingFrames(t){return Go(t)?Vo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Go(t)&&(e&&this.enableResultDeduplication(t,!1),Eo(this,Io,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Go(t)&&Vo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[pt.CRIT_BARCODE,pt.CRIT_TEXT_LINE,pt.CRIT_DETECTED_QUAD,pt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{const e=(BigInt(t.format)&BigInt(jo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(jo.BF_GS1_DATABAR))!=BigInt(0);return new No(h,e?1:2,e,t)}));if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;n>p&&(p=n,m=r,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{const i=Object.assign({},t),r=(BigInt(t.format)&BigInt(jo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(jo.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){Yo(this,t.items,pt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){Yo(this,t.items,pt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){Yo(this,t.items,pt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){Yo(this,t.items,pt.CRIT_NORMALIZED_IMAGE)}},UtilityModule:class{static getVersion(){return`1.4.21(Worker: ${lt.utility&<.utility.worker||"Not Loaded"}, Wasm: ${lt.utility&<.utility.wasm||"Not Loaded"})`}}});t.CVR=De,t.Core=xt,t.DBR=mo,t.DCE=ro,t.License=qt,t.Utility=Ho})); diff --git a/dist/dbr.bundle.mjs b/dist/dbr.bundle.mjs index 29b804a..033fc0f 100644 --- a/dist/dbr.bundle.mjs +++ b/dist/dbr.bundle.mjs @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft -* @version 10.4.2001 +* @version 10.4.2002 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ -function t(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function e(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}var i,r,n;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(i||(i={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(r||(r={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(n||(n={}));const s="undefined"==typeof self,o=(()=>{if(!s&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),a=t=>{if(null==t&&(t="./"),s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},h=t=>Object.prototype.toString.call(t),l=t=>Array.isArray?Array.isArray(t):"[object Array]"===h(t),c=t=>"[object Boolean]"===h(t),u=t=>"number"==typeof t&&!Number.isNaN(t),d=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),f=t=>!(!d(t)||!u(t.x)||!u(t.y)||!u(t.radius)||t.radius<0||!u(t.startAngle)||!u(t.endAngle)),g=t=>!!d(t)&&!!l(t.points)&&0!=t.points.length&&!t.points.some((t=>!y(t))),m=t=>!(!d(t)||!(t.bytes instanceof Uint8Array)||!u(t.width)||t.width<=0||!u(t.height)||t.height<=0||!u(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!_(t.tag)),p=t=>!(!d(t)||!u(t.left)||t.left<0||!u(t.top)||t.top<0||!u(t.right)||t.right<0||!u(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!c(t.isMeasuredInPercentage)),_=t=>!!d(t)&&!!u(t.imageId)&&"type"in t,v=t=>!(!d(t)||!y(t.startPoint)||!y(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),y=t=>!!d(t)&&!!u(t.x)&&!!u(t.y),w=t=>!!d(t)&&!!l(t.points)&&0!=t.points.length&&!t.points.some((t=>!y(t))),C=t=>!!d(t)&&!!l(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!y(t))),E=t=>!(!d(t)||!u(t.x)||!u(t.y)||!u(t.width)||t.width<0||!u(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!c(t.isMeasuredInPercentage));async function b(t,e){return await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(t+" "+n.status):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}}))}function T(t){return/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t)}const S=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t{const i={};for(let r in e){const n=r;let s=t[n];s&&"string"!=typeof s&&s.path&&(s=s.path),t.rootDirectory&&!t.rootDirectory.endsWith("/")&&(t.rootDirectory=t.rootDirectory+"/"),void 0===s?t.rootDirectory?s=`${t.rootDirectory}${x[n]}@${e[n].version}/dist/`:(s=e[n].path,s||(s=e[n])):s.startsWith("@engineRootDirectory/")&&(s=s.replace("@engineRootDirectory/",t.rootDirectory)),i[n]=a(s)}return i},x={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer"},A=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await L(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),O=t=>{m(t)&&(t=D(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},R=(t,e)=>{m(e)&&(e=D(e));const i=O(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r},L=async(t,e)=>{m(e)&&(e=D(e));const i=O(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},D=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===n.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===n.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r=t(this,P,"f"))switch(t(this,k,"f")){case i.BOPM_BLOCK:break;case i.BOPM_UPDATE:if(t(this,F,"f").push(e),d(t(this,N,"f"))&&u(t(this,N,"f").imageId)&&1==t(this,N,"f").keepInBuffer)for(;t(this,F,"f").length>t(this,P,"f");){const e=t(this,F,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)!==t(this,N,"f").imageId}));t(this,F,"f").splice(e,1)}else t(this,F,"f").splice(0,t(this,F,"f").length-t(this,P,"f"))}else t(this,F,"f").push(e)}getImage(){if(0===t(this,F,"f").length)return null;let e;if(t(this,N,"f")&&u(t(this,N,"f").imageId)){const i=t(this,M,"m",U).call(this,t(this,N,"f").imageId);if(i<0)throw new Error(`Image with id ${t(this,N,"f").imageId} doesn't exist.`);e=t(this,F,"f").slice(i,i+1)[0]}else e=t(this,F,"f").pop();if([n.IPF_RGB_565,n.IPF_RGB_555,n.IPF_RGB_888,n.IPF_ARGB_8888,n.IPF_RGB_161616,n.IPF_ARGB_16161616,n.IPF_ABGR_8888,n.IPF_ABGR_16161616,n.IPF_BGR_888].includes(e.format)){if(t(this,j,"f")===r.CCUT_RGB_R_CHANNEL_ONLY){s._onLog&&s._onLog("only get R channel data.");const t=new Uint8Array(e.width*e.height);for(let i=0;i0!==t.length&&t.every((t=>u(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==i&&!c(i))throw new TypeError("Invalid 'keepInBuffer'.");e(this,N,{imageId:t,keepInBuffer:i},"f")}_resetNextReturnedImage(){e(this,N,null,"f")}hasImage(e){return t(this,M,"m",U).call(this,e)>=0}startFetching(){e(this,B,!0,"f")}stopFetching(){e(this,B,!1,"f")}setMaxImageCount(i){if("number"!=typeof i)throw new TypeError("Invalid 'count'.");if(i<1||Math.round(i)!==i)throw new Error("Invalid 'count'.");for(e(this,P,i,"f");t(this,F,"f")&&t(this,F,"f").length>i;)t(this,F,"f").shift()}getMaxImageCount(){return t(this,P,"f")}getImageCount(){return t(this,F,"f").length}clearBuffer(){t(this,F,"f").length=0}isBufferEmpty(){return 0===t(this,F,"f").length}setBufferOverflowProtectionMode(t){e(this,k,t,"f")}getBufferOverflowProtectionMode(){return t(this,k,"f")}setColourChannelUsageType(t){e(this,j,t,"f")}getColourChannelUsageType(){return t(this,j,"f")}};F=new WeakMap,P=new WeakMap,k=new WeakMap,B=new WeakMap,N=new WeakMap,j=new WeakMap,M=new WeakSet,U=function(e){if("number"!=typeof e)throw new TypeError("Invalid 'imageId'.");return t(this,F,"f").findIndex((t=>{var i;return(null===(i=t.tag)||void 0===i?void 0:i.imageId)===e}))};const V=t=>t&&"object"==typeof t&&"function"==typeof t.then;let W,Y,H,X,z,Z=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,V(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(V(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};"undefined"!=typeof navigator&&(W=navigator,Y=W.userAgent,H=W.platform,X=W.mediaDevices),function(){if(!s){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:W.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:H,search:"Win"},Mac:{str:H},Linux:{str:H}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Y,o=n.search||e,a=n.verStr||Y,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Y,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Y.indexOf("Windows NT")&&(n="HarmonyOS"),z={browser:i,version:r,OS:n}}s&&(z={browser:"ssr",version:0,OS:"ssr"})}();const K="undefined"!=typeof WebAssembly&&Y&&!(/Safari/.test(Y)&&!/Chrome/.test(Y)&&/\(.+\s11_2_([2-6]).*\)/.test(Y)),q=!("undefined"==typeof Worker),J=!(!X||!X.getUserMedia),Q=async()=>{let t=!1;if(J)try{(await X.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===z.browser&&z.version>66||"Safari"===z.browser&&z.version>13||"OPR"===z.browser&&z.version>43||"Edge"===z.browser&&z.version;const $={},tt=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push($[t]=$[t]||new Z);await Promise.all(i)},et=async(t,e)=>{let i,r="string"==typeof t?[t]:t,n=[];for(let t of r){let r;n.push(r=$[t]=$[t]||new Z(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(n)};let it,rt=0;const nt=()=>rt++,st={};let ot;const at=t=>{ot=t,it&&it.postMessage({type:"setBLog",body:{value:!!t}})};let ht=!1;const lt=t=>{ht=t,it&&it.postMessage({type:"setBDebug",body:{value:!!t}})},ct={},ut={},dt={std:{version:"1.4.10",path:a(o+"../../dynamsoft-capture-vision-std@1.4.10/dist/")},core:{version:"3.4.20",path:o}},ft={dip:{wasm:!0}},gt={},mt=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=$.core;e=!i||i.isEmpty;let r=new Map;const n=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!ft[t])throw Error("The '"+t+"' module cannot be found.");let e=ft[t].deps;if(null==e?void 0:e.length)for(let t of e)n(t);let i=$[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)n(e);let s=[];e&&s.push("core"),s.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await et(s,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await tt(o);const i=I(gt,dt),n={};for(let e of t)n[e]=ft[e];const s={engineResourcePaths:i,autoResources:n,names:t};let a=new Z;if(e){s.needLoadCore=!0;let t=i.core+pt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),it=new Worker(t),it.onerror=t=>{let e=new Error(t.message);a.reject(e)},it.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":ot&&ot(e.message);break;case"task":try{st[r](n),delete st[r]}catch(t){throw delete st[r],t}break;case"event":try{st[r](n)}catch(t){throw t}break;default:console.log(t)}})),s.bLog=!!ot,s.bd=ht,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await tt("core");let h=rt++;st[h]=t=>{if(t.success)Object.assign(ct,t.versions),"{}"!==JSON.stringify(t.versions)&&(pt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},it.postMessage({type:"loadWasm",body:s,id:h}),await a}))};class pt{static get engineResourcePaths(){return gt}static set engineResourcePaths(t){Object.assign(gt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return ot}static set _onLog(t){at(t)}static get _bDebug(){return ht}static set _bDebug(t){lt(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!$[t]&&$[t].isFulfilled}static async loadWasm(t){return await mt(t)}static async detectEnvironment(){return await(async()=>({wasm:K,worker:q,getUserMedia:J,camera:await Q(),browser:z.browser,version:z.version,OS:z.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.20(Worker: ${ct.core&&ct.core.worker||"Not Loaded"}, Wasm: ${ct.core&&ct.core.wasm||"Not Loaded"})`}static enableLogging(){G._onLog=console.log,pt._onLog=console.log}static disableLogging(){G._onLog=null,pt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var _t,vt,yt,wt,Ct,Et,bt,Tt;pt._bSupportDce4Module=-1,pt._bSupportIRTModule=-1,pt._versions=null,pt._workerName="core.worker.js",pt.browserInfo=z,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(_t||(_t={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(vt||(vt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(yt||(yt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(wt||(wt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(Ct||(Ct={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(Et||(Et={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(bt||(bt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(Tt||(Tt={}));const St={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var It,xt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(It||(It={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(xt||(xt={}));let At="./";if(document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}At=t.substring(0,t.lastIndexOf("/")+1)}pt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(At+"../../")};const Ot="undefined"==typeof self,Rt=Ot?{}:self,Lt=(()=>{if(!Ot&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),Dt=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Mt=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Dt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Dt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ft=" is not allowed to change after `createInstance` or `loadWasm` is called.",Pt=!Ot&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",kt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ft);i._license=e}};!Ot&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Bt=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Bt(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ft);i._licenseServer=e}},jt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ft);i._deviceFriendlyName=e}};let Ut,Gt,Vt,Wt,Yt;"undefined"!=typeof navigator&&(Ut=navigator,Gt=Ut.userAgent,Vt=Ut.platform,Wt=Ut.mediaDevices),function(){if(!Ot){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ut.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Vt,search:"Win"},Mac:{str:Vt},Linux:{str:Vt}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Gt,o=n.search||e,a=n.verStr||Gt,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Gt,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Gt.indexOf("Windows NT")&&(n="HarmonyOS"),Yt={browser:i,version:r,OS:n}}Ot&&(Yt={browser:"ssr",version:0,OS:"ssr"})}(),Wt&&Wt.getUserMedia,"Chrome"===Yt.browser&&Yt.version>66||"Safari"===Yt.browser&&Yt.version>13||"OPR"===Yt.browser&&Yt.version>43||"Edge"===Yt.browser&&Yt.version;const Ht=()=>(mt("license"),et("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=zt;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Bt(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Rt.crypto||(s="Please upgrade your browser to support online key."),Rt.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==l)throw new Error(s);l=0,console.warn(s),i._lastErrorCode=-1,i._lastErrorString=s}return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Ft)})(),o=new Mt;zt._pLoad.task=o,(async()=>{try{await zt._pLoad}catch(t){}})();let a=nt();st[a]=e=>{if(e.message&&zt._onAuthMessage){let t=zt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(ot&&ot("init license success"),e.message&&console.warn(e.message),pt._bSupportIRTModule=e.bSupportIRTModule,pt._bSupportDce4Module=e.bSupportDce4Module,zt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){const t=I(pt.engineResourcePaths,dt);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:zt._bNeverShowDialog,engineResourcePath:t.license,_onLog:ot},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await tt("core"),it.postMessage({type:"license_dynamsoft",body:{v:"3.4.21",brtk:!!t,bptk:1===t,l:e,os:Yt,fn:zt.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),zt.bCallInitLicense=!0,await o})));let Xt;ut.license={},ut.license.dynamsoft=Ht,ut.license.getAR=async()=>{{let t=$.dynamsoft_inited;t&&t.isRejected&&await t}return it?new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success){delete i.success;{let t=zt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},it.postMessage({type:"license_getAR",id:i})})):null};let zt=class t{static setLicenseServer(e){Nt(t,e)}static get license(){return this._license}static set license(e){kt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Nt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){jt(t,e)}static initLicense(e,i){if(kt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Ht()}static setDeviceFriendlyName(e){jt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await et("dynamsoft_uuid",(async()=>{await mt();let t=new Mt,e=nt();st[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},it.postMessage({type:"license_getDeviceUUID",id:e}),Xt=await t})),Xt))()}};zt._pLoad=new Mt,zt.bPassValidation=!1,zt.bCallInitLicense=!1,zt._license=Pt,zt._licenseServer=[],zt._deviceFriendlyName="",dt.license={version:"3.4.21",path:Lt},ft.license={wasm:!0,js:!0},ut.license.LicenseManager=zt;const Zt="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,Zt)<0&&(dt.std={version:Zt,path:(t=>{if(null==t&&(t="./"),Ot);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Lt+`../../dynamsoft-capture-vision-std@${Zt}/dist/`)});let Kt=class{static getVersion(){return`3.4.21(Worker: ${ct.license&&ct.license.worker||"Not Loaded"}, Wasm: ${ct.license&&ct.license.wasm||"Not Loaded"})`}};function qt(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Jt(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Qt=t=>t&&"object"==typeof t&&"function"==typeof t.then;class $t extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Qt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Qt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class te{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ee={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1};const ie=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class re{constructor(t){this._irrRegistryState=ee,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ie(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=nt();st[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},it.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ie(this),await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const ne="undefined"==typeof self,se=(()=>{if(!ne&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),oe=t=>{if(null==t&&(t="./"),ne);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ae;dt.cvr={version:"2.4.21",path:se},ft.cvr={js:!0,wasm:!0,deps:["license","dip"]},ut.cvr={};const he="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,he)<0&&(dt.std={version:he,path:oe(se+`../../dynamsoft-capture-vision-std@${he}/dist/`)});const le="2.4.20";(!dt.dip||"string"!=typeof dt.dip&&S(dt.dip.version,le)<0)&&(dt.dip={version:le,path:oe(se+`../../dynamsoft-image-processing@${le}/dist/`)});class ce{static getVersion(){return this._version}}var ue,de,fe,ge,me,pe,_e,ve,ye,we,Ce,Ee,be;function Te(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Te(t.referencedItem,e)}}function Se(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}ce._version=`2.4.21(Worker: ${null===(ae=ct.cvr)||void 0===ae?void 0:ae.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ue||(ue={})),BigInt(0),BigInt(1),BigInt(2),BigInt(4),BigInt(8),BigInt(16),BigInt(32),BigInt(64),BigInt(128),BigInt(256),BigInt(512),BigInt(1024),BigInt(2048),BigInt(4096),BigInt(8192),BigInt(16384),BigInt(32768),BigInt(65536),BigInt(1<<17),BigInt(1<<18),BigInt(1<<19),BigInt(1<<20),BigInt(1<<21),BigInt(1<<22),BigInt(1<<23),BigInt(1<<24),BigInt(1<<25),BigInt(1<<26),BigInt(1<<27),BigInt(1<<28),BigInt("0xFFFFFFFFFFFFFFFF");const Ie={onTaskResultsReceived:()=>{},isFilter:!0};class xe{constructor(){this.maxCvsSideLength=["iPhone","Android","HarmonyOS"].includes(pt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,de.set(this,null),fe.set(this,null),ge.set(this,null),me.set(this,null),pe.set(this,null),_e.set(this,new Set),ve.set(this,new Set),ye.set(this,new Set),we.set(this,0),Ce.set(this,!1),Ee.set(this,!1),be.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return qt(this,be,"f")}static async createInstance(){if(!ut.license)throw Error("Module `license` is not existed.");await ut.license.dynamsoft(),await mt(["cvr"]);const t=new xe,e=new $t;let i=nt();return st[i]=async i=>{var r;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(i.outputSettings),ce._version=`2.4.21(Worker: ${null===(r=ct.cvr)||void 0===r?void 0:r.worker}, Wasm: ${i.version})`,Jt(t,Ee,!0,"f"),Jt(t,me,t.getIntermediateResultManager(),"f"),Jt(t,Ee,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},it.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of qt(this,_e,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of qt(this,_e,"f"))t.isDce&&t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of qt(this,_e,"f"))if(e.onDecodedBarcodesReceived&&i.barcodeResultItems&&e.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems})),e.onRecognizedTextLinesReceived&&i.textLineResultItems&&e.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems})),e.onDetectedQuadsReceived&&i.detectedQuadResultItems&&e.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems})),e.onNormalizedImagesReceived&&i.normalizedImageResultItems&&e.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems})),e.onParsedResultsReceived&&i.parsedResultItems&&e.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems})),e.onCapturedResultReceived&&!e.isDce){if(this._isOutputOriginalImage){const e=i.items.findIndex((t=>1===t.type));-1!==e&&(i.items[e].imageData=t)}e.onCapturedResultReceived(i)}}setInput(t){if(Se(this),t){if(Jt(this,de,t,"f"),t.isCameraEnhancer){qt(this,me,"f")&&(qt(this,de,"f")._intermediateResultReceiver.isDce=!0,qt(this,me,"f").addResultReceiver(qt(this,de,"f")._intermediateResultReceiver));const t=qt(this,de,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,qt(this,_e,"f").add(e)}}}else Jt(this,de,null,"f")}getInput(){return qt(this,de,"f")}addImageSourceStateListener(t){if(Se(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&qt(this,ve,"f").add(t)}removeImageSourceStateListener(t){return Se(this),qt(this,ve,"f").delete(t)}addResultReceiver(t){if(Se(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(qt(this,_e,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Se(this),qt(this,_e,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of qt(this,_e,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new $t;let i=nt();return st[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},it.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Se(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");qt(this,ye,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Se(this),qt(this,ye,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(qt(this,me,"f").removeResultReceiver(Ie),0===qt(this,ye,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[_t.CRIT_BARCODE]:!1,[_t.CRIT_TEXT_LINE]:!1,[_t.CRIT_DETECTED_QUAD]:!1,[_t.CRIT_NORMALIZED_IMAGE]:!1},e={[_t.CRIT_BARCODE]:!1,[_t.CRIT_TEXT_LINE]:!1,[_t.CRIT_DETECTED_QUAD]:!1,[_t.CRIT_NORMALIZED_IMAGE]:!1};return await Ae(this,t),void await Oe(this,e)}for(let t of qt(this,ye,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(_t.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(_t.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(_t.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(_t.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(_t.CRIT_BARCODE)){[...qt(this,me,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||qt(this,me,"f").addResultReceiver(Ie)}await Ae(this,t.verificationEnabled),await Oe(this,t.duplicateFilterEnabled),await Re(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Se(this),!this._isPauseScan)return;if(!qt(this,de,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const s=await this.containsTask(t);await mt(s);for(let t of qt(this,ye,"f"))await this.addResultFilter(t);if(s.includes("dlr")&&!(null===(e=ut.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=I(pt.engineResourcePaths,dt);await(null===(i=ut.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(qt(this,de,"f").isCameraEnhancer&&(s.includes("ddn")?qt(this,de,"f").setPixelFormat(n.IPF_ABGR_8888):qt(this,de,"f").setPixelFormat(n.IPF_GRAYSCALED)),void 0!==qt(this,de,"f").singleFrameMode&&"disabled"!==qt(this,de,"f").singleFrameMode)return this._templateName=t,void qt(this,de,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return qt(this,de,"f").getColourChannelUsageType()===r.CCUT_AUTO&&qt(this,de,"f").setColourChannelUsageType(s.includes("ddn")?r.CCUT_FULL_CHANNEL:r.CCUT_Y_CHANNEL_ONLY),qt(this,ge,"f")&&qt(this,ge,"f").isPending?qt(this,ge,"f"):(Jt(this,ge,new $t(((e,i)=>{if(this.disposed)return;let r=nt();st[r]=async r=>{if(qt(this,ge,"f")&&!qt(this,ge,"f").isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=r.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&qt(this,de,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},it.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await qt(this,ge,"f"))}stopCapturing(){Se(this),qt(this,de,"f")&&(qt(this,de,"f").isCameraEnhancer&&void 0!==qt(this,de,"f").singleFrameMode&&"disabled"!==qt(this,de,"f").singleFrameMode?qt(this,de,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=nt();const i=new $t;st[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},it.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),qt(this,de,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Jt(this,ge,null,"f"),qt(this,de,"f").setColourChannelUsageType(r.CCUT_AUTO)))}async containsTask(t){return Se(this),await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Jt(this,Ce,!0,"f"),qt(this,de,"f").isBufferEmpty())if(qt(this,de,"f").hasNextImageToFetch())for(let t of qt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_BUFFER_EMPTY);else if(!qt(this,de,"f").hasNextImageToFetch())for(let t of qt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||qt(this,de,"f").isBufferEmpty())try{qt(this,de,"f").isBufferEmpty()&&xe._onLog&&xe._onLog("buffer is empty so fetch image"),xe._onLog&&xe._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=qt(this,de,"f").fetchImage(),xe._onLog&&xe._onLog(`DCE: finish fetching a frame: ${Date.now()}`),qt(this,de,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(qt(this,de,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=qt(this,de,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of qt(this,_e,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(xe._onLog&&xe._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of qt(this,_e,"f")){if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),xe._onLog){const t=Date.now()-e;t>10&&xe._onLog(`draw result time: ${t}`)}}t.onDecodedBarcodesReceived&&i.barcodeResultItems&&t.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems.filter((t=>!t.isFilter))})),t.onRecognizedTextLinesReceived&&i.textLineResultItems&&t.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems.filter((t=>!t.isFilter))})),t.onDetectedQuadsReceived&&i.detectedQuadResultItems&&t.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems.filter((t=>!t.isFilter))})),t.onNormalizedImagesReceived&&i.normalizedImageResultItems&&t.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems.filter((t=>!t.isFilter))})),t.onParsedResultsReceived&&i.parsedResultItems&&t.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems.filter((t=>!t.isFilter))})),t.onCapturedResultReceived&&!t.isDce&&(i.items=i.items.filter((t=>!t.isFilter)),i.barcodeResultItems&&(i.barcodeResultItems=i.barcodeResultItems.filter((t=>!t.isFilter))),i.textLineResultItems&&(i.textLineResultItems=i.textLineResultItems.filter((t=>!t.isFilter))),i.detectedQuadResultItems&&(i.detectedQuadResultItems=i.detectedQuadResultItems.filter((t=>!t.isFilter))),i.normalizedImageResultItems&&(i.normalizedImageResultItems=i.normalizedImageResultItems.filter((t=>!t.isFilter))),i.parsedResultItems&&(i.parsedResultItems=i.parsedResultItems.filter((t=>!t.isFilter))),t.onCapturedResultReceived(i))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,xe._onLog&&(xe._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),xe._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),xe._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),xe._onLog(`averageTime: ${this._averageTime}`))),xe._onLog){const t=Date.now()-n;t>10&&xe._onLog(`fetch image calculate time: ${t}`)}xe._onLog&&xe._onLog(`time finish decode: ${Date.now()}`),xe._onLog&&xe._onLog("main time: "+(Date.now()-e)),xe._onLog&&xe._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{qt(this,de,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{qt(this,de,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;Se(this),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const n=await this.containsTask(e);if(await mt(n),n.includes("dlr")&&!(null===(i=ut.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=I(pt.engineResourcePaths,dt);await(null===(r=ut.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Jt(this,Ce,!1,"f"),m(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await b(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,e){let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*qt(this,we,"f")),r=Math.round(s*qt(this,we,"f"))):(i=n,r=s),qt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=qt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*qt(this,we,"f")),r=Math.round(s*qt(this,we,"f"))):(i=n,r=s),qt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=qt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:r,height:n,stride:s,format:o}=t;let a=nt();const h=new $t;return st[a]=async e=>{var i,r;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const n=Date.now();xe._onLog&&(xe._onLog(`get result time from worker: ${n}`),xe._onLog("worker to main time consume: "+(n-e.workerReturnMsgTime)));try{const n=e.captureResult;if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of n.items)0!==qt(this,we,"f")&&Te(e,qt(this,we,"f")),e.type===_t.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===_t.CRIT_NORMALIZED_IMAGE?null===(i=ut.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===_t.CRIT_PARSED_RESULT&&(null===(r=ut.dcp)||void 0===r||r.handleParsedResultItem(e));if(qt(this,Ce,"f"))for(let t of qt(this,ye,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onDetectedQuadsReceived(n),t.onNormalizedImagesReceived(n);const s=function(t){const e={barcodeResultItems:[],textLineResultItems:[],detectedQuadResultItems:[],normalizedImageResultItems:[],parsedResultItems:[]};return t.items.forEach((t=>{t.type===_t.CRIT_BARCODE?e.barcodeResultItems.push(t):t.type===_t.CRIT_TEXT_LINE?e.textLineResultItems.push(t):t.type===_t.CRIT_DETECTED_QUAD?e.detectedQuadResultItems.push(t):t.type===_t.CRIT_NORMALIZED_IMAGE?e.normalizedImageResultItems.push(t):t.type===_t.CRIT_PARSED_RESULT&&e.parsedResultItems.push(t)})),e}(n);if(s.barcodeResultItems.length&&(n.barcodeResultItems=s.barcodeResultItems),s.textLineResultItems.length&&(n.textLineResultItems=s.textLineResultItems),s.detectedQuadResultItems.length&&(n.detectedQuadResultItems=s.detectedQuadResultItems),s.normalizedImageResultItems.length&&(n.normalizedImageResultItems=s.normalizedImageResultItems),s.parsedResultItems.length&&(n.parsedResultItems=s.parsedResultItems),!this._isPauseScan||!qt(this,Ce,"f")){const e=n.intermediateResult;if(e){let i=0;for(let r of qt(this,me,"f")._intermediateResultReceiverSet){i++;for(let n of e){if("onTaskResultsReceived"===n.info.callbackName){for(let e of n.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);i===qt(this,me,"f")._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}}return n&&n.hasOwnProperty("intermediateResult")&&delete n.intermediateResult,Jt(this,we,0,"f"),h.resolve(n)}catch(t){return h.reject(t)}}},xe._onLog&&xe._onLog(`send buffer to worker: ${Date.now()}`),it.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:r,height:n,stride:s,format:o,templateName:e||"",isScanner:qt(this,Ce,"f")}},[i.buffer]),h}async initSettings(t){return Se(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?(t.startsWith("{")||(t=await b(t,"text")),this._currentSettings=JSON.parse(t)):"object"==typeof t&&(this._currentSettings=t,t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=nt();st[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.exception){let t=new Error(n.description?n.description:"Init Settings Failed.");return t.errorCode=n.exception,i(t)}let s=[],o=JSON.parse(t).CaptureVisionTemplates;for(let t=0;t{let r=nt();st[r]=async t=>{if(t.success){const r=JSON.parse(t.settings);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return delete r.errorCode,delete r.errorString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getSimplifiedSettings(t){Se(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await mt(e),await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success){const r=JSON.parse(t.settings,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));if(r.minImageCaptureInterval=this._minImageCaptureInterval,0!==r.code){let t=new Error(r.codeString);return t.errorCode=r.errorCode,i(t)}return delete r.code,delete r.codeString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Se(this);const i=await this.containsTask(t);return await mt(i),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==n.exception){let t=new Error(n.description?n.description:"Update Settings Failed.");return t.errorCode=n.exception,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Se(this),await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.exception){let t=new Error(r.description?r.description:"Reset Settings Failed.");return t.errorCode=r.exception,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return qt(this,pe,"f")||Jt(this,pe,new te(this),"f"),qt(this,pe,"f")}getIntermediateResultManager(){if(Se(this),!qt(this,Ee,"f")&&0!==pt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return qt(this,me,"f")||Jt(this,me,new re(this),"f"),qt(this,me,"f")}async parseRequiredResources(t){return Se(this),await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Se(this),qt(this,ge,"f")&&this.stopCapturing(),Jt(this,de,null,"f"),qt(this,_e,"f").clear(),qt(this,ve,"f").clear(),qt(this,ye,"f").clear(),qt(this,me,"f")._intermediateResultReceiverSet.clear(),Jt(this,be,!0,"f");let t=nt();st[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},it.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:qt(this,de,"f"),promiseStartScan:qt(this,ge,"f"),intermediateResultManager:qt(this,me,"f"),bufferdItemsManager:qt(this,pe,"f"),resultReceiverSet:qt(this,_e,"f"),isaStateListenerSet:qt(this,ve,"f"),resultFilterSet:qt(this,ye,"f"),compressRate:qt(this,we,"f"),canvas:qt(this,fe,"f"),isScanner:qt(this,Ce,"f"),innerUseTag:qt(this,Ee,"f"),isDestroyed:qt(this,be,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Ae(t,e){return Se(t),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function Oe(t,e){return Se(t),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Re(t,e){return Se(t),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,be=new WeakMap;class Le{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}class De{constructor(){this._observedResultUnitTypes=St.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}var Me;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Me||(Me={}));const Fe="undefined"==typeof self,Pe=(()=>{if(!Fe&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();dt.dce={version:"4.1.0",path:Pe},ft.dce={wasm:!1,js:!1},ut.dce={};let ke,Be,Ne,je,Ue,Ge=class{static getVersion(){return"4.1.0"}};function Ve(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function We(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(ke=navigator,Be=ke.userAgent,Ne=ke.platform,je=ke.mediaDevices),function(){if(!Fe){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:ke.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Ne,search:"Win"},Mac:{str:Ne},Linux:{str:Ne}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Be,o=n.search||e,a=n.verStr||Be,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Be,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Be.indexOf("Windows NT")&&(n="HarmonyOS"),Ue={browser:i,version:r,OS:n}}Fe&&(Ue={browser:"ssr",version:0,OS:"ssr"})}();const Ye="undefined"!=typeof WebAssembly&&Be&&!(/Safari/.test(Be)&&!/Chrome/.test(Be)&&/\(.+\s11_2_([2-6]).*\)/.test(Be)),He=!("undefined"==typeof Worker),Xe=!(!je||!je.getUserMedia),ze=async()=>{let t=!1;if(Xe)try{(await je.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===Ue.browser&&Ue.version>66||"Safari"===Ue.browser&&Ue.version>13||"OPR"===Ue.browser&&Ue.version>43||"Edge"===Ue.browser&&Ue.version;var Ze={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,b,T=T||{version:"5.2.1"};if(e.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var S=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=S.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=S,DOMParser=T.window.DOMParser}function I(t,e){var i=t.canvas,r=e.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:T.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}T.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof T.Gradient||this.set(e,new T.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof T.Pattern?i&&i():this.set(e,new T.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new T.Point(t.x-e.x,t.y-e.y),n=T.util.rotateVector(r,i);return new T.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),r=T.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new T.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new T.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=T.util.createVector(t,e),n=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(r,n),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(r,s),n)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new T.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new T.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(T.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(T.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=T.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new T.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new T.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var b=Math.sqrt(1-C/(_*v));i*=b,s*=b}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var S=E*i*p/s,I=-E*s*m/i,x=d*S-u*I+.5*t,A=u*S+d*I+.5*e,O=n(1,0,(m-S)/i,(p-I)/s),R=n((m-S)/i,(p-I)/s,(-m-S)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var L=Math.ceil(Math.abs(R/l*2)),D=[],M=R/L,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=O+M,k=0;kE)for(var S=1,I=m.length;S2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(T.cachesBoundsOfCurve&&(l=t.call(arguments),T.boundsOfCurveCache[l]))return T.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],b=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var S=0;S<2;++S)if(S>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,A,O=E.length,R=O;O--;)I=(A=1-(f=E[O]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,b[0][O]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,b[1][O]=x;b[0][R]=e,b[1][R]=i,b[0][R+1]=a,b[1][R+1]=h;var L=[{x:y.apply(null,b[0]),y:y.apply(null,b[1])},{x:w.apply(null,b[0]),y:w.apply(null,b[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[l]=L),L},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},T.util.transformPath=function(t,e,i){return i&&(e=T.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),T.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(T.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=T.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=T.document.documentElement,n=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(t,e){var i=T.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=T.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=T.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},T.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},T.util.getById=function(t){return"string"==typeof t?T.document.getElementById(t):t},T.util.toArray=s,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=o,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},T.util.getNodeCanvas=function(t){var e=T.jsdomImplForWrapper(t);return e._canvas||e._image},T.util.cleanUpJsdomNode=function(t){if(T.isLikelyNode){var e=T.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}T.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}T.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},o=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=T.runningAnimations.indexOf(s);return t>-1&&T.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=n,!o){if(!f(w,C,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,n),void a(t));h()}}(l)})),s.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return o.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,r,n){var s=new T.Color(e).getSource(),o=new T.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},T.util.animate(T.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",b=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=n,C.viewBoxHeight=o,y?(C.width=n,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/n,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),b=C.width-n*c,T=C.height-o*c,"Mid"===p.alignX&&(b/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(b=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+b)+" "+(r*u+T)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function m(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function C(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function b(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),b(l,"skewY","scaleY","y",p)}return m}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),b(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,w=m(t,f),E=_(f,y,w),b=e.gestureScale;if(E)return!1;if(b)o=e.scaleX*b,a=e.scaleY*b;else{if(s=C(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),S=e.original,I=T/(Math.abs(h.x*S.scaleX/f.scaleX)+Math.abs(h.y*S.scaleY/f.scaleY));o=S.scaleX*I,a=S.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=w("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),E(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(T))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=C(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),E(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(S))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=w,n.getLocalPoint=C,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new T.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new T.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=m/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=T.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,m=-i.top),new T.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=T.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var t=T.util.object.extend,e=T.util.getElementOffset,i=T.util.removeFromArray,r=T.util.toFixed,n=T.util.transformPoint,s=T.util.invertTransform,o=T.util.getNodeCanvas,a=T.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=T.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?T.util.loadImage(e,(function(e,n){if(e){var s=new T.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=T.util.getById(t)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?T.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=T.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(T.StaticCanvas.prototype,T.Observable),t(T.StaticCanvas.prototype,T.Collection),t(T.StaticCanvas.prototype,T.DataURLExporter),t(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new T.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new T.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new T.Point(r.x,r.y),n=new T.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=T.util.invertTransform(i),n=this.restorePointerVpt(e);return T.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,T.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):T.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new T.Point(e.ex,e.ey),r=T.util.transformPoint(i,this.viewportTransform),n=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof T.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return T.util.transformPoint(t,T.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;T.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,T.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e,selected:n}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),T.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==r&&(T.Canvas[r]=T.StaticCanvas[r])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(T.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(T.document,t+"up",this._onMouseUp),e(T.document,"touchend",this._onTouchEnd,i),e(T.document,t+"move",this._onMouseMove,i),e(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new T.Point(v(r,s),v(n,o)),h=new T.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return T.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):T.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=T.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new T.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof n?n=E[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new T.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new T.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),n=new T.Point(t.x,t.y),this.angle&&(n=T.util.rotatePoint(n,s,-w(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=w(this.angle),n=this.getScaledWidth(),s=T.util.cos(r)*n,o=T.util.sin(r)*n;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=T.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===T.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+T.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=T.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=T.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=T.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?T.util.animateColor(h.startValue,h.endValue,h.duration,h):T.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return T.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);T.filterBackend||(T.filterBackend=T.initFilterBackend());var o=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,T.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=T.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(T.util.getById(t),e),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(t,e){var i=T.util.object.clone(t);T.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],T.util.enlivenObjectEnlivables(i,i,(function(){var r=new T.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,r){e&&e(new T.Image(t,i),r)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(t,i,r){var n=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(n["xlink:href"],i,e(r?T.util.object.clone(r):{},n))})}(e),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(e){if(T.isLikelyNode)return!1;e=e||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){T.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=n,n},T.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}T.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=T.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(t,e){var i=new T.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,b||(n+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=r,E[s+3]=b?m[s+3]:n}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){D=r(1e3*s(T-C.x)),w[D]||(w[D]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-C.y)),w[D][M]||(w[D][M]=f(n(i(D*p,2)+i(M*_,2))/1e3)),(S=w[D][M])>0&&(x+=S,A+=S*c[I=4*(F*e+T)],O+=S*c[I+1],R+=S*c[I+2],L+=S*c[I+3]))}d[I=4*(b*a+h)]=A/x,d[I+1]=O/x,d[I+2]=R/x,d[I+3]=L/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(S+=y*f[3+(D=4*(L+x*e))],C+=y,f[D+3]<255&&(y=y*f[D+3]/250),E+=y*f[D],b+=y*f[D+1],T+=y*f[D+2],w+=y)}m[v]=E/w,m[v+1]=b/w,m[v+2]=T/w,m[v+3]=S/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),T.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);T.Object._fromObject("IText",e,i,"text")}}(),b=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],T.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=T.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=T.util.transformPoint(h,a),(h=T.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=b(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:b(r[i-1])}:n?this.styles[t+i]={0:b(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?b(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=b(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=b(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=T.util.toFixed,e=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},Ke={};function qe(t){var e=Ke[t];if(void 0!==e)return e.exports;var i=Ke[t]={exports:{}};return Ze[t](i,i.exports,qe),i.exports}qe.d=(t,e)=>{for(var i in e)qe.o(e,i)&&!qe.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},qe.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Je={};(()=>{let t;qe.d(Je,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?qe(653).fabric:{version:"5.2.1"}})();var Qe,$e,ti,ei,ii=Je.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(Qe||(Qe={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}($e||($e={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(ti||(ti={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ei||(ei={}));const ri=t=>"number"==typeof t&&!Number.isNaN(t),ni=t=>"string"==typeof t;var si,oi,ai,hi,li,ci;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(li||(li={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(ci||(ci={}));class ui{get mediaType(){return new Map([["rect",Qe.DIMT_RECTANGLE],["quad",Qe.DIMT_QUADRILATERAL],["text",Qe.DIMT_TEXT],["arc",Qe.DIMT_ARC],["image",Qe.DIMT_IMAGE],["polygon",Qe.DIMT_POLYGON],["line",Qe.DIMT_LINE],["group",Qe.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ve(this,oi,"f")){case $e.DIS_DEFAULT:return"default";case $e.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Ve(this,ai,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ve(this,ai,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),We(this,ai,t,"f")}get coordinateBase(){return Ve(this,ai,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(si.add(this),oi.set(this,void 0),ai.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!ri(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState($e.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState($e.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState($e.DIS_SELECTED):this.setState($e.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){We(this,oi,t,"f")}getState(){return Ve(this,oi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)unull!==t&&"object"==typeof t&&!Array.isArray(t),fi=t=>!!ni(t)&&""!==t,gi=m,mi=p,pi=v,_i=w,vi=y,yi=C,wi=E,Ci=t=>!(!di(t)||"id"in t&&!ri(t.id)||"lineWidth"in t&&!ri(t.lineWidth)||"fillStyle"in t&&!fi(t.fillStyle)||"strokeStyle"in t&&!fi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!fi(t.fontFamily)||"fontSize"in t&&!ri(t.fontSize));class Ei{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(wi(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!mi(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var bi,Ti;class Si{constructor(){bi.set(this,new Map),Ti.set(this,!1)}get disposed(){return Ve(this,Ti,"f")}on(t,e){t=t.toLowerCase();const i=Ve(this,bi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ve(this,bi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ve(this,bi,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=Ve(this,bi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=Ve(this,bi,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){We(this,Ti,!0,"f")}}function Ii(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function xi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Ai(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}bi=new WeakMap,Ti=new WeakMap;const Oi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");if(r.insertAdjacentHTML("beforeend",i),1===r.childElementCount&&r.firstChild instanceof HTMLTemplateElement)return r.firstChild.content;const n=new DocumentFragment;for(let t of r.children)n.append(t);return n};var Ri,Li,Di,Mi,Fi;class Pi extends ui{constructor(t,e){if(super(null,e),Ri.set(this,void 0),!wi(t))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new ii.Rect({left:t.x,top:t.y,width:t.width,height:t.height})),We(this,Ri,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="rect"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth"))),this.set("height",this.convertPropFromViewToImage(this.get("scaledHeight")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth"))),this.set("height",this.convertPropFromImageToView(this.get("scaledHeight")))}setPosition(t){this.setRect(t)}getPosition(){return this.getRect()}updatePosition(){Ve(this,Ri,"f")&&this.setRect(Ve(this,Ri,"f"))}setRect(t){if(!wi(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width)),this.set("height",this.convertPropFromViewToImage(t.height));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width),this.set("height",t.height)}this._drawingLayer.renderAll()}else We(this,Ri,JSON.parse(JSON.stringify(t)),"f")}getRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Ri,"f")?JSON.parse(JSON.stringify(Ve(this,Ri,"f"))):null}}function ki(t,e,i){let r=i.points[this.pointIndex].x-i.pathOffset.x,n=i.points[this.pointIndex].y-i.pathOffset.y;return ii.util.transformPoint({x:r,y:n},i.calcTransformMatrix())}function Bi(t){let e=new ii.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new ii.Point(t.width+e.x,t.height+e.y)}function Ni(t,e,i,r){let n=e.target,s=n.controls[n.__corner],o=n.toLocalPoint(new ii.Point(i,r),"center","center"),a=Bi(n),h=n._getTransformedDimensions(0,0),l={x:o.x*a.x/h.x+n.pathOffset.x,y:o.y*a.y/h.y+n.pathOffset.y};return n.points[s.pointIndex]=l,ii.controlsUtils.fireEvent("scaling",{e:t,transform:e,pointer:{x:i,y:r}}),!0}function ji(t,e){return function(i,r,n,s){let o=r.target,a=ii.util.transformPoint({x:o.points[t].x-o.pathOffset.x,y:o.points[t].y-o.pathOffset.y},o.calcTransformMatrix()),h=e(i,r,n,s);o._setPositionDimensions({});let l=Bi(o),c=(o.points[t].x-o.pathOffset.x)/l.x,u=(o.points[t].y-o.pathOffset.y)/l.y;return o.setPositionByOrigin(a,c+.5,u+.5),h}}Ri=new WeakMap;class Ui extends ui{constructor(t,e){if(super(null,e),Li.set(this,void 0),!_i(t))throw new TypeError("Invalid 'polygon'.");this._setFabricObject(new ii.Polygon(t.points,{objectCaching:!1}));const i=this._fabricObject;let r=i.points.length-1;i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ii.Control({positionHandler:ki,actionHandler:ji(i>0?i-1:r,Ni),actionName:"modifyPolygon",pointIndex:i}),t}),{}),We(this,Li,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new ii.Control({positionHandler:ki,actionHandler:ji(r>0?r-1:i,Ni),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=ii.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Ve(this,Li,"f")&&this.setPolygon(Ve(this,Li,"f"))}setPolygon(t){if(!_i(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else We(this,Li,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Li,"f")?JSON.parse(JSON.stringify(Ve(this,Li,"f"))):null}}Li=new WeakMap;class Gi extends ui{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Ve(this,Mi,"f")}constructor(t,e,i,r){if(super(null,r),Di.set(this,void 0),Mi.set(this,void 0),!wi(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new ii.Image(t,{left:e.x,top:e.y}));else{if(!gi(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let r;if(i.width=t.width,i.height=t.height,t.format===n.IPF_GRAYSCALED){r=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ii.Control({positionHandler:ki,actionHandler:ji(i>0?i-1:r,Ni),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=ii.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Ve(this,Yi,"f")&&this.setLine(Ve(this,Yi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!pi(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else We(this,Yi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Yi,"f")?JSON.parse(JSON.stringify(Ve(this,Yi,"f"))):null}}Yi=new WeakMap;class xr extends Ui{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Hi.set(this,void 0),!yi(t))throw new TypeError("Invalid 'quad'.");We(this,Hi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Ve(this,Hi,"f")&&this.setQuad(Ve(this,Hi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!yi(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else We(this,Hi,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Hi,"f")?JSON.parse(JSON.stringify(Ve(this,Hi,"f"))):null}}Hi=new WeakMap;class Ar extends ui{constructor(t){super(new ii.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState($e.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState($e.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}class Or{static createDrawingStyle(t){if(!Ci(t))throw new Error("Invalid style definition.");let e,i=Or.USER_START_STYLE_ID;for(;Ve(Or,Xi,"f",zi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in Ve(Or,Xi,"f",Zi))r.hasOwnProperty(t)||(r[t]=Ve(Or,Xi,"f",Zi)[t]);return Ve(Or,Xi,"f",zi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ve(Or,Xi,"f",zi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Ve(Or,Xi,"f",zi).values())))}static _updateDrawingStyle(t,e){if(!Ci(e))throw new Error("Invalid style definition.");const i=Ve(Or,Xi,"f",zi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Xi=Or,Or.STYLE_BLUE_STROKE=1,Or.STYLE_GREEN_STROKE=2,Or.STYLE_ORANGE_STROKE=3,Or.STYLE_YELLOW_STROKE=4,Or.STYLE_BLUE_STROKE_FILL=5,Or.STYLE_GREEN_STROKE_FILL=6,Or.STYLE_ORANGE_STROKE_FILL=7,Or.STYLE_YELLOW_STROKE_FILL=8,Or.STYLE_BLUE_STROKE_TRANSPARENT=9,Or.STYLE_GREEN_STROKE_TRANSPARENT=10,Or.STYLE_ORANGE_STROKE_TRANSPARENT=11,Or.USER_START_STYLE_ID=1024,zi={value:new Map([[Or.STYLE_BLUE_STROKE,{id:Or.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Or.STYLE_GREEN_STROKE,{id:Or.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_ORANGE_STROKE,{id:Or.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_YELLOW_STROKE,{id:Or.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Or.STYLE_BLUE_STROKE_FILL,{id:Or.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_GREEN_STROKE_FILL,{id:Or.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_ORANGE_STROKE_FILL,{id:Or.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_YELLOW_STROKE_FILL,{id:Or.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_BLUE_STROKE_TRANSPARENT,{id:Or.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_GREEN_STROKE_TRANSPARENT,{id:Or.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Or.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Zi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ii.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ii.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ii.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ii.Object.prototype.transparentCorners=!1,ii.Object.prototype.cornerSize=20,ii.Object.prototype.touchCornerSize=100,ii.Object.prototype.cornerColor="rgb(254,142,20)",ii.Object.prototype.cornerStyle="circle",ii.Object.prototype.strokeUniform=!0,ii.Object.prototype.hasBorders=!1,ii.Canvas.prototype.containerClass="",ii.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=ii.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},ii.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();ii.util.addListener(ii.document,"touchend",this._onTouchEnd,{passive:!1}),ii.util.addListener(ii.document,"touchmove",this._onMouseMove,{passive:!1}),ii.util.removeListener(i,r+"down",this._onMouseDown)},ii.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?ii.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class Rr{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ii.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case Rr.DDN_LAYER_ID:r=Or.getDrawingStyle(Or.STYLE_BLUE_STROKE),n=Or.getDrawingStyle(Or.STYLE_BLUE_STROKE_FILL);break;case Rr.DBR_LAYER_ID:r=Or.getDrawingStyle(Or.STYLE_ORANGE_STROKE),n=Or.getDrawingStyle(Or.STYLE_ORANGE_STROKE_FILL);break;case Rr.DLR_LAYER_ID:r=Or.getDrawingStyle(Or.STYLE_GREEN_STROKE),n=Or.getDrawingStyle(Or.STYLE_GREEN_STROKE_FILL);break;default:r=Or.getDrawingStyle(Or.STYLE_YELLOW_STROKE),n=Or.getDrawingStyle(Or.STYLE_YELLOW_STROKE_FILL)}for(let t of ui.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Or.getDrawingStyle(t.styleId);return Or.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=Or.getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildDrawingItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Or.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=Or.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof ui))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildDrawingItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of ui.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Or.getDrawingStyle(t.styleId);else{s=Or.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of ui.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Or.getDrawingStyle(t.styleId);else{s=Or.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=ui.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=ui.arrStyleSelectors;const r=Or.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&Qe.DIMT_RECTANGLE&&r.push("rect"),i&Qe.DIMT_QUADRILATERAL&&r.push("quad"),i&Qe.DIMT_TEXT&&r.push("text"),i&Qe.DIMT_ARC&&r.push("arc"),i&Qe.DIMT_IMAGE&&r.push("image"),i&Qe.DIMT_POLYGON&&r.push("polygon"),i&Qe.DIMT_LINE&&r.push("line");const n=[];e&$e.DIS_DEFAULT&&n.push("default"),e&$e.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Rr.DDN_LAYER_ID=1,Rr.DBR_LAYER_ID=2,Rr.DLR_LAYER_ID=3,Rr.USER_DEFINED_LAYER_BASE_ID=100,Rr.TIP_LAYER_ID=999;class Lr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Rr(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Dr extends Wi{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),Ki.set(this,void 0),qi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&We(this,qi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Ve(this,Ki,"f")),"f")}getDuration(){return Ve(this,Ki,"f")}}Ki=new WeakMap,qi=new WeakMap;class Mr{constructor(){Ji.add(this),Qi.set(this,void 0),$i.set(this,void 0),tr.set(this,void 0),er.set(this,!0),this._drawingLayerManager=new Lr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=Rr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Rr.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Rr.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(di(e=t)&&vi(e.topLeftPoint)&&ri(e.width))||e.width<=0||!ri(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;We(this,Qi,JSON.parse(JSON.stringify(t)),"f"),Ve(this,Qi,"f").coordinateBase||(Ve(this,Qi,"f").coordinateBase="view"),We(this,tr,t.duration,"f"),Ve(this,Ji,"m",sr).call(this)}getTipConfig(){return Ve(this,Qi,"f")?Ve(this,Qi,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),We(this,er,t,"f")}isTipVisible(){return Ve(this,er,"f")}updateTipMessage(t){if(!Ve(this,Qi,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Or.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Rr.TIP_LAYER_ID)||this._createDrawingLayer(Rr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ve(this,Ji,"m",ir).call(this,t,Ve(this,Qi,"f").topLeftPoint.x,Ve(this,Qi,"f").topLeftPoint.y,Ve(this,Qi,"f").width,Ve(this,Qi,"f").coordinateBase,this._tipStyleId),Ve(this,Ji,"m",rr).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ve(this,er,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ve(this,$i,"f")&&clearTimeout(Ve(this,$i,"f")),Ve(this,tr,"f")>=0&&We(this,$i,setTimeout((()=>{Ve(this,Ji,"m",nr).call(this)}),Ve(this,tr,"f")),"f")}}Qi=new WeakMap,$i=new WeakMap,tr=new WeakMap,er=new WeakMap,Ji=new WeakSet,ir=function(t,e,i,r,n,s){const o=new Dr(t,e,i,r,s);return o.coordinateBase=n,o},rr=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},nr=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},sr=function(){if(!this._tip)return;const t=Ve(this,Qi,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Fr extends HTMLElement{constructor(){super(),or.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),We(this,or,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Ve(this,or,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}or=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Fr);class Pr extends Mr{static get engineResourcePath(){return I(pt.engineResourcePaths,dt).dce}static set defaultUIElementURL(t){Pr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Pr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Pr.engineResourcePath)}static async createInstance(t){const e=new Pr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Pr.engineResourcePath)),await e.setUIElement(t||Pr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ve(this,pr,"f")){if(We(this,pr,t,"f"),Ve(this,ar,"m",yr).call(this))We(this,ur,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Ve(this,ur,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ue.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),We(this,ur,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ve(this,ar,"m",yr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Ve(this,pr,"f")}get disposed(){return Ve(this,vr,"f")}constructor(){super(),ar.add(this),hr.set(this,void 0),lr.set(this,void 0),cr.set(this,void 0),this.containerClassName="dce-video-container",ur.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,dr.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,fr.set(this,!1),gr.set(this,!1),mr.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ve(this,ar,"m",Tr).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Ve(this,ar,"m",br).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Pr._onLog&&Pr._onLog("window resize event triggered."),Ve(this,mr,"f").width===document.documentElement.clientWidth&&Ve(this,mr,"f").height===document.documentElement.clientHeight||(Ve(this,mr,"f").width=document.documentElement.clientWidth,Ve(this,mr,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},pr.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ve(this,ar,"m",yr).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},_r.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>Pr._transformCoordinates(t,i,r,n,s,o,a)));const c=new xr({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ve(this,_r,"f").push(c)};let m,p;for(let t of a)switch(t.type){case _t.CRIT_ORIGINAL_IMAGE:break;case _t.CRIT_BARCODE:m=this.getDrawingLayer(Rr.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Or.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case _t.CRIT_TEXT_LINE:m=this.getDrawingLayer(Rr.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Or.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case _t.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Rr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Or.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case _t.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Rr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Or.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case _t.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},vr.set(this,!1),this.eventHandler=new Si,this.eventHandler.on("content:updated",(()=>{Ve(this,hr,"f")&&clearTimeout(Ve(this,hr,"f")),We(this,hr,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Ve(this,lr,"f")&&clearTimeout(Ve(this,lr,"f")),We(this,lr,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Oi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let r=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!r)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=new Fr,r.appendChild(this._innerComponent),Ve(this,ar,"m",yr).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ue.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),We(this,ur,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Ve(this,ar,"m",yr).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ve(this,ar,"m",yr).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ve(this,ar,"m",Tr).call(this),Ve(this,ar,"m",yr).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ve(this,ar,"m",yr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Pr._onLog&&Pr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Ve(this,mr,"f").width=document.documentElement.clientWidth,Ve(this,mr,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;Ve(this,ar,"m",yr).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ve(this,ar,"m",Tr).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,We(this,ur,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),r=Math.min(t.width,t.height);e=r<=1080?r+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Ve(this,ur,"f")}isVideoLoaded(){return!(!Ve(this,ur,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ve(this,ur,"f"))return;if(Ve(this,ur,"f").style.objectFit=t,Ve(this,ar,"m",yr).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ve(this,ar,"m",Sr).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(Ve(this,ar,"m",yr).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=Ve(this,ur,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ve(this,ur,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=Ei.convert(this.scanRegion,t.width,t.height);We(this,dr,e,"f"),Ve(this,cr,"f")&&clearTimeout(Ve(this,cr,"f")),We(this,cr,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ve(this,ar,"m",wr).call(this,t,e),Ve(this,ar,"m",Sr).call(this,t,e)}),0),"f")}getConvertedRegion(){return Ve(this,dr,"f")}setScanRegion(t){if(null!=t&&!mi(t)&&!wi(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ve(this,ur,"f").videoWidth,i=Ve(this,ur,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=Ve(this,ur,"f").videoWidth,e=Ve(this,ur,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),Ve(this,_r,"f").length=0}dispose(){this._unbindUI(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}function kr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Br(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,ar=new WeakSet,yr=function(){return"disabled"!==this._singleFrameMode},wr=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},Cr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Er=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},br=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Tr=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Sr=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===Wr.browser&&Wr.version>13||"OPR"===Wr.browser&&Wr.version>43||"Edge"===Wr.browser&&Wr.version,"function"==typeof SuppressedError&&SuppressedError;let Xr=class t{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,i,r){return t.multiply(e,[1,0,0,0,1,0,i,r,1])}static rotate(e,i){var r=Math.cos(i),n=Math.sin(i);return t.multiply(e,[r,-n,0,n,r,0,0,0,1])}static scale(e,i,r){return t.multiply(e,[i,0,0,0,r,0,0,0,1])}};var zr,Zr,Kr,qr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,bn,Tn,Sn,In,xn,An,On,Rn,Ln,Dn,Mn,Fn,Pn,kn,Bn,Nn,jn,Un,Gn,Vn,Wn,Yn,Hn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(zr||(zr={}));class Xn{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Hr(Xn,Zr,!1,"f",Kr),!1):(Hr(Xn,Zr,!0,"f",Kr),!0)}get disposed(){return Yr(this,en,"f")}constructor(){qr.set(this,zr.RGBA),Jr.set(this,null),Qr.set(this,null),$r.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,tn.set(this,null),en.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Yr(Xn,Zr,"f",Kr)&&Xn.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Yr(Xn,Zr,"f",Kr))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Xn._onLog&&(o=Date.now(),Xn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=zr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Yr(Xn,Zr,"f",Kr)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Xn._onLog&&Xn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Hr(this,Qr,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Hr(this,$r,e(t),"f"),Hr(this,Jr,i(t),"f"),Hr(this,qr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[zr.GREY,zr.GREY32].includes(p)?1:0);let m,_,v=Xr.translate(Xr.identity(),-1,-1);v=Xr.scale(v,2,2),v=Xr.scale(v,1/t.canvas.width,1/t.canvas.height),m=Xr.translate(v,u,d),m=Xr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Xr.translate(Xr.identity(),a/i,h/r),_=Xr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Yr(this,Jr,"f"),e),v(t,Yr(this,Qr,"f"),Yr(this,$r,"f"),Yr(this,Jr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Xn._onLog&&Xn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Xn._onLog&&Xn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===zr.GREY?zr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Xn._onLog&&Xn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Xn._onLog&&(n=Date.now(),Xn._onLog("transformPixelFormat(), START: "+n)),e===i)return Xn._onLog&&Xn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[zr.RGBA,zr.RBGA,zr.GRBA,zr.GBRA,zr.BRGA,zr.BGRA];if(o.includes(e))if(i===zr.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Xn._onLog&&(s=Date.now(),Xn._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=zr.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Yr(Xn,Zr,"f",Kr)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Xn._onLog&&Xn._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===zr.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Br(this,nn,!0,"f")}}rn=new WeakMap,nn=new WeakMap;const Zn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class Kn{static get version(){return"2.0.13"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Wr.OS))return Kn.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Wr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{t.src&&await t.load(),await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a){await m;try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!kr(this,vn,"f"))return"closed";if("pending"===kr(this,vn,"f"))return"opening";if("fulfilled"===kr(this,vn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Kn.isStorageAvailable("localStorage")?Br(this,gn,!0,"f"):(Br(this,gn,!1,"f"),console.warn("Local storage is unavailable")):Br(this,gn,!1,"f")}get ifSaveLastUsedCamera(){return kr(this,gn,"f")}get isVideoPlaying(){return!(!kr(this,an,"f")||kr(this,an,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=kr(this,Tn,"f"))||void 0===e||e.removeEventListener("click",kr(this,bn,"f")),null===(i=kr(this,Tn,"f"))||void 0===i||i.removeEventListener("touchend",kr(this,bn,"f")),null===(r=kr(this,Tn,"f"))||void 0===r||r.removeEventListener("touchmove",kr(this,En,"f")),Br(this,Tn,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Wr.OS)?(t.addEventListener("touchend",kr(this,bn,"f")),t.addEventListener("touchmove",kr(this,En,"f"))):t.addEventListener("click",kr(this,bn,"f")))}get tapFocusEventBoundEl(){return kr(this,Tn,"f")}get disposed(){return kr(this,Mn,"f")}constructor(t){var e,i;on.add(this),an.set(this,null),hn.set(this,void 0),ln.set(this,(()=>{"opened"===this.state&&kr(this,An,"f").fire("resumed",null,{target:this,async:!1})})),cn.set(this,(()=>{kr(this,An,"f").fire("paused",null,{target:this,async:!1})})),un.set(this,void 0),dn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],fn.set(this,void 0),gn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,mn.set(this,void 0),pn.set(this,!0),_n.set(this,void 0),vn.set(this,void 0),yn.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},wn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(kr(this,an,"f")).objectFit,s=this.getResolution(),o=kr(this,an,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=kr(this,an,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},Cn.set(this,!1),En.set(this,(()=>{Br(this,Cn,!0,"f")})),bn.set(this,(async t=>{var e;if(kr(this,Cn,"f"))return void Br(this,Cn,!1,"f");if(!kr(this,wn,"f"))return;if(!this.isVideoPlaying)return;if(!kr(this,hn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Kn._onLog&&(c=Date.now());try{await kr(this,on,"m",Wn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Kn._onLog)throw Kn._onLog(t),t}Kn._onLog&&Kn._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Kn._onLog&&Kn._onLog("Back to continuous focus."),null===(t=kr(this,hn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),kr(this,An,"f").fire("tapfocus",null,{target:this,async:!1})})),Tn.set(this,null),Sn.set(this,1),In.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!kr(this,an,"f"))return;const t=kr(this,Sn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)kr(this,an,"f").style.transform="";else{const e=window.getComputedStyle(kr(this,an,"f")).objectFit,i=kr(this,an,"f").videoWidth,r=kr(this,an,"f").videoHeight,{width:n,height:s}=kr(this,an,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-kr(this,In,"f").x),c=h*(1-1/t)*(r/2-kr(this,In,"f").y);kr(this,an,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},xn.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===zr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Kn._onLog&&Kn._onLog("document visible. video paused: "+(null===(t=kr(this,an,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Kn._onLog&&Kn._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Kn._onLog&&Kn._onLog("document visible. 1st resume video failed, try open instead.")}e||await kr(this,on,"m",Nn).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Kn._onLog&&Kn._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Kn._onLog&&Kn._onLog("document visible. 2rd resume video failed, try open instead.")}e||await kr(this,on,"m",Nn).call(this)}}}else"hidden"===document.visibilityState&&(Kn._onLog&&Kn._onLog("document hidden. video paused: "+(null===(e=kr(this,an,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Mn.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Kn.onWarning&&Kn.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Br(this,An,new zn,"f"),this.imageDataGetter=new Xn,document.addEventListener("visibilitychange",kr(this,Dn,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",kr(this,ln,"f")),t.addEventListener("pause",kr(this,cn,"f")),Br(this,an,t,"f")}getVideoEl(){return kr(this,an,"f")}releaseVideoEl(){var t,e;null===(t=kr(this,an,"f"))||void 0===t||t.removeEventListener("play",kr(this,ln,"f")),null===(e=kr(this,an,"f"))||void 0===e||e.removeEventListener("pause",kr(this,cn,"f")),Br(this,an,null,"f")}isVideoLoaded(){return!!kr(this,an,"f")&&4==kr(this,an,"f").readyState}async open(){if(kr(this,_n,"f")&&!kr(this,pn,"f")){if("pending"===kr(this,vn,"f"))return kr(this,_n,"f");if("fulfilled"===kr(this,vn,"f"))return}kr(this,An,"f").fire("before:open",null,{target:this}),await kr(this,on,"m",Nn).call(this),kr(this,An,"f").fire("played",null,{target:this,async:!1}),kr(this,An,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;kr(this,An,"f").fire("before:close",null,{target:this});const t=kr(this,_n,"f");if(kr(this,on,"m",Un).call(this),t&&"pending"===kr(this,vn,"f")){try{await t}catch(t){}if(!1===kr(this,pn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Br(this,_n,null,"f"),Br(this,vn,null,"f"),kr(this,An,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");kr(this,an,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await kr(this,an,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof kr(this,un,"f").video&&(kr(this,un,"f").video={}),delete kr(this,un,"f").video.facingMode,kr(this,un,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&kr(this,pn,"f"))){kr(this,An,"f").fire("before:camera:change",[],{target:this,async:!1}),await kr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}return kr(this,dn,"f")}}async switchToFrontCamera(t){if("object"!=typeof kr(this,un,"f").video&&(kr(this,un,"f").video={}),(null==t?void 0:t.resolution)&&(kr(this,un,"f").video.width={ideal:t.resolution.width},kr(this,un,"f").video.height={ideal:t.resolution.height}),delete kr(this,un,"f").video.deviceId,kr(this,un,"f").video.facingMode={exact:"user"},Br(this,fn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&kr(this,pn,"f"))){kr(this,An,"f").fire("before:camera:change",[],{target:this,async:!1}),kr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}return kr(this,dn,"f")}}getCamera(){var t;if(kr(this,dn,"f"))return kr(this,dn,"f");{let e=(null===(t=kr(this,un,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof kr(this,un,"f").video&&(kr(this,un,"f").video={}),i?(kr(this,un,"f").video.width={exact:t},kr(this,un,"f").video.height={exact:e}):(kr(this,un,"f").video.width={ideal:t},kr(this,un,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&kr(this,pn,"f"))return null;kr(this,An,"f").fire("before:resolution:change",[],{target:this,async:!1}),await kr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&kr(this,an,"f"))return{width:kr(this,an,"f").videoWidth,height:kr(this,an,"f").videoHeight};if(kr(this,hn,"f")){const t=kr(this,hn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:kr(this,an,"f").videoWidth,height:kr(this,an,"f").videoHeight};{const t={width:0,height:0};let e=kr(this,un,"f").video.width||0,i=kr(this,un,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=kr(this,Rn,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=kr(this,dn,"f"))||void 0===u?void 0:u.deviceId;let e=kr(this,Rn,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],kr(this,Rn,"f").set(d,e),Br(this,yn,!0,"f");try{for(let t of this.detectedResolutions){await kr(this,hn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),kr(this,on,"m",Pn).call(this);const i=kr(this,hn,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw kr(this,on,"m",Un).call(this),Br(this,yn,!1,"f"),t}try{await kr(this,on,"m",Nn).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Br(this,yn,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(n=null===(r=kr(this,un,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=kr(this,un,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=kr(this,un,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=kr(this,Rn,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],kr(this,Rn,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Br(this,un,JSON.parse(JSON.stringify(t)),"f"),Br(this,fn,null,"f"),e&&kr(this,on,"m",jn).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(kr(this,un,"f")))}resetMediaStreamConstraints(){Br(this,un,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return kr(this,hn,"f").getCapabilities?kr(this,hn,"f").getCapabilities():{}}getCameraSettings(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return kr(this,hn,"f").getSettings()}async turnOnTorch(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await kr(this,hn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await kr(this,hn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await kr(this,hn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await kr(this,hn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await kr(this,hn,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=Zn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await kr(this,hn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await kr(this,on,"m",Wn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await kr(this,hn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Br(this,wn,!0,"f")}disableTapToFocus(){Br(this,wn,!1,"f")}isTapToFocusEnabled(){return kr(this,wn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?kr(this,on,"m",Yn).call(this,t.centerPoint):this.resetScaleCenter();try{if(kr(this,on,"m",Hn).call(this,kr(this,In,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*kr(this,Sn,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await kr(this,hn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&kr(this,on,"m",Yn).call(this,e),Br(this,Sn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return kr(this,Sn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Br(this,In,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(kr(this,yn,"f"))return null;const e=Date.now();Kn._onLog&&Kn._onLog("getFrameData() START: "+e);const i=kr(this,an,"f").videoWidth,r=kr(this,an,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=zr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=kr(this,Sn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=kr(this,In,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(kr(this,an,"f"),i,r,n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return Kn._onLog&&Kn._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:kr(this,xn,"f")}}on(t,e){if(!kr(this,On,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);kr(this,An,"f").on(t,e)}off(t,e){kr(this,An,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),kr(this,An,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",kr(this,Dn,"f")),Br(this,Mn,!0,"f")}}var qn,Jn,Qn,$n,ts,es,is,rs,ns,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,bs,Ts,Ss,Is,xs,As,Os,Rs;an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,bn=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,In=new WeakMap,xn=new WeakMap,An=new WeakMap,On=new WeakMap,Rn=new WeakMap,Ln=new WeakMap,Dn=new WeakMap,Mn=new WeakMap,on=new WeakSet,Fn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(kr(this,fn,"f"))delete t.video.facingMode,t.video.deviceId={exact:kr(this,fn,"f")};else if(this.ifSaveLastUsedCamera&&Kn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Wr.OS)?(await this._getCameras(!1),kr(this,on,"m",Pn).call(this),e=Kn.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Wr.OS)||(await this._getCameras(!1),kr(this,on,"m",Pn).call(this),e=Kn.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},Pn=function(){if(kr(this,pn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},kn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{Kn._onLog&&Kn._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),kr(this,on,"m",Pn).call(this));try{Kn._onLog&&Kn._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),kr(this,on,"m",Pn).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Kn._onLog&&Kn._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Bn=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Br(this,hn,null,"f")},Nn=async function(){Br(this,pn,!1,"f");const t=Br(this,mn,Symbol(),"f");if(kr(this,_n,"f")&&"pending"===kr(this,vn,"f")){try{await kr(this,_n,"f")}catch(t){}kr(this,on,"m",Pn).call(this)}if(t!==kr(this,mn,"f"))return;const e=Br(this,_n,(async()=>{Br(this,vn,"pending","f");try{if(this.videoSrc){if(!kr(this,an,"f"))throw new Error("'videoEl' should be set.");await Kn.playVideo(kr(this,an,"f"),this.videoSrc,this.cameraOpenTimeout),kr(this,on,"m",Pn).call(this)}else{let t=await kr(this,on,"m",Fn).call(this);kr(this,on,"m",Bn).call(this);let e=await kr(this,on,"m",kn).call(this,t);await this._getCameras(!1),kr(this,on,"m",Pn).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=kr(this,un,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(kr(this,fn,"f")||this.ifSaveLastUsedCamera&&Kn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=Kn.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await kr(this,on,"m",kn).call(this,t),kr(this,on,"m",Pn).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(Br(this,fn,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&Kn.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",kr(this,fn,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),kr(this,an,"f")&&(await Kn.playVideo(kr(this,an,"f"),e,this.cameraOpenTimeout),kr(this,on,"m",Pn).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Br(this,hn,s[0],"f"),Br(this,dn,n,"f")}}catch(t){throw kr(this,on,"m",Un).call(this),Br(this,vn,null,"f"),t}Br(this,vn,"fulfilled","f")})(),"f");return e},jn=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=kr(this,dn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await kr(this,on,"m",Nn).call(this);const r=this.getResolution();e&&e!==kr(this,dn,"f").deviceId&&kr(this,An,"f").fire("camera:changed",[kr(this,dn,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||kr(this,An,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),kr(this,An,"f").fire("played",null,{target:this,async:!1})},Un=function(){kr(this,on,"m",Bn).call(this),Br(this,dn,null,"f"),kr(this,an,"f")&&(kr(this,an,"f").srcObject=null,this.videoSrc&&(kr(this,an,"f").pause(),kr(this,an,"f").currentTime=0)),Br(this,pn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Gn=async function t(e,i){const r=t=>{if(!kr(this,hn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){kr(this,hn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=Zn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await kr(this,hn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(kr(this,an,"f"),l.width,l.height,{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:zr.RGBA,bufferContainer:d}))return kr(this,on,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await kr(this,on,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await kr(this,on,"m",Gn).call(this,e,c);if(a>h)return await kr(this,on,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await kr(this,on,"m",t).call(this,e,o,a,c,h);let u=await kr(this,on,"m",Gn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==kr(this,Sn,"f")){const t=kr(this,Sn,"f"),e=kr(this,In,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=Zn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=Zn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Zn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await kr(this,on,"m",Gn).call(this,t,s),a=await kr(this,on,"m",Gn).call(this,t,n),h=await kr(this,on,"m",Gn).call(this,t,r);if(a>h&&ho&&a>o){let e=await kr(this,on,"m",Gn).call(this,t,i);const n=await kr(this,on,"m",Vn).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await kr(this,on,"m",Vn).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},Yn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");Br(this,In,{x:i,y:r},"f")},Hn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Kn.browserInfo=Wr,Kn.onWarning=null===(sn=null===window||void 0===window?void 0:window.console)||void 0===sn?void 0:sn.warn;class Ls{constructor(t){qn.add(this),Jn.set(this,void 0),Qn.set(this,0),$n.set(this,void 0),ts.set(this,0),es.set(this,!1),We(this,Jn,t,"f")}startCharging(){Ve(this,es,"f")||(Ls._onLog&&Ls._onLog("start charging."),Ve(this,qn,"m",rs).call(this),We(this,es,!0,"f"))}stopCharging(){Ve(this,$n,"f")&&clearTimeout(Ve(this,$n,"f")),Ve(this,es,"f")&&(Ls._onLog&&Ls._onLog("stop charging."),We(this,Qn,Date.now()-Ve(this,ts,"f"),"f"),We(this,es,!1,"f"))}}Jn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,ts=new WeakMap,es=new WeakMap,qn=new WeakSet,is=function(){pt.cfd(1),Ls._onLog&&Ls._onLog("charge 1.")},rs=function t(){0==Ve(this,Qn,"f")&&Ve(this,qn,"m",is).call(this),We(this,ts,Date.now(),"f"),Ve(this,$n,"f")&&clearTimeout(Ve(this,$n,"f")),We(this,$n,setTimeout((()=>{We(this,Qn,0,"f"),Ve(this,qn,"m",t).call(this)}),Ve(this,Jn,"f")-Ve(this,Qn,"f")),"f")};class Ds{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ve(this,ns,"f",as)<100)){if(We(this,ns,e,"f",as),Ve(this,ns,"f",ss).size&&(t=Ve(this,ns,"f",ss).values().next().value,this.beepSoundSource==t.src?(Ve(this,ns,"f",ss).delete(t),t.play()):t=null),!t)if(Ve(this,ns,"f",os).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Ve(this,ns,"f",os).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ve(this,ns,"f",os).delete(t),Ve(this,ns,"f",ss).add(t)}))}else Ve(this,ns,"f",hs)||(We(this,ns,!0,"f",hs),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ve(this,ns,"f",os).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ds.vibrateDuration)}}}ns=Ds,ss={value:new Set},os={value:new Set},as={value:0},hs={value:!1},Ds.allowBeep=!0,Ds.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Ds.allowVibrate=!0,Ds.vibrateDuration=300;const Ms=new Map([[n.IPF_GRAYSCALED,zr.GREY],[n.IPF_ABGR_8888,zr.RGBA],[n.IPF_ARGB_8888,zr.BGRA]]),Fs=new Map([[zr.GREY,n.IPF_GRAYSCALED],[zr.RGBA,n.IPF_ABGR_8888],[zr.BGRA,n.IPF_ARGB_8888]]),Ps="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class ks extends G{static set _onLog(t){We(ks,cs,t,"f",us),Kn._onLog=t,Ls._onLog=t}static get _onLog(){return Ve(ks,cs,"f",us)}static async detectEnvironment(){return await(async()=>({wasm:Ye,worker:He,getUserMedia:Xe,camera:await ze(),browser:Ue.browser,version:Ue.version,OS:Ue.OS}))()}static async testCameraAccess(){const t=await Kn.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Pr))throw new TypeError("Invalid view.");if(null===(e=ut.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ut.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await pt.loadWasm(["license"]),await ut.license.dynamsoft()}const r=new ks(t);return ks.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ks.onWarning&&ks.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ks.onWarning&&ks.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");We(this,gs,t,"f")}get singleFrameMode(){return Ve(this,gs,"f")}get _isFetchingStarted(){return Ve(this,ws,"f")}get disposed(){return Ve(this,Ss,"f")}constructor(t){if(super(),ls.add(this),ds.set(this,"closed"),fs.set(this,void 0),this.isTorchOn=void 0,gs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ms.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,e,i,s,{pixelFormat:Ms.get(this.getPixelFormat())});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===zr.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:Fs.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Et.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:Ve(this,ps,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Ei.convert(Ve(this,vs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ve(this,ms,"f").call(this,t,t.width,t.height,e);Ve(this,fs,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ps.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===n.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(Ue.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Ve(this,Ts,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Ve(this,Ts,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Ve(this,Es,"f").tapToFocus&&Ve(this,Ts,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(Ve(this,ls,"m",Is).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;ks._onLog&&(ks._onLog("intermediateResultUnits:"),ks._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===St.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===St.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(ks._onLog&&(ks._onLog("hasLocalizedBarcodes:"),ks._onLog(h)),Ve(this,Es,"f").autoZoom||Ve(this,Es,"f").enhancedFocus)if(a)Ve(this,bs,"f").autoZoomInFrameArray.length=0,Ve(this,bs,"f").autoZoomOutFrameCount=0,Ve(this,bs,"f").frameArrayInIdealZoom.length=0,Ve(this,bs,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ve(this,Es,"f").autoZoom&&Ve(this,Ts,"f").startCharging()},a=async t=>{await this.setFocus(t),Ve(this,Es,"f").enhancedFocus&&Ve(this,Ts,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-Ve(this,bs,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ve(this,bs,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-Ve(this,bs,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ve(this,bs,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}ks._onLog&&(ks._onLog("detectionArea:"),ks._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=xi(a.y-i)>0&&xi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(Ai([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Ai([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Ai([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Ai([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===St.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Pr._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(ks._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Or.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===St.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new Ui({points:i},e);t.addDrawingItems([n])}}}if(ks._onLog&&(ks._onLog("intersectedResults:"),ks._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==Ps.BF_QR_CODE||t.possibleFormats==Ps.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Ps.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Ve(this,bs,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Ve(this,bs,"f").autoZoomInFrameLimit[1]){Ve(this,bs,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Ve(this,bs,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ve(this,bs,"f").autoZoomInMaxTimes),Ve(this,bs,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ve(this,bs,"f").minValue,u),u=Math.min(Ve(this,bs,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ve(this,bs,"f").autoZoomInFrameArray.length=0,Ve(this,bs,"f").frameArrayInIdealZoom.push(!0),Ve(this,bs,"f").frameArrayInIdealZoom.splice(0,Ve(this,bs,"f").frameArrayInIdealZoom.length-Ve(this,bs,"f").frameLimitInIdealZoom[0]),Ve(this,bs,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Ve(this,bs,"f").frameLimitInIdealZoom[1]&&(Ve(this,bs,"f").frameArrayInIdealZoom.length=0,Ve(this,Es,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Ve(this,Es,"f").autoZoom&&Ve(this,Es,"f").enhancedFocus&&(Ve(this,bs,"f").autoFocusFrameArray.push(!0),Ve(this,bs,"f").autoFocusFrameArray.splice(0,Ve(this,bs,"f").autoFocusFrameArray.length-Ve(this,bs,"f").autoFocusFrameLimit[0]),Ve(this,bs,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Ve(this,bs,"f").autoFocusFrameLimit[1])){Ve(this,bs,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Ve(this,Es,"f").autoZoom){if(Ve(this,bs,"f").autoZoomInFrameArray.push(!1),Ve(this,bs,"f").autoZoomInFrameArray.splice(0,Ve(this,bs,"f").autoZoomInFrameArray.length-Ve(this,bs,"f").autoZoomInFrameLimit[0]),Ve(this,bs,"f").autoZoomOutFrameCount++,Ve(this,bs,"f").frameArrayInIdealZoom.push(!1),Ve(this,bs,"f").frameArrayInIdealZoom.splice(0,Ve(this,bs,"f").frameArrayInIdealZoom.length-Ve(this,bs,"f").frameLimitInIdealZoom[0]),Ve(this,bs,"f").autoZoomOutFrameCount>=Ve(this,bs,"f").autoZoomOutFrameLimit){Ve(this,bs,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*Ve(this,bs,"f").autoZoomOutStepRate,Ve(this,bs,"f").autoZoomOutMinStep);r=Math.max(Ve(this,bs,"f").minValue,r),r=Math.min(Ve(this,bs,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ve(this,Es,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Ve(this,Es,"f").autoZoom&&Ve(this,Es,"f").enhancedFocus&&(Ve(this,bs,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},We(this,Ts,new Ls(1e4),"f")}setCameraView(t){if(!(t instanceof Pr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Ve(this,ls,"m",Is).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Ve(this,ls,"m",Is).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Ve(this,ls,"m",Is).call(this)?Ve(this,ds,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Ve(this,ls,"m",Is).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Ve(this,ls,"m",Is).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,r=t.getUIElement();if(r=r.shadowRoot||r,i=r.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=r.elTorchAuto=r.querySelector(".dce-mn-torch-auto"),e=r.elTorchOn=r.querySelector(".dce-mn-torch-on"),n=r.elTorchOff=r.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),n&&(n.style.display=0==this.isTorchOn?"":"none");let s=r.elBeepOn=r.querySelector(".dce-mn-beep-on"),o=r.elBeepOff=r.querySelector(".dce-mn-beep-off");s&&(s.style.display=Ds.allowBeep?"":"none"),o&&(o.style.display=Ds.allowBeep?"none":"");let a=r.elVibrateOn=r.querySelector(".dce-mn-vibrate-on"),h=r.elVibrateOff=r.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=Ds.allowVibrate?"":"none"),h&&(h.style.display=Ds.allowVibrate?"none":""),r.elResolutionBox=r.querySelector(".dce-mn-resolution-box");let l,c=r.elZoom=r.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=r.elZoomSpan=c.querySelector("span"));let u=r.elToast=r.querySelector(".dce-mn-toast"),d=r.elCameraClose=r.querySelector(".dce-mn-camera-close"),f=r.elTakePhoto=r.querySelector(".dce-mn-take-photo"),g=r.elCameraSwitch=r.querySelector(".dce-mn-camera-switch"),m=r.elCameraAndResolutionSettings=r.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=r.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==n||n.addEventListener("pointerdown",y);const w=()=>{Ds.allowBeep=!Ds.allowBeep,s&&(s.style.display=Ds.allowBeep?"":"none"),o&&(o.style.display=Ds.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{Ds.allowVibrate=!Ds.allowVibrate,a&&(a.style.display=Ds.allowVibrate?"":"none"),h&&(h.style.display=Ds.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),r=parseInt(e.getAttribute("data-height")),n=await this.setResolution({width:i,height:r});{let e=Math.max(n.width,n.height),i=Math.min(n.width,n.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&S(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};r.addEventListener("click",E);let b=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout((()=>{c.style.display="none",b=null}),e))};let T=null,S=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const A=()=>{var t,e;let i,r=this.getVideoSettings(),n=r.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==n?void 0:n.ideal)||(null==n?void 0:n.exact)||n)),r.video.facingMode={ideal:i?"environment":"user"},delete r.video.deviceId,this.updateVideoSettings(r)};null==g||g.addEventListener("pointerdown",A);let O=-1/0,R=1;const L=t=>{let e=Date.now();e-O>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),O=e};i.addEventListener("wheel",L);const D=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],r=t.touches[1],n=D.get(i.identifier),s=D.get(r.identifier);if(!n||!s)break;let o=Math.pow(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-r.clientX,2)+Math.pow(i.clientY-r.clientY,2),.5),h=Date.now();if(M||h-O<100)return;h-O>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==Ue?void 0:Ue.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&S("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,O=Date.now();break}D.clear();for(let e of t.touches)D.set(e.identifier,{x:e.clientX,y:e.clientY})};r.addEventListener("touchstart",F),r.addEventListener("touchmove",F),r.addEventListener("touchend",F),r.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==n||n.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);r.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",A),i.removeEventListener("wheel",L),r.removeEventListener("touchstart",F),r.removeEventListener("touchmove",F),r.removeEventListener("touchend",F),r.removeEventListener("touchcancel",F),delete r.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const n=this.getResolution();e.width=n.width,e.height=n.height,e.deviceId=this.getSelectedCamera().deviceId}return We(this,ds,"open","f"),t&&(t._innerComponent.style.display="",Ve(this,ls,"m",Is).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Ve(this,fs,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Ve(this,ls,"m",Is).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}We(this,ds,"closed","f"),Ve(this,Ts,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ve(this,ls,"m",Is).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ve(this,fs,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ve(this,ls,"m",Is).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ve(this,ls,"m",Is).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ve(this,ls,"m",Is).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),r=this.cameraView;return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ve(this,fs,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ve(this,fs,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Ve(this,ls,"m",Is).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,s;if(e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(n.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){console.log(`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(t=null==e?void 0:e.dceMnFs)||void 0===t||t.funcShowToast("Torch Auto On")}catch(t){console.error(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(s,t),this.isTorchOn=void 0,s();let o=this.cameraView.getUIElement();o=o.shadowRoot||o,o.elTorchAuto&&(o.elTorchAuto.style.display=""),o.elTorchOn&&(o.elTorchOn.style.display="none"),o.elTorchOff&&(o.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ve(this,ls,"m",Is).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,r;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(r=null==e?void 0:e.dceMnFs)||void 0===r||r.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Ve(this,ls,"m",Is).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Ve(this,bs,"f").minValue=t.min,Ve(this,bs,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ve(this,bs,"f").minValue,max:Ve(this,bs,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ut.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==pt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ti.EF_ENHANCED_FOCUS&&(Ve(this,Es,"f").enhancedFocus=!0),t&ti.EF_AUTO_ZOOM&&(Ve(this,Es,"f").autoZoom=!0),t&ti.EF_TAP_TO_FOCUS&&(Ve(this,Es,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ti.EF_ENHANCED_FOCUS&&(Ve(this,Es,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&ti.EF_AUTO_ZOOM&&(Ve(this,Es,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&ti.EF_TAP_TO_FOCUS&&(Ve(this,Es,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ve(this,ls,"m",As).call(this)&&Ve(this,ls,"m",xs).call(this)||Ve(this,Ts,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!mi(t)&&!wi(t))throw TypeError("Invalid 'region'.");We(this,vs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Ve(this,vs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");We(this,_s,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ve(this,ls,"m",Is).call(this))}startFetching(){if(Ve(this,ls,"m",Is).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ve(this,ws,"f")||(We(this,ws,!0,"f"),Ve(this,ls,"m",Os).call(this))}stopFetching(){Ve(this,ws,"f")&&(ks._onLog&&ks._onLog("DCE: stop fetching loop: "+Date.now()),Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),We(this,ws,!1,"f"))}fetchImage(){if(Ve(this,ls,"m",Is).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Ei.convert(Ve(this,vs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=this.cameraManager.getFrameData({position:i,pixelFormat:Ms.get(this.getPixelFormat())});if(!n)return null;let s;s=n.pixelFormat===zr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:Fs.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Et.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:Ve(this,ps,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ve(this,ws,"f")&&(Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),We(this,Cs,setTimeout((()=>{this.disposed||Ve(this,ls,"m",Os).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){We(this,ys,t,"f")}getPixelFormat(){return Ve(this,ys,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ve(this,ls,"m",Is).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=Ei.convert(Ve(this,vs,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=Ve(this,ms,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ve(this,ls,"m",Rs).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ve(this,ls,"m",Rs).call(this,t);return{x:e.clientX,y:e.clientY}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}function Bs(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Ns(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}cs=ks,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,Es=new WeakMap,bs=new WeakMap,Ts=new WeakMap,Ss=new WeakMap,ls=new WeakSet,Is=function(){return"disabled"!==this.singleFrameMode},xs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},As=function(){for(let t in Ve(this,Es,"f"))if(1==Ve(this,Es,"f")[t])return!0;return!1},Os=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ve(this,ws,"f"))return Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),void We(this,Cs,setTimeout((()=>{this.disposed||Ve(this,ls,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;ks._onLog&&ks._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Ve(this,_s,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Ve(this,_s,"f"))||void 0===t||t.onErrorReceived(yt.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),ks._onLog&&ks._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ve(this,fs,"f").fire("frameAddedToBuffer",null,{async:!1})):ks._onLog&&ks._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case i.BOPM_BLOCK:break;case i.BOPM_UPDATE:e()}else e();Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),We(this,Cs,setTimeout((()=>{this.disposed||Ve(this,ls,"m",t).call(this)}),this.fetchInterval),"f")},Rs=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ve(this,ls,"m",Is).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ve(this,ls,"m",Is).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ve(this,ls,"m",Is).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)ut+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return js.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return js.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return js.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Us,Gs,Vs,Ws,Ys,Hs,Xs,zs,Zs,Ks,qs,Js,Qs,$s,to,eo,io,ro;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Us||(Us={}));class no{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Ns(no,Gs,!1,"f",Vs),!1):(Ns(no,Gs,!0,"f",Vs),!0)}get disposed(){return Bs(this,Zs,"f")}constructor(){Ws.set(this,Us.RGBA),Ys.set(this,null),Hs.set(this,null),Xs.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,zs.set(this,null),Zs.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Bs(no,Gs,"f",Vs)&&no.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Bs(no,Gs,"f",Vs))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;no._onLog&&(o=Date.now(),no._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=Us.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Bs(no,Gs,"f",Vs)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){no._onLog&&no._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Ns(this,Hs,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Ns(this,Xs,e(t),"f"),Ns(this,Ys,i(t),"f"),Ns(this,Ws,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Us.GREY,Us.GREY32].includes(p)?1:0);let m,_,v=js.translate(js.identity(),-1,-1);v=js.scale(v,2,2),v=js.scale(v,1/t.canvas.width,1/t.canvas.height),m=js.translate(v,u,d),m=js.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=js.translate(js.identity(),a/i,h/r),_=js.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Bs(this,Ys,"f"),e),v(t,Bs(this,Hs,"f"),Bs(this,Xs,"f"),Bs(this,Ys,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){no._onLog&&no._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return no._onLog&&no._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Us.GREY?Us.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return no._onLog&&no._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(no._onLog&&(n=Date.now(),no._onLog("transformPixelFormat(), START: "+n)),e===i)return no._onLog&&no._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[Us.RGBA,Us.RBGA,Us.GRBA,Us.GBRA,Us.BRGA,Us.BGRA];if(o.includes(e))if(i===Us.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;no._onLog&&(s=Date.now(),no._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=Us.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Bs(no,Gs,"f",Vs)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){no._onLog&&no._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===Us.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{var e;if(!this.isUseMagnifier)return;if(Ve(this,$s,"f")||We(this,$s,new so,"f"),!Ve(this,$s,"f").magnifierCanvas)return;document.body.contains(Ve(this,$s,"f").magnifierCanvas)||(Ve(this,$s,"f").magnifierCanvas.style.position="fixed",Ve(this,$s,"f").magnifierCanvas.style.boxSizing="content-box",Ve(this,$s,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ve(this,$s,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Ve(this,eo,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];Ve(this,$s,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Ve(this,$s,"f").magnifierCanvas.style.left="auto",Ve(this,$s,"f").magnifierCanvas.style.top="0",Ve(this,$s,"f").magnifierCanvas.style.right="0"):(Ve(this,$s,"f").magnifierCanvas.style.left="0",Ve(this,$s,"f").magnifierCanvas.style.top="0",Ve(this,$s,"f").magnifierCanvas.style.right="auto")}Ve(this,$s,"f").show()})),eo.set(this,(()=>{Ve(this,$s,"f")&&Ve(this,$s,"f").hide()})),io.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Oi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=new Fr,e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(gi(t)){We(this,Qs,t,"f");const{width:e,height:i,bytes:r,format:s}=Object.assign({},t);let o;if(s===n.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!ao&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),lo=t=>{if(null==t&&(t="./"),ao);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};dt.dbr={version:"10.4.20",path:ho},ft.dbr={js:!1,wasm:!0,deps:["license","dip"]},ut.dbr={};const co="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,co)<0&&(dt.std={version:co,path:lo(ho+`../../dynamsoft-capture-vision-std@${co}/dist/`)});const uo="2.4.20";(!dt.dip||"string"!=typeof dt.dip&&S(dt.dip.version,uo)<0)&&(dt.dip={version:uo,path:lo(ho+`../../dynamsoft-image-processing@${uo}/dist/`)});let fo=class{static getVersion(){const t=ct.dbr&&ct.dbr.wasm;return`10.4.20(Worker: ${ct.dbr&&ct.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const go={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var mo,po,_o,vo;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(mo||(mo={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(po||(po={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP"}(_o||(_o={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(vo||(vo={}));const yo=async t=>{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class wo{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const r=D(t);return A(r,e,i)}async drawOnImage(t,e,i,r=4294901760,n=1,s){let o;if(t instanceof Blob)o=await yo(t);else if("string"==typeof t){let e=await b(t,"blob");o=await yo(e)}return await new Promise(((t,a)=>{let h=nt();st[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},it.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}}const Co="undefined"==typeof self,Eo=(()=>{if(!Co&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),bo=t=>{if(null==t&&(t="./"),Co);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};dt.utility={version:"1.4.20",path:Eo},ft.utility={js:!0,wasm:!0};const To="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,To)<0&&(dt.std={version:To,path:bo(Eo+`../../dynamsoft-capture-vision-std@${To}/dist/`)});const So="2.4.20";(!dt.dip||"string"!=typeof dt.dip&&S(dt.dip.version,So)<0)&&(dt.dip={version:So,path:bo(Eo+`../../dynamsoft-image-processing@${So}/dist/`)});class Io{static getVersion(){return`1.4.20(Worker: ${ct.utility&&ct.utility.worker||"Not Loaded"}, Wasm: ${ct.utility&&ct.utility.wasm||"Not Loaded"})`}}function xo(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}var Ao,Oo,Ro;"function"==typeof SuppressedError&&SuppressedError;const Lo={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Do=t=>Object.values(Lo).includes(t)||Lo.hasOwnProperty(t),Mo=(t,e)=>"string"==typeof t?e[Lo[t]]:e[t],Fo=(t,e,i)=>{"string"==typeof t?e[Lo[t]]=i:e[t]=i},Po=(t,e,i)=>{if(t.isResultCrossVerificationEnabled(i))for(let t=0;t{Fo(e,this.verificationEnabled,t)})),xo(this,Oo,"f").forEach(((t,e)=>{Fo(e,this.duplicateFilterEnabled,t)})),xo(this,Ro,"f").forEach(((t,e)=>{Fo(e,this.duplicateForgetTime,t)}))}enableResultCrossVerification(t,e){Do(t)&&xo(this,Ao,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Do(t)&&Mo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Do(t)&&xo(this,Oo,"f").set(t,e)}isResultDeduplicationEnabled(t){return!!Do(t)&&Mo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Do(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),xo(this,Ro,"f").set(t,e))}getDuplicateForgetTime(t){return Do(t)?Mo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){}getMaxOverlappingFrames(t){}enableLatestOverlapping(t,e){Do(t)&&Fo(t,this.latestOverlappingEnabled,e)}isLatestOverlappingEnabled(t){return!!Do(t)&&Mo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[_t.CRIT_BARCODE,_t.CRIT_TEXT_LINE,_t.CRIT_DETECTED_QUAD,_t.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(!s&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),a=t=>{if(null==t&&(t="./"),s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},h=t=>Object.prototype.toString.call(t),l=t=>Array.isArray?Array.isArray(t):"[object Array]"===h(t),c=t=>"[object Boolean]"===h(t),u=t=>"number"==typeof t&&!Number.isNaN(t),d=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),f=t=>!(!d(t)||!u(t.x)||!u(t.y)||!u(t.radius)||t.radius<0||!u(t.startAngle)||!u(t.endAngle)),g=t=>!!d(t)&&!!l(t.points)&&0!=t.points.length&&!t.points.some((t=>!y(t))),m=t=>!(!d(t)||!(t.bytes instanceof Uint8Array)||!u(t.width)||t.width<=0||!u(t.height)||t.height<=0||!u(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!_(t.tag)),p=t=>!(!d(t)||!u(t.left)||t.left<0||!u(t.top)||t.top<0||!u(t.right)||t.right<0||!u(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!c(t.isMeasuredInPercentage)),_=t=>!!d(t)&&!!u(t.imageId)&&"type"in t,v=t=>!(!d(t)||!y(t.startPoint)||!y(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),y=t=>!!d(t)&&!!u(t.x)&&!!u(t.y),w=t=>!!d(t)&&!!l(t.points)&&0!=t.points.length&&!t.points.some((t=>!y(t))),C=t=>!!d(t)&&!!l(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!y(t))),E=t=>!(!d(t)||!u(t.x)||!u(t.y)||!u(t.width)||t.width<0||!u(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!c(t.isMeasuredInPercentage));async function b(t,e){return await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(t+" "+n.status):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}}))}function T(t){return/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t)}const S=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t{const i={};for(let r in e){const n=r;let s=t[n];s&&"string"!=typeof s&&s.path&&(s=s.path),t.rootDirectory&&!t.rootDirectory.endsWith("/")&&(t.rootDirectory=t.rootDirectory+"/"),void 0===s?t.rootDirectory?s=`${t.rootDirectory}${x[n]}@${e[n].version}/dist/`:(s=e[n].path,s||(s=e[n])):s.startsWith("@engineRootDirectory/")&&(s=s.replace("@engineRootDirectory/",t.rootDirectory)),i[n]=a(s)}return i},x={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer"},A=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await L(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),O=t=>{m(t)&&(t=D(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},R=(t,e)=>{m(e)&&(e=D(e));const i=O(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r},L=async(t,e)=>{m(e)&&(e=D(e));const i=O(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},D=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===n.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===n.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r=t(this,P,"f"))switch(t(this,k,"f")){case i.BOPM_BLOCK:break;case i.BOPM_UPDATE:if(t(this,F,"f").push(e),d(t(this,N,"f"))&&u(t(this,N,"f").imageId)&&1==t(this,N,"f").keepInBuffer)for(;t(this,F,"f").length>t(this,P,"f");){const e=t(this,F,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)!==t(this,N,"f").imageId}));t(this,F,"f").splice(e,1)}else t(this,F,"f").splice(0,t(this,F,"f").length-t(this,P,"f"))}else t(this,F,"f").push(e)}getImage(){if(0===t(this,F,"f").length)return null;let e;if(t(this,N,"f")&&u(t(this,N,"f").imageId)){const i=t(this,M,"m",U).call(this,t(this,N,"f").imageId);if(i<0)throw new Error(`Image with id ${t(this,N,"f").imageId} doesn't exist.`);e=t(this,F,"f").slice(i,i+1)[0]}else e=t(this,F,"f").pop();if([n.IPF_RGB_565,n.IPF_RGB_555,n.IPF_RGB_888,n.IPF_ARGB_8888,n.IPF_RGB_161616,n.IPF_ARGB_16161616,n.IPF_ABGR_8888,n.IPF_ABGR_16161616,n.IPF_BGR_888].includes(e.format)){if(t(this,j,"f")===r.CCUT_RGB_R_CHANNEL_ONLY){s._onLog&&s._onLog("only get R channel data.");const t=new Uint8Array(e.width*e.height);for(let i=0;i0!==t.length&&t.every((t=>u(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==i&&!c(i))throw new TypeError("Invalid 'keepInBuffer'.");e(this,N,{imageId:t,keepInBuffer:i},"f")}_resetNextReturnedImage(){e(this,N,null,"f")}hasImage(e){return t(this,M,"m",U).call(this,e)>=0}startFetching(){e(this,B,!0,"f")}stopFetching(){e(this,B,!1,"f")}setMaxImageCount(i){if("number"!=typeof i)throw new TypeError("Invalid 'count'.");if(i<1||Math.round(i)!==i)throw new Error("Invalid 'count'.");for(e(this,P,i,"f");t(this,F,"f")&&t(this,F,"f").length>i;)t(this,F,"f").shift()}getMaxImageCount(){return t(this,P,"f")}getImageCount(){return t(this,F,"f").length}clearBuffer(){t(this,F,"f").length=0}isBufferEmpty(){return 0===t(this,F,"f").length}setBufferOverflowProtectionMode(t){e(this,k,t,"f")}getBufferOverflowProtectionMode(){return t(this,k,"f")}setColourChannelUsageType(t){e(this,j,t,"f")}getColourChannelUsageType(){return t(this,j,"f")}};F=new WeakMap,P=new WeakMap,k=new WeakMap,B=new WeakMap,N=new WeakMap,j=new WeakMap,M=new WeakSet,U=function(e){if("number"!=typeof e)throw new TypeError("Invalid 'imageId'.");return t(this,F,"f").findIndex((t=>{var i;return(null===(i=t.tag)||void 0===i?void 0:i.imageId)===e}))};const V=t=>t&&"object"==typeof t&&"function"==typeof t.then;let W,Y,H,X,z,Z=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,V(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(V(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};"undefined"!=typeof navigator&&(W=navigator,Y=W.userAgent,H=W.platform,X=W.mediaDevices),function(){if(!s){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:W.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:H,search:"Win"},Mac:{str:H},Linux:{str:H}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Y,o=n.search||e,a=n.verStr||Y,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Y,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Y.indexOf("Windows NT")&&(n="HarmonyOS"),z={browser:i,version:r,OS:n}}s&&(z={browser:"ssr",version:0,OS:"ssr"})}();const q="undefined"!=typeof WebAssembly&&Y&&!(/Safari/.test(Y)&&!/Chrome/.test(Y)&&/\(.+\s11_2_([2-6]).*\)/.test(Y)),K=!("undefined"==typeof Worker),J=!(!X||!X.getUserMedia),Q=async()=>{let t=!1;if(J)try{(await X.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===z.browser&&z.version>66||"Safari"===z.browser&&z.version>13||"OPR"===z.browser&&z.version>43||"Edge"===z.browser&&z.version;const $={},tt=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push($[t]=$[t]||new Z);await Promise.all(i)},et=async(t,e)=>{let i,r="string"==typeof t?[t]:t,n=[];for(let t of r){let r;n.push(r=$[t]=$[t]||new Z(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(n)};let it,rt=0;const nt=()=>rt++,st={};let ot;const at=t=>{ot=t,it&&it.postMessage({type:"setBLog",body:{value:!!t}})};let ht=!1;const lt=t=>{ht=t,it&&it.postMessage({type:"setBDebug",body:{value:!!t}})},ct={},ut={},dt={std:{version:"1.4.10",path:a(o+"../../dynamsoft-capture-vision-std@1.4.10/dist/")},core:{version:"3.4.21",path:o}},ft={dip:{wasm:!0}},gt={},mt=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=$.core;e=!i||i.isEmpty;let r=new Map;const n=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!ft[t])throw Error("The '"+t+"' module cannot be found.");let e=ft[t].deps;if(null==e?void 0:e.length)for(let t of e)n(t);let i=$[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)n(e);let s=[];e&&s.push("core"),s.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await et(s,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await tt(o);const i=I(gt,dt),n={};for(let e of t)n[e]=ft[e];const s={engineResourcePaths:i,autoResources:n,names:t};let a=new Z;if(e){s.needLoadCore=!0;let t=i.core+pt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),it=new Worker(t),it.onerror=t=>{let e=new Error(t.message);a.reject(e)},it.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":ot&&ot(e.message);break;case"task":try{st[r](n),delete st[r]}catch(t){throw delete st[r],t}break;case"event":try{st[r](n)}catch(t){throw t}break;default:console.log(t)}})),s.bLog=!!ot,s.bd=ht,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await tt("core");let h=rt++;st[h]=t=>{if(t.success)Object.assign(ct,t.versions),"{}"!==JSON.stringify(t.versions)&&(pt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},it.postMessage({type:"loadWasm",body:s,id:h}),await a}))};class pt{static get engineResourcePaths(){return gt}static set engineResourcePaths(t){Object.assign(gt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return ot}static set _onLog(t){at(t)}static get _bDebug(){return ht}static set _bDebug(t){lt(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!$[t]&&$[t].isFulfilled}static async loadWasm(t){return await mt(t)}static async detectEnvironment(){return await(async()=>({wasm:q,worker:K,getUserMedia:J,camera:await Q(),browser:z.browser,version:z.version,OS:z.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.21(Worker: ${ct.core&&ct.core.worker||"Not Loaded"}, Wasm: ${ct.core&&ct.core.wasm||"Not Loaded"})`}static enableLogging(){G._onLog=console.log,pt._onLog=console.log}static disableLogging(){G._onLog=null,pt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var _t,vt,yt,wt,Ct,Et,bt,Tt;pt._bSupportDce4Module=-1,pt._bSupportIRTModule=-1,pt._versions=null,pt._workerName="core.worker.js",pt.browserInfo=z,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(_t||(_t={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(vt||(vt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(yt||(yt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(wt||(wt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(Ct||(Ct={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(Et||(Et={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(bt||(bt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(Tt||(Tt={}));const St={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var It,xt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(It||(It={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(xt||(xt={}));let At="./";if(document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}At=t.substring(0,t.lastIndexOf("/")+1)}pt.engineResourcePaths={rootDirectory:(t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t})(At+"../../")};const Ot="undefined"==typeof self,Rt=Ot?{}:self,Lt=(()=>{if(!Ot&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),Dt=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Mt=class extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Dt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Dt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ft=" is not allowed to change after `createInstance` or `loadWasm` is called.",Pt=!Ot&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",kt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ft);i._license=e}};!Ot&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Bt=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Bt(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ft);i._licenseServer=e}},jt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ft);i._deviceFriendlyName=e}};let Ut,Gt,Vt,Wt,Yt;"undefined"!=typeof navigator&&(Ut=navigator,Gt=Ut.userAgent,Vt=Ut.platform,Wt=Ut.mediaDevices),function(){if(!Ot){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ut.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Vt,search:"Win"},Mac:{str:Vt},Linux:{str:Vt}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Gt,o=n.search||e,a=n.verStr||Gt,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Gt,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Gt.indexOf("Windows NT")&&(n="HarmonyOS"),Yt={browser:i,version:r,OS:n}}Ot&&(Yt={browser:"ssr",version:0,OS:"ssr"})}(),Wt&&Wt.getUserMedia,"Chrome"===Yt.browser&&Yt.version>66||"Safari"===Yt.browser&&Yt.version>13||"OPR"===Yt.browser&&Yt.version>43||"Edge"===Yt.browser&&Yt.version;const Ht=()=>(mt("license"),et("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=zt;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Bt(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Rt.crypto||(s="Please upgrade your browser to support online key."),Rt.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==l)throw new Error(s);l=0,console.warn(s),i._lastErrorCode=-1,i._lastErrorString=s}return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Ft)})(),o=new Mt;zt._pLoad.task=o,(async()=>{try{await zt._pLoad}catch(t){}})();let a=nt();st[a]=e=>{if(e.message&&zt._onAuthMessage){let t=zt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(ot&&ot("init license success"),e.message&&console.warn(e.message),pt._bSupportIRTModule=e.bSupportIRTModule,pt._bSupportDce4Module=e.bSupportDce4Module,zt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){const t=I(pt.engineResourcePaths,dt);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:zt._bNeverShowDialog,engineResourcePath:t.license,_onLog:ot},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await tt("core"),it.postMessage({type:"license_dynamsoft",body:{v:"3.4.21",brtk:!!t,bptk:1===t,l:e,os:Yt,fn:zt.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),zt.bCallInitLicense=!0,await o})));let Xt;ut.license={},ut.license.dynamsoft=Ht,ut.license.getAR=async()=>{{let t=$.dynamsoft_inited;t&&t.isRejected&&await t}return it?new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success){delete i.success;{let t=zt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},it.postMessage({type:"license_getAR",id:i})})):null};let zt=class t{static setLicenseServer(e){Nt(t,e)}static get license(){return this._license}static set license(e){kt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Nt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){jt(t,e)}static initLicense(e,i){if(kt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Ht()}static setDeviceFriendlyName(e){jt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await et("dynamsoft_uuid",(async()=>{await mt();let t=new Mt,e=nt();st[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},it.postMessage({type:"license_getDeviceUUID",id:e}),Xt=await t})),Xt))()}};zt._pLoad=new Mt,zt.bPassValidation=!1,zt.bCallInitLicense=!1,zt._license=Pt,zt._licenseServer=[],zt._deviceFriendlyName="",dt.license={version:"3.4.21",path:Lt},ft.license={wasm:!0,js:!0},ut.license.LicenseManager=zt;const Zt="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,Zt)<0&&(dt.std={version:Zt,path:(t=>{if(null==t&&(t="./"),Ot);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Lt+`../../dynamsoft-capture-vision-std@${Zt}/dist/`)});let qt=class{static getVersion(){return`3.4.21(Worker: ${ct.license&&ct.license.worker||"Not Loaded"}, Wasm: ${ct.license&&ct.license.wasm||"Not Loaded"})`}};function Kt(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Jt(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Qt=t=>t&&"object"==typeof t&&"function"==typeof t.then;class $t extends Promise{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Qt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Qt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class te{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ee={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1};const ie=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class re{constructor(t){this._irrRegistryState=ee,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ie(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=nt();st[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},it.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ie(this),await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const ne="undefined"==typeof self,se=(()=>{if(!ne&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),oe=t=>{if(null==t&&(t="./"),ne);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ae;dt.cvr={version:"2.4.22",path:se},ft.cvr={js:!0,wasm:!0,deps:["license","dip"]},ut.cvr={};const he="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,he)<0&&(dt.std={version:he,path:oe(se+`../../dynamsoft-capture-vision-std@${he}/dist/`)});const le="2.4.20";(!dt.dip||"string"!=typeof dt.dip&&S(dt.dip.version,le)<0)&&(dt.dip={version:le,path:oe(se+`../../dynamsoft-image-processing@${le}/dist/`)});class ce{static getVersion(){return this._version}}var ue,de,fe,ge,me,pe,_e,ve,ye,we,Ce,Ee,be;function Te(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Te(t.referencedItem,e)}}function Se(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}ce._version=`2.4.22(Worker: ${null===(ae=ct.cvr)||void 0===ae?void 0:ae.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ue||(ue={})),BigInt(0),BigInt(1),BigInt(2),BigInt(4),BigInt(8),BigInt(16),BigInt(32),BigInt(64),BigInt(128),BigInt(256),BigInt(512),BigInt(1024),BigInt(2048),BigInt(4096),BigInt(8192),BigInt(16384),BigInt(32768),BigInt(65536),BigInt(1<<17),BigInt(1<<18),BigInt(1<<19),BigInt(1<<20),BigInt(1<<21),BigInt(1<<22),BigInt(1<<23),BigInt(1<<24),BigInt(1<<25),BigInt(1<<26),BigInt(1<<27),BigInt(1<<28),BigInt("0xFFFFFFFFFFFFFFFF");const Ie={onTaskResultsReceived:()=>{},isFilter:!0};class xe{constructor(){this.maxCvsSideLength=["iPhone","Android","HarmonyOS"].includes(pt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,de.set(this,null),fe.set(this,null),ge.set(this,null),me.set(this,null),pe.set(this,null),_e.set(this,new Set),ve.set(this,new Set),ye.set(this,new Set),we.set(this,0),Ce.set(this,!1),Ee.set(this,!1),be.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Kt(this,be,"f")}static async createInstance(){if(!ut.license)throw Error("Module `license` is not existed.");await ut.license.dynamsoft(),await mt(["cvr"]);const t=new xe,e=new $t;let i=nt();return st[i]=async i=>{var r;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(i.outputSettings),ce._version=`2.4.22(Worker: ${null===(r=ct.cvr)||void 0===r?void 0:r.worker}, Wasm: ${i.version})`,Jt(t,Ee,!0,"f"),Jt(t,me,t.getIntermediateResultManager(),"f"),Jt(t,Ee,!1,"f"),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},it.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of Kt(this,_e,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of Kt(this,_e,"f"))t.isDce&&t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of Kt(this,_e,"f"))if(e.onDecodedBarcodesReceived&&i.barcodeResultItems&&e.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems})),e.onRecognizedTextLinesReceived&&i.textLineResultItems&&e.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems})),e.onDetectedQuadsReceived&&i.detectedQuadResultItems&&e.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems})),e.onNormalizedImagesReceived&&i.normalizedImageResultItems&&e.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems})),e.onParsedResultsReceived&&i.parsedResultItems&&e.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems})),e.onCapturedResultReceived&&!e.isDce){if(this._isOutputOriginalImage){const e=i.items.findIndex((t=>1===t.type));-1!==e&&(i.items[e].imageData=t)}e.onCapturedResultReceived(i)}}setInput(t){if(Se(this),t){if(Jt(this,de,t,"f"),t.isCameraEnhancer){Kt(this,me,"f")&&(Kt(this,de,"f")._intermediateResultReceiver.isDce=!0,Kt(this,me,"f").addResultReceiver(Kt(this,de,"f")._intermediateResultReceiver));const t=Kt(this,de,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Kt(this,_e,"f").add(e)}}}else Jt(this,de,null,"f")}getInput(){return Kt(this,de,"f")}addImageSourceStateListener(t){if(Se(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Kt(this,ve,"f").add(t)}removeImageSourceStateListener(t){return Se(this),Kt(this,ve,"f").delete(t)}addResultReceiver(t){if(Se(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Kt(this,_e,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Se(this),Kt(this,_e,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of Kt(this,_e,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new $t;let i=nt();return st[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},it.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Se(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Kt(this,ye,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Se(this),Kt(this,ye,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Kt(this,me,"f").removeResultReceiver(Ie),0===Kt(this,ye,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[_t.CRIT_BARCODE]:!1,[_t.CRIT_TEXT_LINE]:!1,[_t.CRIT_DETECTED_QUAD]:!1,[_t.CRIT_NORMALIZED_IMAGE]:!1},e={[_t.CRIT_BARCODE]:!1,[_t.CRIT_TEXT_LINE]:!1,[_t.CRIT_DETECTED_QUAD]:!1,[_t.CRIT_NORMALIZED_IMAGE]:!1};return await Ae(this,t),void await Oe(this,e)}for(let t of Kt(this,ye,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(_t.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(_t.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(_t.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(_t.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(_t.CRIT_BARCODE)){[...Kt(this,me,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||Kt(this,me,"f").addResultReceiver(Ie)}await Ae(this,t.verificationEnabled),await Oe(this,t.duplicateFilterEnabled),await Re(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Se(this),!this._isPauseScan)return;if(!Kt(this,de,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const s=await this.containsTask(t);await mt(s);for(let t of Kt(this,ye,"f"))await this.addResultFilter(t);if(s.includes("dlr")&&!(null===(e=ut.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=I(pt.engineResourcePaths,dt);await(null===(i=ut.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(Kt(this,de,"f").isCameraEnhancer&&(s.includes("ddn")?Kt(this,de,"f").setPixelFormat(n.IPF_ABGR_8888):Kt(this,de,"f").setPixelFormat(n.IPF_GRAYSCALED)),void 0!==Kt(this,de,"f").singleFrameMode&&"disabled"!==Kt(this,de,"f").singleFrameMode)return this._templateName=t,void Kt(this,de,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return Kt(this,de,"f").getColourChannelUsageType()===r.CCUT_AUTO&&Kt(this,de,"f").setColourChannelUsageType(s.includes("ddn")?r.CCUT_FULL_CHANNEL:r.CCUT_Y_CHANNEL_ONLY),Kt(this,ge,"f")&&Kt(this,ge,"f").isPending?Kt(this,ge,"f"):(Jt(this,ge,new $t(((e,i)=>{if(this.disposed)return;let r=nt();st[r]=async r=>{if(Kt(this,ge,"f")&&!Kt(this,ge,"f").isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=r.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&Kt(this,de,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},it.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),"f"),await Kt(this,ge,"f"))}stopCapturing(){Se(this),Kt(this,de,"f")&&(Kt(this,de,"f").isCameraEnhancer&&void 0!==Kt(this,de,"f").singleFrameMode&&"disabled"!==Kt(this,de,"f").singleFrameMode?Kt(this,de,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=nt();const i=new $t;st[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},it.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),Kt(this,de,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Jt(this,ge,null,"f"),Kt(this,de,"f").setColourChannelUsageType(r.CCUT_AUTO)))}async containsTask(t){return Se(this),await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(Jt(this,Ce,!0,"f"),Kt(this,de,"f").isBufferEmpty())if(Kt(this,de,"f").hasNextImageToFetch())for(let t of Kt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_BUFFER_EMPTY);else if(!Kt(this,de,"f").hasNextImageToFetch())for(let t of Kt(this,ve,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Kt(this,de,"f").isBufferEmpty())try{Kt(this,de,"f").isBufferEmpty()&&xe._onLog&&xe._onLog("buffer is empty so fetch image"),xe._onLog&&xe._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Kt(this,de,"f").fetchImage(),xe._onLog&&xe._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Kt(this,de,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(Kt(this,de,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Kt(this,de,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of Kt(this,_e,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(xe._onLog&&xe._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Kt(this,_e,"f")){if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),xe._onLog){const t=Date.now()-e;t>10&&xe._onLog(`draw result time: ${t}`)}}t.onDecodedBarcodesReceived&&i.barcodeResultItems&&t.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems.filter((t=>!t.isFilter))})),t.onRecognizedTextLinesReceived&&i.textLineResultItems&&t.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems.filter((t=>!t.isFilter))})),t.onDetectedQuadsReceived&&i.detectedQuadResultItems&&t.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems.filter((t=>!t.isFilter))})),t.onNormalizedImagesReceived&&i.normalizedImageResultItems&&t.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems.filter((t=>!t.isFilter))})),t.onParsedResultsReceived&&i.parsedResultItems&&t.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems.filter((t=>!t.isFilter))})),t.onCapturedResultReceived&&!t.isDce&&(i.items=i.items.filter((t=>!t.isFilter)),i.barcodeResultItems&&(i.barcodeResultItems=i.barcodeResultItems.filter((t=>!t.isFilter))),i.textLineResultItems&&(i.textLineResultItems=i.textLineResultItems.filter((t=>!t.isFilter))),i.detectedQuadResultItems&&(i.detectedQuadResultItems=i.detectedQuadResultItems.filter((t=>!t.isFilter))),i.normalizedImageResultItems&&(i.normalizedImageResultItems=i.normalizedImageResultItems.filter((t=>!t.isFilter))),i.parsedResultItems&&(i.parsedResultItems=i.parsedResultItems.filter((t=>!t.isFilter))),t.onCapturedResultReceived(i))}const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,xe._onLog&&(xe._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),xe._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),xe._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),xe._onLog(`averageTime: ${this._averageTime}`))),xe._onLog){const t=Date.now()-n;t>10&&xe._onLog(`fetch image calculate time: ${t}`)}xe._onLog&&xe._onLog(`time finish decode: ${Date.now()}`),xe._onLog&&xe._onLog("main time: "+(Date.now()-e)),xe._onLog&&xe._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{Kt(this,de,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{Kt(this,de,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;Se(this),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const n=await this.containsTask(e);if(await mt(n),n.includes("dlr")&&!(null===(i=ut.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=I(pt.engineResourcePaths,dt);await(null===(r=ut.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(Jt(this,Ce,!1,"f"),m(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await b(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,e){let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*Kt(this,we,"f")),r=Math.round(s*Kt(this,we,"f"))):(i=n,r=s),Kt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=Kt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxCvsSideLength?(Jt(this,we,this.maxCvsSideLength/o,"f"),i=Math.round(n*Kt(this,we,"f")),r=Math.round(s*Kt(this,we,"f"))):(i=n,r=s),Kt(this,fe,"f")||Jt(this,fe,document.createElement("canvas"),"f");const a=Kt(this,fe,"f");a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:r,height:n,stride:s,format:o}=t;let a=nt();const h=new $t;return st[a]=async e=>{var i,r;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const n=Date.now();xe._onLog&&(xe._onLog(`get result time from worker: ${n}`),xe._onLog("worker to main time consume: "+(n-e.workerReturnMsgTime)));try{const n=e.captureResult;if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,h.reject(t)}t.bytes=e.bytes;for(let e of n.items)0!==Kt(this,we,"f")&&Te(e,Kt(this,we,"f")),e.type===_t.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===_t.CRIT_NORMALIZED_IMAGE?null===(i=ut.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===_t.CRIT_PARSED_RESULT&&(null===(r=ut.dcp)||void 0===r||r.handleParsedResultItem(e));if(Kt(this,Ce,"f"))for(let t of Kt(this,ye,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onDetectedQuadsReceived(n),t.onNormalizedImagesReceived(n);const s=function(t){const e={barcodeResultItems:[],textLineResultItems:[],detectedQuadResultItems:[],normalizedImageResultItems:[],parsedResultItems:[]};return t.items.forEach((t=>{t.type===_t.CRIT_BARCODE?e.barcodeResultItems.push(t):t.type===_t.CRIT_TEXT_LINE?e.textLineResultItems.push(t):t.type===_t.CRIT_DETECTED_QUAD?e.detectedQuadResultItems.push(t):t.type===_t.CRIT_NORMALIZED_IMAGE?e.normalizedImageResultItems.push(t):t.type===_t.CRIT_PARSED_RESULT&&e.parsedResultItems.push(t)})),e}(n);if(s.barcodeResultItems.length&&(n.barcodeResultItems=s.barcodeResultItems),s.textLineResultItems.length&&(n.textLineResultItems=s.textLineResultItems),s.detectedQuadResultItems.length&&(n.detectedQuadResultItems=s.detectedQuadResultItems),s.normalizedImageResultItems.length&&(n.normalizedImageResultItems=s.normalizedImageResultItems),s.parsedResultItems.length&&(n.parsedResultItems=s.parsedResultItems),!this._isPauseScan||!Kt(this,Ce,"f")){const e=n.intermediateResult;if(e){let i=0;for(let r of Kt(this,me,"f")._intermediateResultReceiverSet){i++;for(let n of e){if("onTaskResultsReceived"===n.info.callbackName){for(let e of n.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);i===Kt(this,me,"f")._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}}return n&&n.hasOwnProperty("intermediateResult")&&delete n.intermediateResult,Jt(this,we,0,"f"),h.resolve(n)}catch(t){return h.reject(t)}}},xe._onLog&&xe._onLog(`send buffer to worker: ${Date.now()}`),it.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:r,height:n,stride:s,format:o,templateName:e||"",isScanner:Kt(this,Ce,"f")}},[i.buffer]),h}async initSettings(t){return Se(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?(t.startsWith("{")||(t=await b(t,"text")),this._currentSettings=JSON.parse(t)):"object"==typeof t&&(this._currentSettings=t,t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=nt();st[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.exception){let t=new Error(n.description?n.description:"Init Settings Failed.");return t.errorCode=n.exception,i(t)}let s=[],o=JSON.parse(t).CaptureVisionTemplates;for(let t=0;t{let r=nt();st[r]=async t=>{if(t.success){const r=JSON.parse(t.settings);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return delete r.errorCode,delete r.errorString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getSimplifiedSettings(t){Se(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await mt(e),await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success){const r=JSON.parse(t.settings,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));if(r.minImageCaptureInterval=this._minImageCaptureInterval,0!==r.code){let t=new Error(r.codeString);return t.errorCode=r.errorCode,i(t)}return delete r.code,delete r.codeString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Se(this);const i=await this.containsTask(t);return await mt(i),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==n.exception){let t=new Error(n.description?n.description:"Update Settings Failed.");return t.errorCode=n.exception,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Se(this),await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.exception){let t=new Error(r.description?r.description:"Reset Settings Failed.");return t.errorCode=r.exception,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return Kt(this,pe,"f")||Jt(this,pe,new te(this),"f"),Kt(this,pe,"f")}getIntermediateResultManager(){if(Se(this),!Kt(this,Ee,"f")&&0!==pt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Kt(this,me,"f")||Jt(this,me,new re(this),"f"),Kt(this,me,"f")}async parseRequiredResources(t){return Se(this),await new Promise(((e,i)=>{let r=nt();st[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},it.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Se(this),Kt(this,ge,"f")&&this.stopCapturing(),Jt(this,de,null,"f"),Kt(this,_e,"f").clear(),Kt(this,ve,"f").clear(),Kt(this,ye,"f").clear(),Kt(this,me,"f")._intermediateResultReceiverSet.clear(),Jt(this,be,!0,"f");let t=nt();st[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},it.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Kt(this,de,"f"),promiseStartScan:Kt(this,ge,"f"),intermediateResultManager:Kt(this,me,"f"),bufferdItemsManager:Kt(this,pe,"f"),resultReceiverSet:Kt(this,_e,"f"),isaStateListenerSet:Kt(this,ve,"f"),resultFilterSet:Kt(this,ye,"f"),compressRate:Kt(this,we,"f"),canvas:Kt(this,fe,"f"),isScanner:Kt(this,Ce,"f"),innerUseTag:Kt(this,Ee,"f"),isDestroyed:Kt(this,be,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=nt();st[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},it.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Ae(t,e){return Se(t),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function Oe(t,e){return Se(t),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Re(t,e){return Se(t),await new Promise(((i,r)=>{let n=nt();st[n]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},it.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,be=new WeakMap;class Le{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}class De{constructor(){this._observedResultUnitTypes=St.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}var Me;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Me||(Me={}));const Fe="undefined"==typeof self,Pe=(()=>{if(!Fe&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();dt.dce={version:"4.1.0",path:Pe},ft.dce={wasm:!1,js:!1},ut.dce={};let ke,Be,Ne,je,Ue,Ge=class{static getVersion(){return"4.1.0"}};function Ve(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function We(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(ke=navigator,Be=ke.userAgent,Ne=ke.platform,je=ke.mediaDevices),function(){if(!Fe){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:ke.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Ne,search:"Win"},Mac:{str:Ne},Linux:{str:Ne}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Be,o=n.search||e,a=n.verStr||Be,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Be,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Be.indexOf("Windows NT")&&(n="HarmonyOS"),Ue={browser:i,version:r,OS:n}}Fe&&(Ue={browser:"ssr",version:0,OS:"ssr"})}();const Ye="undefined"!=typeof WebAssembly&&Be&&!(/Safari/.test(Be)&&!/Chrome/.test(Be)&&/\(.+\s11_2_([2-6]).*\)/.test(Be)),He=!("undefined"==typeof Worker),Xe=!(!je||!je.getUserMedia),ze=async()=>{let t=!1;if(Xe)try{(await je.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===Ue.browser&&Ue.version>66||"Safari"===Ue.browser&&Ue.version>13||"OPR"===Ue.browser&&Ue.version>43||"Edge"===Ue.browser&&Ue.version;var Ze={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,b,T=T||{version:"5.2.1"};if(e.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var S=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=S.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=S,DOMParser=T.window.DOMParser}function I(t,e){var i=t.canvas,r=e.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:T.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}T.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof T.Gradient||this.set(e,new T.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof T.Pattern?i&&i():this.set(e,new T.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new T.Point(t.x-e.x,t.y-e.y),n=T.util.rotateVector(r,i);return new T.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),r=T.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new T.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new T.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=T.util.createVector(t,e),n=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(r,n),o=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(r,s),n)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new T.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new T.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(T.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(T.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=T.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new T.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new T.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var b=Math.sqrt(1-C/(_*v));i*=b,s*=b}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var S=E*i*p/s,I=-E*s*m/i,x=d*S-u*I+.5*t,A=u*S+d*I+.5*e,O=n(1,0,(m-S)/i,(p-I)/s),R=n((m-S)/i,(p-I)/s,(-m-S)/i,(-p-I)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var L=Math.ceil(Math.abs(R/l*2)),D=[],M=R/L,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=O+M,k=0;kE)for(var S=1,I=m.length;S2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(T.cachesBoundsOfCurve&&(l=t.call(arguments),T.boundsOfCurveCache[l]))return T.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],b=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var S=0;S<2;++S)if(S>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,A,O=E.length,R=O;O--;)I=(A=1-(f=E[O]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,b[0][O]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,b[1][O]=x;b[0][R]=e,b[1][R]=i,b[0][R+1]=a,b[1][R+1]=h;var L=[{x:y.apply(null,b[0]),y:y.apply(null,b[1])},{x:w.apply(null,b[0]),y:w.apply(null,b[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[l]=L),L},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},T.util.transformPath=function(t,e,i){return i&&(e=T.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),T.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(T.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=T.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=T.document.documentElement,n=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(t,e){var i=T.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=T.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=T.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},T.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},T.util.getById=function(t){return"string"==typeof t?T.document.getElementById(t):t},T.util.toArray=s,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=o,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},T.util.getNodeCanvas=function(t){var e=T.jsdomImplForWrapper(t);return e._canvas||e._image},T.util.cleanUpJsdomNode=function(t){if(T.isLikelyNode){var e=T.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}T.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new T.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}T.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},o=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=T.runningAnimations.indexOf(s);return t>-1&&T.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=n,!o){if(!f(w,C,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,n),void a(t));h()}}(l)})),s.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return o.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,r,n){var s=new T.Color(e).getSource(),o=new T.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},T.util.animate(T.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",b=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=n,C.viewBoxHeight=o,y?(C.width=n,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/n,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),b=C.width-n*c,T=C.height-o*c,"Mid"===p.alignX&&(b/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(b=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+b)+" "+(r*u+T)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function m(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function C(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function b(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),b(l,"skewY","scaleY","y",p)}return m}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),E(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),b(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,w=m(t,f),E=_(f,y,w),b=e.gestureScale;if(E)return!1;if(b)o=e.scaleX*b,a=e.scaleY*b;else{if(s=C(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),S=e.original,I=T/(Math.abs(h.x*S.scaleX/f.scaleX)+Math.abs(h.y*S.scaleY/f.scaleY));o=S.scaleX*I,a=S.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=w("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),E(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(T))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=C(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),E(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(S))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=w,n.getLocalPoint=C,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new T.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new T.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=m/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=T.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,m=-i.top),new T.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=T.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var t=T.util.object.extend,e=T.util.getElementOffset,i=T.util.removeFromArray,r=T.util.toFixed,n=T.util.transformPoint,s=T.util.invertTransform,o=T.util.getNodeCanvas,a=T.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=T.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?T.util.loadImage(e,(function(e,n){if(e){var s=new T.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=T.util.getById(t)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?T.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=T.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(T.StaticCanvas.prototype,T.Observable),t(T.StaticCanvas.prototype,T.Collection),t(T.StaticCanvas.prototype,T.DataURLExporter),t(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new T.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new T.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new T.Point(r.x,r.y),n=new T.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=T.util.invertTransform(i),n=this.restorePointerVpt(e);return T.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,T.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):T.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new T.Point(e.ex,e.ey),r=T.util.transformPoint(i,this.viewportTransform),n=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof T.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return T.util.transformPoint(t,T.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;T.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,T.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e,selected:n}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),T.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==r&&(T.Canvas[r]=T.StaticCanvas[r])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(T.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(T.document,t+"up",this._onMouseUp),e(T.document,"touchend",this._onTouchEnd,i),e(T.document,t+"move",this._onMouseMove,i),e(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new T.Point(v(r,s),v(n,o)),h=new T.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return T.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):T.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=T.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new T.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof n?n=E[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new T.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new T.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),n=new T.Point(t.x,t.y),this.angle&&(n=T.util.rotatePoint(n,s,-w(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=w(this.angle),n=this.getScaledWidth(),s=T.util.cos(r)*n,o=T.util.sin(r)*n;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=T.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===T.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+T.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=T.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=T.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=T.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?T.util.animateColor(h.startValue,h.endValue,h.duration,h):T.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return T.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);T.filterBackend||(T.filterBackend=T.initFilterBackend());var o=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,T.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=T.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(T.util.getById(t),e),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(t,e){var i=T.util.object.clone(t);T.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],T.util.enlivenObjectEnlivables(i,i,(function(){var r=new T.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,r){e&&e(new T.Image(t,i),r)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(t,i,r){var n=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(n["xlink:href"],i,e(r?T.util.object.clone(r):{},n))})}(e),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(e){if(T.isLikelyNode)return!1;e=e||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){T.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){T.webGlPrecision=s[o];break}}return this.isSupported=n,n},T.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}T.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=T.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(t,e){var i=new T.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,b||(n+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=r,E[s+3]=b?m[s+3]:n}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){D=r(1e3*s(T-C.x)),w[D]||(w[D]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-C.y)),w[D][M]||(w[D][M]=f(n(i(D*p,2)+i(M*_,2))/1e3)),(S=w[D][M])>0&&(x+=S,A+=S*c[I=4*(F*e+T)],O+=S*c[I+1],R+=S*c[I+2],L+=S*c[I+3]))}d[I=4*(b*a+h)]=A/x,d[I+1]=O/x,d[I+2]=R/x,d[I+3]=L/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(S+=y*f[3+(D=4*(L+x*e))],C+=y,f[D+3]<255&&(y=y*f[D+3]/250),E+=y*f[D],b+=y*f[D+1],T+=y*f[D+2],w+=y)}m[v]=E/w,m[v+1]=b/w,m[v+2]=T/w,m[v+3]=S/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),T.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);T.Object._fromObject("IText",e,i,"text")}}(),b=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],T.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=T.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=T.util.transformPoint(h,a),(h=T.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=b(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:b(r[i-1])}:n?this.styles[t+i]={0:b(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?b(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=b(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=b(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=T.util.toFixed,e=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},qe={};function Ke(t){var e=qe[t];if(void 0!==e)return e.exports;var i=qe[t]={exports:{}};return Ze[t](i,i.exports,Ke),i.exports}Ke.d=(t,e)=>{for(var i in e)Ke.o(e,i)&&!Ke.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},Ke.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Je={};(()=>{let t;Ke.d(Je,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?Ke(653).fabric:{version:"5.2.1"}})();var Qe,$e,ti,ei,ii=Je.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(Qe||(Qe={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}($e||($e={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(ti||(ti={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ei||(ei={}));const ri=t=>"number"==typeof t&&!Number.isNaN(t),ni=t=>"string"==typeof t;var si,oi,ai,hi,li,ci;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(li||(li={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(ci||(ci={}));let ui=class{get mediaType(){return new Map([["rect",Qe.DIMT_RECTANGLE],["quad",Qe.DIMT_QUADRILATERAL],["text",Qe.DIMT_TEXT],["arc",Qe.DIMT_ARC],["image",Qe.DIMT_IMAGE],["polygon",Qe.DIMT_POLYGON],["line",Qe.DIMT_LINE],["group",Qe.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ve(this,oi,"f")){case $e.DIS_DEFAULT:return"default";case $e.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Ve(this,ai,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ve(this,ai,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),We(this,ai,t,"f")}get coordinateBase(){return Ve(this,ai,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(si.add(this),oi.set(this,void 0),ai.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!ri(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState($e.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState($e.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState($e.DIS_SELECTED):this.setState($e.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){We(this,oi,t,"f")}getState(){return Ve(this,oi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)unull!==t&&"object"==typeof t&&!Array.isArray(t),fi=t=>!!ni(t)&&""!==t,gi=m,mi=p,pi=v,_i=w,vi=y,yi=C,wi=E,Ci=t=>!(!di(t)||"id"in t&&!ri(t.id)||"lineWidth"in t&&!ri(t.lineWidth)||"fillStyle"in t&&!fi(t.fillStyle)||"strokeStyle"in t&&!fi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!fi(t.fontFamily)||"fontSize"in t&&!ri(t.fontSize));class Ei{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(wi(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!mi(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var bi,Ti;class Si{constructor(){bi.set(this,new Map),Ti.set(this,!1)}get disposed(){return Ve(this,Ti,"f")}on(t,e){t=t.toLowerCase();const i=Ve(this,bi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ve(this,bi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ve(this,bi,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=Ve(this,bi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=Ve(this,bi,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){We(this,Ti,!0,"f")}}function Ii(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function xi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Ai(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}bi=new WeakMap,Ti=new WeakMap;const Oi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");if(r.insertAdjacentHTML("beforeend",i),1===r.childElementCount&&r.firstChild instanceof HTMLTemplateElement)return r.firstChild.content;const n=new DocumentFragment;for(let t of r.children)n.append(t);return n};var Ri,Li,Di,Mi,Fi;class Pi extends ui{constructor(t,e){if(super(null,e),Ri.set(this,void 0),!wi(t))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new ii.Rect({left:t.x,top:t.y,width:t.width,height:t.height})),We(this,Ri,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="rect"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth"))),this.set("height",this.convertPropFromViewToImage(this.get("scaledHeight")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth"))),this.set("height",this.convertPropFromImageToView(this.get("scaledHeight")))}setPosition(t){this.setRect(t)}getPosition(){return this.getRect()}updatePosition(){Ve(this,Ri,"f")&&this.setRect(Ve(this,Ri,"f"))}setRect(t){if(!wi(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width)),this.set("height",this.convertPropFromViewToImage(t.height));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width),this.set("height",t.height)}this._drawingLayer.renderAll()}else We(this,Ri,JSON.parse(JSON.stringify(t)),"f")}getRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Ri,"f")?JSON.parse(JSON.stringify(Ve(this,Ri,"f"))):null}}function ki(t,e,i){let r=i.points[this.pointIndex].x-i.pathOffset.x,n=i.points[this.pointIndex].y-i.pathOffset.y;return ii.util.transformPoint({x:r,y:n},i.calcTransformMatrix())}function Bi(t){let e=new ii.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new ii.Point(t.width+e.x,t.height+e.y)}function Ni(t,e,i,r){let n=e.target,s=n.controls[n.__corner],o=n.toLocalPoint(new ii.Point(i,r),"center","center"),a=Bi(n),h=n._getTransformedDimensions(0,0),l={x:o.x*a.x/h.x+n.pathOffset.x,y:o.y*a.y/h.y+n.pathOffset.y};return n.points[s.pointIndex]=l,ii.controlsUtils.fireEvent("scaling",{e:t,transform:e,pointer:{x:i,y:r}}),!0}function ji(t,e){return function(i,r,n,s){let o=r.target,a=ii.util.transformPoint({x:o.points[t].x-o.pathOffset.x,y:o.points[t].y-o.pathOffset.y},o.calcTransformMatrix()),h=e(i,r,n,s);o._setPositionDimensions({});let l=Bi(o),c=(o.points[t].x-o.pathOffset.x)/l.x,u=(o.points[t].y-o.pathOffset.y)/l.y;return o.setPositionByOrigin(a,c+.5,u+.5),h}}Ri=new WeakMap;class Ui extends ui{constructor(t,e){if(super(null,e),Li.set(this,void 0),!_i(t))throw new TypeError("Invalid 'polygon'.");this._setFabricObject(new ii.Polygon(t.points,{objectCaching:!1}));const i=this._fabricObject;let r=i.points.length-1;i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ii.Control({positionHandler:ki,actionHandler:ji(i>0?i-1:r,Ni),actionName:"modifyPolygon",pointIndex:i}),t}),{}),We(this,Li,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new ii.Control({positionHandler:ki,actionHandler:ji(r>0?r-1:i,Ni),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=ii.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Ve(this,Li,"f")&&this.setPolygon(Ve(this,Li,"f"))}setPolygon(t){if(!_i(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else We(this,Li,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Li,"f")?JSON.parse(JSON.stringify(Ve(this,Li,"f"))):null}}Li=new WeakMap;class Gi extends ui{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Ve(this,Mi,"f")}constructor(t,e,i,r){if(super(null,r),Di.set(this,void 0),Mi.set(this,void 0),!wi(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new ii.Image(t,{left:e.x,top:e.y}));else{if(!gi(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let r;if(i.width=t.width,i.height=t.height,t.format===n.IPF_GRAYSCALED){r=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ii.Control({positionHandler:ki,actionHandler:ji(i>0?i-1:r,Ni),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=ii.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Ve(this,Yi,"f")&&this.setLine(Ve(this,Yi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!pi(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else We(this,Yi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Yi,"f")?JSON.parse(JSON.stringify(Ve(this,Yi,"f"))):null}}Yi=new WeakMap;class xr extends Ui{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Hi.set(this,void 0),!yi(t))throw new TypeError("Invalid 'quad'.");We(this,Hi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Ve(this,Hi,"f")&&this.setQuad(Ve(this,Hi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!yi(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else We(this,Hi,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ve(this,Hi,"f")?JSON.parse(JSON.stringify(Ve(this,Hi,"f"))):null}}Hi=new WeakMap;class Ar extends ui{constructor(t){super(new ii.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState($e.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState($e.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}class Or{static createDrawingStyle(t){if(!Ci(t))throw new Error("Invalid style definition.");let e,i=Or.USER_START_STYLE_ID;for(;Ve(Or,Xi,"f",zi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in Ve(Or,Xi,"f",Zi))r.hasOwnProperty(t)||(r[t]=Ve(Or,Xi,"f",Zi)[t]);return Ve(Or,Xi,"f",zi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ve(Or,Xi,"f",zi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Ve(Or,Xi,"f",zi).values())))}static _updateDrawingStyle(t,e){if(!Ci(e))throw new Error("Invalid style definition.");const i=Ve(Or,Xi,"f",zi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Xi=Or,Or.STYLE_BLUE_STROKE=1,Or.STYLE_GREEN_STROKE=2,Or.STYLE_ORANGE_STROKE=3,Or.STYLE_YELLOW_STROKE=4,Or.STYLE_BLUE_STROKE_FILL=5,Or.STYLE_GREEN_STROKE_FILL=6,Or.STYLE_ORANGE_STROKE_FILL=7,Or.STYLE_YELLOW_STROKE_FILL=8,Or.STYLE_BLUE_STROKE_TRANSPARENT=9,Or.STYLE_GREEN_STROKE_TRANSPARENT=10,Or.STYLE_ORANGE_STROKE_TRANSPARENT=11,Or.USER_START_STYLE_ID=1024,zi={value:new Map([[Or.STYLE_BLUE_STROKE,{id:Or.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Or.STYLE_GREEN_STROKE,{id:Or.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_ORANGE_STROKE,{id:Or.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_YELLOW_STROKE,{id:Or.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Or.STYLE_BLUE_STROKE_FILL,{id:Or.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_GREEN_STROKE_FILL,{id:Or.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_ORANGE_STROKE_FILL,{id:Or.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_YELLOW_STROKE_FILL,{id:Or.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_BLUE_STROKE_TRANSPARENT,{id:Or.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_GREEN_STROKE_TRANSPARENT,{id:Or.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Or.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Or.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Zi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ii.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ii.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ii.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ii.Object.prototype.transparentCorners=!1,ii.Object.prototype.cornerSize=20,ii.Object.prototype.touchCornerSize=100,ii.Object.prototype.cornerColor="rgb(254,142,20)",ii.Object.prototype.cornerStyle="circle",ii.Object.prototype.strokeUniform=!0,ii.Object.prototype.hasBorders=!1,ii.Canvas.prototype.containerClass="",ii.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=ii.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},ii.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();ii.util.addListener(ii.document,"touchend",this._onTouchEnd,{passive:!1}),ii.util.addListener(ii.document,"touchmove",this._onMouseMove,{passive:!1}),ii.util.removeListener(i,r+"down",this._onMouseDown)},ii.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?ii.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class Rr{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ii.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case Rr.DDN_LAYER_ID:r=Or.getDrawingStyle(Or.STYLE_BLUE_STROKE),n=Or.getDrawingStyle(Or.STYLE_BLUE_STROKE_FILL);break;case Rr.DBR_LAYER_ID:r=Or.getDrawingStyle(Or.STYLE_ORANGE_STROKE),n=Or.getDrawingStyle(Or.STYLE_ORANGE_STROKE_FILL);break;case Rr.DLR_LAYER_ID:r=Or.getDrawingStyle(Or.STYLE_GREEN_STROKE),n=Or.getDrawingStyle(Or.STYLE_GREEN_STROKE_FILL);break;default:r=Or.getDrawingStyle(Or.STYLE_YELLOW_STROKE),n=Or.getDrawingStyle(Or.STYLE_YELLOW_STROKE_FILL)}for(let t of ui.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Or.getDrawingStyle(t.styleId);return Or.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=Or.getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildDrawingItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Or.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=Or.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof ui))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildDrawingItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of ui.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Or.getDrawingStyle(t.styleId);else{s=Or.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of ui.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Or.getDrawingStyle(t.styleId);else{s=Or.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,Or.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=ui.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=ui.arrStyleSelectors;const r=Or.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&Qe.DIMT_RECTANGLE&&r.push("rect"),i&Qe.DIMT_QUADRILATERAL&&r.push("quad"),i&Qe.DIMT_TEXT&&r.push("text"),i&Qe.DIMT_ARC&&r.push("arc"),i&Qe.DIMT_IMAGE&&r.push("image"),i&Qe.DIMT_POLYGON&&r.push("polygon"),i&Qe.DIMT_LINE&&r.push("line");const n=[];e&$e.DIS_DEFAULT&&n.push("default"),e&$e.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Rr.DDN_LAYER_ID=1,Rr.DBR_LAYER_ID=2,Rr.DLR_LAYER_ID=3,Rr.USER_DEFINED_LAYER_BASE_ID=100,Rr.TIP_LAYER_ID=999;class Lr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Rr(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Dr extends Wi{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),qi.set(this,void 0),Ki.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&We(this,Ki,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Ve(this,qi,"f")),"f")}getDuration(){return Ve(this,qi,"f")}}qi=new WeakMap,Ki=new WeakMap;class Mr{constructor(){Ji.add(this),Qi.set(this,void 0),$i.set(this,void 0),tr.set(this,void 0),er.set(this,!0),this._drawingLayerManager=new Lr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=Rr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Rr.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Rr.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(di(e=t)&&vi(e.topLeftPoint)&&ri(e.width))||e.width<=0||!ri(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;We(this,Qi,JSON.parse(JSON.stringify(t)),"f"),Ve(this,Qi,"f").coordinateBase||(Ve(this,Qi,"f").coordinateBase="view"),We(this,tr,t.duration,"f"),Ve(this,Ji,"m",sr).call(this)}getTipConfig(){return Ve(this,Qi,"f")?Ve(this,Qi,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),We(this,er,t,"f")}isTipVisible(){return Ve(this,er,"f")}updateTipMessage(t){if(!Ve(this,Qi,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Or.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Rr.TIP_LAYER_ID)||this._createDrawingLayer(Rr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ve(this,Ji,"m",ir).call(this,t,Ve(this,Qi,"f").topLeftPoint.x,Ve(this,Qi,"f").topLeftPoint.y,Ve(this,Qi,"f").width,Ve(this,Qi,"f").coordinateBase,this._tipStyleId),Ve(this,Ji,"m",rr).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ve(this,er,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ve(this,$i,"f")&&clearTimeout(Ve(this,$i,"f")),Ve(this,tr,"f")>=0&&We(this,$i,setTimeout((()=>{Ve(this,Ji,"m",nr).call(this)}),Ve(this,tr,"f")),"f")}}Qi=new WeakMap,$i=new WeakMap,tr=new WeakMap,er=new WeakMap,Ji=new WeakSet,ir=function(t,e,i,r,n,s){const o=new Dr(t,e,i,r,s);return o.coordinateBase=n,o},rr=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},nr=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},sr=function(){if(!this._tip)return;const t=Ve(this,Qi,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Fr extends HTMLElement{constructor(){super(),or.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),We(this,or,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Ve(this,or,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}or=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Fr);class Pr extends Mr{static get engineResourcePath(){return I(pt.engineResourcePaths,dt).dce}static set defaultUIElementURL(t){Pr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Pr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Pr.engineResourcePath)}static async createInstance(t){const e=new Pr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Pr.engineResourcePath)),await e.setUIElement(t||Pr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ve(this,pr,"f")){if(We(this,pr,t,"f"),Ve(this,ar,"m",yr).call(this))We(this,ur,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Ve(this,ur,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ue.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),We(this,ur,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ve(this,ar,"m",yr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Ve(this,pr,"f")}get disposed(){return Ve(this,vr,"f")}constructor(){super(),ar.add(this),hr.set(this,void 0),lr.set(this,void 0),cr.set(this,void 0),this.containerClassName="dce-video-container",ur.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,dr.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,fr.set(this,!1),gr.set(this,!1),mr.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ve(this,ar,"m",Tr).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Ve(this,ar,"m",br).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Pr._onLog&&Pr._onLog("window resize event triggered."),Ve(this,mr,"f").width===document.documentElement.clientWidth&&Ve(this,mr,"f").height===document.documentElement.clientHeight||(Ve(this,mr,"f").width=document.documentElement.clientWidth,Ve(this,mr,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},pr.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ve(this,ar,"m",yr).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},_r.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>Pr._transformCoordinates(t,i,r,n,s,o,a)));const c=new xr({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ve(this,_r,"f").push(c)};let m,p;for(let t of a)switch(t.type){case _t.CRIT_ORIGINAL_IMAGE:break;case _t.CRIT_BARCODE:m=this.getDrawingLayer(Rr.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Or.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case _t.CRIT_TEXT_LINE:m=this.getDrawingLayer(Rr.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Or.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case _t.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Rr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Or.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case _t.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Rr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Or.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case _t.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},vr.set(this,!1),this.eventHandler=new Si,this.eventHandler.on("content:updated",(()=>{Ve(this,hr,"f")&&clearTimeout(Ve(this,hr,"f")),We(this,hr,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{Ve(this,lr,"f")&&clearTimeout(Ve(this,lr,"f")),We(this,lr,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Oi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let r=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!r)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=new Fr,r.appendChild(this._innerComponent),Ve(this,ar,"m",yr).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ue.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),We(this,ur,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Ve(this,ar,"m",yr).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ve(this,ar,"m",yr).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ve(this,ar,"m",Tr).call(this),Ve(this,ar,"m",yr).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ve(this,ar,"m",yr).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Pr._onLog&&Pr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Ve(this,mr,"f").width=document.documentElement.clientWidth,Ve(this,mr,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;Ve(this,ar,"m",yr).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ve(this,ar,"m",Tr).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,We(this,ur,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),r=Math.min(t.width,t.height);e=r<=1080?r+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Ve(this,ur,"f")}isVideoLoaded(){return!(!Ve(this,ur,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ve(this,ur,"f"))return;if(Ve(this,ur,"f").style.objectFit=t,Ve(this,ar,"m",yr).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ve(this,ar,"m",Sr).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(Ve(this,ar,"m",yr).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=Ve(this,ur,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ve(this,ur,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=Ei.convert(this.scanRegion,t.width,t.height);We(this,dr,e,"f"),Ve(this,cr,"f")&&clearTimeout(Ve(this,cr,"f")),We(this,cr,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ve(this,ar,"m",wr).call(this,t,e),Ve(this,ar,"m",Sr).call(this,t,e)}),0),"f")}getConvertedRegion(){return Ve(this,dr,"f")}setScanRegion(t){if(null!=t&&!mi(t)&&!wi(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ve(this,ur,"f").videoWidth,i=Ve(this,ur,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=Ve(this,ur,"f").videoWidth,e=Ve(this,ur,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),Ve(this,_r,"f").length=0}dispose(){this._unbindUI(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}function kr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Br(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,ar=new WeakSet,yr=function(){return"disabled"!==this._singleFrameMode},wr=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},Cr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Er=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},br=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Tr=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Sr=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===Wr.browser&&Wr.version>13||"OPR"===Wr.browser&&Wr.version>43||"Edge"===Wr.browser&&Wr.version,"function"==typeof SuppressedError&&SuppressedError;let Xr=class t{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,i,r){return t.multiply(e,[1,0,0,0,1,0,i,r,1])}static rotate(e,i){var r=Math.cos(i),n=Math.sin(i);return t.multiply(e,[r,-n,0,n,r,0,0,0,1])}static scale(e,i,r){return t.multiply(e,[i,0,0,0,r,0,0,0,1])}};var zr,Zr,qr,Kr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,bn,Tn,Sn,In,xn,An,On,Rn,Ln,Dn,Mn,Fn,Pn,kn,Bn,Nn,jn,Un,Gn,Vn,Wn,Yn,Hn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(zr||(zr={}));class Xn{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Hr(Xn,Zr,!1,"f",qr),!1):(Hr(Xn,Zr,!0,"f",qr),!0)}get disposed(){return Yr(this,en,"f")}constructor(){Kr.set(this,zr.RGBA),Jr.set(this,null),Qr.set(this,null),$r.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,tn.set(this,null),en.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Yr(Xn,Zr,"f",qr)&&Xn.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Yr(Xn,Zr,"f",qr))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Xn._onLog&&(o=Date.now(),Xn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=zr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Yr(Xn,Zr,"f",qr)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Xn._onLog&&Xn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Hr(this,Qr,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Hr(this,$r,e(t),"f"),Hr(this,Jr,i(t),"f"),Hr(this,Kr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[zr.GREY,zr.GREY32].includes(p)?1:0);let m,_,v=Xr.translate(Xr.identity(),-1,-1);v=Xr.scale(v,2,2),v=Xr.scale(v,1/t.canvas.width,1/t.canvas.height),m=Xr.translate(v,u,d),m=Xr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Xr.translate(Xr.identity(),a/i,h/r),_=Xr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Yr(this,Jr,"f"),e),v(t,Yr(this,Qr,"f"),Yr(this,$r,"f"),Yr(this,Jr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Xn._onLog&&Xn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Xn._onLog&&Xn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===zr.GREY?zr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Xn._onLog&&Xn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Xn._onLog&&(n=Date.now(),Xn._onLog("transformPixelFormat(), START: "+n)),e===i)return Xn._onLog&&Xn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[zr.RGBA,zr.RBGA,zr.GRBA,zr.GBRA,zr.BRGA,zr.BGRA];if(o.includes(e))if(i===zr.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Xn._onLog&&(s=Date.now(),Xn._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=zr.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Yr(Xn,Zr,"f",qr)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Xn._onLog&&Xn._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===zr.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Br(this,nn,!0,"f")}}rn=new WeakMap,nn=new WeakMap;const Zn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class qn{static get version(){return"2.0.13"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Wr.OS))return qn.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Wr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{t.src&&await t.load(),await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a){await m;try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!kr(this,vn,"f"))return"closed";if("pending"===kr(this,vn,"f"))return"opening";if("fulfilled"===kr(this,vn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?qn.isStorageAvailable("localStorage")?Br(this,gn,!0,"f"):(Br(this,gn,!1,"f"),console.warn("Local storage is unavailable")):Br(this,gn,!1,"f")}get ifSaveLastUsedCamera(){return kr(this,gn,"f")}get isVideoPlaying(){return!(!kr(this,an,"f")||kr(this,an,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=kr(this,Tn,"f"))||void 0===e||e.removeEventListener("click",kr(this,bn,"f")),null===(i=kr(this,Tn,"f"))||void 0===i||i.removeEventListener("touchend",kr(this,bn,"f")),null===(r=kr(this,Tn,"f"))||void 0===r||r.removeEventListener("touchmove",kr(this,En,"f")),Br(this,Tn,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Wr.OS)?(t.addEventListener("touchend",kr(this,bn,"f")),t.addEventListener("touchmove",kr(this,En,"f"))):t.addEventListener("click",kr(this,bn,"f")))}get tapFocusEventBoundEl(){return kr(this,Tn,"f")}get disposed(){return kr(this,Mn,"f")}constructor(t){var e,i;on.add(this),an.set(this,null),hn.set(this,void 0),ln.set(this,(()=>{"opened"===this.state&&kr(this,An,"f").fire("resumed",null,{target:this,async:!1})})),cn.set(this,(()=>{kr(this,An,"f").fire("paused",null,{target:this,async:!1})})),un.set(this,void 0),dn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],fn.set(this,void 0),gn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,mn.set(this,void 0),pn.set(this,!0),_n.set(this,void 0),vn.set(this,void 0),yn.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},wn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(kr(this,an,"f")).objectFit,s=this.getResolution(),o=kr(this,an,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=kr(this,an,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},Cn.set(this,!1),En.set(this,(()=>{Br(this,Cn,!0,"f")})),bn.set(this,(async t=>{var e;if(kr(this,Cn,"f"))return void Br(this,Cn,!1,"f");if(!kr(this,wn,"f"))return;if(!this.isVideoPlaying)return;if(!kr(this,hn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;qn._onLog&&(c=Date.now());try{await kr(this,on,"m",Wn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(qn._onLog)throw qn._onLog(t),t}qn._onLog&&qn._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;qn._onLog&&qn._onLog("Back to continuous focus."),null===(t=kr(this,hn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),kr(this,An,"f").fire("tapfocus",null,{target:this,async:!1})})),Tn.set(this,null),Sn.set(this,1),In.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!kr(this,an,"f"))return;const t=kr(this,Sn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)kr(this,an,"f").style.transform="";else{const e=window.getComputedStyle(kr(this,an,"f")).objectFit,i=kr(this,an,"f").videoWidth,r=kr(this,an,"f").videoHeight,{width:n,height:s}=kr(this,an,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-kr(this,In,"f").x),c=h*(1-1/t)*(r/2-kr(this,In,"f").y);kr(this,an,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},xn.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===zr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(qn._onLog&&qn._onLog("document visible. video paused: "+(null===(t=kr(this,an,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){qn._onLog&&qn._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){qn._onLog&&qn._onLog("document visible. 1st resume video failed, try open instead.")}e||await kr(this,on,"m",Nn).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){qn._onLog&&qn._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){qn._onLog&&qn._onLog("document visible. 2rd resume video failed, try open instead.")}e||await kr(this,on,"m",Nn).call(this)}}}else"hidden"===document.visibilityState&&(qn._onLog&&qn._onLog("document hidden. video paused: "+(null===(e=kr(this,an,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Mn.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{qn.onWarning&&qn.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Br(this,An,new zn,"f"),this.imageDataGetter=new Xn,document.addEventListener("visibilitychange",kr(this,Dn,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",kr(this,ln,"f")),t.addEventListener("pause",kr(this,cn,"f")),Br(this,an,t,"f")}getVideoEl(){return kr(this,an,"f")}releaseVideoEl(){var t,e;null===(t=kr(this,an,"f"))||void 0===t||t.removeEventListener("play",kr(this,ln,"f")),null===(e=kr(this,an,"f"))||void 0===e||e.removeEventListener("pause",kr(this,cn,"f")),Br(this,an,null,"f")}isVideoLoaded(){return!!kr(this,an,"f")&&4==kr(this,an,"f").readyState}async open(){if(kr(this,_n,"f")&&!kr(this,pn,"f")){if("pending"===kr(this,vn,"f"))return kr(this,_n,"f");if("fulfilled"===kr(this,vn,"f"))return}kr(this,An,"f").fire("before:open",null,{target:this}),await kr(this,on,"m",Nn).call(this),kr(this,An,"f").fire("played",null,{target:this,async:!1}),kr(this,An,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;kr(this,An,"f").fire("before:close",null,{target:this});const t=kr(this,_n,"f");if(kr(this,on,"m",Un).call(this),t&&"pending"===kr(this,vn,"f")){try{await t}catch(t){}if(!1===kr(this,pn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Br(this,_n,null,"f"),Br(this,vn,null,"f"),kr(this,An,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");kr(this,an,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await kr(this,an,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof kr(this,un,"f").video&&(kr(this,un,"f").video={}),delete kr(this,un,"f").video.facingMode,kr(this,un,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&kr(this,pn,"f"))){kr(this,An,"f").fire("before:camera:change",[],{target:this,async:!1}),await kr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}return kr(this,dn,"f")}}async switchToFrontCamera(t){if("object"!=typeof kr(this,un,"f").video&&(kr(this,un,"f").video={}),(null==t?void 0:t.resolution)&&(kr(this,un,"f").video.width={ideal:t.resolution.width},kr(this,un,"f").video.height={ideal:t.resolution.height}),delete kr(this,un,"f").video.deviceId,kr(this,un,"f").video.facingMode={exact:"user"},Br(this,fn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&kr(this,pn,"f"))){kr(this,An,"f").fire("before:camera:change",[],{target:this,async:!1}),kr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}return kr(this,dn,"f")}}getCamera(){var t;if(kr(this,dn,"f"))return kr(this,dn,"f");{let e=(null===(t=kr(this,un,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof kr(this,un,"f").video&&(kr(this,un,"f").video={}),i?(kr(this,un,"f").video.width={exact:t},kr(this,un,"f").video.height={exact:e}):(kr(this,un,"f").video.width={ideal:t},kr(this,un,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&kr(this,pn,"f"))return null;kr(this,An,"f").fire("before:resolution:change",[],{target:this,async:!1}),await kr(this,on,"m",jn).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&kr(this,an,"f"))return{width:kr(this,an,"f").videoWidth,height:kr(this,an,"f").videoHeight};if(kr(this,hn,"f")){const t=kr(this,hn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:kr(this,an,"f").videoWidth,height:kr(this,an,"f").videoHeight};{const t={width:0,height:0};let e=kr(this,un,"f").video.width||0,i=kr(this,un,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=kr(this,Rn,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=kr(this,dn,"f"))||void 0===u?void 0:u.deviceId;let e=kr(this,Rn,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],kr(this,Rn,"f").set(d,e),Br(this,yn,!0,"f");try{for(let t of this.detectedResolutions){await kr(this,hn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),kr(this,on,"m",Pn).call(this);const i=kr(this,hn,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw kr(this,on,"m",Un).call(this),Br(this,yn,!1,"f"),t}try{await kr(this,on,"m",Nn).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Br(this,yn,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(n=null===(r=kr(this,un,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=kr(this,un,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=kr(this,un,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=kr(this,Rn,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],kr(this,Rn,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Br(this,un,JSON.parse(JSON.stringify(t)),"f"),Br(this,fn,null,"f"),e&&kr(this,on,"m",jn).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(kr(this,un,"f")))}resetMediaStreamConstraints(){Br(this,un,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return kr(this,hn,"f").getCapabilities?kr(this,hn,"f").getCapabilities():{}}getCameraSettings(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return kr(this,hn,"f").getSettings()}async turnOnTorch(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await kr(this,hn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await kr(this,hn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await kr(this,hn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await kr(this,hn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await kr(this,hn,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=Zn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await kr(this,hn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await kr(this,on,"m",Wn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await kr(this,hn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Br(this,wn,!0,"f")}disableTapToFocus(){Br(this,wn,!1,"f")}isTapToFocusEnabled(){return kr(this,wn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?kr(this,on,"m",Yn).call(this,t.centerPoint):this.resetScaleCenter();try{if(kr(this,on,"m",Hn).call(this,kr(this,In,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*kr(this,Sn,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!kr(this,hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=Zn(t,r.min,r.step,r.max)),await kr(this,hn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&kr(this,on,"m",Yn).call(this,e),Br(this,Sn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return kr(this,Sn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Br(this,In,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(kr(this,yn,"f"))return null;const e=Date.now();qn._onLog&&qn._onLog("getFrameData() START: "+e);const i=kr(this,an,"f").videoWidth,r=kr(this,an,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=zr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=kr(this,Sn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=kr(this,In,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(kr(this,an,"f"),i,r,n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return qn._onLog&&qn._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:kr(this,xn,"f")}}on(t,e){if(!kr(this,On,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);kr(this,An,"f").on(t,e)}off(t,e){kr(this,An,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),kr(this,An,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",kr(this,Dn,"f")),Br(this,Mn,!0,"f")}}var Kn,Jn,Qn,$n,ts,es,is,rs,ns,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,bs,Ts,Ss,Is,xs,As,Os,Rs;an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,bn=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,In=new WeakMap,xn=new WeakMap,An=new WeakMap,On=new WeakMap,Rn=new WeakMap,Ln=new WeakMap,Dn=new WeakMap,Mn=new WeakMap,on=new WeakSet,Fn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(kr(this,fn,"f"))delete t.video.facingMode,t.video.deviceId={exact:kr(this,fn,"f")};else if(this.ifSaveLastUsedCamera&&qn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Wr.OS)?(await this._getCameras(!1),kr(this,on,"m",Pn).call(this),e=qn.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Wr.OS)||(await this._getCameras(!1),kr(this,on,"m",Pn).call(this),e=qn.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},Pn=function(){if(kr(this,pn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},kn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{qn._onLog&&qn._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),kr(this,on,"m",Pn).call(this));try{qn._onLog&&qn._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),kr(this,on,"m",Pn).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,qn._onLog&&qn._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Bn=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Br(this,hn,null,"f")},Nn=async function(){Br(this,pn,!1,"f");const t=Br(this,mn,Symbol(),"f");if(kr(this,_n,"f")&&"pending"===kr(this,vn,"f")){try{await kr(this,_n,"f")}catch(t){}kr(this,on,"m",Pn).call(this)}if(t!==kr(this,mn,"f"))return;const e=Br(this,_n,(async()=>{Br(this,vn,"pending","f");try{if(this.videoSrc){if(!kr(this,an,"f"))throw new Error("'videoEl' should be set.");await qn.playVideo(kr(this,an,"f"),this.videoSrc,this.cameraOpenTimeout),kr(this,on,"m",Pn).call(this)}else{let t=await kr(this,on,"m",Fn).call(this);kr(this,on,"m",Bn).call(this);let e=await kr(this,on,"m",kn).call(this,t);await this._getCameras(!1),kr(this,on,"m",Pn).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=kr(this,un,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(kr(this,fn,"f")||this.ifSaveLastUsedCamera&&qn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=qn.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await kr(this,on,"m",kn).call(this,t),kr(this,on,"m",Pn).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(Br(this,fn,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&qn.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",kr(this,fn,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),kr(this,an,"f")&&(await qn.playVideo(kr(this,an,"f"),e,this.cameraOpenTimeout),kr(this,on,"m",Pn).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Br(this,hn,s[0],"f"),Br(this,dn,n,"f")}}catch(t){throw kr(this,on,"m",Un).call(this),Br(this,vn,null,"f"),t}Br(this,vn,"fulfilled","f")})(),"f");return e},jn=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=kr(this,dn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await kr(this,on,"m",Nn).call(this);const r=this.getResolution();e&&e!==kr(this,dn,"f").deviceId&&kr(this,An,"f").fire("camera:changed",[kr(this,dn,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||kr(this,An,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),kr(this,An,"f").fire("played",null,{target:this,async:!1})},Un=function(){kr(this,on,"m",Bn).call(this),Br(this,dn,null,"f"),kr(this,an,"f")&&(kr(this,an,"f").srcObject=null,this.videoSrc&&(kr(this,an,"f").pause(),kr(this,an,"f").currentTime=0)),Br(this,pn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Gn=async function t(e,i){const r=t=>{if(!kr(this,hn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){kr(this,hn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=Zn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await kr(this,hn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(kr(this,an,"f"),l.width,l.height,{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:zr.RGBA,bufferContainer:d}))return kr(this,on,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await kr(this,on,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await kr(this,on,"m",Gn).call(this,e,c);if(a>h)return await kr(this,on,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await kr(this,on,"m",t).call(this,e,o,a,c,h);let u=await kr(this,on,"m",Gn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==kr(this,Sn,"f")){const t=kr(this,Sn,"f"),e=kr(this,In,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=Zn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=Zn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Zn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await kr(this,on,"m",Gn).call(this,t,s),a=await kr(this,on,"m",Gn).call(this,t,n),h=await kr(this,on,"m",Gn).call(this,t,r);if(a>h&&ho&&a>o){let e=await kr(this,on,"m",Gn).call(this,t,i);const n=await kr(this,on,"m",Vn).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await kr(this,on,"m",Vn).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},Yn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");Br(this,In,{x:i,y:r},"f")},Hn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},qn.browserInfo=Wr,qn.onWarning=null===(sn=null===window||void 0===window?void 0:window.console)||void 0===sn?void 0:sn.warn;class Ls{constructor(t){Kn.add(this),Jn.set(this,void 0),Qn.set(this,0),$n.set(this,void 0),ts.set(this,0),es.set(this,!1),We(this,Jn,t,"f")}startCharging(){Ve(this,es,"f")||(Ls._onLog&&Ls._onLog("start charging."),Ve(this,Kn,"m",rs).call(this),We(this,es,!0,"f"))}stopCharging(){Ve(this,$n,"f")&&clearTimeout(Ve(this,$n,"f")),Ve(this,es,"f")&&(Ls._onLog&&Ls._onLog("stop charging."),We(this,Qn,Date.now()-Ve(this,ts,"f"),"f"),We(this,es,!1,"f"))}}Jn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,ts=new WeakMap,es=new WeakMap,Kn=new WeakSet,is=function(){pt.cfd(1),Ls._onLog&&Ls._onLog("charge 1.")},rs=function t(){0==Ve(this,Qn,"f")&&Ve(this,Kn,"m",is).call(this),We(this,ts,Date.now(),"f"),Ve(this,$n,"f")&&clearTimeout(Ve(this,$n,"f")),We(this,$n,setTimeout((()=>{We(this,Qn,0,"f"),Ve(this,Kn,"m",t).call(this)}),Ve(this,Jn,"f")-Ve(this,Qn,"f")),"f")};class Ds{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ve(this,ns,"f",as)<100)){if(We(this,ns,e,"f",as),Ve(this,ns,"f",ss).size&&(t=Ve(this,ns,"f",ss).values().next().value,this.beepSoundSource==t.src?(Ve(this,ns,"f",ss).delete(t),t.play()):t=null),!t)if(Ve(this,ns,"f",os).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Ve(this,ns,"f",os).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ve(this,ns,"f",os).delete(t),Ve(this,ns,"f",ss).add(t)}))}else Ve(this,ns,"f",hs)||(We(this,ns,!0,"f",hs),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ve(this,ns,"f",os).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ds.vibrateDuration)}}}ns=Ds,ss={value:new Set},os={value:new Set},as={value:0},hs={value:!1},Ds.allowBeep=!0,Ds.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Ds.allowVibrate=!0,Ds.vibrateDuration=300;const Ms=new Map([[n.IPF_GRAYSCALED,zr.GREY],[n.IPF_ABGR_8888,zr.RGBA],[n.IPF_ARGB_8888,zr.BGRA]]),Fs=new Map([[zr.GREY,n.IPF_GRAYSCALED],[zr.RGBA,n.IPF_ABGR_8888],[zr.BGRA,n.IPF_ARGB_8888]]),Ps="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class ks extends G{static set _onLog(t){We(ks,cs,t,"f",us),qn._onLog=t,Ls._onLog=t}static get _onLog(){return Ve(ks,cs,"f",us)}static async detectEnvironment(){return await(async()=>({wasm:Ye,worker:He,getUserMedia:Xe,camera:await ze(),browser:Ue.browser,version:Ue.version,OS:Ue.OS}))()}static async testCameraAccess(){const t=await qn.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Pr))throw new TypeError("Invalid view.");if(null===(e=ut.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ut.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await pt.loadWasm(["license"]),await ut.license.dynamsoft()}const r=new ks(t);return ks.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ks.onWarning&&ks.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ks.onWarning&&ks.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");We(this,gs,t,"f")}get singleFrameMode(){return Ve(this,gs,"f")}get _isFetchingStarted(){return Ve(this,ws,"f")}get disposed(){return Ve(this,Ss,"f")}constructor(t){if(super(),ls.add(this),ds.set(this,"closed"),fs.set(this,void 0),this.isTorchOn=void 0,gs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ms.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,e,i,s,{pixelFormat:Ms.get(this.getPixelFormat())});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===zr.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:Fs.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Et.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:Ve(this,ps,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Ei.convert(Ve(this,vs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ve(this,ms,"f").call(this,t,t.width,t.height,e);Ve(this,fs,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ps.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===n.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(Ue.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Ve(this,Ts,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Ve(this,Ts,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Ve(this,Es,"f").tapToFocus&&Ve(this,Ts,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(Ve(this,ls,"m",Is).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;ks._onLog&&(ks._onLog("intermediateResultUnits:"),ks._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===St.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===St.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(ks._onLog&&(ks._onLog("hasLocalizedBarcodes:"),ks._onLog(h)),Ve(this,Es,"f").autoZoom||Ve(this,Es,"f").enhancedFocus)if(a)Ve(this,bs,"f").autoZoomInFrameArray.length=0,Ve(this,bs,"f").autoZoomOutFrameCount=0,Ve(this,bs,"f").frameArrayInIdealZoom.length=0,Ve(this,bs,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ve(this,Es,"f").autoZoom&&Ve(this,Ts,"f").startCharging()},a=async t=>{await this.setFocus(t),Ve(this,Es,"f").enhancedFocus&&Ve(this,Ts,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-Ve(this,bs,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ve(this,bs,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-Ve(this,bs,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ve(this,bs,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}ks._onLog&&(ks._onLog("detectionArea:"),ks._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=xi(a.y-i)>0&&xi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(Ai([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Ai([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Ai([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Ai([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===St.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Pr._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(ks._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Or.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===St.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new Ui({points:i},e);t.addDrawingItems([n])}}}if(ks._onLog&&(ks._onLog("intersectedResults:"),ks._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==Ps.BF_QR_CODE||t.possibleFormats==Ps.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Ps.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),Ve(this,bs,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Ve(this,bs,"f").autoZoomInFrameLimit[1]){Ve(this,bs,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,Ve(this,bs,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ve(this,bs,"f").autoZoomInMaxTimes),Ve(this,bs,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ve(this,bs,"f").minValue,u),u=Math.min(Ve(this,bs,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ve(this,bs,"f").autoZoomInFrameArray.length=0,Ve(this,bs,"f").frameArrayInIdealZoom.push(!0),Ve(this,bs,"f").frameArrayInIdealZoom.splice(0,Ve(this,bs,"f").frameArrayInIdealZoom.length-Ve(this,bs,"f").frameLimitInIdealZoom[0]),Ve(this,bs,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Ve(this,bs,"f").frameLimitInIdealZoom[1]&&(Ve(this,bs,"f").frameArrayInIdealZoom.length=0,Ve(this,Es,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Ve(this,Es,"f").autoZoom&&Ve(this,Es,"f").enhancedFocus&&(Ve(this,bs,"f").autoFocusFrameArray.push(!0),Ve(this,bs,"f").autoFocusFrameArray.splice(0,Ve(this,bs,"f").autoFocusFrameArray.length-Ve(this,bs,"f").autoFocusFrameLimit[0]),Ve(this,bs,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Ve(this,bs,"f").autoFocusFrameLimit[1])){Ve(this,bs,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Ve(this,Es,"f").autoZoom){if(Ve(this,bs,"f").autoZoomInFrameArray.push(!1),Ve(this,bs,"f").autoZoomInFrameArray.splice(0,Ve(this,bs,"f").autoZoomInFrameArray.length-Ve(this,bs,"f").autoZoomInFrameLimit[0]),Ve(this,bs,"f").autoZoomOutFrameCount++,Ve(this,bs,"f").frameArrayInIdealZoom.push(!1),Ve(this,bs,"f").frameArrayInIdealZoom.splice(0,Ve(this,bs,"f").frameArrayInIdealZoom.length-Ve(this,bs,"f").frameLimitInIdealZoom[0]),Ve(this,bs,"f").autoZoomOutFrameCount>=Ve(this,bs,"f").autoZoomOutFrameLimit){Ve(this,bs,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*Ve(this,bs,"f").autoZoomOutStepRate,Ve(this,bs,"f").autoZoomOutMinStep);r=Math.max(Ve(this,bs,"f").minValue,r),r=Math.min(Ve(this,bs,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ve(this,Es,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!Ve(this,Es,"f").autoZoom&&Ve(this,Es,"f").enhancedFocus&&(Ve(this,bs,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},We(this,Ts,new Ls(1e4),"f")}setCameraView(t){if(!(t instanceof Pr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Ve(this,ls,"m",Is).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Ve(this,ls,"m",Is).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Ve(this,ls,"m",Is).call(this)?Ve(this,ds,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Ve(this,ls,"m",Is).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Ve(this,ls,"m",Is).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,r=t.getUIElement();if(r=r.shadowRoot||r,i=r.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=r.elTorchAuto=r.querySelector(".dce-mn-torch-auto"),e=r.elTorchOn=r.querySelector(".dce-mn-torch-on"),n=r.elTorchOff=r.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),n&&(n.style.display=0==this.isTorchOn?"":"none");let s=r.elBeepOn=r.querySelector(".dce-mn-beep-on"),o=r.elBeepOff=r.querySelector(".dce-mn-beep-off");s&&(s.style.display=Ds.allowBeep?"":"none"),o&&(o.style.display=Ds.allowBeep?"none":"");let a=r.elVibrateOn=r.querySelector(".dce-mn-vibrate-on"),h=r.elVibrateOff=r.querySelector(".dce-mn-vibrate-off");a&&(a.style.display=Ds.allowVibrate?"":"none"),h&&(h.style.display=Ds.allowVibrate?"none":""),r.elResolutionBox=r.querySelector(".dce-mn-resolution-box");let l,c=r.elZoom=r.querySelector(".dce-mn-zoom");c&&(c.style.display="none",l=r.elZoomSpan=c.querySelector("span"));let u=r.elToast=r.querySelector(".dce-mn-toast"),d=r.elCameraClose=r.querySelector(".dce-mn-camera-close"),f=r.elTakePhoto=r.querySelector(".dce-mn-take-photo"),g=r.elCameraSwitch=r.querySelector(".dce-mn-camera-switch"),m=r.elCameraAndResolutionSettings=r.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=r.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==n||n.addEventListener("pointerdown",y);const w=()=>{Ds.allowBeep=!Ds.allowBeep,s&&(s.style.display=Ds.allowBeep?"":"none"),o&&(o.style.display=Ds.allowBeep?"none":"")};for(let t of[o,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{Ds.allowVibrate=!Ds.allowVibrate,a&&(a.style.display=Ds.allowVibrate?"":"none"),h&&(h.style.display=Ds.allowVibrate?"none":"")};for(let t of[h,a])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),r=parseInt(e.getAttribute("data-height")),n=await this.setResolution({width:i,height:r});{let e=Math.max(n.width,n.height),i=Math.min(n.width,n.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&S(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};r.addEventListener("click",E);let b=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&l&&(l.textContent=t.toFixed(1),c.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout((()=>{c.style.display="none",b=null}),e))};let T=null,S=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const A=()=>{var t,e;let i,r=this.getVideoSettings(),n=r.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==n?void 0:n.ideal)||(null==n?void 0:n.exact)||n)),r.video.facingMode={ideal:i?"environment":"user"},delete r.video.deviceId,this.updateVideoSettings(r)};null==g||g.addEventListener("pointerdown",A);let O=-1/0,R=1;const L=t=>{let e=Date.now();e-O>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),O=e};i.addEventListener("wheel",L);const D=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],r=t.touches[1],n=D.get(i.identifier),s=D.get(r.identifier);if(!n||!s)break;let o=Math.pow(Math.pow(n.x-s.x,2)+Math.pow(n.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-r.clientX,2)+Math.pow(i.clientY-r.clientY,2),.5),h=Date.now();if(M||h-O<100)return;h-O>1e3&&(R=this.getZoomSettings().factor),R*=a/o,R>20&&(R=20),R<1&&(R=1);let l=!1;"safari"==(null===(e=null==Ue?void 0:Ue.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&R<2?(R=2,l=!0):a/o<1&&R<2&&(R=1,l=!0)),M=!0,l&&S("zooming..."),await this.setZoom({factor:R}),l&&(u.textContent=""),M=!1,O=Date.now();break}D.clear();for(let e of t.touches)D.set(e.identifier,{x:e.clientX,y:e.clientY})};r.addEventListener("touchstart",F),r.addEventListener("touchmove",F),r.addEventListener("touchend",F),r.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==n||n.removeEventListener("pointerdown",y);for(let t of[o,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[h,a])null==t||t.removeEventListener("pointerdown",C);r.removeEventListener("click",E),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",A),i.removeEventListener("wheel",L),r.removeEventListener("touchstart",F),r.removeEventListener("touchmove",F),r.removeEventListener("touchend",F),r.removeEventListener("touchcancel",F),delete r.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const n=this.getResolution();e.width=n.width,e.height=n.height,e.deviceId=this.getSelectedCamera().deviceId}return We(this,ds,"open","f"),t&&(t._innerComponent.style.display="",Ve(this,ls,"m",Is).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Ve(this,fs,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Ve(this,ls,"m",Is).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}We(this,ds,"closed","f"),Ve(this,Ts,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ve(this,ls,"m",Is).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ve(this,fs,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ve(this,ls,"m",Is).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ve(this,ls,"m",Is).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ve(this,ls,"m",Is).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),r=this.cameraView;return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ve(this,fs,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ve(this,fs,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Ve(this,ls,"m",Is).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,s;if(e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(++r>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(n.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){console.log(`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(t=null==e?void 0:e.dceMnFs)||void 0===t||t.funcShowToast("Torch Auto On")}catch(t){console.error(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(s,t),this.isTorchOn=void 0,s();let o=this.cameraView.getUIElement();o=o.shadowRoot||o,o.elTorchAuto&&(o.elTorchAuto.style.display=""),o.elTorchOn&&(o.elTorchOn.style.display="none"),o.elTorchOff&&(o.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ve(this,ls,"m",Is).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,r;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(r=null==e?void 0:e.dceMnFs)||void 0===r||r.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Ve(this,ls,"m",Is).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Ve(this,ls,"m",Is).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Ve(this,bs,"f").minValue=t.min,Ve(this,bs,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ve(this,bs,"f").minValue,max:Ve(this,bs,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ut.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==pt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ti.EF_ENHANCED_FOCUS&&(Ve(this,Es,"f").enhancedFocus=!0),t&ti.EF_AUTO_ZOOM&&(Ve(this,Es,"f").autoZoom=!0),t&ti.EF_TAP_TO_FOCUS&&(Ve(this,Es,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ti.EF_ENHANCED_FOCUS&&(Ve(this,Es,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&ti.EF_AUTO_ZOOM&&(Ve(this,Es,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&ti.EF_TAP_TO_FOCUS&&(Ve(this,Es,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ve(this,ls,"m",As).call(this)&&Ve(this,ls,"m",xs).call(this)||Ve(this,Ts,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!mi(t)&&!wi(t))throw TypeError("Invalid 'region'.");We(this,vs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Ve(this,vs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");We(this,_s,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ve(this,ls,"m",Is).call(this))}startFetching(){if(Ve(this,ls,"m",Is).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ve(this,ws,"f")||(We(this,ws,!0,"f"),Ve(this,ls,"m",Os).call(this))}stopFetching(){Ve(this,ws,"f")&&(ks._onLog&&ks._onLog("DCE: stop fetching loop: "+Date.now()),Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),We(this,ws,!1,"f"))}fetchImage(){if(Ve(this,ls,"m",Is).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Ei.convert(Ve(this,vs,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=this.cameraManager.getFrameData({position:i,pixelFormat:Ms.get(this.getPixelFormat())});if(!n)return null;let s;s=n.pixelFormat===zr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:Fs.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:Et.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:Ve(this,ps,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ve(this,ws,"f")&&(Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),We(this,Cs,setTimeout((()=>{this.disposed||Ve(this,ls,"m",Os).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){We(this,ys,t,"f")}getPixelFormat(){return Ve(this,ys,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ve(this,ls,"m",Is).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=Ei.convert(Ve(this,vs,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=Ve(this,ms,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ve(this,ls,"m",Rs).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ve(this,ls,"m",Rs).call(this,t);return{x:e.clientX,y:e.clientY}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}function Bs(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Ns(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}cs=ks,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,Es=new WeakMap,bs=new WeakMap,Ts=new WeakMap,Ss=new WeakMap,ls=new WeakSet,Is=function(){return"disabled"!==this.singleFrameMode},xs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},As=function(){for(let t in Ve(this,Es,"f"))if(1==Ve(this,Es,"f")[t])return!0;return!1},Os=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ve(this,ws,"f"))return Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),void We(this,Cs,setTimeout((()=>{this.disposed||Ve(this,ls,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;ks._onLog&&ks._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Ve(this,_s,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Ve(this,_s,"f"))||void 0===t||t.onErrorReceived(yt.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),ks._onLog&&ks._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ve(this,fs,"f").fire("frameAddedToBuffer",null,{async:!1})):ks._onLog&&ks._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case i.BOPM_BLOCK:break;case i.BOPM_UPDATE:e()}else e();Ve(this,Cs,"f")&&clearTimeout(Ve(this,Cs,"f")),We(this,Cs,setTimeout((()=>{this.disposed||Ve(this,ls,"m",t).call(this)}),this.fetchInterval),"f")},Rs=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ve(this,ls,"m",Is).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ve(this,ls,"m",Is).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ve(this,ls,"m",Is).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)ut+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return js.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return js.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return js.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Us,Gs,Vs,Ws,Ys,Hs,Xs,zs,Zs,qs,Ks,Js,Qs,$s,to,eo,io,ro;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Us||(Us={}));class no{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(Ns(no,Gs,!1,"f",Vs),!1):(Ns(no,Gs,!0,"f",Vs),!0)}get disposed(){return Bs(this,Zs,"f")}constructor(){Ws.set(this,Us.RGBA),Ys.set(this,null),Hs.set(this,null),Xs.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,zs.set(this,null),Zs.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Bs(no,Gs,"f",Vs)&&no.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Bs(no,Gs,"f",Vs))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;no._onLog&&(o=Date.now(),no._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=Us.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Bs(no,Gs,"f",Vs)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){no._onLog&&no._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);Ns(this,Hs,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Ns(this,Xs,e(t),"f"),Ns(this,Ys,i(t),"f"),Ns(this,Ws,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Us.GREY,Us.GREY32].includes(p)?1:0);let m,_,v=js.translate(js.identity(),-1,-1);v=js.scale(v,2,2),v=js.scale(v,1/t.canvas.width,1/t.canvas.height),m=js.translate(v,u,d),m=js.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=js.translate(js.identity(),a/i,h/r),_=js.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Bs(this,Ys,"f"),e),v(t,Bs(this,Hs,"f"),Bs(this,Xs,"f"),Bs(this,Ys,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){no._onLog&&no._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return no._onLog&&no._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Us.GREY?Us.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return no._onLog&&no._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(no._onLog&&(n=Date.now(),no._onLog("transformPixelFormat(), START: "+n)),e===i)return no._onLog&&no._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[Us.RGBA,Us.RBGA,Us.GRBA,Us.GBRA,Us.BRGA,Us.BGRA];if(o.includes(e))if(i===Us.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;no._onLog&&(s=Date.now(),no._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=Us.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Bs(no,Gs,"f",Vs)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){no._onLog&&no._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===Us.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{var e;if(!this.isUseMagnifier)return;if(Ve(this,$s,"f")||We(this,$s,new so,"f"),!Ve(this,$s,"f").magnifierCanvas)return;document.body.contains(Ve(this,$s,"f").magnifierCanvas)||(Ve(this,$s,"f").magnifierCanvas.style.position="fixed",Ve(this,$s,"f").magnifierCanvas.style.boxSizing="content-box",Ve(this,$s,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ve(this,$s,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Ve(this,eo,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];Ve(this,$s,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Ve(this,$s,"f").magnifierCanvas.style.left="auto",Ve(this,$s,"f").magnifierCanvas.style.top="0",Ve(this,$s,"f").magnifierCanvas.style.right="0"):(Ve(this,$s,"f").magnifierCanvas.style.left="0",Ve(this,$s,"f").magnifierCanvas.style.top="0",Ve(this,$s,"f").magnifierCanvas.style.right="auto")}Ve(this,$s,"f").show()})),eo.set(this,(()=>{Ve(this,$s,"f")&&Ve(this,$s,"f").hide()})),io.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Oi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=new Fr,e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(gi(t)){We(this,Qs,t,"f");const{width:e,height:i,bytes:r,format:s}=Object.assign({},t);let o;if(s===n.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!ao&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),lo=t=>{if(null==t&&(t="./"),ao);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};dt.dbr={version:"10.4.20",path:ho},ft.dbr={js:!1,wasm:!0,deps:["license","dip"]},ut.dbr={};const co="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,co)<0&&(dt.std={version:co,path:lo(ho+`../../dynamsoft-capture-vision-std@${co}/dist/`)});const uo="2.4.20";(!dt.dip||"string"!=typeof dt.dip&&S(dt.dip.version,uo)<0)&&(dt.dip={version:uo,path:lo(ho+`../../dynamsoft-image-processing@${uo}/dist/`)});let fo=class{static getVersion(){const t=ct.dbr&&ct.dbr.wasm;return`10.4.20(Worker: ${ct.dbr&&ct.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const go={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)};var mo,po,_o,vo;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(mo||(mo={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(po||(po={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP"}(_o||(_o={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(vo||(vo={}));const yo=async t=>{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class wo{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const r=D(t);return A(r,e,i)}async drawOnImage(t,e,i,r=4294901760,n=1,s){let o;if(t instanceof Blob)o=await yo(t);else if("string"==typeof t){let e=await b(t,"blob");o=await yo(e)}return await new Promise(((t,a)=>{let h=nt();st[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},it.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}}const Co="undefined"==typeof self,Eo=(()=>{if(!Co&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),bo=t=>{if(null==t&&(t="./"),Co);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};dt.utility={version:"1.4.21",path:Eo},ft.utility={js:!0,wasm:!0};const To="1.4.10";"string"!=typeof dt.std&&S(dt.std.version,To)<0&&(dt.std={version:To,path:bo(Eo+`../../dynamsoft-capture-vision-std@${To}/dist/`)});const So="2.4.20";(!dt.dip||"string"!=typeof dt.dip&&S(dt.dip.version,So)<0)&&(dt.dip={version:So,path:bo(Eo+`../../dynamsoft-image-processing@${So}/dist/`)});class Io{static getVersion(){return`1.4.21(Worker: ${ct.utility&&ct.utility.worker||"Not Loaded"}, Wasm: ${ct.utility&&ct.utility.wasm||"Not Loaded"})`}}function xo(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}var Ao,Oo,Ro,Lo,Do;function Mo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=n+u*(o-n),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function ko(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*n,y:t.y+l*s}:null}function jo(t){let e=0;for(let i=0;i0}function Go(t,e){for(let i=0;i<4;i++)if(!Uo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function Vo(t,e,i,r){const n=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=ko(n)[3],h=ko(n)[1],l=ko(s)[3],c=ko(s)[1];let u,d=0;if(u=Math.max(Math.abs(Po(a,e.points[0])),Math.abs(Po(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(h,e.points[1])),Math.abs(Po(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Po(l,t.points[0])),Math.abs(Po(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(c,t.points[1])),Math.abs(Po(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=Bo(ko(n)[0]),g=Bo(ko(n)[2]),m=Bo(ko(s)[0]),p=Bo(ko(s)[2]),_=Fo(f,p),v=Fo(m,g),y=_>v,w=Math.min(_,v),C=Fo(f,g),E=Fo(m,p);let b=12*i;return b=Math.max(b,5),b=Math.min(b,C),b=Math.min(b,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,r=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-r.area)>.4*i.area)return!1;let n=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)n[t]=Math.round(100*(r.points[t].x-i.points[t].x))/100,o+=n[t],s[t]=Math.round(100*(r.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(n[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Go(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Go(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Go(t,this.location.points[e]))return!0;if(Go(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const r=[this.location.points[0],this.location.points[3]],n=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?r:n;if(Math.abs(Po(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const r=t.location.points[i],n=this.location.points[i];if(!(Math.abs(n.x+e.x-r.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const r=Object.assign({},t.location);for(let t=0;t<4;t++)r.points[t].x-=e.x,r.points[t].y-=e.y;if(!this.isLocationOverlap(r,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let r=0;r<4;r++)for(let n=0;n<4;n++){const s=No(t[r],t[(r+1)%4],e[n],e[(n+1)%4]);s&&i.push(s)}return t.forEach((t=>{Mo(e,t)&&i.push(t)})),e.forEach((e=>{Mo(t,e)&&i.push(e)})),jo(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],r.points)>this.locationArea*t}return!0}}const Yo={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},Ho={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Xo=t=>Object.values(Ho).includes(t)||Ho.hasOwnProperty(t),zo=(t,e)=>"string"==typeof t?e[Ho[t]]:e[t],Zo=(t,e,i)=>{"string"==typeof t?e[Ho[t]]=i:e[t]=i},qo=(t,e,i)=>{if(t.isResultCrossVerificationEnabled(i))for(let t=0;t{Zo(e,this.verificationEnabled,t)})),xo(this,Oo,"f").forEach(((t,e)=>{Zo(e,this.duplicateFilterEnabled,t)})),xo(this,Ro,"f").forEach(((t,e)=>{Zo(e,this.duplicateForgetTime,t)})),xo(this,Lo,"f").forEach(((t,e)=>{Zo(e,this.latestOverlappingEnabled,t)})),xo(this,Do,"f").forEach(((t,e)=>{Zo(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){Xo(t)&&xo(this,Ao,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Xo(t)&&zo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Xo(t)&&(e&&this.enableLatestOverlapping(t,!1),xo(this,Oo,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Xo(t)&&zo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Xo(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),xo(this,Ro,"f").set(t,e))}getDuplicateForgetTime(t){return Xo(t)?zo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Xo(t)&&xo(this,Do,"f").set(t,e)}getMaxOverlappingFrames(t){return Xo(t)?zo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Xo(t)&&(e&&this.enableResultDeduplication(t,!1),xo(this,Lo,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Xo(t)&&zo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[_t.CRIT_BARCODE,_t.CRIT_TEXT_LINE,_t.CRIT_DETECTED_QUAD,_t.CRIT_NORMALIZED_IMAGE];for(let i=0;i{const e=(BigInt(t.format)&BigInt(Yo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Yo.BF_GS1_DATABAR))!=BigInt(0);return new Wo(h,e?1:2,e,t)}));if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;n>p&&(p=n,m=r,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{const i=Object.assign({},t),r=(BigInt(t.format)&BigInt(Yo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Yo.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){qo(this,t.items,_t.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){qo(this,t.items,_t.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){qo(this,t.items,_t.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){qo(this,t.items,_t.CRIT_NORMALIZED_IMAGE)}}Ao=new WeakMap,Oo=new WeakMap,Ro=new WeakMap,Lo=new WeakMap,Do=new WeakMap;export{fo as BarcodeReaderModule,ks as CameraEnhancer,Ge as CameraEnhancerModule,Pr as CameraView,xe as CaptureVisionRouter,ce as CaptureVisionRouterModule,Le as CapturedResultReceiver,pt as CoreModule,ui as DrawingItem,Or as DrawingStyleManager,go as EnumBarcodeFormat,i as EnumBufferOverflowProtectionMode,_t as EnumCapturedResultItemType,r as EnumColourChannelUsageType,vt as EnumCornerType,vo as EnumDeblurMode,Qe as EnumDrawingItemMediaType,$e as EnumDrawingItemState,ti as EnumEnhancedFeatures,yt as EnumErrorCode,mo as EnumExtendedBarcodeResultType,wt as EnumGrayscaleEnhancementMode,Ct as EnumGrayscaleTransformationMode,n as EnumImagePixelFormat,ue as EnumImageSourceState,Et as EnumImageTagType,St as EnumIntermediateResultUnitType,_o as EnumLocalizationMode,bt as EnumPDFReadingMode,Me as EnumPresetTemplate,po as EnumQRCodeErrorCorrectionLevel,Tt as EnumRasterDataSource,It as EnumRegionObjectElementType,xt as EnumSectionType,Ds as Feedback,Ar as GroupDrawingItem,Gi as ImageDrawingItem,oo as ImageEditorView,wo as ImageManager,G as ImageSourceAdapter,De as IntermediateResultReceiver,zt as LicenseManager,qt as LicenseModule,Ir as LineDrawingItem,Ko as MultiFrameResultCrossFilter,xr as QuadDrawingItem,Pi as RectDrawingItem,Wi as TextDrawingItem,Io as UtilityModule,D as _getNorImageData,f as _isArc,g as _isContour,m as _isDSImageData,p as _isDSRect,_ as _isImageTag,v as _isLineSegment,y as _isPoint,w as _isPolygon,C as _isQuad,E as _isRect,A as _saveToFile,L as _toBlob,O as _toCanvas,R as _toImage,dt as autoDiscoveryPaths,ht as bDebug,T as checkIsLink,S as compareVersion,et as doOrWaitAsyncDependency,nt as getNextTaskID,I as handleEngineResourcePaths,ct as innerVersions,f as isArc,g as isContour,m as isDSImageData,p as isDSRect,_ as isImageTag,v as isLineSegment,d as isObject,y as isPoint,w as isPolygon,C as isQuad,E as isRect,mt as loadWasm,$ as mapAsyncDependency,ut as mapPackageRegister,st as mapTaskCallBack,ot as onLog,b as requestResource,lt as setBDebug,at as setOnLog,tt as waitAsyncDependency,it as worker,ft as workerAutoResources}; diff --git a/dist/dbr.no-content-bundle.esm.js b/dist/dbr.no-content-bundle.esm.js index 4b1967d..200f8f6 100644 --- a/dist/dbr.no-content-bundle.esm.js +++ b/dist/dbr.no-content-bundle.esm.js @@ -4,7 +4,7 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft -* @version 10.4.2001 +* @version 10.4.2002 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ diff --git a/package.json b/package.json index 0701697..06e7deb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dynamsoft-barcode-reader-bundle", - "version": "10.4.2001", + "version": "10.4.2002", "description": "Dynamsoft Barcode Reader JS is a recognition SDK which enables you to embed barcode reading functionality in your web, desktop, and mobile applications. With a few lines of JavaScript code, you can develop a robust application to scan a linear barcode, QR Code, DaraMatrix, PDF417, and Aztec Code.", "main": "dist/dbr.bundle.js", "module": "dist/dbr.no-content-bundle.esm.js", @@ -78,9 +78,9 @@ "dependencies": { "dynamsoft-barcode-reader": "10.4.20", "dynamsoft-camera-enhancer": "4.1.0", - "dynamsoft-capture-vision-router": "2.4.21", - "dynamsoft-core": "3.4.20", + "dynamsoft-capture-vision-router": "2.4.22", + "dynamsoft-core": "3.4.21", "dynamsoft-license": "3.4.21", - "dynamsoft-utility": "1.4.20" + "dynamsoft-utility": "1.4.21" } }