/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/dynamsoft-mobile-web-capture@4.0.0/dist/mwc.bundle.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
/*!
* Dynamsoft Mobile Web Capture JavaScript Library
* @product Dynamsoft Mobile Web Capture JS Edition Bundle
* @website http://www.dynamsoft.com
* @copyright Copyright 2026, Dynamsoft Corporation
* @author Dynamsoft
* @version 4.0.0
* @fileoverview Dynamsoft Mobile Web Capture (MWC) is an advanced sample designed to extend the features of Dynamsoft Mobile Document Scanner (MDS) with multi-document management, annotation, and uploading.
* More info on MWC: https://www.dynamsoft.com/mobile-document-scanner/docs/web/code-gallery/mobile-web-capture/index.html
*/
!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";const e=t=>t&&"object"==typeof t&&"function"==typeof t.then,i=(async()=>{})().constructor;let n=class extends i{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 n;this._task=t,e(t)?n=t:"function"==typeof t&&(n=new i(t)),n&&(async()=>{try{const e=await n;t===this._task&&this.resolve(e)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let i,n;super((t,e)=>{i=t,n=e}),this._s="pending",this.resolve=t=>{this.isPending&&(e(t)?this.task=t:(this._s="fulfilled",i(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=t}};var s,o,r;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(s||(s={})),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"}(o||(o={})),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"}(r||(r={}));const a="undefined"==typeof self,l="function"==typeof importScripts,h=(()=>{if(!l){if(!a&&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"./"}})(),c=t=>{if(null==t&&(t="./"),a||l);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};let d,u,p,g,f;"undefined"!=typeof navigator&&(d=navigator,u=d.userAgent,p=d.platform,g=d.mediaDevices),function(){if(!a){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:d.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:p,search:"Win"},Mac:{str:p},Linux:{str:p}};let i="unknownBrowser",n=0,s="unknownOS";for(let e in t){const s=t[e]||{};let o=s.str||u,r=s.search||e,a=s.verStr||u,l=s.verSearch||e;if(l instanceof Array||(l=[l]),-1!=o.indexOf(r)){i=e;for(let t of l){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||u,o=i.search||t;if(-1!=n.indexOf(o)){s=t;break}}"Linux"==s&&-1!=u.indexOf("Windows NT")&&(s="HarmonyOS"),f={browser:i,version:n,OS:s}}a&&(f={browser:"ssr",version:0,OS:"ssr"})}();const m="undefined"!=typeof WebAssembly&&u&&!(/Safari/.test(u)&&!/Chrome/.test(u)&&/\(.+\s11_2_([2-6]).*\)/.test(u)),v=!("undefined"==typeof Worker),y=!(!g||!g.getUserMedia),x=async()=>{let t=!1;if(y)try{(await g.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===f.browser&&f.version>66||"Safari"===f.browser&&f.version>13||"OPR"===f.browser&&f.version>43||"Edge"===f.browser&&f.version;const w={},C=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(w[t]=w[t]||new n);await Promise.all(i)};let b,S=0;const T=()=>S++,E={};let _;let P=!1;const A={},I={},D={dip:{wasm:!0}},R={std:{version:"1.4.21",path:c(h+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:h,isInternal:!0}},k=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=w.core;e=!i||i.isEmpty;let s=new Map;const o=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!D[t])throw Error("The '"+t+"' module cannot be found.");let e=D[t].deps;if(null==e?void 0:e.length)for(let t of e)o(t);let i=w[t];s.has(t)||s.set(t,!i||i.isEmpty)};for(let e of t)o(e);let r=[];e&&r.push("core"),r.push(...s.keys());const a=[...s.entries()].filter(t=>!t[1]).map(t=>t[0]);await(async(t,e)=>{let i,s="string"==typeof t?[t]:t,o=[];for(let t of s){let s;o.push(s=w[t]=w[t]||new n(i=i||e())),s.isEmpty&&(s.task=i=i||e())}await Promise.all(o)})(r,async()=>{const t=[...s.entries()].filter(t=>t[1]).map(t=>t[0]);await C(a);const i=(t=>{const e={},i={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",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let s=n,o=t[s],r=o&&"object"==typeof o&&o.path?o.path:o,a=t.rootDirectory;if(a&&!a.endsWith("/")&&(a+="/"),"object"==typeof o&&o.isInternal)a&&(r=t[s].version?`${a}${i[s]}@${t[s].version}/dist/${"ddv"===s?"engine":""}`:`${a}${i[s]}/dist/${"ddv"===s?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof r&&(r=r.replace(i,a||"")),"object"==typeof r&&"dwt"===s){const n=t[s].resourcesPath,o=t[s].serviceInstallerLocation;e[s]={resourcesPath:n.replace(i,a||""),serviceInstallerLocation:o.replace(i,a||"")};continue}}e[s]=c(r)}return e})(R),o={};for(let e of t)o[e]=D[e];const r={engineResourcePaths:i,autoResources:o,names:t};let l=new n;if(e){r.needLoadCore=!0;let t=i.core+M._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),b=new Worker(t),b.onerror=t=>{let e=new Error(t.message);l.reject(e)},b.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,s=e.body;switch(i){case"log":_&&_(e.message);break;case"task":try{E[n](s),delete E[n]}catch(t){throw delete E[n],t}break;case"event":try{E[n](s)}catch(t){throw t}break;default:console.log(t)}}),r.bLog=!!_,r.bd=P,r.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await C("core");let h=S++;E[h]=t=>{if(t.success)Object.assign(A,t.versions),"{}"!==JSON.stringify(t.versions)&&(M._versions=t.versions),l.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),l.reject(e)}},b.postMessage({type:"loadWasm",body:r,id:h}),await l})};class M{static get engineResourcePaths(){return R}static set engineResourcePaths(t){Object.assign(R,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return _}static set _onLog(t){(t=>{_=t,b&&b.postMessage({type:"setBLog",body:{value:!!t}})})(t)}static get _bDebug(){return P}static set _bDebug(t){(t=>{P=t,b&&b.postMessage({type:"setBDebug",body:{value:!!t}})})(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!w[t]&&w[t].isFulfilled}static async loadWasm(t){return await k(t)}static async detectEnvironment(){return await(async()=>({wasm:m,worker:v,getUserMedia:y,camera:await x(),browser:f.browser,version:f.version,OS:f.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=T();E[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)}},b.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`3.4.31(Worker: ${A.core&&A.core.worker||"Not Loaded"}, Wasm: ${A.core&&A.core.wasm||"Not Loaded"})`}static enableLogging(){M._onLog=console.log}static disableLogging(){M._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=T();E[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},b.postMessage({type:"cfd",id:n,body:{count:t}})})}}var L,O,B,N,U,F,V,W,H,j,z,G,Y,$,X,q,Z,J,K,Q,tt,et,it,nt,st,ot,rt,at,lt,ht,ct,dt,ut,pt,gt,ft,mt,vt,yt,xt,wt,Ct,bt,St,Tt,Et,_t,Pt,At,It,Dt,Rt,kt,Mt,Lt,Ot,Bt,Nt,Ut,Ft,Vt,Wt,Ht,jt,zt,Gt,Yt,$t,Xt,qt,Zt,Jt,Kt,Qt,te,ee,ie,ne,se,oe,re,ae,le,he,ce,de,ue,pe,ge,fe,me,ve,ye,xe,we,Ce,be,Se,Te,Ee,_e,Pe,Ae,Ie,De,Re,ke,Me,Le,Oe,Be,Ne,Ue,Fe,Ve,We,He,je,ze,Ge,Ye,$e,Xe,qe,Ze,Je,Ke,Qe,ti,ei,ii,ni,si,oi,ri,ai,li,hi,ci,di,ui,pi,gi,fi,mi,vi,yi,xi,wi,Ci,bi,Si,Ti,Ei,_i,Pi,Ai,Ii,Di,Ri,ki,Mi,Li,Oi,Bi,Ni,Ui,Fi,Vi,Wi,Hi,ji,zi,Gi;function Yi(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function $i(t,e){return Qi(t,qi(t,e,"get"))}function Xi(t,e,i){return tn(t,qi(t,e,"set"),i),i}function qi(t,e,i){if(!e.has(t))throw new TypeError("attempted to "+i+" private field on non-instance");return e.get(t)}function Zi(t,e,i){return en(t,e),nn(i,"get"),Qi(t,i)}function Ji(t,e,i,n){return en(t,e),nn(i,"set"),tn(t,i,n),n}function Ki(t,e,i){return en(t,e),i}function Qi(t,e){return e.get?e.get.call(t):e.value}function tn(t,e,i){if(e.set)e.set.call(t,i);else{if(!e.writable)throw new TypeError("attempted to set read only private field");e.value=i}}function en(t,e){if(t!==e)throw new TypeError("Private static access of wrong provenance")}function nn(t,e){if(void 0===t)throw new TypeError("attempted to "+e+" private static field before its declaration")}function sn(t,e,i){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return i}function on(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function rn(t,e,i){on(t,e),e.set(t,i)}function an(t,e){on(t,e),e.add(t)}function ln(t,e,i,n){return new(i||(i=Promise))(function(e,s){function o(t){try{a(n.next(t))}catch(t){s(t)}}function r(t){try{a(n.throw(t))}catch(t){s(t)}}function a(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i(function(t){t(n)})).then(o,r)}a((n=n.apply(t,[])).next())})}function hn(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function cn(t,e,i,n,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s?s.value=i:e.set(t,i),i}M._bSupportDce4Module=-1,M._bSupportIRTModule=-1,M._versions=null,M._workerName="core.worker.js",M.browserInfo=f,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"}(L||(L={})),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"}(O||(O={})),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"}(B||(B={})),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"}(N||(N={})),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"}(U||(U={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(F||(F={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(V||(V={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(W||(W={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(H||(H={})),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(1<<29),BigInt("0xFFFFFFFFFFFFFFFF"),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"}(j||(j={})),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"}(z||(z={})),"function"==typeof SuppressedError&&SuppressedError,function(t){t.logInfo="logInfo",t.logDebug="logDebug",t.logAll="logAll",t.imgIO="imgIO",t.imgProc="imgProc",t.binaryBlobType="application/octet-stream",t.wasmExtension=".wasm"}(G||(G={})),function(t){t.imgCore="imgCore",t.imgProc="imgProc",t.pdfCore="pdfCore"}(Y||(Y={})),function(t){t.core="ddv-core",t.reader="ddv-reader",t.detector="ddv-detector",t.loader="ddv-loader",t.proc="ddv-proc"}($||($={})),function(t){t.pending="pending",t.ready="ready",t.failed="failed",t.destroyed="destroyed",t.init="init"}(X||(X={})),function(t){t.PARAMETER_TYPE_ERROR="Parameter Type not Supported = ",t.TIMEOUT="Timeout no Response = ",t.FILE_STREAM_ERROR="File Stream Error = ",t.WASM_EXCEPTION_ERROR="An WASM exception occurred."}(q||(q={})),function(t){t[t.LONG_KEY=0]="LONG_KEY",t[t.DLS_KEY=1]="DLS_KEY"}(Z||(Z={})),function(t){t[t.wasmSucceed=0]="wasmSucceed",t[t.wasmBase=-4e3]="wasmBase",t[t.wasmException=-4001]="wasmException",t[t.wasmNoModule=-4002]="wasmNoModule",t[t.wasmJsBase=-4100]="wasmJsBase",t[t.wasmJsObjectNotInit=-4101]="wasmJsObjectNotInit",t[t.wasmJsObjectTerminated=-4102]="wasmJsObjectTerminated",t[t.wasmJsObjectInitFailed=-4103]="wasmJsObjectInitFailed",t[t.wasmJsNotLoaded=-4104]="wasmJsNotLoaded",t[t.wasmJsInvalidJson=-4105]="wasmJsInvalidJson",t[t.wasmJsWorkerRunException=-4106]="wasmJsWorkerRunException",t[t.wasmJsWorkerRunFailed=-4107]="wasmJsWorkerRunFailed",t[t.wasmJsReadFileFailed=-4108]="wasmJsReadFileFailed",t[t.wasmJsCoreTaskException=-4109]="wasmJsCoreTaskException",t[t.wasmJsProcTaskException=-4110]="wasmJsProcTaskException",t[t.wasmJsSavePdfFailed=-4111]="wasmJsSavePdfFailed",t[t.wasmJsSaveTiffFailed=-4112]="wasmJsSaveTiffFailed"}(J||(J={})),function(t){t[t.IT_DIB=-1]="IT_DIB",t[t.IT_RGBA=-2]="IT_RGBA",t[t.IT_BGRA=-3]="IT_BGRA",t[t.IT_BMP=0]="IT_BMP",t[t.IT_JPG=1]="IT_JPG",t[t.IT_PNG=3]="IT_PNG",t[t.IT_ALL=5]="IT_ALL"}(K||(K={})),function(t){t[t.RT_AUTO=-1]="RT_AUTO",t[t.RT_BINARY=1]="RT_BINARY",t[t.RT_BASE64=2]="RT_BASE64"}(Q||(Q={})),function(t){t[t.SF_DEF=0]="SF_DEF",t[t.SF_ENABLE=1]="SF_ENABLE",t[t.SF_DISABLE=2]="SF_DISABLE"}(tt||(tt={})),function(t){t.imgIOVer="3.2.0",t.imgProcVer="3.2.0"}(At||(At={}));let dn=class{static setLogFunc(t,e,i){cn(this,et,t,0,it),cn(this,et,e,0,nt),cn(this,et,i,0,st)}static get level(){return hn(this,et,"f",it)}static get func(){return hn(this,et,"f",nt)}static get context(){return hn(this,et,"f",st)}static logAll(t){this.log(G.logAll,t)}static logD(t){this.log(G.logDebug,t)}static log(t,e){hn(this,et,"f",nt)&&hn(this,et,"f",it)===t&&hn(this,et,"f",nt).call(this,e,hn(this,et,"f",st))}};et=dn,it={value:""},nt={value:void 0},st={value:null};let un=class t{static unload(){cn(this,ot,"",0,rt),cn(this,ot,"",0,lt),cn(this,ot,null,0,ht),cn(this,ot,{name:G.imgIO,instanceName:Y.imgCore,workerName:$.core,autoLoad:!1,ver:At.imgIOVer,prefixName:t.ImageIOPrefixName,useSimd:!1,fetchOptions:hn(t,ot,"f",Ct),useBrotli:t.UseBrotli},0,Et),cn(this,ot,{name:G.imgProc,instanceName:Y.imgProc,workerName:$.proc,autoLoad:!1,ver:At.imgProcVer,prefixName:t.ImageProcPrefixName,useSimd:t.UseSimd,useBrotli:t.UseBrotli},0,_t),dn.setLogFunc("",void 0,null)}static get UseSimd(){return hn(this,ot,"f",dt)}static set UseSimd(t){cn(this,ot,t,0,dt)}static get UseBrotli(){return hn(this,ot,"f",ut)}static set UseBrotli(t){cn(this,ot,t,0,ut)}static get License(){return hn(this,ot,"f",rt)}static set License(t){cn(this,ot,t,0,rt)}static get LicMode(){return hn(this,ot,"f",at)}static set LicMode(t){cn(this,ot,t,0,at)}static get UUID(){return hn(this,ot,"f",lt)}static set UUID(t){cn(this,ot,t,0,lt)}static get NavInfo(){return hn(this,ot,"f",ht)}static set NavInfo(t){cn(this,ot,t,0,ht)}static get Mobile(){return hn(this,ot,"f",ct)}static set Mobile(t){cn(this,ot,t,0,ct)}static get DefHeapSize(){return hn(this,ot,"f",pt)}static set DefHeapSize(t){cn(this,ot,t,0,pt)}static get MaxHeapSize(){return hn(this,ot,"f",gt)}static get HeapConfig(){return hn(this,ot,"m",mt).call(this),Object.assign({},hn(this,ot,"f",ft))}static getWorkerHeap(t){return void 0!==hn(this,ot,"f",ft)[t]?hn(this,ot,"f",ft)[t]:{maxHeapSize:hn(this,ot,"f",gt),initHeapSize:hn(this,ot,"f",pt)}}static UpdateHeapConfig(t,e,i){hn(this,ot,"m",mt).call(this),e&&void 0!==hn(this,ot,"f",ft)[t]&&(hn(this,ot,"f",ft)[t].maxHeapSize=e),i&&void 0!==hn(this,ot,"f",ft)[t]&&(hn(this,ot,"f",ft)[t].initHeapSize=i)}static get FileReadModeSize(){return hn(this,ot,"f",vt)}static set FileReadModeSize(t){cn(this,ot,t,0,vt)}static get FontUseFileReadMode(){return{load:hn(this,ot,"f",yt),save:hn(this,ot,"f",xt)}}static set FontUseFileReadMode(t){"boolean"==typeof t.load&&cn(this,ot,t.load,0,yt),"boolean"==typeof t.save&&cn(this,ot,t.save,0,xt)}static get ImageIOWorkerJS(){return"ddv-imageio.worker.js?v="+At.imgIOVer}static get ImageProcWorkerJS(){return"ddv-imageproc.worker.js?v="+At.imgProcVer}static get ImageProcSimdWorkerJS(){return"ddv-imageproc-simd.worker.js?v="+At.imgProcVer}static get ImageIOPrefixName(){return"ddv-imageio"}static get ImageProcPrefixName(){return"ddv-imageproc"}static get ImageIOResource(){return hn(this,ot,"f",bt)}static set ImageIOResource(t){cn(this,ot,hn(this,ot,"m",wt).call(this,t),0,bt),hn(this,ot,"m",Tt).call(this,hn(this,ot,"f",bt),hn(this,ot,"f",Et)),hn(this,ot,"m",Tt).call(this,hn(this,ot,"f",bt),hn(this,ot,"f",_t))}static get ImageProcResource(){return hn(this,ot,"f",St)}static set ImageProcResource(t){t.useFastCompEdition=!1,cn(this,ot,hn(this,ot,"m",wt).call(this,t),0,St),hn(this,ot,"m",Tt).call(this,hn(this,ot,"f",St),hn(this,ot,"f",_t))}static get ImageIOModule(){return hn(this,ot,"f",Et)}static get ImageReadereModule(){const t=Object.assign({},hn(this,ot,"f",Et));return t.workerName=$.reader,t}static get PdfReaderModule(){const t=Object.assign({},hn(this,ot,"f",Et));return t.workerName=$.reader,t.singleInstance=!0,t.instanceName=Y.pdfCore,t}static get PdfWriterModule(){const t=Object.assign({},hn(this,ot,"f",Et));return t.singleInstance=!0,t.instanceName=Y.pdfCore,t}static get ImageProcModule(){return hn(this,ot,"f",_t)}static get DetectorModule(){return cn(this,ot,Object.assign({},hn(this,ot,"f",_t)),0,Pt),hn(this,ot,"f",Pt).workerName=$.detector,hn(this,ot,"f",Pt)}static setLogFunc(t,e,i){dn.setLogFunc(t,e,i)}static hasLogFunc(){return void 0!==dn.func}};ot=un,mt=function(){0===Object.keys(hn(this,ot,"f",ft)).length&&(hn(this,ot,"f",ft)[$.core]={},hn(this,ot,"f",ft)[$.core].maxHeapSize=hn(this,ot,"f",gt),hn(this,ot,"f",ft)[$.core].initHeapSize=hn(this,ot,"f",pt),hn(this,ot,"f",ft)[$.reader]={},hn(this,ot,"f",ft)[$.reader].maxHeapSize=hn(this,ot,"f",gt),hn(this,ot,"f",ft)[$.reader].initHeapSize=hn(this,ot,"f",pt),hn(this,ot,"f",ft)[$.detector]={},hn(this,ot,"f",ft)[$.detector].maxHeapSize=hn(this,ot,"f",gt),hn(this,ot,"f",ft)[$.detector].initHeapSize=hn(this,ot,"f",pt),hn(this,ot,"f",ft)[$.proc]={},hn(this,ot,"f",ft)[$.proc].maxHeapSize=hn(this,ot,"f",gt),hn(this,ot,"f",ft)[$.proc].initHeapSize=hn(this,ot,"f",pt))},wt=function(t){var e,i,n,s;let o={crossScript:!1,resourceDir:t.resourceDir,workerScript:t.workerScript,useFastCompEdition:null!==(e=t.useFastCompEdition)&&void 0!==e&&e,useSimd:null!==(i=t.useSimd)&&void 0!==i?i:hn(this,ot,"f",dt),fetchOptions:null!==(n=t.fetchOptions)&&void 0!==n?n:hn(this,ot,"f",Ct),useBrotli:null!==(s=t.useBrotli)&&void 0!==s?s:hn(this,ot,"f",ut)};return o.workerScript=t.resourceDir+t.workerScript,o.workerScript.startsWith("http://")||o.workerScript.startsWith("https://")||o.workerScript.includes("://")?(o.resourceDir=t.resourceDir,o.workerScript.startsWith(location.origin)||(o.crossScript=!0)):t.resourceDir.startsWith("/")?null!=location.origin&&(o.resourceDir=location.origin+t.resourceDir):null!=location.href&&(o.resourceDir=location.href.substring(0,location.href.replace(/[?#].*/,"").lastIndexOf("/")+1)+t.resourceDir),o.resourceDir.endsWith("/")||(o.resourceDir+="/"),t.useFastCompEdition&&(o.resourceDir+="fastcomp/",o.workerScript=o.resourceDir+t.workerScript),o},Tt=function(t,e){e.resourceDir=t.resourceDir,e.crossScript=t.crossScript,e.name===G.imgProc?e.useSimd=t.useSimd:e.useSimd=!1,e.script=t.workerScript,e.fetchOptions=t.fetchOptions,e.useBrotli=t.useBrotli},rt={value:""},at={value:Z.LONG_KEY},lt={value:""},ht={value:null},ct={value:!1},dt={value:!1},ut={value:!1},pt={value:32},gt={value:200},ft={value:Object.create(null)},vt={value:20},yt={value:!0},xt={value:!1},Ct={value:{mode:"cors",credentials:"same-origin",retries:3,retryDelay:500}},bt={value:{resourceDir:"",workerScript:un.ImageIOWorkerJS,useFastCompEdition:!1,useSimd:!1,crossScript:!1,fetchOptions:hn(un,ot,"f",Ct),useBrotli:un.UseBrotli}},St={value:{resourceDir:"",workerScript:un.ImageIOWorkerJS,useFastCompEdition:!1,useSimd:!1,crossScript:!1,fetchOptions:hn(un,ot,"f",Ct),useBrotli:un.UseBrotli}},Et={value:{name:G.imgIO,instanceName:Y.imgCore,workerName:$.core,autoLoad:!1,ver:At.imgIOVer,prefixName:un.ImageIOPrefixName,useSimd:!1,fetchOptions:hn(un,ot,"f",Ct),useBrotli:un.UseBrotli}},_t={value:{name:G.imgProc,instanceName:Y.imgProc,workerName:$.proc,autoLoad:!1,ver:At.imgProcVer,prefixName:un.ImageProcPrefixName,useSimd:un.UseSimd,useBrotli:un.UseBrotli}},Pt={value:void 0};let pn=class t{static read(e){return new Promise(function(i,n){let s=Object.prototype.toString.call(e);if("[object String]"===s){if(0===e.indexOf("blob:")||e.indexOf(".jpg")>0||e.indexOf(".jpeg")>0||e.indexOf(".png")>0||e.indexOf(".bmp")>0||e.indexOf(".dib")>0||e.indexOf(".pdf")>0||e.indexOf(".tiff")>0||e.indexOf(".tif")>0)return fetch(e,{mode:"cors"}).then(function(t){return t.arrayBuffer()}).then(function(t){return i(t)}).catch(function(t){return Promise.reject(t)});n("Error url: Can not read the file URL")}else if("[object Blob]"===s||"[object FileList]"===s||"[object File]"===s){let o=e;"[object FileList]"!==s&&"[object File]"!==s||(o=e[0]?e[0]:e),hn(t,It,"m",Dt).call(t,o,i,n)}else"[object ArrayBuffer]"===s||"[object Uint8ClampedArray]"===s?i(e):n("Not support source type: "+s)})}};It=pn,Dt=function(t,e,i){let n,s,o=0;try{n=new ArrayBuffer(t.size),s=new Uint8Array(n)}catch(t){i(t)}!function r(){const a=new FileReader;a.onload=function(a){var l;if(null===(l=null==a?void 0:a.target)||void 0===l?void 0:l.result){const i=a.target.result;s.set(new Uint8Array(i),o),o+=i.byteLength,o<t.size?r():e(n)}else i(a)},a.onerror=function(t){i(t)},a.onabort=function(t){i(t)};const l=Math.min(o+1048576,t.size),h=t.slice(o,l);a.readAsArrayBuffer(h)}()};let gn=class{static fetchRetry(t,e,i,n){let s=e.retries,o=e.retryDelay;return new Promise(function(r,a){const l=function(h){return fetch(t,e).then(function(t){r(t)}).catch(function(t){h<s?function(t,e){i&&i(e,n),setTimeout(function(){l(++t)},o)}(h,t):a(t)})};return l(0)})}},fn=class{constructor(t,e,i,n,s,o){Rt.add(this),kt.set(this,void 0),Mt.set(this,void 0),Lt.set(this,void 0),Ot.set(this,void 0),Bt.set(this,void 0),Nt.set(this,void 0),Ut.set(this,void 0),Ft.set(this,void 0),Vt.set(this,void 0),Wt.set(this,void 0),Ht.set(this,void 0),jt.set(this,void 0),zt.set(this,void 0),Gt.set(this,0),Yt.set(this,{}),$t.set(this,null),cn(this,kt,t),cn(this,Vt,n),cn(this,zt,i),cn(this,Lt,[]),cn(this,Ot,!1),cn(this,Bt,!1),cn(this,Gt,e),cn(this,$t,Object.create(null)),hn(this,Yt,"f").modulesInfo=[],cn(this,Ht,Object.create(null)),cn(this,Ft,null),cn(this,Wt,0),cn(this,jt,0),cn(this,Mt,hn(this,Rt,"m",qt).call(this,hn(this,kt,"f"))),hn(this,Mt,"f").on("message",hn(this,Rt,"m",Jt),this),hn(this,Mt,"f").on("error",hn(this,Rt,"m",Zt),this),hn(this,Mt,"f").on("exit",function(e,i,n){let s="Worker #terminated Unexpectedly\n";s+=" exitCode: `"+e+"`\n",s+=" signalCode: `"+i+"`\n",s+=" #script: `"+t+"`\n",hn(n,Rt,"m",Zt).call(n,new Error(s),n)},this)}get WorkerScript(){return hn(this,Vt,"f")}get id(){return hn(this,Gt,"f")}get Module(){return hn(this,Yt,"f")}get Instances(){return hn(this,$t,"f")}get WorkerName(){return hn(this,zt,"f")}execTask(t,e,i){i||((i={}).promise=new Promise(function(t,e){i.resolve=t,i.reject=e}));let n=cn(this,jt,+hn(this,jt,"f")+1);hn(this,Ht,"f")[n]={id:n,insId:e.insId,resolver:i,cost:e.cost},delete e.cost;let s={id:n,func:t,params:e};return dn.logD("["+e.insId+"] "+t+" send"),hn(this,Bt,"f")?i.reject(new Error("Worker is #terminated")):hn(this,Ot,"f")?i.reject(new Error("Worker is #terminating")):hn(this,Mt,"f").wasmReady||hn(this,Mt,"f").ready&&"loadWasm"===t?hn(this,Mt,"f").send(s):hn(this,Lt,"f").push(s),i.promise}get memSize(){return hn(this,Wt,"f")}get busy(){return this.howManyTasks>0}get howManyTasks(){return Object.keys(hn(this,Ht,"f")).length}get alive(){return!hn(this,Ot,"f")&&!hn(this,Bt,"f")}terminate(t,e){if(dn.logD("["+this.id+"] worker terminate "+t),t&&hn(this,Rt,"m",Qt).call(this,"Worker has been #terminated"),"function"==typeof e&&cn(this,Ft,e),this.busy)cn(this,Ot,!0);else{if(hn(this,Mt,"f")){if("function"!=typeof hn(this,Mt,"f").terminate)throw new Error("Failed to terminate worker");dn.logD("["+this.id+"] will be terminated"),hn(this,Mt,"f").terminate(),cn(this,Mt,null)}cn(this,Ot,!1),cn(this,Bt,!0),hn(this,Ft,"f")&&hn(this,Ft,"f").call(this,this)}}hasInstance(t){if(t){const e=hn(this,$t,"f")[t];if(e)return 0!=Object.keys(e).length}else{const t=Object.keys(hn(this,$t,"f"));for(const e of t)if(0!=Object.keys(hn(this,$t,"f")[e]).length)return!0}return!1}exceedMaxMemory(){const t=1024*un.getWorkerHeap(this.WorkerName).maxHeapSize*1024;return!!(hn(this,Wt,"f")&&hn(this,Wt,"f")>t&&0!=t)&&(dn.logD("[w-"+this.id+"] current memSize="+hn(this,Wt,"f")+", max="+t),!0)}shouldBeFreed(){return!(!this.exceedMaxMemory()||this.hasInstance(void 0)||(dn.logD("[w-"+this.id+"] try to terminate the worker"),this.terminate(),0))}};kt=new WeakMap,Mt=new WeakMap,Lt=new WeakMap,Ot=new WeakMap,Bt=new WeakMap,Nt=new WeakMap,Ut=new WeakMap,Ft=new WeakMap,Vt=new WeakMap,Wt=new WeakMap,Ht=new WeakMap,jt=new WeakMap,zt=new WeakMap,Gt=new WeakMap,Yt=new WeakMap,$t=new WeakMap,Rt=new WeakSet,Xt=function(t){let e=new Error(""),i=Object.keys(t);for(let n=0;n<i.length;n++)e[i[n]]=t[i[n]];return e},qt=function(t){if("function"!=typeof Worker&&"object"!=typeof Worker)throw new Error("Web Workers not supported");let e=new Worker(t,{name:this.WorkerName});return e.on=function(t,e,i){this.addEventListener(t,function(n){"exit"===t?e(n.data,"",i):e(n.data,i)})},e.send=function(t){if(null!=t&&null!=t.params&&null!=t.params.input){let e=Object.prototype.toString.call(t.params.input);if("[object Array]"===Object.prototype.toString.call(t.params.input)){if(e=Object.prototype.toString.call(t.params.input[0]),"[object ArrayBuffer]"===e||"[object Uint8ClampedArray]"===e||"[object Uint8Array]"===e)return void this.postMessage(t,[null!=t.params.input[0].buffer?t.params.input[0].buffer:t.params.input[0]])}else if("[object ArrayBuffer]"===e||"[object Uint8ClampedArray]"===e||"[object Uint8Array]"===e)return void this.postMessage(t,[null!=t.params.input.buffer?t.params.input.buffer:t.params.input])}this.postMessage(t)},e},Zt=function(t,e){cn(e,Bt,!0),dn.logD("[js]["+e.id+"] worker error "+JSON.stringify(t)),hn(e,Ot,"f")&&hn(e,Ft,"f")&&hn(e,Ft,"f").call(e,e),cn(e,Ot,!1),hn(e,Rt,"m",Qt).call(e)},Jt=function(t,e){let i=t.id,n=hn(e,Ht,"f")[i];if(t&&t.cost&&n&&n.cost){const e=n.cost;e.exec=t.cost;const i=Date.now();e.total=i-e.ctime,e.msgQueue=t.ctime-e.time;const s=i-t.time;delete e.time,delete e.ctime,t.cost=e,t.cost.receive=s,delete t.ctime,delete t.time}if(dn.logD(t.log?t.log:t),"string"==typeof t&&"ready"===t)hn(e,Mt,"f").ready=!0,setTimeout(()=>{hn(e,Rt,"m",Kt).call(e)},0);else if(!t.log){if("object"==typeof t){let i=t.result;"object"==typeof i?(null!=i.errorCode&&(i.code=i.errorCode,delete i.errorCode),null!=i.errorMessage&&(i.message=i.errorMessage,delete i.errorMessage)):"string"==typeof i&&(i=i.replace('"errorCode"','"code"'),i=i.replace("'errorCode'","'code'"),i=i.replace('"errorMessage"','"message"'),i=i.replace("'errorMessage'","'message'"),t.result=i),null!=t.memSize&&cn(e,Wt,t.memSize)}if(void 0!==n){const s=n.insId;delete hn(e,Ht,"f")[i],dn.logD("["+s+"] "+t.func+" received"),!0===hn(e,Ot,"f")&&e.terminate(),"loadWasm"===t.func&&null!=t.result&&(hn(e,Mt,"f").wasmReady=!0,setTimeout(()=>{hn(e,Rt,"m",Kt).call(e)},0)),t.error?n.resolver.reject(hn(e,Rt,"m",Xt).call(e,t.error)):t.result&&n.resolver.resolve(t.result)}}},Kt=function(){this.alive&&(hn(this,Lt,"f").forEach(hn(this,Mt,"f").send.bind(hn(this,Mt,"f"))),cn(this,Lt,[]))},Qt=function(t){for(let e in hn(this,Ht,"f"))void 0!==hn(this,Ht,"f")[e]&&hn(this,Ht,"f")[e].resolver.reject(new Error(t));cn(this,Ht,Object.create(null))};let mn=class t{constructor(){te.add(this),ne.set(this,[]),se.set(this,4),oe.set(this,60),re.set(this,!1),ae.set(this,0),he.set(this,!1)}static get Instance(){return hn(this,ee,"f",ie)||cn(this,ee,new t,0,ie),hn(this,ee,"f",ie)}get Terminated(){return hn(this,re,"f")}getModuleLoadedError(e){for(let i of hn(t,ee,"f",le))if(i.name==e)return i.error}getModuleStatus(e){for(let i of hn(t,ee,"f",le))if(i.name==e)return i.status;return""}addModules(e,i){let n=!1;if(hn(t,ee,"f",le).forEach(function(t,i,s){t.name==e.name&&(t.ver==e.ver?n=!0:s.splice(i,1))}),!n){let n=e;n.status=i||"",n.wasmModule=null,hn(t,ee,"f",le).push(n)}}loadModule(e,i){return ln(this,0,void 0,function*(){let n,s;null==i&&(i=0!=hn(this,te,"m",ve).call(this,e).length),this.addModules(e);for(let o of hn(t,ee,"f",le))if(o.name===e.name){if(o.status===X.pending)return!1;if(o.wasmModule){if(i)return!0;n=o.wasmModule,s=o.wasmBinary;break}break}let o=null;if(n)o=e,o.wasmModule=n,o.wasmBinary=s,o.status=X.pending;else if(o=e,""===o.status)o.status=X.pending,o.wasmModule=null;else{if(o.status===X.pending)return!1;i||(o.error={code:0,message:""},o.status=X.pending)}return hn(this,te,"m",ce).call(this,o)})}get busy(){hn(this,te,"m",Ce).call(this);let t=hn(this,ne,"f");for(let e of t)if(e.busy)return!0;return!1}getWorker(t,e){return ln(this,0,void 0,function*(){if(hn(this,te,"m",ye).call(this,t.name))return hn(this,te,"m",we).call(this),{worker:null,workers:0};let i=hn(this,te,"m",ve).call(this,t,!0);return 0!=i.length?{worker:hn(this,te,"m",be).call(this,i,e,t),workers:i.length}:(yield this.loadModule(t,!1),{worker:null,workers:0})})}removeInstanceInWorker(t,e,i,n){if(hn(this,te,"m",Se).call(this,e,t.instanceName,i),n&&e&&e.shouldBeFreed()){let t=hn(this,ne,"f").indexOf(e);-1!==t&&hn(this,ne,"f").splice(t,1)}}terminate(e){cn(t,ee,null,0,ie),dn.logD("worker pool terminate "+e),cn(this,re,!0);let i=[];return hn(this,ne,"f").splice(0).forEach(function(t){let n={};n.promise=new Promise(function(t,e){n.resolve=t,n.reject=e}),i.push(n.promise),t.terminate(e,function(t){n.resolve(t)})}),Promise.all(i)}static unload(){cn(t,ee,new Array,0,le)}terminateWorker(t){hn(this,ne,"f").splice(0,hn(this,ne,"f").length,...hn(this,ne,"f").filter(e=>e.WorkerName!==t||(e.terminate(!0),!1)))}getMemoryUsed(){let t=hn(this,ne,"f"),e=[],i=0;for(let n of t)n&&null!=n.memSize&&(e[i]={},e[i].size=n.memSize,e[i].limit=1024*un.getWorkerHeap(n.WorkerName).maxHeapSize*1024,e[i].name=n.WorkerName,e[i].id=n.id,i+=1);return e}};ee=mn,ne=new WeakMap,se=new WeakMap,oe=new WeakMap,re=new WeakMap,ae=new WeakMap,he=new WeakMap,te=new WeakSet,ce=function(t){return ln(this,0,void 0,function*(){let e=this,i=yield hn(this,te,"m",fe).call(this,t);if(i){let n={id:0,func:"loadWasm",params:{insId:0,priority:0,module:{modulesInfo:[]},fetchOptions:t.fetchOptions}};n.params.resourceDir=t.resourceDir,n.params.initMemory=un.getWorkerHeap(t.workerName).initHeapSize,n.params.module&&n.params.module.modulesInfo.push(t),yield hn(this,te,"m",ue).call(this,i,n),cn(e,se,hn(e,te,"m",ge).call(e)),t.status===X.pending&&(t.status="")}else t.status="",t.wasmModule=null})},de=function(t,e,i,n){for(let s of hn(mn,ee,"f",le))if(s.name===t){s.status=e,s.wasmModule=i.wasmModule,s.wasmBinary=i.wasmBinary,s.error=n;break}},ue=function(t,e,i){return ln(this,0,void 0,function*(){let n=this;try{const i=yield t.execTask(e.func,e.params);let s=!1;return void 0===i.code||i.modules?s=hn(n,te,"m",pe).call(n,i,t):dn.logD(i),s}catch(n){return dn.logD(n),!1}finally{i&&i()}})},pe=function(t,e){if(dn.logD("handleWasmLoad:"),dn.logD(t),hn(this,re,"f"))return e.terminate(),!1;if(("object"!=typeof t||null==t.modules)&&"object"==typeof t)return!1;let i=!1;for(const n of t.modules)t.code?(hn(this,te,"m",de).call(this,n.name,X.failed,null,{code:t.code,message:t.message}),e.Module.modulesInfo[n.name]=!1):(hn(this,te,"m",de).call(this,n.name,X.ready,n.wasmResource,void 0),e.Module.modulesInfo[n.name]=!0,i=!0);return i},ge=function(){let t=2;return"hardwareConcurrency"in self.navigator&&(t=self.navigator.hardwareConcurrency),Math.max(Math.min(hn(this,se,"f"),Math.max(hn(this,se,"f"),t/2)),1)},fe=function(t){return ln(this,0,void 0,function*(){hn(this,te,"m",Ce).call(this);let e=hn(this,ne,"f");for(let i of e)if(i.WorkerName===t.workerName)return i.busy?null:i;return hn(this,te,"m",me).call(this,t)})},me=function(t){var e;return ln(this,0,void 0,function*(){let i=this,n=hn(i,ne,"f");if(n.length<hn(i,se,"f")&&!hn(i,he,"f")){cn(i,he,!0);let s=t.script;t.crossScript&&(s=yield gn.fetchRetry(t.script,t.fetchOptions,dn.func,i).then(t=>t.blob()).then(t=>URL.createObjectURL(t)).catch(t=>(dn.logD("get new worker fetch failed: "),dn.logD(t),cn(i,he,!1),null)));let o=new fn(s,cn(e=i,ae,+hn(e,ae,"f")+1),t.workerName,t.script,dn.func,dn.context);return n.push(o),cn(i,he,!1),dn.logAll(n),dn.logD("[wl-"+hn(i,ne,"f").length+"] got new worker w-"+o.id+"("+o.WorkerName+") succeed!"),o}return null})},ve=function(t,e){hn(this,te,"m",Ce).call(this);let i=hn(this,ne,"f");dn.logAll(i);let n=[];for(let s of i)if(s.Module.modulesInfo[t.name]){if(e&&s.WorkerName!==t.workerName)continue;n.push(s)}return dn.logAll("[wl-"+i.length+"] got workers for module "+t.name),dn.logAll(n),n},ye=function(t){for(let e of hn(mn,ee,"f",le))if(e.name===t&&e.status===X.pending)return!0;return!1},xe=function(){return ln(this,0,void 0,function*(){this.terminate(!0);for(let t of hn(mn,ee,"f",le))yield hn(this,te,"m",ce).call(this,t)})},we=function(){hn(this,te,"m",Ce).call(this),0==hn(this,ne,"f").length&&0!=hn(mn,ee,"f",le).length&&(dn.logD("no worker ready, reinit"),hn(this,te,"m",xe).call(this))},Ce=function(){hn(this,ne,"f").splice(0,hn(this,ne,"f").length,...hn(this,ne,"f").filter(function(t){return t.alive}))},be=function(t,e,i){dn.logAll("[wl-"+hn(this,ne,"f").length+"] getWorkerByIntanceId"),dn.logAll(t);let n,s=9007199254740991;for(let o of t){if(i.singleInstance&&o.hasInstance(i.instanceName)&&!o.Instances[i.instanceName][e])continue;const t=o.Instances[i.instanceName];if(!t||void 0!==t[e]){n=o;break}{let t=o.howManyTasks;t<s&&(n=o,s=t)}}if(n){if(n.shouldBeFreed())return null;const s=n.Instances[i.instanceName];if(s)s[e]="";else{const t=Object.create(null);t[e]="",n.Instances[i.instanceName]=t}return dn.logAll(t),dn.logD("[wl-"+t.length+"]["+e+"] got worker w-"+n.id),n}return dn.logAll("#getWorkerByIntanceId: no suitable worker"),null},Se=function(t,e,i){let n=hn(this,ne,"f");dn.logAll("removeInstanceInWorkerInner"),dn.logAll(n);for(let s of n)if(s===t){const o=s.Instances[e];if(o){if(null!=o[i]){delete o[i],dn.logAll(n),dn.logD("[w-"+s.id+"] removeInstanceInWorkerInner "+i+" in "+t.id+" succeed!");break}dn.logD("[w-"+s.id+"] not found instance "+i)}}},ie={value:null},le={value:new Array};let vn=class{static buildWasmFileName(t,e,i,n,s){return t+(n?"-simd":"")+i+"?v="+e}static base64DecToArr(t,e){let i=t.replace(/[^A-Za-z0-9\+\/]/g,""),n=i.length,s=e?Math.ceil((3*n+1>>>2)/e)*e:3*n+1>>>2,o=new Uint8Array(s);for(let t,e,r=0,a=0,l=0;l<n;l++)if(e=3&l,r|=hn(this,Te,"m",Ee).call(this,i.charCodeAt(l))<<18-6*e,3===e||n-l==1){for(t=0;t<3&&a<s;t++,a++)o[a]=r>>>(16>>>t&24)&255;r=0}return o}static isWasmSupport(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){let t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch(t){}return!1}static random(){return(Date.now()%10086).toString(36).slice(2)+Math.random().toString(36).slice(2)}static newBlobInChunks(t,e,i){var n;let s;const o=i||t.byteLength,r=8388608,a=[];for(let e=0;e<o;e+=r)a.push(new Blob([new Uint8Array(null!==(n=t.buffer)&&void 0!==n?n:t,e,Math.min(o-e,r))]));return s=null!=e?new Blob(a,{type:e}):new Blob(a),s}};Te=vn,Ee=function(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:43===t?62:47===t?63:0};let yn=class t{constructor(e,i){var n,s,o,r;_e.add(this),Ie.set(this,void 0),this._outputType=K.IT_JPG,this._inputType=K.IT_ALL,this._jpegQuality=80,De.set(this,null!==(n=un.License)&&void 0!==n?n:""),Re.set(this,[]),ke.set(this,null),Me.set(this,0),Le.set(this,cn(r=t,Pe,+hn(r,Pe,"f",Ae)+1,0,Ae)),Oe.set(this,null),Be.set(this,JSON.parse(JSON.stringify(un.NavInfo))),Ne.set(this,un.Mobile),Ue.set(this,location.origin),Fe.set(this,""),Ve.set(this,X.init),We.set(this,!1),He.set(this,null!==(s=un.LicMode)&&void 0!==s?s:Z.LONG_KEY),je.set(this,null!==(o=un.UUID)&&void 0!==o?o:""),ze.set(this,0),Ge.set(this,!1),Ye.set(this,!1),this._handleBooleanResult=function(t,e){return!0},cn(this,Ie,e),cn(this,De,null!=i?i:un.License)}_prepareModule(t){}get workerId(){return hn(this,ke,"f")&&hn(this,ke,"f").alive?hn(this,ke,"f").id:0}get id(){return hn(this,Le,"f")}hasTask(){return hn(this,Re,"f").length>0}_canTerminateWork(){return!1}_makeSureWorkerMemoryNotExceed(){return!(hn(this,ke,"f")&&hn(this,ke,"f").alive&&this._canTerminateWork()&&hn(this,ke,"f").exceedMaxMemory()&&(dn.logD(`[${this.id}] try to termiate worker [${hn(this,ke,"f").id}]`),hn(this,ke,"f").terminate(!0),cn(this,ke,null),cn(this,Ve,X.init),1))}_makeSureWorkerChanged(){return!!(hn(this,ke,"f")&&hn(this,ke,"f").alive&&this._canTerminateWork())&&(dn.logD(`[${this.id}] try to termiate worker [${hn(this,ke,"f").id}]`),hn(this,ke,"f").terminate(!0),cn(this,ke,null),cn(this,Ve,X.init),!0)}_workerChanged(t){}_handleBasicResult(t,e){return delete t.code,delete t.message,t}_handleImageData(t,e){var i,n,s;if("object"==typeof t.imageData)if(null!=t.imageCount&&t.imageCount>1)for(let n=0;n<t.imageCount;n++)t.imageData[n]=hn(i=e.context,_e,"m",qe).call(i,t.imageData[n],t.blobType,e.params.returnBlob,t.imageDataSize);else t.imageData=hn(n=e.context,_e,"m",qe).call(n,t.imageData,t.blobType,e.params.returnBlob,t.imageDataSize);return"object"==typeof t.pdfData&&(t.pdfData=hn(s=e.context,_e,"m",qe).call(s,t.pdfData,t.blobType,e.params.returnBlob,t.pdfDataSize)),t}_handleResult(t,e){var i,n;let s=hn(n=e.context,_e,"m",Ze).call(n,t);if(void 0===s.code||!s.code&&"Successful."===s.message)s=e.handleResult(s,e),setTimeout(()=>{var t;hn(t=e.context,_e,"m",Xe).call(t)},0),(0,e.resolve)(s);else{let t={code:s.code,message:s.code===J.wasmException?q.WASM_EXCEPTION_ERROR+"("+(null===(i=e.params)||void 0===i?void 0:i.moduleName)+":"+e.func+":"+s.message+")":s.message};e.context.terminated?e.resolve(t):e.reject(t)}}_execTask(t){let e=this,i=hn(e,ke,"f");if(dn.logAll(t),i)try{if(t.params.cost){const e=t.params.cost.time;t.params.cost.time=Date.now(),t.params.cost.taskQueue=t.params.cost.time-e}i.execTask(t.func,t.params).then(function(i){e._handleResult(hn(e,_e,"m",Ze).call(e,i),t)}).catch(function(i){dn.logD(i),setTimeout(()=>{hn(e,_e,"m",Xe).call(e)},0);let n=i;"object"==typeof i&&null!=i.message&&(n=i.message);let s={code:J.wasmJsWorkerRunFailed,message:n};hn(e,We,"f")?t.resolve(s):t.reject(s)})}catch(i){setTimeout(()=>{hn(e,_e,"m",Xe).call(e)},0),dn.logD(i);let n={code:J.wasmJsWorkerRunException,message:i.message,stack:i.stack};hn(e,We,"f")?t.resolve(n):t.reject(n)}}_cancelAllTasks(t,e){for(let i of hn(this,Re,"f"))if(void 0!==i){let n={code:t,message:e};hn(this,We,"f")?i.resolve(n):i.reject(n)}cn(this,Re,[])}_createTask(t,e,i){let n={moduleName:hn(this,Ie,"f").instanceName,insId:hn(this,Le,"f")},s={id:cn(this,Me,+hn(this,Me,"f")+1),func:t,params:n};return s.promise=new Promise(function(t,e){s.resolve=t,s.reject=e}),s.func=t,s.context=this,s.handleResult=void 0!==i&&i?i:this._handleBasicResult,s.params.input=void 0!==e&&e?e:"",s.params.returnType=Q.RT_AUTO,s.params.returnBlob=!0,s.params.logLevel=dn.level,s.params.cost={},s.params.cost.ctime=Date.now(),s.params.cost.time=s.params.cost.ctime,s}_addTask(t,e){if(t.params.cost){const e=t.params.cost.time;t.params.cost.time=Date.now(),t.params.cost.create=t.params.cost.time-e}return hn(this,Ve,"f")===X.destroyed?t.reject({code:J.wasmJsObjectNotInit,message:hn(this,We,"f")?"object has been disposed":"object not init"}):hn(this,Ve,"f")===X.failed?t.reject({code:J.wasmJsObjectInitFailed,message:hn(this,Fe,"f")}):(e?hn(this,Re,"f").unshift(t):hn(this,Re,"f").push(t),hn(this,_e,"m",Xe).call(this)),t.promise}terminate(t){let e=this;hn(e,Ge,"f")?cn(e,We,!0):(cn(this,Ye,!0),hn(e,_e,"m",Ke).call(e).then(function(t){dn.logD("["+e.id+"] "+hn(e,Ie,"f").name+" destroy return: "),dn.logD(t)}).catch(function(t){dn.logD(hn(e,Ie,"f").name+" destroy failed"),dn.logD(t)}).finally(()=>{mn.Instance&&mn.Instance.removeInstanceInWorker(hn(e,Ie,"f"),hn(e,ke,"f"),hn(e,Le,"f"),null==t||t),cn(e,ke,null),cn(e,We,!0),cn(e,Ye,!1)})),cn(e,Ve,"")}_readFile(t){return pn.read(t).catch(function(t){let e=t;return"object"!=typeof e&&(e={},e.code=J.wasmJsReadFileFailed,e.message=t),Promise.reject(e)})}updateLicense(t,e,i){return ln(this,0,void 0,function*(){cn(this,De,t),cn(this,He,null!=e?e:Z.LONG_KEY),cn(this,je,null!=i?i:"");let n=this,s=n._createTask("UpdateLicense");return s.params.input=[hn(n,De,"f"),hn(n,He,"f"),hn(n,je,"f")],n._addTask(s),s.promise})}};Pe=yn,Ie=new WeakMap,De=new WeakMap,Re=new WeakMap,ke=new WeakMap,Me=new WeakMap,Le=new WeakMap,Oe=new WeakMap,Be=new WeakMap,Ne=new WeakMap,Ue=new WeakMap,Fe=new WeakMap,Ve=new WeakMap,We=new WeakMap,He=new WeakMap,je=new WeakMap,ze=new WeakMap,Ge=new WeakMap,Ye=new WeakMap,_e=new WeakSet,$e=function t(e){let i=null!=e?e:this;return hn(i,Oe,"f")&&clearTimeout(hn(i,Oe,"f")),hn(i,We,"f")?(dn.logD(`[${i.id}] has been termiated.(getWorker)`),i._cancelAllTasks(J.wasmJsObjectTerminated,`Instance [${i.id}] has been termiated.`),hn(i,ke,"f")):hn(i,ke,"f")&&hn(i,ke,"f").alive?hn(i,ke,"f"):void(mn.Instance?mn.Instance.getWorker(hn(i,Ie,"f"),hn(i,Le,"f")).then(e=>{var n;if(cn(i,ke,e.worker),hn(i,ke,"f")&&hn(i,ke,"f").alive)hn(i,ze,"f")!=hn(i,ke,"f").id&&(0!==hn(i,ze,"f")&&i._workerChanged(hn(i,ke,"f").id),cn(i,ze,hn(i,ke,"f").id)),hn(i,Re,"f").length>0&&setTimeout(()=>{hn(i,_e,"m",Xe).call(i)},0);else{let e=null===(n=mn.Instance)||void 0===n?void 0:n.getModuleLoadedError(hn(i,Ie,"f").name);if(null==e?void 0:e.code)return i._cancelAllTasks(J.wasmJsNotLoaded,e.message),hn(i,ke,"f");hn(i,Re,"f").length>0&&cn(i,Oe,setTimeout(hn(i,_e,"m",t),50,i))}return hn(i,ke,"f")}).catch(t=>hn(i,ke,"f")):i._cancelAllTasks(J.wasmJsNotLoaded,"wasm env not loaded or unloaded"))},Xe=function(){if(dn.logAll(hn(this,Re,"f")),hn(this,Ve,"f")!=X.init)if(hn(this,ke,"f")&&hn(this,ke,"f").alive){if(hn(this,Re,"f").length>0&&(hn(this,Ve,"f")===X.ready||"init"===hn(this,Re,"f")[0].func)){const t=hn(this,Re,"f").shift();this._execTask(t)}}else{if(hn(this,ke,"f")&&!hn(this,ke,"f").alive&&hn(this,Re,"f").length>0&&"init"!=hn(this,Re,"f")[0].func)return cn(this,ke,null),void hn(this,_e,"m",Je).call(this);hn(this,Re,"f").length>0&&hn(this,Ie,"f").script&&hn(this,_e,"m",$e).call(this,this)}else hn(this,_e,"m",Je).call(this)},qe=function(t,e,i,n){return i?vn.newBlobInChunks(t,e,n):void 0===n||n===t.byteLength?t:t.slice(0,n)},Ze=function(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return t}},Je=function(){let t=this;t._prepareModule(hn(this,Ie,"f"));let e=this._createTask("init");e.params.key=hn(this,De,"f"),e.params.uuid=hn(this,je,"f"),e.params.licMode=hn(this,He,"f"),e.params.val={nv:hn(this,Be,"f"),mb:hn(this,Ne,"f"),dm:hn(this,Ue,"f")},e.handleResult=function(t,e){return cn(e.context,Ve,X.ready),t},cn(this,Ve,X.pending),this._addTask(e,!0),e.promise.then(function(e){dn.logD("["+t.id+"] "+hn(t,Ie,"f").name+" init return: "),dn.logD(e),cn(t,Ge,!1)}).catch(function(e){cn(t,Ve,X.failed),cn(t,Fe,e.message),dn.logD(hn(t,Ie,"f").name+" init failed"),dn.logD(e),t._cancelAllTasks(J.wasmJsObjectInitFailed,e.message)})},Ke=function(){if(hn(this,Ve,"f")==X.pending||hn(this,Ve,"f")==X.ready){let t=this._createTask("destroy",null,this._handleBooleanResult);return this._addTask(t),t.promise}return Promise.resolve(!0)},Ae={value:0};let xn=class extends yn{constructor(t,e){super(t,e)}_prepareModule(t){mn.Instance.addModules(t)}},wn=class extends xn{constructor(t){super(un.ImageIOModule,t),Qe.add(this),ti.set(this,0)}getImageFormat(t){return ln(this,0,void 0,function*(){let e=this,i=e._createTask("GetImageFormat");const n=yield e._readFile(t);return i.params.input=n,e._addTask(i),i.promise})}readImageInfo(t){return ln(this,0,void 0,function*(){let e=this,i=e._createTask("ReadImageInfo");const n=yield e._readFile(t);return i.params.input=n,e._addTask(i),i.promise})}getMD5(t){return ln(this,0,void 0,function*(){let e=this,i=e._createTask("GetMD5");const n=yield e._readFile(t);return i.params.input=n,i.handleResult=function(t,e){return t.MD5},e._addTask(i),i.promise})}getLicenseInfo(){return ln(this,0,void 0,function*(){return this._addTask(this._createTask("GetLicenseInfo"))})}getAesResult(t){return ln(this,0,void 0,function*(){return t=null!=t?t:"",this._addTask(this._createTask("GetAesResult",[t]))})}saveImage(t,e,i,n,s){return ln(this,0,void 0,function*(){return(s=null!=s&&s)?hn(this,Qe,"m",ei).call(this,t,void 0,void 0,void 0,1,void 0,void 0,e,i,n):hn(this,Qe,"m",ei).call(this,t,void 0,void 0,void 0,void 0,void 0,void 0,e,i,n)})}readImage(t,e,i,n,s){return ln(this,0,void 0,function*(){e=null!=e?e:this._outputType,i=null!=i?i:this._jpegQuality,n=null!=n?n:Q.RT_AUTO,s=null!=s&&s;let o=this,r=o._createTask("ReadImage");const a=yield o._readFile(t);r.params.input=[a,e,i,s],r.params.returnType=n,r.params.returnBlob=n===Q.RT_AUTO,r.handleResult=o._handleImageData,o._addTask(r);const l=yield r.promise;if(l.srcBuffer){let e=Object.prototype.toString.call(t);"[object ArrayBuffer]"!=e&&"[object Uint8ClampedArray]"!=e&&delete l.srcBuffer}return l})}openTiff(t,e){return ln(this,0,void 0,function*(){let i=this,n=i._createTask("LoadTiff");e=null!=e&&e;const s=yield i._readFile(t);n.params.input=[s,e],i._addTask(n);const o=yield n.promise;if(o.srcBuffer){let e=Object.prototype.toString.call(t);"[object ArrayBuffer]"!=e&&"[object Uint8ClampedArray]"!=e&&delete o.srcBuffer}return o})}readTiff(t,e,i,n){t=null!=t?t:0,e=null!=e?e:this._outputType,i=null!=i?i:Q.RT_AUTO,n=null!=n&&n;let s=this._createTask("ReadTiffPage");return s.params.input=[t,e,n],s.params.returnType=i,s.params.returnBlob=i===Q.RT_AUTO,s.handleResult=this._handleImageData,this._addTask(s)}readTiffInfos(t){let e=this._createTask("GetTiffPageInfos");return e.params.input=[t],this._addTask(e)}closeTiff(){return this._addTask(this._createTask("EndReadTiff",null,this._handleBooleanResult))}createTiff(){return this._addTask(this._createTask("NewTiff",null,this._handleBooleanResult))}appendImage(t,e,i,n,s){return ln(this,0,void 0,function*(){e=null!=e?e:this._inputType,i=null!=i?i:hn(this,ti,"f"),n=null!=n?n:this._jpegQuality,s=null!=s&&s;let o=this,r=o._createTask("AppendImageToTiff");const a=yield o._readFile(t);return r.params.input=[a,e,i,n,s],r.handleResult=o._handleBooleanResult,o._addTask(r),r.promise})}addTag(t,e,i){return i=null!=i&&i,this._addTask(this._createTask("AddTagToNextPage",[t,e,i],this._handleBooleanResult))}getTiff(t){t=null!=t?t:Q.RT_AUTO;let e=this._createTask("GetTiffStream");return e.handleResult=this._handleImageData,e.params.returnType=t,e.params.returnBlob=t===Q.RT_AUTO,this._addTask(e)}getMemoryUsed(){return this._addTask(this._createTask("getMemoryUsed",null,function(t,e){return t.memoryUsed}))}getWasmVersion(){return this._addTask(this._createTask("GetWasmVersion",null,function(t,e){return t.version}))}getMultiPartFile(t,e){return this._addTask(this._createTask("ds_get_file",[t,e],function(t,e){return t}))}};ti=new WeakMap,Qe=new WeakSet,ei=function(t,e,i,n,s,o,r,a,l,h){return ln(this,0,void 0,function*(){let c=this;e=null!=e?e:this._inputType,i=null!=i?i:0,n=null!=n?n:0,s=null!=s?s:24,o=null!=o?o:96,r=null!=r?r:96,a=null!=a?a:this._outputType,l=null!=l?l:this._jpegQuality,h=null!=h?h:Q.RT_AUTO;let d=c._createTask("SaveImage");const u=yield c._readFile(t);return d.params.input=[u,e,i,n,s,o,r,a,l],d.params.returnType=h,d.params.returnBlob=h===Q.RT_AUTO,d.handleResult=c._handleImageData,c._addTask(d),d.promise})};let Cn=class extends xn{constructor(t){super(un.ImageReadereModule,t),ii.add(this),ni.set(this,0),si.set(this,!1),oi.set(this,null),ri.set(this,void 0),ai.set(this,0),li.set(this,void 0),hi.set(this,void 0)}workerChanged(t){cn(this,si,!1),t&&(dn.logD("["+this.id+"] worker changed to "+t),cn(this,ai,t))}setExternalWorkerChanged(t,e){cn(this,li,t),cn(this,hi,e)}_workerChanged(t){this.workerChanged(t),hn(this,li,"f")&&hn(this,li,"f").call(this,hn(this,hi,"f"),this,t)}_canTerminateWork(){return!0}makeSureWorkerMemoryNotExceed(){this._makeSureWorkerMemoryNotExceed()||(cn(this,si,!1),hn(this,li,"f")&&hn(this,li,"f").call(this,hn(this,hi,"f"),this))}getImageFormat(t){return ln(this,0,void 0,function*(){let e=this,i=e._createTask("GetImageFormat");const n=yield e._readFile(t.fileSource);return i.params.input=n,e._addTask(i),i.promise})}readImageInfo(t){return ln(this,0,void 0,function*(){let e=this,i=e._createTask("ReadImageInfo");const n=yield e._readFile(t.fileSource);return i.params.input=n,e._addTask(i),i.promise})}readImage(t,e,i,n,s){return ln(this,0,void 0,function*(){e=null!=e?e:this._outputType,i=null!=i?i:this._jpegQuality,n=null!=n?n:Q.RT_AUTO,s=null!=s&&s;let o=this,r=o._createTask("ReadImage");const a=yield o._readFile(t.fileSource);r.params.input=[a,e,i,s],r.params.returnType=null!=n?n:Q.RT_AUTO,r.params.returnBlob=n===Q.RT_AUTO,r.handleResult=o._handleImageData,o._addTask(r);const l=yield r.promise;if(l.srcBuffer){let e=Object.prototype.toString.call(t.fileSource);"[object ArrayBuffer]"!=e&&"[object Uint8ClampedArray]"!=e&&delete l.srcBuffer}return l})}openTiff(t,e){return ln(this,0,void 0,function*(){e=null!=e&&e;let i,n=this,s=n._createTask("LoadTiff");t!=hn(this,oi,"f")&&(t instanceof Blob?cn(n,oi,t):(i=yield n._readFile(t),cn(n,oi,vn.newBlobInChunks(i)))),hn(n,oi,"f").size>1024*un.FileReadModeSize*1024?s.params.input=[hn(n,oi,"f"),e]:(i||(i=yield n._readFile(hn(n,oi,"f"))),s.params.input=[i,e]),n._addTask(s);const o=yield s.promise;if(cn(n,si,!0),o.srcBuffer){let e=Object.prototype.toString.call(t);"[object ArrayBuffer]"!=e&&"[object Uint8ClampedArray]"!=e&&delete o.srcBuffer}return cn(n,ri,{pageCount:o.pageCount}),o})}readTiffPage(t,e,i,n,s){return ln(this,0,void 0,function*(){yield hn(this,ii,"m",ci).call(this,t.fileSource),e=null!=e?e:0,i=null!=i?i:this._outputType,n=null!=n?n:Q.RT_AUTO,s=null!=s&&s;let o=this._createTask("ReadTiffPage");return o.params.input=[e,i,s],o.params.returnType=null!=n?n:Q.RT_AUTO,o.params.returnBlob=n===Q.RT_AUTO,o.handleResult=this._handleImageData,this._addTask(o)})}getTiffInfo(t,e){return ln(this,0,void 0,function*(){return yield hn(this,ii,"m",ci).call(this,t.fileSource),hn(this,ri,"f")})}getTiffPageInfos(t,e){return ln(this,0,void 0,function*(){yield hn(this,ii,"m",ci).call(this,t.fileSource);let i=this._createTask("GetTiffPageInfos");return i.params.input=[e],this._addTask(i)})}};ni=new WeakMap,si=new WeakMap,oi=new WeakMap,ri=new WeakMap,ai=new WeakMap,li=new WeakMap,hi=new WeakMap,ii=new WeakSet,ci=function(t){return ln(this,0,void 0,function*(){if(this.makeSureWorkerMemoryNotExceed(),hn(this,si,"f")){if(hn(this,oi,"f")===t)return void dn.logD("["+this.id+"] already opened in "+this.workerId);yield hn(this,ii,"m",di).call(this)}dn.logD("["+this.id+"] reopen in worker "+this.workerId),yield this.openTiff(t,!1)})},di=function(){if(cn(this,oi,null),hn(this,si,"f"))return cn(this,si,!1),this._addTask(this._createTask("EndReadTiff",null,this._handleBooleanResult))};let bn=class{static decode(t){const e={decodeChars:[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1]};function i(t){let e,i,n,s,o,r,a,l=[],h=t.length;for(e=0;e<h;e++)s=t.charCodeAt(e),s>>7&255?6==(s>>5&255)?(o=t.charCodeAt(++e),i=(31&s)<<6,n=63&o,a=i|n,l.push(String.fromCharCode(a))):14==(s>>4&255)&&(o=t.charCodeAt(++e),r=t.charCodeAt(++e),i=s<<4|o>>2&15,n=(3&o)<<6|63&r,a=(255&i)<<8|n,l.push(String.fromCharCode(a))):l.push(t.charAt(e));return l.join("")}return function(t){let n,s,o,r,a=[],l=0,h=t.length;for(;l<h;){do{n=e.decodeChars[255&t.charCodeAt(l++)]}while(l<h&&-1==n);if(-1==n)break;do{s=e.decodeChars[255&t.charCodeAt(l++)]}while(l<h&&-1==s);if(-1==s)break;a.push(String.fromCharCode(n<<2|(48&s)>>4));do{if(o=255&t.charCodeAt(l++),61==o)return i(a.join(""));o=e.decodeChars[o]}while(l<h&&-1==o);if(-1==o)break;a.push(String.fromCharCode((15&s)<<4|(60&o)>>2));do{if(r=255&t.charCodeAt(l++),61==r)return i(a.join(""));r=e.decodeChars[r]}while(l<h&&-1==r);if(-1==r)break;a.push(String.fromCharCode((3&o)<<6|r))}return i(a.join(""))}(t)}};!function(t){t[t.render=1]="render",t[t.extractImageOnly=2]="extractImageOnly",t[t.auto=3]="auto",t[t.renderWithAnnot=4]="renderWithAnnot"}(Ri||(Ri={}));let Sn=class extends yn{constructor(t){super(un.PdfReaderModule,t),ui.add(this),fi.set(this,void 0),mi.set(this,void 0),yi.set(this,0),xi.set(this,200),wi.set(this,3),Ci.set(this,!1),bi.set(this,void 0),Si.set(this,null),Ti.set(this,""),this._outputType=K.IT_ALL}static get fonts(){return hn(this,pi,"f",gi)}static addPdfFont(t,e){return ln(this,0,void 0,function*(){return hn(this,pi,"m",vi).call(this,t,e)})}static getPdfFonts(){return this.fonts?Object.keys(this.fonts):[]}static removeFont(){cn(this,pi,Object.create(null),0,gi)}workerChanged(t){cn(this,Ci,!1),t&&(dn.logD("["+this.id+"] worker changed to "+t),cn(this,yi,t))}setExternalWorkerChanged(t,e){cn(this,fi,t),cn(this,mi,e)}_workerChanged(t){this.workerChanged(t),hn(this,fi,"f")&&hn(this,fi,"f").call(this,hn(this,mi,"f"),this,t)}_canTerminateWork(){return!0}makeSureWorkerMemoryNotExceed(){this._makeSureWorkerMemoryNotExceed()||(cn(this,Ci,!1),hn(this,fi,"f")&&hn(this,fi,"f").call(this,hn(this,mi,"f"),this))}makeSureWorkerChanged(){this._makeSureWorkerChanged()&&(cn(this,Ci,!1),hn(this,fi,"f")&&hn(this,fi,"f").call(this,hn(this,mi,"f"),this))}getPdfInfo(t){return ln(this,0,void 0,function*(){return yield hn(this,ui,"m",Ei).call(this,t),hn(this,bi,"f")})}readPage(t,e,i,n,s,o,r,a){return ln(this,0,void 0,function*(){return this.readPageEx(t,e,{convertMode:n,renderOptions:{resolution:i}},s,o,r,a)})}readPageEx(t,e,i,n,s,o,r){return ln(this,0,void 0,function*(){yield hn(this,ui,"m",Ei).call(this,t),e=null!=e?e:0,n=null!=n?n:this._outputType,o=null!=o?o:Q.RT_AUTO,s=null!=s&&s,r=null!=r&&r;let a=i?JSON.stringify(i):"{}",l=this._createTask("ReadPdfPageEx");return l.params.input=[e,a,n,s,r],l.params.returnType=o,l.params.returnBlob=o===Q.RT_AUTO,l.handleResult=this._handleImageData,this._addTask(l)})}renderPage(t,e,i,n,s){var o,r,a,l;return ln(this,0,void 0,function*(){yield hn(this,ui,"m",Ei).call(this,t),e=null!=e?e:0;const h=null!==(o=null==s?void 0:s.outputType)&&void 0!==o?o:K.IT_RGBA,c=null!==(r=null==s?void 0:s.rect)&&void 0!==r?r:null,d=null!==(a=null==s?void 0:s.returnType)&&void 0!==a?a:Q.RT_AUTO,u=null!==(l=null==s?void 0:s.is1BitTo8Bit)&&void 0!==l&&l;let p=(null==s?void 0:s.renderOptions)?JSON.stringify(s.renderOptions):"{}",g=this._createTask("RenderPdfPage");return g.params.input=[e,p,c,i,n,h,u],g.params.returnType=d,g.params.returnBlob=d===Q.RT_AUTO,g.handleResult=this._handleImageData,this._addTask(g)})}readPageImageInfos(t,e,i,n){return ln(this,0,void 0,function*(){yield hn(this,ui,"m",Ei).call(this,t),n=null!=n?n:this._outputType;let s=i?JSON.stringify(i):"{}",o=this._createTask("ReadPageImageInfos");return o.params.input=[e,s,n],this._addTask(o)})}readPageAnnot(t,e){return ln(this,0,void 0,function*(){yield hn(this,ui,"m",Ei).call(this,t),e=null!=e?e:0;let i=this._createTask("GetPageAnnot",[e]);return this._addTask(i)})}findText(t,e,i,n){return ln(this,0,void 0,function*(){yield hn(this,ui,"m",Ei).call(this,t);let s=0;return n&&(n.matchCase&&(s|=1),n.matchWholeWord&&(s|=2),n.consecutive&&(s|=4)),this._addTask(this._createTask("SearchText",[e,i,s]))})}getCharInfos(t,e){return ln(this,0,void 0,function*(){return yield hn(this,ui,"m",Ei).call(this,t),this._addTask(this._createTask("GetPageCharInfos",[e]))})}getPageInfos(t,e){return ln(this,0,void 0,function*(){return yield hn(this,ui,"m",Ei).call(this,t),this._addTask(this._createTask("GetPdfPageInfos",[e]))})}getPdfPageType(t,e){return ln(this,0,void 0,function*(){return yield hn(this,ui,"m",Ei).call(this,t),this._addTask(this._createTask("GetPageContentType",[e]))})}UnloadPage(t){return ln(this,0,void 0,function*(){return t=null!=t?t:0,this._addTask(this._createTask("UnloadPdfPage",[t]))})}SetLoadedPageCapacity(t){return ln(this,0,void 0,function*(){return t=null!=t?t:0,this._addTask(this._createTask("SetLoadedPageCapacity",[t]))})}};pi=Sn,fi=new WeakMap,mi=new WeakMap,yi=new WeakMap,xi=new WeakMap,wi=new WeakMap,Ci=new WeakMap,bi=new WeakMap,Si=new WeakMap,Ti=new WeakMap,ui=new WeakSet,vi=function(t,e){return ln(this,0,void 0,function*(){if("string"==typeof t&&0!==t.length||Promise.reject("The 'name' should be a valid string"),void 0===hn(this,pi,"f",gi)[t])if(e instanceof Blob)hn(this,pi,"f",gi)[t]=e;else{const i=yield pn.read(e);hn(this,pi,"f",gi)[t]=vn.newBlobInChunks(i)}})},Ei=function(t){var e,i;return ln(this,0,void 0,function*(){if(this.makeSureWorkerMemoryNotExceed(),hn(this,Ci,"f")){if(hn(this,Si,"f")===t.fileSource)return void dn.logD("["+this.id+"] already opened in "+this.workerId);yield hn(this,ui,"m",Di).call(this)}dn.logD("["+this.id+"] reopen in worker "+this.workerId),yield hn(this,ui,"m",Ii).call(this,null!==(e=t.fileSource)&&void 0!==e?e:hn(this,Si,"f"),null!==(i=t.password)&&void 0!==i?i:hn(this,Ti,"f"))})},_i=function(){return ln(this,0,void 0,function*(){if(0===hn(this,yi,"f")||hn(this,yi,"f")!==this.workerId){if(dn.logD("["+this.id+"] load font in worker "+this.workerId),un.FontUseFileReadMode.load)return yield hn(this,ui,"m",Pi).call(this);const t=Sn.fonts,e=Object.keys(t);for(let i of e){const e=t[i],n=yield pn.read(e);n&&(yield hn(this,ui,"m",Ai).call(this,i,n))}}})},Pi=function(){return ln(this,0,void 0,function*(){return this._addTask(this._createTask("SetSystemFonts",[Sn.fonts]))})},Ai=function(t,e){return ln(this,0,void 0,function*(){return this._addTask(this._createTask("AddSystemFont",[t,e]))})},Ii=function(t,e){return ln(this,0,void 0,function*(){yield hn(this,ui,"m",_i).call(this),e=null!=e?e:"";let i,n=this,s=n._createTask("LoadPdf");return t!==hn(n,Si,"f")||e!==hn(n,Ti,"f")?(t instanceof Blob?cn(n,Si,t):(i=yield n._readFile(t),cn(n,Si,vn.newBlobInChunks(i))),cn(n,Ti,e)):e=hn(n,Ti,"f"),hn(n,Si,"f").size>1024*un.FileReadModeSize*1024?s.params.input=[hn(n,Si,"f"),e]:(i||(i=yield n._readFile(hn(n,Si,"f"))),s.params.input=[i,e]),s.handleResult=function(e,i){if(e.srcBuffer){let i=Object.prototype.toString.call(t);"[object ArrayBuffer]"!=i&&"[object Uint8ClampedArray]"!=i&&delete e.srcBuffer}let s=bn.decode(e.infoBase64);try{let t;try{s.replace(new RegExp("\\\\","gi"),"\\\\"),t=JSON.parse(s)}catch(e){t=s}let i={PdfCount:e.pageCount,PdfInfo:t,isTextBased:e.isTextBased};return e.srcBuffer&&(i.srcBuffer=e.srcBuffer,delete e.srcBuffer),cn(n,Ci,!0),cn(n,bi,i),i}catch(e){i.reject({code:J.wasmJsInvalidJson,message:e.message,stack:e.stack})}},n._addTask(s)})},Di=function(){return ln(this,0,void 0,function*(){if(cn(this,Si,null),cn(this,Ti,""),hn(this,Ci,"f"))return cn(this,Ci,!1),this._addTask(this._createTask("UnloadDocument",null,this._handleBooleanResult))})},gi={value:Object.create(null)};const Tn=["readPdfPage","readTiffPage","readImage","renderPdfPage"];let En=class{constructor(t){this.items=[],t&&(this.items=t)}push(t){this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return 0===this.items.length}size(){return this.items.length}add(t){let e;-1!==Tn.indexOf(t.api)&&this.push(t);for(let i of this.items)i.api===t.api&&i.params[0]===t.params[0]&&i.params[1]===t.params[1]&&(e=i);e?(e.resolves=[...e.resolves,...t.resolves],e.rejects=[...e.rejects,...t.rejects]):this.push(t)}remove(t){-1!==Tn.indexOf(t.api)&&this.items.forEach((e,i)=>{if(e.api===t.api){let n=!1;t.id?n=e.id===t.id:e.params[0]===t.params[0]&&e.params[1]===t.params[1]&&(n=!0),n&&this.items.splice(i,1).forEach(t=>{null==t||t.resolves.forEach(t=>{t(null)})})}})}},_n=class t{static unload(){if(cn(this,ki,[],0,Mi),cn(this,ki,new En,0,Li),cn(this,ki,!1,0,Ni),cn(this,ki,0,0,Vi),cn(this,ki,!1,0,Wi),Sn.removeFont(),hn(this,ki,"f",Oi)){dn.logD("pdfReader destroy");const t=hn(this,ki,"f",Oi);cn(this,ki,null,0,Oi),t.terminate()}if(hn(this,ki,"f",Bi)){dn.logD("imageReader destroy");const t=hn(this,ki,"f",Bi);cn(this,ki,null,0,Bi),t.terminate()}}static updateLicense(t,e,i){return ln(this,0,void 0,function*(){let n=[];return hn(this,ki,"f",Oi)&&n.push(hn(this,ki,"f",Oi).updateLicense(t,e,i)),hn(this,ki,"f",Bi)&&n.push(hn(this,ki,"f",Bi).updateLicense(t,e,i)),Promise.all(n)})}static add(e){return ln(this,0,void 0,function*(){hn(this,ki,"f",Mi).push(e),hn(this,ki,"f",Oi)||(cn(this,ki,new Sn,0,Oi),hn(this,ki,"f",Oi).setExternalWorkerChanged(hn(t,ki,"m",Hi),this),this.initPdfReaderFunctionMap()),hn(this,ki,"f",Bi)||(cn(this,ki,new Cn,0,Bi),hn(this,ki,"f",Bi).setExternalWorkerChanged(hn(t,ki,"m",Hi),this),this.initImageReaderFunctionMap())})}static addFont(t,e){return ln(this,0,void 0,function*(){Sn.addPdfFont(t,e)})}static getFonts(){return Sn.getPdfFonts()}static delete(t){const e=hn(this,ki,"f",Mi).indexOf(t);if(e>=0&&(hn(this,ki,"f",Mi).splice(e,1),0===hn(this,ki,"f",Mi).length&&!hn(this,ki,"f",Ni))){if(hn(this,ki,"f",Oi)){dn.logD("pdfReader destroy");const t=hn(this,ki,"f",Oi);cn(this,ki,null,0,Oi),t.terminate()}if(hn(this,ki,"f",Bi)){dn.logD("imageReader destroy");const t=hn(this,ki,"f",Bi);cn(this,ki,null,0,Bi),t.terminate()}}}static createTask(t,e,i){const n={api:t,id:null!=i?i:"",params:[],promise:[],resolves:[],rejects:[],retry:0};for(const t of e)n.params.push(t);const s=new Promise(function(t,e){n.resolves.push(t),n.rejects.push(e)});return n.promise.push(s),hn(this,ki,"m",ji).call(this,n),s}static cancelTask(t,e,i){if(-1!==Tn.indexOf(t)){const n={api:t,id:null!=i?i:"",params:[],promise:[],resolves:[],rejects:[],retry:0};for(const t of e)n.params.push(t);hn(this,ki,"f",Li).remove(n)}}static initPdfReaderFunctionMap(){var t,e,i,n,s,o,r,a,l;hn(this,ki,"f",Ui).findPdfText=null===(t=hn(this,ki,"f",Oi))||void 0===t?void 0:t.findText,hn(this,ki,"f",Ui).getPdfPageInfos=null===(e=hn(this,ki,"f",Oi))||void 0===e?void 0:e.getPageInfos,hn(this,ki,"f",Ui).getPdfInfo=null===(i=hn(this,ki,"f",Oi))||void 0===i?void 0:i.getPdfInfo,hn(this,ki,"f",Ui).readPdfPageAnnot=null===(n=hn(this,ki,"f",Oi))||void 0===n?void 0:n.readPageAnnot,hn(this,ki,"f",Ui).readPdfPage=null===(s=hn(this,ki,"f",Oi))||void 0===s?void 0:s.readPageEx,hn(this,ki,"f",Ui).readPdfPageImageInfos=null===(o=hn(this,ki,"f",Oi))||void 0===o?void 0:o.readPageImageInfos,hn(this,ki,"f",Ui).getPdfCharInfos=null===(r=hn(this,ki,"f",Oi))||void 0===r?void 0:r.getCharInfos,hn(this,ki,"f",Ui).getPdfPageType=null===(a=hn(this,ki,"f",Oi))||void 0===a?void 0:a.getPdfPageType,hn(this,ki,"f",Ui).renderPdfPage=null===(l=hn(this,ki,"f",Oi))||void 0===l?void 0:l.renderPage}static initImageReaderFunctionMap(){var t,e,i,n,s,o;hn(this,ki,"f",Fi).readImage=null===(t=hn(this,ki,"f",Bi))||void 0===t?void 0:t.readImage,hn(this,ki,"f",Fi).getImageFormat=null===(e=hn(this,ki,"f",Bi))||void 0===e?void 0:e.getImageFormat,hn(this,ki,"f",Fi).readImageInfo=null===(i=hn(this,ki,"f",Bi))||void 0===i?void 0:i.readImageInfo,hn(this,ki,"f",Fi).getTiffInfo=null===(n=hn(this,ki,"f",Bi))||void 0===n?void 0:n.getTiffInfo,hn(this,ki,"f",Fi).readTiffPage=null===(s=hn(this,ki,"f",Bi))||void 0===s?void 0:s.readTiffPage,hn(this,ki,"f",Fi).getTiffPageInfos=null===(o=hn(this,ki,"f",Bi))||void 0===o?void 0:o.getTiffPageInfos}};ki=_n,Hi=function(t,e,i){let n=null!=t?t:this;hn(n,ki,"f",Oi)&&hn(n,ki,"f",Oi)!==e&&hn(n,ki,"f",Oi).workerChanged(i),hn(n,ki,"f",Bi)&&hn(n,ki,"f",Bi)!==e&&hn(n,ki,"f",Bi).workerChanged(i)},ji=function(t){hn(this,ki,"f",Li).add(t),hn(this,ki,"f",Ni)||(cn(this,ki,!0,0,Ni),hn(this,ki,"m",Gi).call(this))},zi=function(){try{hn(this,ki,"f",Bi)&&hn(this,ki,"f",Bi).makeSureWorkerMemoryNotExceed(),hn(this,ki,"f",Oi)&&hn(this,ki,"f",Oi).makeSureWorkerMemoryNotExceed()}catch(t){}},Gi=function(){return ln(this,0,void 0,function*(){do{if(hn(this,ki,"f",Li).isEmpty()||!hn(this,ki,"f",Oi)||!hn(this,ki,"f",Bi))break;const t=hn(this,ki,"f",Li).pop();if(t)try{let e,i=hn(this,ki,"f",Ui)[t.api];if(i){const i=this.getFonts().length;hn(this,ki,"f",Vi)!==i&&(hn(this,ki,"f",Wi)&&(hn(this,ki,"f",Oi).makeSureWorkerChanged(),cn(this,ki,!1,0,Wi)),cn(this,ki,i,0,Vi)),e=yield hn(this,ki,"f",Ui)[t.api].apply(hn(this,ki,"f",Oi),t.params),"renderPdfPage"===t.api&&t.id&&(e.id=t.id),hn(this,ki,"f",Oi).makeSureWorkerMemoryNotExceed(),cn(this,ki,!0,0,Wi)}else i=hn(this,ki,"f",Fi)[t.api],i&&(e=yield hn(this,ki,"f",Fi)[t.api].apply(hn(this,ki,"f",Bi),t.params),hn(this,ki,"f",Bi).makeSureWorkerMemoryNotExceed());null==t||t.resolves.forEach(t=>{t(e)})}catch(e){dn.logD(e),t.retry<1&&-80202!==(null==e?void 0:e.code)?(t.retry+=1,hn(this,ki,"m",zi).call(this),hn(this,ki,"f",Li).push(t)):null==t||t.rejects.forEach(t=>{t(e)})}}while(!hn(this,ki,"f",Li).isEmpty());cn(this,ki,!1,0,Ni)})},Mi={value:[]},Li={value:new En},Oi={value:void 0},Bi={value:void 0},Ni={value:!1},Ui={value:Object.create(null)},Fi={value:Object.create(null)},Vi={value:0},Wi={value:!1};let Pn=class{constructor(){_n.add(this)}destroy(){_n.delete(this)}readImage(t,e,i,n,s){return ln(this,0,void 0,function*(){return _n.createTask("readImage",[t,e,i,n,s])})}getImageFormat(t){return ln(this,0,void 0,function*(){return _n.createTask("getImageFormat",[t])})}readImageInfo(t){return ln(this,0,void 0,function*(){return _n.createTask("readImageInfo",[t])})}cancelReadImage(t,e){return _n.cancelTask("readImage",[t,e])}getTiffInfo(t){return ln(this,0,void 0,function*(){return _n.createTask("getTiffInfo",[t,!1])})}readTiffPage(t,e,i,n,s){return ln(this,0,void 0,function*(){return _n.createTask("readTiffPage",[t,e,i,n,s])})}cancelReadTiffPage(t,e){return _n.cancelTask("readTiffPage",[t,e])}getTiffPageInfos(t,e){return ln(this,0,void 0,function*(){return _n.createTask("getTiffPageInfos",[t,e])})}};var An,In,Dn,Rn,kn,Mn,Ln,On,Bn,Nn,Un,Fn,Vn,Wn,Hn,jn,zn,Gn,Yn,$n;!function(t){t[t.NearestNeighbour=1]="NearestNeighbour",t[t.Bilinear=2]="Bilinear",t[t.Bicublic=3]="Bicublic",t[t.BestQuality=5]="BestQuality"}(Dn||(Dn={}));let Xn=class extends xn{constructor(t){super(un.ImageProcModule,t),An.add(this)}initImage(t,e,i,n,s){return ln(this,0,void 0,function*(){e=null!=e&&e,i=null!=i?i:0,n=null!=n?n:0,s=null!=s&&s;let o=this,r=o._createTask("InitImageObject");if(r.params.input=[t,i,n],e||s){const i=yield o._readFile(t);r.params.input[0]=i,e?r.params.input.push(K.IT_RGBA):r.params.input.push(K.IT_BGRA),o._addTask(r)}else{const e=yield o._readFile(t);r.params.input[0]=e,r.params.input.push(K.IT_ALL),o._addTask(r)}const a=yield r.promise;if(a.srcBuffer){let e=Object.prototype.toString.call(t);"[object ArrayBuffer]"!=e&&"[object Uint8ClampedArray]"!=e&&delete a.srcBuffer}return a})}restore(){return this._addTask(this._createTask("BackToOriginal",null,this._handleBooleanResult))}filter(t,e,i){var n,s,o,r,a,l,h,c,d;let u=this;e=null!=e?e:{},i=null!=i?i:{};let p=u._createTask("Filter");if(p.params.input=[],p.params.input.push(t),"toBW"===t)p.params.input.push(JSON.stringify(hn(u,An,"m",In).call(u,e)));else if("toGray"===t)p.params.input.push(JSON.stringify(hn(u,An,"m",In).call(u,e)));else if("removeShadow"===t)p.params.input.push(JSON.stringify(hn(u,An,"m",In).call(u,e)));else if("enhance"===t)p.params.input.push(JSON.stringify(hn(u,An,"m",In).call(u,e)));else if("invert"===t)p.params.input.push(JSON.stringify(hn(u,An,"m",In).call(u,e)));else if("brightnessAndContrast"===t){let t=null!==(n=e.brightness)&&void 0!==n?n:0,i=null!==(s=e.contrast)&&void 0!==s?s:0;p.params.input.push(t),p.params.input.push(i)}let g=i.outputType,f=null!==(o=i.returnType)&&void 0!==o?o:Q.RT_AUTO,m=null!==(r=i.jpegQuality)&&void 0!==r?r:this._jpegQuality,v=null!==(a=i.bRGBA)&&void 0!==a&&a,y=null!==(l=i.bitDepth)&&void 0!==l?l:0,x=null!==(h=i.xdpi)&&void 0!==h?h:0,w=null!==(c=i.ydpi)&&void 0!==c?c:0;g=v&&null==g?K.IT_JPG:null!=g?g:K.IT_ALL;let C=null!==(d=i.is1BitTo8Bit)&&void 0!==d&&d;return p.params.input.push([g,y,x,w,!1,m,!1,C]),p.params.returnBlob=f===Q.RT_AUTO,p.handleResult=this._handleImageData,u._addTask(p),p.promise}rotate(t,e,i,n){return t=null!=t?t:0,i=null!=i&&i,n=null!=n?n:Dn.Bicublic,e=null!=e?e:"FFFFFF",(t<0||t>360)&&(t%=360)<0&&(t+=360),this._addTask(this._createTask("RotateEx",[t,i,n,e],this._handleBooleanResult))}flip(t){t=null!=t?t:1;let e=this._createTask("");return e.handleResult=this._handleBooleanResult,1===t?e.func="Flip":-1===t&&(e.func="Mirror"),this._addTask(e),e.promise}erase(t,e,i,n,s){let o=this,r=o._createTask("Erase");return r.handleResult=this._handleBooleanResult,r.params.input=[t,e,i,n,JSON.stringify(hn(o,An,"m",In).call(o,s))],o._addTask(r),r.promise}crop(t,e,i,n){return this._addTask(this._createTask("Crop",[t,e,i,n],this._handleBooleanResult))}resize(t,e,i){return i=null!=i?i:Dn.BestQuality,this._addTask(this._createTask("ChangeImageSize",[t,e,i],this._handleBooleanResult))}toGrayscaleLevel(t){(t=null!=t?t:1)<1&&(t=1),t>3&&(t=3);let e={};return 2===t?(e.clean=!0,e.sigma=3,e.scaleLimit=720,e.alpha=1.05):3===t&&(e.clean=!0,e.sigma=5,e.scaleLimit=1080,e.alpha=1.05),this.toGrayscale(e)}toGrayscale(t){return this._addTask(this._createTask("ConvertToGrayScale",JSON.stringify(hn(this,An,"m",In).call(this,t)),this._handleBooleanResult))}toBinaryLevel(t,e){(e=null!=e?e:1)<1&&(e=1),e>3&&(e=3);let i={};return null!=t&&(t?i.method="adaptiveThreshold":(i.method="threshold",2===e?(i.clean=!0,i.sigma=3,i.scaleLimit=720,i.alpha=1.05):3===e&&(i.clean=!0,i.sigma=5,i.scaleLimit=1080,i.alpha=1.05))),this.toBinary(i)}toBinary(t){return this._addTask(this._createTask("ConvertToBW",JSON.stringify(hn(this,An,"m",In).call(this,t)),this._handleBooleanResult))}invert(){return this._addTask(this._createTask("Invert",null,this._handleBooleanResult))}setImageWidth(t,e){return this._addTask(this._createTask("SetImageWidth",[t,JSON.stringify(hn(this,An,"m",In).call(this,e))],this._handleBooleanResult))}setImageHeight(t,e){return this._addTask(this._createTask("SetImageHeight",[t,JSON.stringify(hn(this,An,"m",In).call(this,e))],this._handleBooleanResult))}setDPI(t,e,i,n,s,o){return s=null!=s&&s,o=null!=o?o:Dn.Bilinear,this._addTask(this._createTask("SetDPI",[t,e,i,n,s,o],this._handleBooleanResult))}getImage(t,e,i,n,s,o,r,a,l){t=null!=t?t:this._jpegQuality,e=null==e||e,i=null!=i&&i,n=null!=n?n:0,s=null!=s?s:0,o=null!=o?o:0,r=null!=r?r:Q.RT_AUTO,a=i&&null==a?K.IT_JPG:null!=a?a:K.IT_ALL,l=null!=l&&l;let h=this._createTask("GetCurrentImage");return h.params.input=[a,n,s,o,!1,t,e,l],h.params.returnBlob=r===Q.RT_AUTO,h.handleResult=this._handleImageData,this._addTask(h)}getSkewAngle(t){return this._addTask(this._createTask("GetSkewAngle",[JSON.stringify(hn(this,An,"m",In).call(this,t))],function(t,e){return t.skewAngle}))}freeReservedData(){return this._addTask(this._createTask("FreeReservedData",null,this._handleBooleanResult))}detectDocument(t,e,i,n,s){return t=null!=t?t:Dn.Bilinear,e=null!=e?e:75,i=null!=i?i:100,n=null!=n?n:0,s=null!=s?s:"",this._addTask(this._createTask("DocumentDetect",[t,e/100,i,n/255,s,"1"]))}perspective(t,e,i,n,s,o,r,a){return this._addTask(this._createTask("Perspective",[t,e,i,n,s,o,r,a],this._handleBooleanResult))}changeBrightness(t,e){return t=null!=t?t:0,0!=(e=null!=e?e:1)&&1!=e&&(e=0),1===e?this._addTask(this._createTask("ChangeBrightnessAndContrast",[t,0],this._handleBooleanResult)):this._addTask(this._createTask("ChangeBrightness",[Math.floor(t/1e3*255)],this._handleBooleanResult))}changeContrast(t,e){return t=null!=t?t:0,0!=(e=null!=e?e:1)&&1!=e&&(e=0),1===e?this._addTask(this._createTask("ChangeBrightnessAndContrast",[0,t],this._handleBooleanResult)):this._addTask(this._createTask("ChangeContrast",[1+t/1e3],this._handleBooleanResult))}changeBrightnessAndContrast(t,e){return t=null!=t?t:0,e=null!=e?e:0,this._addTask(this._createTask("ChangeBrightnessAndContrast",[t,e],this._handleBooleanResult))}removeShadowLevel(t,e){e=null!=e?e:1.05,(t=null!=t?t:1)<1&&(t=1),t>3&&(t=3);let i={};return 1===t&&(i.sigma=3,i.scaleLimit=720,i.alpha=e),2===t?(i.sigma=5,i.scaleLimit=1080,i.alpha=e):3===t&&(i.sigma=10,i.scaleLimit=0,i.alpha=e),this.removeShadow(i)}removeShadow(t){return this._addTask(this._createTask("ShadowRemovel",[JSON.stringify(hn(this,An,"m",In).call(this,t))],this._handleBooleanResult))}enhanceAndSharpenImage(){return this._addTask(this._createTask("EnhanceAndSharpen",[""],this._handleBooleanResult))}brighten(){return this._addTask(this._createTask("Brighten",[""],this._handleBooleanResult))}getBlurryScore(){return this._addTask(this._createTask("GetBlurScore",[""],function(t,e){return t.blurryScore}))}drawQuadrangle(t,e,i,n,s,o,r,a,l){return this._addTask(this._createTask("DrawQuadrangle",[t,e,i,n,s,o,r,a,JSON.stringify(hn(this,An,"m",In).call(this,l))],this._handleBooleanResult))}getImageInfo(){return this._addTask(this._createTask("GetImageInfo",[]))}};An=new WeakSet,In=function(t){let e={};if(null!=t&&"object"==typeof t)for(let i in t)e[i]=t[i];return e};let qn=class{constructor(){_n.add(this)}destroy(){_n.delete(this)}static addPdfFont(t,e){return ln(this,0,void 0,function*(){return _n.addFont(t,e)})}static getPdfFonts(){return _n.getFonts()}getPdfInfo(t){return ln(this,0,void 0,function*(){return _n.createTask("getPdfInfo",[t])})}getPdfPageType(t,e){return ln(this,0,void 0,function*(){return _n.createTask("getPdfPageType",[t,e])})}readPage(t,e,i,n,s,o,r,a){return ln(this,0,void 0,function*(){return this.readPageEx(t,e,{convertMode:n,renderOptions:{resolution:i}},s,o,r,a)})}readPageEx(t,e,i,n,s,o,r){return ln(this,0,void 0,function*(){return _n.createTask("readPdfPage",[t,e,i,n,s,o,r])})}renderPage(t,e,i,n,s,o){return ln(this,0,void 0,function*(){return _n.createTask("renderPdfPage",[t,e,i,n,s],o)})}cancelReadPage(t,e){return _n.cancelTask("readPdfPage",[t,e])}cancelRenderPage(t){return _n.cancelTask("renderPdfPage",[],t)}readPageImageInfos(t,e,i,n,s,o,r){return ln(this,0,void 0,function*(){return _n.createTask("readPdfPageImageInfos",[t,e,i,n,s,o,r])})}readPageAnnot(t,e){return ln(this,0,void 0,function*(){return _n.createTask("readPdfPageAnnot",[t,e])})}findText(t,e,i,n){return ln(this,0,void 0,function*(){return _n.createTask("findPdfText",[t,e,i,n])})}getCharInfos(t,e){return ln(this,0,void 0,function*(){return _n.createTask("getPdfCharInfos",[t,e])})}getPageInfos(t,e){return ln(this,0,void 0,function*(){return _n.createTask("getPdfPageInfos",[t,e])})}};!function(t){t[t.auto=0]="auto",t[t.store=1]="store"}(On||(On={}));let Zn=class extends xn{constructor(t){super(un.PdfWriterModule,t),Rn.add(this)}initPdfSetting(t){return ln(this,0,void 0,function*(){let e=this,i=e._createTask("CreateDocument");return i.params.input=[JSON.stringify(hn(e,Rn,"m",Ln).call(e,t))],i.handleResult=this._handleBooleanResult,yield hn(this,Rn,"m",kn).call(this),e._addTask(i)})}appendPage(t,e){return ln(this,0,void 0,function*(){let i=this,n=i._createTask("InsertImagePage");e=null!=e&&e;const s=yield i._readFile(t);return n.params.input=[s,-1,e],n.handleResult=i._handleBooleanResult,i._addTask(n),n.promise})}insertPage(t,e,i){return ln(this,0,void 0,function*(){let n=this,s=n._createTask("InsertImagePage");i=null!=i&&i;const o=yield n._readFile(t);return s.params.input=[o,e,i],s.handleResult=n._handleBooleanResult,n._addTask(s),s.promise})}writePdf(t){return ln(this,0,void 0,function*(){let e=this._createTask("GetCurrentPdf");return e.params.returnType=null!=t?t:Q.RT_AUTO,e.params.returnBlob=t===Q.RT_AUTO,e.handleResult=this._handleImageData,this._addTask(e)})}insertBlankPage(t,e,i){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:595,i=null!=i?i:842,this._addTask(this._createTask("InsertBlankPage",[t,e,i]))})}insertBlankPages(t,e,i,n){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:595,i=null!=i?i:842,n=null!=n?n:1,this._addTask(this._createTask("InsertBlankPages",[t,e,i,n]))})}deletePage(t){return ln(this,0,void 0,function*(){return t=null!=t?t:0,this._addTask(this._createTask("DeletePage",[t],this._handleBooleanResult))})}movePages(t,e){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:[],this._addTask(this._createTask("MovePages",[t,e],this._handleBooleanResult))})}pageSetRotation(t,e){return ln(this,0,void 0,function*(){t=null!=t?t:0,0!=(e=((e=null!=e?e:0)%360+360)%360)&&90!==e&&180!==e&&270!==e&&(e=0);let i=this._createTask("SetPageRotation");return i.params.input=[t,e],i.handleResult=this._handleBooleanResult,this._addTask(i)})}pageSetCropBox(t,e,i,n,s){return ln(this,0,void 0,function*(){t=null!=t?t:0,e=null!=e?e:0,i=null!=i?i:0,(n=null!=n?n:e)<e&&(n=e),(s=null!=s?s:i)<i&&(s=i);let o=this._createTask("SetPageCropBox");return o.params.input=[t,e,i,n,s],o.handleResult=this._handleBooleanResult,this._addTask(o)})}pageSetMediaBox(t,e,i,n,s){return ln(this,0,void 0,function*(){t=null!=t?t:0,e=null!=e?e:0,i=null!=i?i:0,(n=null!=n?n:e)<e&&(n=e),(s=null!=s?s:i)<i&&(s=i);let o=this._createTask("SetPageMediaBox");return o.params.input=[t,e,i,n,s],o.handleResult=this._handleBooleanResult,this._addTask(o)})}pageAddImage(t,e,i,n,s,o){return ln(this,0,void 0,function*(){o=null!=o&&o;let r=this,a=r._createTask("PageAddImage"),l=JSON.stringify(hn(r,Rn,"m",Ln).call(r,i));const h=yield r._readFile(t);return a.params.input=[h,e,l,n,s,o],a.handleResult=r._handleBooleanResult,r._addTask(a),a.promise})}pageAddText(t,e){return ln(this,0,void 0,function*(){let i=JSON.stringify(e);return this._addTask(this._createTask("PageAddText",[t,i],this._handleBooleanResult))})}pageAddPath(t,e){return ln(this,0,void 0,function*(){let i=JSON.stringify(e);return this._addTask(this._createTask("PageAddPath",[t,i],this._handleBooleanResult))})}pageClearObjects(t){return ln(this,0,void 0,function*(){return t=null!=t?t:0,this._addTask(this._createTask("PageClearObjects",[t],this._handleBooleanResult))})}pageSetAnnot(t,e){return ln(this,0,void 0,function*(){let i;return t=null!=t?t:0,Array.isArray(e)?(i="[",e.forEach((t,e)=>{e>0&&(i+=","),i+=JSON.stringify(t)}),i+="]"):i=JSON.stringify(e),this._addTask(this._createTask("SetPageAnnot",[t,i],this._handleBooleanResult))})}pageFlattenAnnot(t,e){return ln(this,0,void 0,function*(){let i;return t=null!=t?t:0,Array.isArray(e)?(i="[",e.forEach((t,e)=>{e>0&&(i+=","),i+=JSON.stringify(t)}),i+="]"):i=JSON.stringify(e),this._addTask(this._createTask("FlattenPageAnnot",[t,i],this._handleBooleanResult))})}pageRedact(t,e){return ln(this,0,void 0,function*(){let i;return t=null!=t?t:0,Array.isArray(e)?(i="[",e.forEach((t,e)=>{e>0&&(i+=","),i+=JSON.stringify(t)}),i+="]"):i=JSON.stringify(e),this._addTask(this._createTask("PageRedact",[t,i],this._handleBooleanResult))})}getFontFromTextObject(t){return t.fontName?t.fontName:""}getFontFromAnnot(t){let e=[];t&&t.normalAppearance&&t.normalAppearance.objs&&t.normalAppearance.objs.forEach(t=>{if("text"===t.type){const i=t,n=this.getFontFromTextObject(i);n&&e.push(n)}});const i=new Set(e);return e=[...i],e}getFontFromAnnots(t){let e=[];Array.isArray(t)?t.forEach(t=>{const i=this.getFontFromAnnot(t);e=e.concat(i)}):e=this.getFontFromAnnot(t);const i=new Set(e);return e=[...i],e}pageAddAnnot(t,e){return ln(this,0,void 0,function*(){let i;return t=null!=t?t:0,Array.isArray(e)?(i="[",e.forEach((t,e)=>{e>0&&(i+=","),i+=JSON.stringify(t)}),i+="]"):i=JSON.stringify(e),this._addTask(this._createTask("PageAddAnnot",[t,i],this._handleBooleanResult))})}pageDeleteAnnot(t,e){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:0,this._addTask(this._createTask("DeletePageAnnot",[t,e],this._handleBooleanResult))})}pageDeleteAnnotByTypes(t,e){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:"",this._addTask(this._createTask("DeletePageAnnotByTypes",[t,e],this._handleBooleanResult))})}pageDeleteAnnotExceptTypes(t,e){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:"",this._addTask(this._createTask("DeletePageAnnotExceptTypes",[t,e],this._handleBooleanResult))})}pageDeleteAnnotByNames(t,e){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:"",this._addTask(this._createTask("DeletePageAnnotByNames",[t,e],this._handleBooleanResult))})}mergePdf(t,e,i,n,s){return ln(this,0,void 0,function*(){n=null!=n?n:-1,i=null!=i?i:[],e=null!=e?e:"",s=null!=s&&s;let o,r=this,a=r._createTask("MergePdfPages");return o=t instanceof Blob?t:yield r._readFile(t),a.params.input=[o,n,e,i,s],a.handleResult=r._handleBooleanResult,r._addTask(a),a.promise})}replacePdfPages(t,e,i,n,s){return ln(this,0,void 0,function*(){i=null!=i?i:[],n=null!=n?n:[],e=null!=e?e:"",s=null!=s&&s;let o,r=this,a=r._createTask("ReplacePdfPages");return o=t instanceof Blob?t:yield r._readFile(t),a.params.input=[o,e,i,n,s],a.handleResult=r._handleBooleanResult,r._addTask(a),a.promise})}pageFlatten(t,e){return ln(this,0,void 0,function*(){return t=null!=t?t:0,e=null!=e?e:0,this._addTask(this._createTask("PageFlatten",[t,e],this._handleBooleanResult))})}GetFontInfo(t){return ln(this,0,void 0,function*(){const e=yield this._readFile(t);return this._addTask(this._createTask("GetFontInfo",[e]))})}IfFontsExist(t){return ln(this,0,void 0,function*(){let e=JSON.stringify(t);return yield hn(this,Rn,"m",kn).call(this),this._addTask(this._createTask("IfFontsExist",[e]))})}UnloadPage(t){return ln(this,0,void 0,function*(){return t=null!=t?t:0,this._addTask(this._createTask("UnloadPdfPage",[t]))})}};Rn=new WeakSet,kn=function(){return ln(this,0,void 0,function*(){if(dn.logD("["+this.id+"] load font in worker "+this.workerId),0===Object.keys(Sn.fonts).length)return null;if(un.FontUseFileReadMode.save)return this._addTask(this._createTask("LoadFonts",[Sn.fonts]));const t=Sn.fonts,e=Object.keys(t);for(let i of e){const e=t[i],n=yield pn.read(e);n&&(yield hn(this,Rn,"m",Mn).call(this,i,n))}})},Mn=function(t,e){return ln(this,0,void 0,function*(){return this._addTask(this._createTask("LoadFont",[e,t]))})},Ln=function(t){let e={};if(null!=t&&"object"==typeof t)for(let i in t)e[i]=t[i];return e},function(t){t.Text="Text",t.Link="Link",t.FreeText="FreeText",t.Line="Line",t.Square="Square",t.Circle="Circle",t.Polygon="Polygon",t.PolyLine="PolyLine",t.Hignlight="Highlight",t.Underline="Underline",t.Squiggly="Squiggly",t.StrikeOut="StrikeOut",t.Stamp="Stamp",t.Caret="Caret",t.Ink="Ink",t.Popup="Popup"}(Bn||(Bn={})),function(t){t.None="none",t.Invisible="invisible",t.Hidden="hidden",t.Print="print",t.NoZoom="nozoom",t.NoRotate="norotate",t.NoView="noview",t.ReadOnly="readonly",t.Locked="locked",t.ToggleNoView="togglenoview",t.LockedContents="lockedcontents"}(Nn||(Nn={})),function(t){t.Solid="S",t.Dashed="D",t.Beveled="B",t.Insert="I",t.Underline="U"}(Un||(Un={})),function(t){t.NoEffect="S",t.Cloudy="C"}(Fn||(Fn={})),function(t){t.Comment="Comment",t.Key="Key",t.Note="Note",t.Help="Help",t.NewParagraph="NewParagraph",t.Paragraph="Paragraph",t.Insert="Insert"}(Vn||(Vn={})),function(t){t.Marked="Marked",t.Review="Review"}(Wn||(Wn={})),function(t){t.Accepted="Accepted",t.Rejected="Rejected",t.Cancelled="Cancelled",t.Completed="Completed",t.None="None"}(Hn||(Hn={})),function(t){t.None="None",t.Square="Square",t.Circle="Circle",t.Diamond="Diamond",t.OpenArrow="OpenArrow",t.ClosedArrow="ClosedArrow",t.Butt="Butt",t.ROpenArrow="ROpenArrow",t.RClosedArrow="RClosedArrow",t.Slash="Slash"}(jn||(jn={})),function(t){t[t.LeftJustified=0]="LeftJustified",t[t.Centered=1]="Centered",t[t.RightJustified=2]="RightJustified"}(zn||(zn={})),function(t){t.FreeText="FreeText",t.FreeTextCallout="FreeTextCallout",t.FreeTextTypeWriter="FreeTextTypeWriter"}(Gn||(Gn={})),function(t){t.LineArrow="LineArrow",t.LineDimension="LineDimension"}(Yn||(Yn={})),function(t){t.Approved="Approved",t.Experimental="Experimental",t.NotApproved="NotApproved",t.Asls="Asls",t.Expired="Expired",t.NotForPublicRelease="NotForPublicRelease",t.Confidential="Confidential",t.Final="Final",t.Sold="Sold",t.Departmental="Departmental",t.ForComment="ForComment",t.TopSecret="TopSecret",t.Draft="Draft",t.ForPublicRelease="ForPublicRelease"}($n||($n={}));const Jn="undefined"==typeof self,Kn=Jn?{}:self;let Qn,ts,es,is,ns;"undefined"!=typeof navigator&&(Qn=navigator,ts=Qn.userAgent,es=Qn.platform,is=Qn.mediaDevices),function(){if(!Jn){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Qn.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:es,search:"Win"},Mac:{str:es},Linux:{str:es}};let i="unknownBrowser",n=0,s="unknownOS";for(let e in t){const s=t[e]||{};let o=s.str||ts,r=s.search||e,a=s.verStr||ts,l=s.verSearch||e;if(l instanceof Array||(l=[l]),-1!=o.indexOf(r)){i=e;for(let t of l){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||ts,o=i.search||t;if(-1!=n.indexOf(o)){s=t;break}}"Linux"==s&&-1!=ts.indexOf("Windows NT")&&(s="HarmonyOS"),ns={browser:i,version:n,OS:s}}Jn&&(ns={browser:"ssr",version:0,OS:"ssr"})}(),is&&is.getUserMedia;const ss="Chrome"===ns.browser&&ns.version>66||"Safari"===ns.browser&&ns.version>13||"OPR"===ns.browser&&ns.version>43||"Edge"===ns.browser&&ns.version>15,os="\\s*([+-]?\\d+)\\s*",rs="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",as="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",ls=/^#([0-9a-f]{3,8})$/,hs=new RegExp(`^rgb\\(${os},${os},${os}\\)$`),cs=new RegExp(`^rgb\\(${as},${as},${as}\\)$`),ds=new RegExp(`^rgba\\(${os},${os},${os},${rs}\\)$`),us=new RegExp(`^rgba\\(${as},${as},${as},${rs}\\)$`),ps=new RegExp(`^hsl\\(${rs},${as},${as}\\)$`),gs=new RegExp(`^hsla\\(${rs},${as},${as},${rs}\\)$`),fs={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};let ms=class{constructor(t,e,i,n){Yi(this,"r",void 0),Yi(this,"g",void 0),Yi(this,"b",void 0),Yi(this,"opacity",void 0),this.r=t,this.g=e,this.b=i,this.opacity=n}};function vs(t){return new ms(t>>16&255,t>>8&255,255&t,1)}function ys(t,e,i,n){return n<=0&&(t=NaN,e=NaN,i=NaN),new ms(t,e,i,n)}function xs(t,e,i,n){return n<=0?(t=NaN,e=NaN,i=NaN):i<=0||i>=1?(t=NaN,e=NaN):e<=0&&(t=NaN),{h:t,s:e,l:i,opacity:n}}function ws(t,e,i){return t<60?(e+(i-e)*t)/60*255:t<180?255*i:t<240?(e+(i-e)*(240-t))/60*255:255*e}function Cs(t){const e=t.h<0?t.h%360+360:t.h%360,i=Number.isNaN(e)||Number.isNaN(t.s)?0:t.s,{l:n}=t,s=n+(n<.5?n:1-n)*i,o=2*n-s;return new ms(ws(e>=240?e-240:e+120,o,s),ws(e,o,s),ws(e<120?e+240:e-120,o,s),t.opacity)}const bs=t=>t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`),Ss=t=>Object.prototype.toString.call(t),Ts=t=>Array.isArray?Array.isArray(t):"[object Array]"===Ss(t),Es=t=>null!==t&&"[object Object]"===Ss(t),_s=t=>{let e=null;return Ts(t)&&(e||(e=[]),t.forEach(t=>{e.push(_s(t))})),Es(t)&&(e||(e={}),Object.keys(t).forEach(i=>{e[i]=_s(t[i])})),e||t},Ps=t=>void 0===t,As=(t,e)=>{var i;t=null!==(i=t)&&void 0!==i?i:"yyyy-MM-dd hh:mm:ss";const n=Ps(e)?new Date:new Date(e),s={"M+":(n.getMonth()+1).toString(),"d+":n.getDate().toString(),"h+":n.getHours().toString(),"m+":n.getMinutes().toString(),"s+":n.getSeconds().toString(),"q+":Math.floor((n.getMonth()+3)/3).toString(),S:n.getMilliseconds().toString()};return/(y+)/.test(t)&&(t=t.replace(RegExp.$1,`${n.getFullYear()}`.substring(4-RegExp.$1.length))),Object.keys(s).forEach(e=>{new RegExp(`(${e})`).test(t)&&(t=t.replace(RegExp.$1,1===RegExp.$1.length?s[e]:`00${s[e]}`.substring(`${s[e]}`.length)))}),t},Is=t=>"[object ArrayBuffer]"===Ss(t),Ds=t=>"[object Blob]"===Ss(t),Rs=t=>"[object Boolean]"===Ss(t),ks=t=>"function"==typeof t,Ms=()=>"ontouchstart"in document.documentElement,Ls=t=>"number"==typeof t&&!Number.isNaN(t),Os=t=>"string"==typeof t,Bs=(t,e,i)=>Math.min(Math.max(t,e),i);let Ns=0;const Us=()=>(Ns+=1,`${(new Date).getTime().toString(36)}${Ns.toString(36)}`),Fs=t=>{const e=window.URL||window.webkitURL;let i="string";return Os(t)?i="string":Ds(t)?(i="blob",t=e.createObjectURL(t)):(Is(t)||Ts(t))&&(i="blob",t=e.createObjectURL(new Blob([t]))),{type:i,data:t}};function Vs(t){return"object"==typeof HTMLElement?t instanceof HTMLElement:t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.nodeName}let Ws=class t{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";Yi(this,"prefix",void 0),Yi(this,"postfix",void 0),Yi(this,"isDestroyed",!1),Yi(this,"uid",Us()),Yi(this,"cacheEvents",void 0),Yi(this,"events",void 0),Yi(this,"isCached",void 0),this.cacheEvents=[],this.events={},this.isCached=!1,this.prefix=t,this.postfix=e}static create(e,i){return new t(e,i)}hasCallback(t){return this.events[t]&&this.events[t].length>0}save(){this.isCached=!0}restore(){this.isCached=!1,this.cacheEvents.forEach(t=>{let{eventName:e,param:i}=t;this.emit(e,...i)}),this.cacheEvents.length=0}destroy(){if(!this.isDestroyed){for(const t in this.events)if(Object.prototype.hasOwnProperty.call(this.events,t)){const e=this.events[t];e&&e.slice().forEach(t=>{let{name:e,fn:i,context:n,once:s}=t;this.off(e,i,n,s)})}this.events={},this.isDestroyed=!0}}on(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const{events:s}=this,o={name:t=this.format(t),uid:Us(),context:i,once:n,fn:e};return s[t]||(s[t]=[]),s[t].indexOf(o)<0&&s[t].push(o),o}once(t,e,i){return this.on(t,e,i,!0)}emit(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];if(this.isCached)return this.cacheEvents.push({eventName:t,param:i}),!0;const{events:s}=this,o=s[t=this.format(t)];return!(!o||!o.length||(o.slice().forEach(t=>{let{fn:e,context:n}=t;e.call(n||null,...i)}),o.slice().forEach(e=>{let{fn:i,context:n,once:s}=e;s&&this.off(t,i,n,s)}),0))}off(t,e,i,n){const{events:s}=this,o=s[t=this.format(t)];if(!o)return!1;if(!arguments.length)return o.length=0,!0;for(let t=o.length-1;t>=0;t--){const s=o[t];e&&s.fn!==e||i&&s.context!==i||n&&s.once!==n||o.splice(t,1)}return!0}removeAllEventListeners(t){if(t){t=this.format(t);const e=this.cacheEvents.findIndex(e=>e.eventName===t);e>-1&&this.cacheEvents.splice(e,1),this.events[t]&&delete this.events[t]}else this.cacheEvents=[],this.events={}}getAllEvents(){return this.events}format(t){return`${this.prefix||""}${t}${this.postfix||""}`}};const Hs="default";let js=class t{constructor(){Yi(this,"emitter",new Ws)}static create(){return new t}hasCallback(){return this.emitter.hasCallback(Hs)}on(t){this.emitter.on(Hs,t)}emit(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this.emitter.emit(Hs,...e)}off(t){this.emitter.off(Hs,t)}};function zs(){return new js}let Gs=class t{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;Yi(this,"x",void 0),Yi(this,"y",void 0),Yi(this,"z",void 0),this.x=t,this.y=e,this.z=i}static fromPoint(e){return new t(e.x,e.y,e.z)}static fromTwoPoint(e,i){var n,s,o,r,a,l;return new t((null!==(n=i.x)&&void 0!==n?n:0)-(null!==(s=e.x)&&void 0!==s?s:0),(null!==(o=i.y)&&void 0!==o?o:0)-(null!==(r=e.y)&&void 0!==r?r:0),(null!==(a=i.z)&&void 0!==a?a:0)-(null!==(l=e.z)&&void 0!==l?l:0))}static fromValue(e,i,n){return new t(e,i,n)}setFromVector(t){var e;this.x=t.x,this.y=t.y,this.z=null!==(e=t.z)&&void 0!==e?e:0}clone(){return new t(this.x,this.y,this.z)}norm(){return Math.hypot(this.x,this.y,this.z)}dot(t){var e;return this.x*t.x+this.y*t.y+this.z*(null!==(e=t.z)&&void 0!==e?e:0)}projectionTo(t){const e=Math.hypot(t.x,t.y,t.z);return this.dot(t)/e}angle(t){const e=this.norm()*Math.hypot(t.x,t.y,t.z),i=e&&this.dot(t)/e;return Math.acos(Bs(i,-1,1))}equals(t){var e;return this.x===t.x&&this.y===t.y&&this.z===(null!==(e=t.z)&&void 0!==e?e:0)}distance(t){var e;return Math.hypot(this.x-t.x,this.y-t.y,this.z-(null!==(e=t.z)&&void 0!==e?e:0))}lerp(e){var i;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5;const{x:s,y:o,z:r}=this;return new t(s+n*(e.x-s),o+n*(e.y-o),r+n*((null!==(i=e.z)&&void 0!==i?i:0)-r))}normalize(){const t=this,e=t.norm();return t.x/=e,t.y/=e,t.z/=e,this}negate(){return this.x*=-1,this.y*=-1,this.z*=-1,this}cross(t){const e=this;return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}};function Ys(t,e){return Gs.fromTwoPoint(t,e)}let $s=class t{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;Yi(this,"x",void 0),Yi(this,"y",void 0),Yi(this,"z",void 0),this.x=t,this.y=e,this.z=i}static fromPoint(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new t(e.x,e.y,e.z)}matrixTransform(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{x:e,y:i,z:n}=this,{m11:s,m21:o,m31:r,m41:a,m12:l,m22:h,m32:c,m42:d,m13:u,m23:p,m33:g,m43:f,m14:m,m24:v,m34:y,m44:x}=t,w=m*e+v*i+y*n+x;return Xs({x:(s*e+o*i+r*n+a)/w,y:(l*e+h*i+c*n+d)/w,z:(u*e+p*i+g*n+f)/w})}setFromPoint(t){return this.x=t.x||0,this.y=t.y||0,this.z=t.z||0,this}clone(){return Xs(this)}equals(t){const{x:e=0,y:i=0,z:n=0}=t,s=this;return s.x===e&&s.y===i&&s.z===n}distanceTo(t){const{x:e=0,y:i=0,z:n=0}=t,s=this;return Math.hypot(s.x-e,s.y-i,s.z-n)}lerpTo(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5;const{x:i=0,y:n=0,z:s=0}=t,o=this;return Xs({x:o.x+e*(i-o.x),y:o.y+e*(n-o.y),z:o.z+e*(s-o.z)})}footPointInSegment(t,e){const i=Ys(t,this),n=Ys(t,e),s=n.norm(),o=Xs(t);if(0===s)return o;const r=i.projectionTo(n)/s;return o.lerpTo(e,r)}perpendicularToSegment(t,e){const i=this.footPointInSegment(t,e);return this.distanceTo(i)}};function Xs(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return Ls(t)?new $s(t,e,i):new $s(t.x,t.y,t.z)}function qs(t,e){return((t.x-e.x)**2+(t.y-e.y)**2)**.5}let Zs=class{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;Yi(this,"x",0),Yi(this,"y",0),Yi(this,"left",0),Yi(this,"top",0),Yi(this,"right",0),Yi(this,"bottom",0),Yi(this,"width",0),Yi(this,"height",0),this.update(t,e,i,n)}update(t,e,i,n){this.x=t,this.y=e,this.left=t,this.top=e,this.right=t+i,this.bottom=e+n,this.width=i,this.height=n}toJSON(){}};const Js=new class{constructor(){Yi(this,"tasks",[])}createTimer(t,e){const i=Us();return this.tasks.push({uid:i,callback:t,time:e}),this.executeTimer(i),i}executeTimer(t){const e=this.tasks.find(e=>e.uid===t);if(!e)return;const i=()=>{e.callback(),null!==e.timer&&(e.timer=setTimeout(i,e.time))};e.timer=setTimeout(i,e.time)}clearTimer(t){const e=this.tasks.findIndex(e=>e.uid===t);e>-1&&(clearTimeout(this.tasks[e].timer),this.tasks[e].timer=null,this.tasks.splice(e,1))}};function Ks(t,e){return((t.x-e.x)**2+(t.y-e.y)**2)**.5}function Qs(t){const{type:e,value:i}=t;return"hex"===e?`#${i}`:"literal"===e?i:"rgb"===e?`rgb(${i.join(",")})`:`rgba(${i.join(",")})`}const to=function(){const t=/^(linear\-gradient)/i,e=/^(repeating\-linear\-gradient)/i,i=/^(radial\-gradient)/i,n=/^(repeating\-radial\-gradient)/i,s=/^(conic\-gradient)/i,o=/^to (left (top|bottom)|right (top|bottom)|top (left|right)|bottom (left|right)|left|right|top|bottom)/i,r=/^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,a=/^(left|center|right|top|bottom)/i,l=/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,h=/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,c=/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,d=/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,u=/^\(/,p=/^\)/,g=/^,/,f=/^\#([0-9a-fA-F]+)/,m=/^([a-zA-Z]+)/,v=/^rgb/i,y=/^rgba/i,x=/^(([0-9]*\.[0-9]+)|([0-9]+\.?))/;let w="";function C(t){throw new Error(`${w}: ${t}`)}function b(){return S("linear-gradient",t,E)||S("repeating-linear-gradient",e,E)||S("radial-gradient",i,_)||S("repeating-radial-gradient",n,_)||S("conic-gradient",s,_)}function S(t,e,i){return T(e,e=>{const n=i();return n&&(N(g)||C("Missing comma before color stops")),{type:t,orientation:n,colorStops:R(k)}})}function T(t,e){const i=N(t);if(i){N(u)||C("Missing (");const t=e(i);return N(p)||C("Missing )"),t}}function E(){return B("directional",o,1)||B("angular",d,1)}function _(){let t,e,i=P();return i&&(t=[],t.push(i),e=w,N(g)&&(i=P(),i?t.push(i):w=e)),t}function P(){let t=function(){const t=B("shape",/^(circle)/i,0);return t&&(t.style=O()||A()),t}()||function(){const t=B("shape",/^(ellipse)/i,0);return t&&(t.style=L()||A()),t}();if(t)t.at=I();else{const e=A();if(e){t=e;const i=I();i&&(t.at=i)}else{const e=D();e&&(t={type:"default-radial",at:e})}}return t}function A(){return B("extent-keyword",r,1)}function I(){if(B("position",/^at/,0)){const t=D();return t||C("Missing positioning value"),t}}function D(){const t={x:L(),y:L()};if(t.x||t.y)return{type:"position",value:t}}function R(t){let e=t();const i=[];if(e)for(i.push(e);N(g);)e=t(),e?i.push(e):C("One extra comma");return i}function k(){const t=B("hex",f,1)||T(y,()=>({type:"rgba",value:R(M)}))||T(v,()=>({type:"rgb",value:R(M)}))||B("literal",m,0);return t||C("Expected color definition"),t.length=L(),t}function M(){return N(x)[1]}function L(){return B("%",h,1)||B("position-keyword",a,1)||O()}function O(){return B("px",l,1)||B("em",c,1)}function B(t,e,i){const n=N(e);if(n)return{type:t,value:n[i]}}function N(t){const e=/^[\n\r\t\s]+/.exec(w);e&&U(e[0].length);const i=t.exec(w);return i&&U(i[0].length),i}function U(t){w=w.substring(t)}return function(t){return w=t,function(){const t=R(b);return w.length>0&&C("Invalid input not EOF"),t}()}}(),eo={"&amp;":"&","&gt;":">","&lt;":"<","&nbsp;":" ","&quot;":'"',"&#x27;":"'"},io={};let no;function so(t,e){const i=Object.keys(t);let n=0;for(;n<i.length;n++){const s=i[n];if(!1===e.call(null,t[s],s,t))break}}so(eo,(t,e)=>{io[t]=e});const oo=t=>{const{parentNode:e}=t,{children:i}=e;for(let e=0;e<i.length;e++)if(i[e]===t)return e;return-1},ro=(t,e,i)=>{try{void 0===e?i.appendChild(t):i.insertBefore(t,e)}catch(t){}},ao=()=>{const t=window;if(t){if(t.devicePixelRatio)return t.devicePixelRatio;if(t.screen.deviceXDPI&&t.screen.logicalXDPI)return t.screen.deviceXDPI/t.screen.logicalXDPI}return 1};function lo(t){let e="0px",i="",n="solid";if(!Ps(t)&&""!==t){const s=document.createElement("div");s.style.border=t;const{borderWidth:o,borderColor:r,borderStyle:a}=s.style;"initial"!==o&&""!==o&&(e=o),"initial"!==r&&""!==r&&(i=r),"initial"!==a&&""!==a&&(n=a)}return{borderWidth:e,borderColor:i,borderStyle:n}}const ho=t=>{const{pointerType:e}=t;return"touch"===e||"pen"===e||void 0===e};let co;function uo(){return void 0===co&&(co=/Mac OS/.test(navigator.userAgent)),co}function po(t){return uo()?yo(t,3):yo(t,2)}function go(t){return uo()&&yo(t,3)||yo(t,2)}function fo(t){return yo(t,5)}function mo(t){return yo(t,1)}function vo(t){return yo(t,0)}function yo(t,e){const{ctrlKey:i,metaKey:n,altKey:s,shiftKey:o}=t;switch(e){case 0:return i||n||s||o;case 1:return!(i||n||s||o);case 2:return i&&!n&&!s&&!o;case 3:return!i&&n&&!s&&!o;case 4:return!i&&!n&&s&&!o;case 5:return!i&&!n&&!s&&o;default:return!1}}const xo=function(t,e){const i=t.indexOf(e);return!(i<0||(t.splice(i,1),0))},wo=function(t,e,i){if(Ls(i)){let n=[],s=[];if(e.includes(i)){const t=e.length;if(t>1){const o=e.indexOf(i);0===o?s=e.slice(1):o===t-1?n=e.slice(0,-1):(n=e.slice(0,o),s=e.slice(o+1))}}else n=e;const o=t[i],r=n.map(e=>t[e]),a=s.map(e=>t[e]);r.forEach(e=>{const i=t.indexOf(e);i>-1&&t.splice(i,1)}),a.forEach(e=>{const i=t.indexOf(e);i>-1&&t.splice(i,1)});const l=t.indexOf(o);t.splice(l+1,0,...a),t.splice(l,0,...r)}else e.map(e=>t[e]).forEach(e=>{const i=t.indexOf(e);t.splice(i,1),t.push(e)});return!0},Co=function(t,e,i){if(e===i)return!0;const n=t[e];return t[e]=t[i],t[i]=n,!0},bo=function(t,e){const i=e.length;return!(t.length!==i||!i||(e.every((t,e)=>t===e)||e.map(e=>t[e]).forEach((e,i)=>{t[i]=e}),0))};function So(t){return null==t}const To=(t,e)=>t in e,Eo=(t,e)=>{const i=[];for(;t;){const n=t.match(e);if(!n)break;i.push(n),t=t.substring(n.index+n[0].length)}return i};function _o(t,e){return Object.keys(t).forEach(i=>{(function(t){return"__proto__"===t||"constructor"===t||"prototype"===t})(i)||(Ps(e[i])?e[i]=t[i]:Es(t[i])?_o(t[i],e[i]):e[i]=t[i])}),e}let Po=class t{static read(e){return new Promise((i,n)=>{const s=Object.prototype.toString.call(e);if("[object String]"===s){if(0===e.indexOf("blob:")||e.indexOf(".jpg")>0||e.indexOf(".jpeg")>0||e.indexOf(".png")>0||e.indexOf(".bmp")>0||e.indexOf(".dib")>0||e.indexOf(".pdf")>0||e.indexOf(".tiff")>0||e.indexOf(".tif")>0)return fetch(e,{mode:"cors"}).then(t=>t.arrayBuffer()).then(t=>i(t)).catch(t=>Promise.reject(t));n("Error url: Can not read the file URL")}else if("[object Blob]"===s||"[object FileList]"===s||"[object File]"===s){let o=e;"[object FileList]"!==s&&"[object File]"!==s||(o=e[0]?e[0]:e),Ki(t,t,Ao).call(t,o,i,n)}else"[object ArrayBuffer]"===s||"[object Uint8ClampedArray]"===s?i(e):n(`Not support source type: ${s}`)})}};function Ao(t,e,i){let n,s,o=0;try{n=new ArrayBuffer(t.size),s=new Uint8Array(n)}catch(t){i(t)}!function r(){const a=new FileReader;a.onload=function(a){var l;if(null!=a&&null!==(l=a.target)&&void 0!==l&&l.result){const i=a.target.result;s.set(new Uint8Array(i),o),o+=i.byteLength,o<t.size?r():e(n)}else i(a)},a.onerror=function(t){i(t)},a.onabort=function(t){i(t)};const l=Math.min(o+1048576,t.size),h=t.slice(o,l);a.readAsArrayBuffer(h)}()}async function Io(t){let e;if(t instanceof ArrayBuffer)t.byteLength>12&&(e=new Uint8Array(t.slice(0,12)));else if(t instanceof Blob&&t.size>12){const i=t.slice(0,12),n=await Po.read(i);e=new Uint8Array(n)}if(e){if(function(t){return 37===t[0]&&80===t[1]&&68===t[2]&&70===t[3]}(e))return"application/pdf";if(function(t){return 137===t[0]&&80===t[1]&&78===t[2]&&71===t[3]}(e))return"image/png";if(function(t){return 255===t[0]&&216===t[1]}(e))return"image/jpeg";if(function(t){return 66===t[0]&&77===t[1]}(e))return"image/bmp";if(function(t){return 73===t[0]&&73===t[1]&&42===t[2]&&0===t[3]||77===t[0]&&77===t[1]&&0===t[2]&&42===t[3]}(e))return"image/tiff";if(function(t){return 0===t[0]&&0===t[1]&&0===t[2]&&12===t[3]&&106===t[4]&&80===t[5]&&32===t[6]&&32===t[7]||255===t[0]&&79===t[1]&&255===t[2]&&81===t[3]}(e))return"image/jp2";if(function(t){return 82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]&&87===t[8]&&69===t[9]&&66===t[10]&&80===t[11]}(e))return null;if(t instanceof Blob&&("application/pdf"===t.type||"image/bmp"===t.type||"image/jp2"===t.type||"image/jpeg"===t.type||"image/png"===t.type||"image/tiff"===t.type||"image/rgba"===t.type))return t.type}return t instanceof Blob&&"application/ddv-blank-image"===t.type?t.type:null}function Do(t,e,i,n){if(function(t,e,i,n){return Math.min(t[0],e[0])<=Math.max(i[0],n[0])&&Math.min(i[0],n[0])<=Math.max(t[0],e[0])&&Math.min(t[1],e[1])<=Math.max(i[1],n[1])&&Math.min(i[1],n[1])<=Math.max(t[1],e[1])}(t,e,i,n)&&function(t,e,i,n){let s=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),o=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((s^o)>=0&&0!==s&&0!==o||(s=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),o=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(s^o)>=0&&0!==s&&0!==o))}(t,e,i,n)){let s=(n[0]-i[0])*(t[1]-e[1])-(e[0]-t[0])*(i[1]-n[1]),o=(t[1]-i[1])*(e[0]-t[0])*(n[0]-i[0])+i[0]*(n[1]-i[1])*(e[0]-t[0])-t[0]*(e[1]-t[1])*(n[0]-i[0]);if(0===s||0===o){const s=Ro(t,e),o=Ro(i,n),r=s[0],a=s[1],l=o[0],h=o[1];if(a[0]===l[0]&&a[1]===l[1])return a;if(r[0]===h[0]&&r[1]===h[1])return r;if(ko(a,o)&&ko(l,s))return[l,a];if(ko(r,o)&&ko(h,s))return[r,h];if(ko(r,o)&&ko(a,o))return[r,a];if(ko(l,o)&&ko(h,o))return[l,h]}const r=o/s;return s=(t[0]-e[0])*(n[1]-i[1])-(e[1]-t[1])*(i[0]-n[0]),o=e[1]*(t[0]-e[0])*(n[1]-i[1])+(n[0]-e[0])*(n[1]-i[1])*(t[1]-e[1])-n[1]*(i[0]-n[0])*(e[1]-t[1]),[r,o/s]}return!1}function Ro(t,e){return t[0]===e[0]?t[1]<e[1]?[t,e]:[e,t]:t[0]<e[0]?[t,e]:[e,t]}function ko(t,e){return e[0][0]===e[1][0]?t[1]>=e[0][1]&&t[1]<=e[1][1]:t[0]>=e[0][0]&&t[0]<=e[1][0]}function Mo(t){const e=[];let i=null;const n=t.slice(0,8).concat(t[0],t[1]);for(let t=0;t<4;t++){const s=n[2*(t+1)+1]-n[2*t+1],o=n[2*(t+1)]-n[2*t];i=0===s&&0===o?0:s/o,e.push(i)}return e}function Lo(t,e){return Number.parseFloat(t.toFixed(e))}function Oo(t){const[e,i,n,s,o,r,a,l]=t,h=(a-e)*(s-i)-(l-i)*(n-e),c=(e-n)*(r-s)-(i-s)*(o-n),d=(n-o)*(l-r)-(s-r)*(a-o),u=(o-a)*(i-l)-(r-l)*(e-a);if(h*c*d*u<0)return!1;const p=t.slice().concat(t.slice(0,2)),g=Mo(t);if(g.length)for(let t=0;t<2;t++)if(g[t]!==g[t+2]&&Do(p.slice(2*t,2*(t+1)),p.slice(2*(t+1),2*(t+2)),p.slice(2*(t+2),2*(t+3)),p.slice(2*(t+3),2*(t+4))))return!1;return h*c*d*u>0}function Bo(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return e===i?t:Ls(t)?n?Lo(t/e*i,2):t/e*i:Ts(t)?t.map(t=>Ts(t)?[n?Lo(t[0]/e*i,2):t[0]/e*i,n?Lo(t[1]/e*i,2):t[1]/e*i]:n?Lo(t/e*i,2):t/e*i):(t={...t},Object.keys(t).forEach(s=>{t[s]=n?Lo(t[s]/e*i,2):t[s]/e*i}),t)}function No(t,e){return t.every((t,i)=>{let[n,s]=t;const[o,r]=e[i];return n===o&&s===r})}function Uo(t,e){return Number.parseFloat(t.toFixed(e))}function Fo(t){if(0===t.length)return!0;if(1===t.length)return 0===t[0];t.length%2!=0&&(t=t.concat(t));for(let e=1;e<t.length;e+=2)if(0!==t[e])return!1;return!0}let Vo=class{constructor(){Yi(this,"disposed",!1),Yi(this,"toDispose",new Set)}get isDisposed(){return this.disposed}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this.disposed||this.toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this.toDispose.delete(t),t.dispose()}}dispose(){this.disposed||(this.disposed=!0,this.clear())}clear(){try{for(const t of this.toDispose)if(t)try{t.dispose()}catch(t){throw new Error("can not dispose an object")}}finally{this.toDispose.clear()}}},Wo=class{constructor(){Yi(this,"store",new Vo)}dispose(){this.store.dispose()}register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this.store.add(t)}},Ho=class t{static create(e){return new t(e)}constructor(t){Yi(this,"isDisposed",!1),Yi(this,"listeners",void 0),Yi(this,"options",void 0),this.options=t,this.listeners=[]}dispose(){this.isDisposed||(this.isDisposed=!0,this.listeners&&(this.listeners=[]))}hasCallback(){var t;return(null===(t=this.listeners)||void 0===t?void 0:t.length)>0}on(t,e,i){var n,s,o,r;if(this.isDisposed)return{dispose:()=>{}};const a={uid:Us(),callback:t,context:e};this.listeners.length?this.listeners.push(a):(null!==(n=this.options)&&void 0!==n&&null!==(s=n.beforeAddFirstListener)&&void 0!==s&&s.call(n,this),this.listeners.push(a),null===(o=this.options)||void 0===o||null===(r=o.afterAddFirstListener)||void 0===r||r.call(o,this));const l={dispose:()=>{this.remove(a)}};return i instanceof Vo?i.add(l):Array.isArray(i)?i.push(l):i instanceof Wo&&i.register(l),l}remove(t){var e,i,n,s;if(null!==(e=this.options)&&void 0!==e&&null!==(i=e.beforeRemoveListener)&&void 0!==i&&i.call(e,this),!this.listeners)return;if(1===this.listeners.length)return this.listeners=[],void(null===(n=this.options)||void 0===n||null===(s=n.afterRemoveLastListener)||void 0===s||s.call(n,this));const o=this.listeners.indexOf(t);o>=0&&this.listeners.splice(o,1)}off(t){if(this.isDisposed||!this.listeners)return;const e=this.listeners.findIndex(e=>e.callback===t);e>-1&&this.listeners.splice(e,1)}emit(t){this.listeners&&this.listeners.length&&this.listeners.slice().forEach(e=>{try{e.context?e.callback.call(e.context,t):e.callback(t)}catch(e){}})}};function jo(t){const e=t.register(new Ho);return{on:(i,n)=>e.on(i,t,n),emit:t=>{e.hasCallback()&&e.emit(t)},hasCallback:()=>e.hasCallback()}}function zo(t,e,i){return{on:(n,s)=>{const o=new Ho({beforeAddFirstListener:()=>{t.addEventListener(e,n,s)},afterRemoveLastListener:()=>{t.removeEventListener(e,n)}});i.register(o.on(()=>{})),i.register(o)}}}var Go,Yo;!function(t){t.core="ddv-core",t.reader="ddv-reader",t.detector="ddv-detector",t.loader="ddv-loader"}(Yo||(Yo={}));let $o=class t{static get isApple(){return Zi(this,t,or)}static get version(){return un.ImageIOModule.ver}static enableDebugOutput(e,i){if(e){const e=e=>{var n,s,o;let r=_s(e);r.srcBuffer&&(r.srcBuffer=Ki(this,t,Xo).call(this,r.srcBuffer)),null!==(n=r.result)&&void 0!==n&&n.srcBuffer&&(r.result.srcBuffer=Ki(this,t,Xo).call(this,r.result.srcBuffer)),null!==(s=r.result)&&void 0!==s&&s.imageData&&(r.result.imageData=Ki(this,t,Xo).call(this,r.result.imageData)),null!==(o=r.result)&&void 0!==o&&o.pdfData&&(r.result.pdfData=Ki(this,t,Xo).call(this,r.result.pdfData)),r.imageData&&(r.imageData=Ki(this,t,Xo).call(this,r.imageData)),i&&(Os(r)&&(r=`[${Date.now()}]${r}`),i(r))};un.setLogFunc("logDebug",e)}else un.setLogFunc("",void 0)}static hasDebugOutput(){return un.hasLogFunc()}static get blobReadModeSettings(){const{FontUseFileReadMode:t}=un;return{minBlobSize:un.FileReadModeSize,fontForLoad:t.load,fontForSave:t.save}}static set blobReadModeSettings(t){"number"==typeof t.minBlobSize&&(un.FileReadModeSize=t.minBlobSize),un.FontUseFileReadMode={load:t.fontForLoad,save:t.fontForSave}}static getMemoryUsed(){return mn.Instance.getMemoryUsed()}static get heapConfig(){return un.HeapConfig}static updateHeapConfig(e,i,n){un.UpdateHeapConfig(e,i,n),Zi(this,t,ar)[e]||(Zi(this,t,ar)[e]={}),i&&(Zi(this,t,ar)[e].maxHeapSize=i),n&&(Zi(this,t,ar)[e].initHeapSize=n)}static async getLicenseInfo(e,i,n){this.Init(e,i,n),await _n.updateLicense(Zi(this,t,Jo),Zi(this,t,Ko),Zi(this,t,Qo));const s=new wn(Zi(this,t,Jo));try{return await s.getLicenseInfo()}finally{s.terminate()}}static Init(e,i,n){var s;Ji(this,t,Jo,null!=e?e:Zi(this,t,Jo)),void 0!==i&&Ji(this,t,Ko,i?1:0),Ji(this,t,Qo,null!=n?n:Zi(this,t,Qo));const o={bMac:"Mac"===ns.OS,biPhone:"iPhone"===ns.OS,biPad:"iPad"===ns.OS};Ji(this,t,or,o.bMac||o.biPhone||o.biPad),un.NavInfo=o,un.License=Zi(this,t,Jo),un.UUID=Zi(this,t,Qo),un.LicMode=Zi(this,t,Ko),Ki(this,t,Zo).call(this),un.UpdateHeapConfig(Yo.detector,null!==(s=Ki(this,t,qo).call(this,Yo.detector))&&void 0!==s?s:100)}static async isResourceDirValid(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;Ki(this,t,Zo).call(this);let n=0;for(;n<e;){try{const e=un.PdfReaderModule;if(Zi(this,t,rr)===e.script)return!0;const i={...e.fetchOptions};if(i.method="HEAD",(await fetch(e.script,i)).ok)return Ji(this,t,rr,e.script),!0}catch(e){}await new Promise(t=>setTimeout(t,i)),n+=1}return!1}static async isResourceVersionMatch(){Ki(this,t,Zo).call(this);const e=new wn(Zi(this,t,Jo));try{return this.version===await e.getWasmVersion()}catch(e){return!1}finally{e.terminate()}}static async loadPdfReader(e,i,n){return this.Init(e,i,n),Zi(this,t,nr)||(await mn.Instance.loadModule(un.ImageProcModule),Ji(this,t,nr,mn.Instance.loadModule(un.PdfReaderModule)),await Zi(this,t,nr)),Zi(this,t,nr)}static async loadMain(e,i,n){return this.Init(e,i,n),Zi(this,t,sr)||mn.Instance.loadModule(un.ImageProcModule),Zi(this,t,sr)}static async load(t,e,i){mn.Instance.terminate(!0),this.Init(t,e,i),await this.loadMain(t,e,i)}static async preloadModule(e){let i;un.PdfReaderModule;const n={...un.ImageProcModule};switch(e){case"core":case"pdf":if(Zi(this,t,sr)){i=Zi(this,t,sr);break}Ji(this,t,sr,mn.Instance.loadModule(un.ImageIOModule)),i=Zi(this,t,sr),await Zi(this,t,sr);break;case"proc":if(Zi(this,t,nr)){i=Zi(this,t,nr);break}Ji(this,t,nr,mn.Instance.loadModule(n)),i=Zi(this,t,nr),await Zi(this,t,nr)}return i}static unloadMainWorker(){Ji(this,t,sr,void 0),mn.Instance.terminateWorker(un.ImageIOModule.workerName)}static unloadPdfReaderWorker(){Ji(this,t,nr,void 0),mn.Instance.terminateWorker(un.PdfReaderModule.workerName)}static unloadDocumentDetectorWorker(){mn.Instance.terminateWorker(un.DetectorModule.workerName)}static async unloadWorker(){Ji(this,t,sr,void 0),Ji(this,t,nr,void 0),await mn.Instance.terminate(!0)}static async unload(){mn.unload(),_n.unload(),un.unload(),Ji(this,t,sr,void 0),Ji(this,t,nr,void 0);try{await mn.Instance.terminate(!0)}catch(t){}}static getUseSimd(){if(this.enableSimd){var t;const e=navigator;if(null!==(t=e.userAgentData)&&void 0!==t&&t.brands)for(const{brand:t,version:i}of e.userAgentData.brands)if(t&&("Chromium"===t||"Google Chrome"===t)&&i&&parseInt(i,10)>=94)return!0}return!1}static getPdfFonts(){return qn.getPdfFonts()}static async getPdfInfo(t,e){let i;try{i=new qn;const n=await i.getPdfInfo({fileSource:t,password:e});return i.destroy(),n}catch(t){return null}finally{i&&i.destroy()}}};function Xo(t){return t instanceof ArrayBuffer?{type:"ArrayBuffer",length:t.byteLength}:t instanceof Uint8ClampedArray?{type:"Uint8ClampedArray",length:t.byteLength}:{type:Object.prototype.toString.call(t)}}function qo(t){return void 0!==Zi(this,Go,ar)[t]?Zi(this,Go,ar)[t].maxHeapSize:null}function Zo(){this.enableSimd?un.UseSimd=this.getUseSimd():un.UseSimd=!1,un.UseBrotli=this.enableWasmCompression;const t={resourceDir:this.resourceDir,workerScript:"",useFastCompEdition:!1,useSimd:un.UseSimd,fetchOptions:this.fetchOptions,useBrotli:un.UseBrotli};t.workerScript=un.ImageIOWorkerJS,un.ImageIOResource=t;const e={...t};e.workerScript=un.UseSimd?un.ImageProcSimdWorkerJS:un.ImageProcWorkerJS,un.ImageProcResource=e}Go=$o,Yi($o,"resourceDir","");var Jo={writable:!0,value:""},Ko={writable:!0,value:Z.LONG_KEY},Qo={writable:!0,value:""};Yi($o,"fetchOptions",{mode:"cors",credentials:"same-origin",retries:3,retryDelay:500}),Yi($o,"enableSimd",!0),Yi($o,"enableWasmCompression",!1);var tr,er,ir,nr={writable:!0,value:void 0},sr={writable:!0,value:void 0},or={writable:!0,value:!1},rr={writable:!0,value:void 0},ar={value:Object.create(null)};let lr=class{constructor(){Yi(this,"processor",void 0),this.processor=new Xn}async initImage(t){return this.processor.initImage(t.source,t.isRGBA,t.width,t.height,t.isBGRA)}async getImage(t){return await this.processor.getImage(t.jpegQuality,t.ifDeleteObject,t.isRGBA,t.bitDepth,t.xDpi,t.yDpi,t.returnType,t.outputType,$o.isApple)}async getImageInfo(){return await this.processor.getImageInfo()}async freeReservedData(){this.processor.freeReservedData()}async toBinaryLevel(t,e){return this.processor.toBinaryLevel(t,e)}async toGrayscale(t){return this.processor.toGrayscale(t)}async removeShadowLevel(t,e){return this.processor.removeShadowLevel(t,e)}async brighten(){return this.processor.brighten()}async invert(){return this.processor.invert()}async changeBrightnessAndContrast(t,e){return this.processor.changeBrightnessAndContrast(t,e)}async perspective(t){return this.processor.perspective(t[0][0],t[0][1],t[1][0],t[1][1],t[2][0],t[2][1],t[3][0],t[3][1])}async getSkewAngle(t){return this.processor.getSkewAngle(t)}async rotate(t){return this.processor.rotate(t.angle,t.fillColor,t.keepSize,t.mode)}async flip(){return this.processor.flip()}async resize(t,e,i){return this.processor.resize(t,e,i)}async resizeWidth(t,e){return this.processor.setImageWidth(t,e)}async resizeHeight(t,e){return this.processor.setImageHeight(t,e)}async crop(t){return this.processor.crop(t.left,t.top,t.left+t.width,t.top+t.height)}async erase(t,e){return this.processor.erase(t.left,t.top,t.left+t.width,t.top+t.height,e)}async setDpi(t){return this.processor.setDPI(t.rawResolutionX,t.rawResolutionY,t.resolutionX,t.resolutionY,t.resample,t.mode)}async drawQuadrangle(t){return this.processor.drawQuadrangle(t.location[0][0],t.location[0][1],t.location[1][0],t.location[1][1],t.location[2][0],t.location[2][1],t.location[3][0],t.location[3][1],t)}async filter(t,e,i){return this.processor.filter(t,e,i)}async setImageWidth(t,e){return this.processor.setImageWidth(t,e)}async setImageHeight(t,e){return this.processor.setImageHeight(t,e)}terminate(t){return this.processor.terminate(t)}},hr=class{constructor(){Yi(this,"reader",void 0),this.reader=new Pn}async readImage(t){return await this.reader.readImage(t.source,t.outputType,t.jpegQuality,t.returnType,$o.isApple)}async readImageInfo(t){return await this.reader.readImageInfo(t)}cancelReadImage(t,e){this.reader.cancelReadImage(t,e)}async readTiffPage(t){return await this.reader.readTiffPage(t.source,t.index,t.outputType,t.returnType,$o.isApple)}async readTiffPageInfo(t,e){const{imageInfos:i}=await this.reader.getTiffPageInfos(t,e);return i}async getTiffPageCount(t){return(await this.reader.getTiffInfo(t)).pageCount}cancelReadTiffPage(t,e){this.reader.cancelReadTiffPage(t,e)}destroy(){var t;null===(t=this.reader)||void 0===t||t.destroy(),this.reader=void 0}};!function(t){t[t.RGBA=1]="RGBA",t[t.BGRA=2]="BGRA",t[t.JPEG=3]="JPEG",t[t.PNG=4]="PNG"}(tr||(tr={})),function(t){t[t.IT_DIB=-1]="IT_DIB",t[t.IT_RGBA=-2]="IT_RGBA",t[t.IT_BGRA=-3]="IT_BGRA",t[t.IT_BMP=0]="IT_BMP",t[t.IT_JPG=1]="IT_JPG",t[t.IT_PNG=3]="IT_PNG",t[t.IT_ALL=5]="IT_ALL"}(er||(er={})),function(t){t[t.RT_AUTO=-1]="RT_AUTO",t[t.RT_BINARY=1]="RT_BINARY",t[t.RT_BASE64=2]="RT_BASE64"}(ir||(ir={}));let cr=class{constructor(){Yi(this,"writer",void 0),this.writer=new wn}terminate(){var t;null===(t=this.writer)||void 0===t||t.terminate(),this.writer=void 0}createTiff(){return this.writer.createTiff()}addTiffTag(t,e,i){return this.writer.addTag(t,e,i)}async appendImage(t,e){var i;return e=null!==(i=e)&&void 0!==i?i:{},await this.writer.appendImage(t,e.inputType,e.tiffFormat,e.jpegQuality,e.is1Bit)}async getTiff(){return(await this.writer.getTiff(ir.RT_AUTO)).imageData}async saveImage(t,e){var i;return e=null!==(i=e)&&void 0!==i?i:{},(await this.writer.saveImage(t,e.outputType,e.jpegQuality,e.returnType,e.is1Bit)).imageData}},dr=class t{constructor(){Yi(this,"reader",void 0),this.reader=new qn}initFonts(e){if(e)for(const i of e)i.name&&i.data&&t.addPdfFont(i.name,i.data)}static addPdfFont(t,e){qn.addPdfFont(t,e)}async readPageImageInfos(t){var e;await this.initFonts(null===(e=t.readOptions)||void 0===e||null===(e=e.renderOptions)||void 0===e?void 0:e.fonts);const{imageInfos:i}=await this.reader.readPageImageInfos(t.source,t.indices,t.readOptions,t.outputType,t.isInfoOnly,t.returnType,$o.isApple);return i}async readPage(t){var e;return await this.initFonts(null===(e=t.readOptions)||void 0===e||null===(e=e.renderOptions)||void 0===e?void 0:e.fonts),await this.reader.readPageEx(t.source,t.index,t.readOptions,t.outputType,t.isInfoOnly,t.returnType,$o.isApple)}async renderPage(t,e){var i;if(e.canceled)return null;if(await this.initFonts(null===(i=t.renderOptions)||void 0===i?void 0:i.fonts),e.canceled)return null;const n=await this.reader.renderPage(t.source,t.index,t.width,t.height,{rect:[t.rect[0],t.rect[1],t.rect[2],t.rect[3]],renderOptions:t.renderOptions,outputType:t.outputType,returnType:t.returnType,is1BitTo8Bit:$o.isApple},e.taskUid);return e.canceled?null:n}cancelReadPage(t,e){this.reader.cancelReadPage(t,e)}cancelRenderPage(t){this.reader.cancelRenderPage(t.taskUid)}async getPdfPageCount(t,e){var i;return await this.initFonts(null==e||null===(i=e.renderOptions)||void 0===i?void 0:i.fonts),(await this.reader.getPdfInfo(t)).PdfCount}async getPdfPageContentType(t,e){const i=await this.reader.getPdfPageType(t,e);return 1===i.pageContentType?"application/pdf/text":2===i.pageContentType?"application/pdf/image":"application/pdf"}async readAnnotations(t,e){const{annot:{annots:i}}=await this.reader.readPageAnnot(t,e);return i}async findText(t,e,i,n){return await this.reader.findText(t,e,i,n)}async getCharInfos(t,e){return(await this.reader.getCharInfos(t,e)).pageCharInfos}destroy(){this.reader.destroy(),this.reader=null}},ur=class{constructor(){Yi(this,"writer",void 0),this.writer=new Zn}terminate(){var t;null===(t=this.writer)||void 0===t||t.terminate(),this.writer=null}async initPdfSetting(t){return this.writer.initPdfSetting(t)}async insertBlankPage(t,e,i){return this.writer.insertBlankPage(t,e,i)}async insertBlankPages(t,e,i,n){return this.writer.insertBlankPages(t,e,i,n)}async appendPage(t,e){return this.writer.appendPage(t,e)}async addImageToPages(t,e,i,n,s,o){return this.writer.pageAddImage(t,e,i,n,s,o)}async mergeRawPdfPages(t,e,i){return this.writer.mergePdf(t,e,i)}async replaceRawPdfPages(t,e,i,n){return this.writer.replacePdfPages(t,e,i,n)}async setPageRotation(t,e){return this.writer.pageSetRotation(t,e)}async clearPageObjects(t){return this.writer.pageClearObjects(t)}async setPageCropBox(t,e,i,n,s){return this.writer.pageSetCropBox(t,e,i,n,s)}async setPageMediaBox(t,e,i,n,s){return this.writer.pageSetMediaBox(t,e,i,n,s)}async setPageAnnotations(t,e){return this.writer.pageSetAnnot(t,e)}async addAnnotationsToPage(t,e){return this.writer.pageAddAnnot(t,e)}async flattenPageAnnotations(t,e){return this.writer.pageFlattenAnnot(t,e)}async deletePageAnnotationsByTypes(t,e){return this.writer.pageDeleteAnnotByTypes(t,e)}async deletePageAnnotationsExceptTypes(t,e){return this.writer.pageDeleteAnnotExceptTypes(t,e)}async deletePageAnnotations(t){return this.writer.pageDeleteAnnot(t)}async flattenPage(t,e){return this.writer.pageFlatten(t,e)}async redactPage(t,e){return this.writer.pageRedact(t,e)}async deletePage(t){return this.writer.deletePage(t)}async movePages(t,e){return this.writer.movePages(t,e)}async getPdf(t){return(await this.writer.writePdf(t)).pdfData}async getFontInfo(t){return await this.writer.GetFontInfo(t)}async ifFontsExist(t){return(await this.writer.IfFontsExist(t)).fontsExist}async unloadPage(t){var e,i;await(null===(e=(i=this.writer).UnloadPage)||void 0===e?void 0:e.call(i,t))}},pr=class{constructor(t){Yi(this,"items",[]),t&&(this.items=t)}push(t){this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return 0===this.items.length}size(){return this.items.length}remove(t){const e=this.items.findIndex(e=>e.api===t.api);if(-1!==e){const t=this.items[e];this.items.splice(e,1),t.resolve(null)}}};var gr=new WeakMap,fr=new WeakMap,mr=new WeakSet;let vr=class{constructor(){an(this,mr),rn(this,gr,{writable:!0,value:new pr}),rn(this,fr,{writable:!0,value:!1})}handler(t){return Promise.resolve(null)}createTask(t,e,i){const n={api:t,taskInfo:i,params:[],promise:void 0,resolve:void 0,reject:void 0,retry:0};for(const t of e)n.params.push(t);return n.promise=new Promise((t,e)=>{n.resolve=t,n.reject=e}),$i(this,gr).push(n),$i(this,fr)||(Xi(this,fr,!0),sn(this,mr,yr).call(this)),n.promise}cancelTask(t,e,i){const n={api:t,taskInfo:i,params:[],promise:void 0,resolve:void 0,reject:void 0,retry:0};for(const t of e)n.params.push(t);$i(this,gr).remove(n)}};async function yr(){if($i(this,gr).isEmpty())Xi(this,fr,!1);else{for(;!$i(this,gr).isEmpty();){const t=$i(this,gr).pop();if(t.taskInfo.canceled)t.resolve(null);else try{const e=await this.handler(t);e&&(e.taskInfo=t.taskInfo),t.resolve(e)}catch(e){t.retry<1?(t.retry+=1,$i(this,gr).push(t)):null==t||t.reject(e)}}Xi(this,fr,!1)}}const xr={[tr.BGRA]:er.IT_BGRA,[tr.RGBA]:er.IT_RGBA,[tr.PNG]:er.IT_PNG,[tr.JPEG]:er.IT_JPG},wr={[er.IT_BGRA]:tr.BGRA,[er.IT_RGBA]:tr.RGBA,[er.IT_PNG]:tr.PNG,[er.IT_JPG]:tr.JPEG},Cr={displayResolution:96,dataResolution:72,pdfResolution:72,enableResolution:!0,autoReleaseImg:Ms(),autoReleaseBlob:!0,loadRawPageTimeout:2e4,defaultRenderPageWidth:1654,defaultRenderPageHeight:2339};class br{constructor(){Yi(this,"db",void 0),this.db=new Map}has(t){throw new Error("Method not implemented.")}save(t){throw new Error("Method not implemented.")}getSaverConstructor(t){return this.db.get(t)}setSaverConstructor(t,e){this.db.set(t,e)}deleteSaverConstructor(t){this.db.delete(t)}clear(){this.db.clear()}}const Sr=new br,Tr=new br,Er=new class{constructor(t,e){Yi(this,"saverConstructorRepo",void 0),Yi(this,"customSaverConstructorRepo",void 0),this.saverConstructorRepo=t,this.customSaverConstructorRepo=e}execute(t){let e=this.customSaverConstructorRepo.getSaverConstructor(t);return e||(e=this.saverConstructorRepo.getSaverConstructor(t)),new e}}(Sr,Tr),_r=new class{constructor(t){Yi(this,"saverConstructorRepo",void 0),this.saverConstructorRepo=t}execute(t){let{mime:e,saverConstructor:i}=t;this.saverConstructorRepo.setSaverConstructor(e,i)}}(Sr),Pr=new class{constructor(t){Yi(this,"saverConstructorRepo",void 0),this.saverConstructorRepo=t}execute(t){this.saverConstructorRepo.deleteSaverConstructor(t)}}(Sr);var Ar,Ir,Dr,Rr;!function(t){t.TIFF_AUTO="tiff/auto",t.TIFF_FAX3="tiff/fax3",t.TIFF_FAX4="tiff/fax4",t.TIFF_LZW="tiff/lzw",t.TIFF_JPEG="tiff/jpeg"}(Ar||(Ar={})),function(t){t.PDF_AUTO="pdf/auto",t.PDF_FAX4="pdf/fax4",t.PDF_LZW="pdf/lzw",t.PDF_JPEG="pdf/jpeg",t.PDF_JP2000="pdf/jp2000",t.PDF_JBIG2="pdf/jbig2"}(Ir||(Ir={})),function(t){t.PAGE_DEFAULT="page/default",t.PAGE_A4="page/a4",t.PAGE_A4_REVERSE="page/a4reverse",t.PAGE_A3="page/a3",t.PAGE_A3_REVERSE="page/a3reverse",t.PAGE_LETTER="page/letter",t.PAGE_LETTER_REVERSE="page/letterreverse",t.PAGE_LEGAL="page/legal",t.PAGE_LEGAL_REVERSE="page/legalreverse"}(Dr||(Dr={})),function(t){t.PRINT="print",t.MODIFY_CONTENTS="modify_contents",t.COPY_CONTENTS="copy_contents",t.EXTRACT_CONTENTS="extract_contents",t.MODIFY_ANNOTATIONS="modify_annotations",t.FILL_IN="fill_in",t.ASSEMBLY="assembly",t.DEGRADED_PRINT="degraded_print"}(Rr||(Rr={})),new Map([[Rr.PRINT,2052],[Rr.MODIFY_CONTENTS,8],[Rr.COPY_CONTENTS,16],[Rr.MODIFY_ANNOTATIONS,32],[Rr.FILL_IN,256],[Rr.EXTRACT_CONTENTS,512],[Rr.ASSEMBLY,1024],[Rr.DEGRADED_PRINT,4]]);const kr=new Map([[Dr.PAGE_DEFAULT,0],[Dr.PAGE_A4,2],[Dr.PAGE_A4_REVERSE,3],[Dr.PAGE_A3,4],[Dr.PAGE_A3_REVERSE,5],[Dr.PAGE_LETTER,6],[Dr.PAGE_LETTER_REVERSE,7],[Dr.PAGE_LEGAL,8],[Dr.PAGE_LEGAL_REVERSE,9]]),Mr=new Map([[Ir.PDF_AUTO,0],[Ir.PDF_FAX4,2],[Ir.PDF_LZW,3],[Ir.PDF_JPEG,5],[Ir.PDF_JP2000,6],[Ir.PDF_JBIG2,7]]),Lr=new Map([[Ar.TIFF_AUTO,0],[Ar.TIFF_FAX3,1],[Ar.TIFF_FAX4,2],[Ar.TIFF_LZW,3],[Ar.TIFF_JPEG,5]]);var Or=new WeakMap,Br=new WeakMap,Nr=new WeakMap;class Ur{constructor(){rn(this,Or,{writable:!0,value:void 0}),rn(this,Br,{writable:!0,value:void 0}),rn(this,Nr,{writable:!0,value:void 0}),Xi(this,Or,new ur),Xi(this,Br,new Map)}destroy(){var t;null===(t=$i(this,Or))||void 0===t||t.terminate(),Xi(this,Or,void 0)}convertPageSize(t,e){let i=0,n=0,s=0,o=0,r=0,a=0,l=0,h=0;const{pdfResolution:c,displayResolution:d}=Cr;switch(t){case Dr.PAGE_A4:s=210/25.4*c,o=297/25.4*c,l=s,a=o;break;case Dr.PAGE_A4_REVERSE:s=297/25.4*c,o=210/25.4*c,l=s,a=o;break;case Dr.PAGE_A3:s=297/25.4*c,o=420/25.4*c,l=s,a=o;break;case Dr.PAGE_A3_REVERSE:s=420/25.4*c,o=297/25.4*c,l=s,a=o;break;case Dr.PAGE_LETTER:s=8.5*c,o=11*c,l=s,a=o;break;case Dr.PAGE_LETTER_REVERSE:s=11*c,o=8.5*c,l=s,a=o;break;case Dr.PAGE_LEGAL:s=8.5*c,o=14*c,l=s,a=o;break;case Dr.PAGE_LEGAL_REVERSE:s=14*c,o=8.5*c,l=s,a=o;break;default:i=e.mediaBox.left/d*c,n=e.mediaBox.top/d*c,s=e.mediaBox.width/d*c,o=e.mediaBox.height/d*c,r=e.cropBox.left/d*c,a=2*n+o-e.cropBox.top/d*c,l=Math.max(r+e.cropBox.width/d*c,r+1),h=Math.min(a-e.cropBox.height/d*c,a-1)}return{left:i,top:n,width:s,height:o,cropLeft:r,cropTop:a,cropRight:l,cropBottom:h}}convertPdfSettings(t){const e={};return e.author=null==t?void 0:t.author,e.compression=null!=t&&t.compression?Mr.get(t.compression):void 0,e.creationDate=null==t?void 0:t.creationDate,e.creator=null==t?void 0:t.creator,e.keyWords=null==t?void 0:t.keyWords,e.modifiedDate=null==t?void 0:t.modifiedDate,e.pageType=null!=t&&t.pageType?kr.get(t.pageType):void 0,e.producer=null==t?void 0:t.producer,e.quality=null==t?void 0:t.quality,e.subject=null==t?void 0:t.subject,e.title=null==t?void 0:t.title,e.version=null==t?void 0:t.version,null!=t&&t.password&&(e.encryptOptions={},e.encryptOptions.enabled=!0,e.encryptOptions.userPassword=t.password),e}async init(t){Xi(this,Nr,t||{});const e=this.convertPdfSettings(t);await $i(this,Or).initPdfSetting(e)}async appendBlankPages(t,e,i){await $i(this,Or).insertBlankPages(-1,t,e,i)}async applyImageToPage(t,e,i){const{mediaBox:n,cropBox:s}=i,o=this.convertPageSize($i(this,Nr).pageType,i);await $i(this,Or).setPageMediaBox(t,o.left,o.top,o.left+o.width,o.top+o.height),i.rotation&&await $i(this,Or).setPageRotation(t,i.rotation);const{displayResolution:r,pdfResolution:a}=Cr;let l=o.width,h=o.height,c=0,d=0;if($i(this,Nr).pageType&&$i(this,Nr).pageType!==Dr.PAGE_DEFAULT){const e={width:s.width/r*a,height:s.height/r*a},i=o.width/e.width,u=o.height/e.height;if(i<u){const t=e.height*i;d=(o.height-t)/2,l=o.width,h=t}else{const t=e.width*u;c=(o.width-t)/2,l=t,h=o.height}const p=s.left/r*a,g=(n.height-(s.top+s.height))/r*a;$i(this,Br).set(t,[l/e.width,0,0,h/e.height,c-l/e.width*p,d-h/e.height*g])}c+=o.left,d+=o.top;let u=i.width,p=i.height,g=e;if($i(this,Nr).imageScaleFactor){let t=Math.floor(i.width*$i(this,Nr).imageScaleFactor+.5),n=Math.floor(i.height*$i(this,Nr).imageScaleFactor+.5);if(t<1&&(t=1),n<1&&(n=1),t!==u&&n!==p){const i=new lr;await i.initImage({source:e}),await i.resize(t,n),g=(await i.getImage({})).imageData,u=t,p=n,await i.freeReservedData()}}const f=await $i(this,Or).addImageToPages(g,[t],{imageWidth:l,imageHeight:h,position:[c,d]},u,p,1===i.bitDepth);return await $i(this,Or).setPageCropBox(t,o.cropLeft,o.cropBottom,o.cropRight,o.cropTop),await $i(this,Or).unloadPage(t),f}async appendImagePage(t,e){const{mediaBox:i}=e,n=this.convertPageSize($i(this,Nr).pageType,e);let s=await $i(this,Or).insertBlankPage(-1,n.left+n.width,n.top+n.height);const{pageIndex:o}=s;await $i(this,Or).setPageMediaBox(o,n.left,n.top,n.left+n.width,n.top+n.height),e.rotation&&await $i(this,Or).setPageRotation(o,e.rotation);const{displayResolution:r,pdfResolution:a}=Cr;let l=n.width,h=n.height,c=0,d=0;if($i(this,Nr).pageType&&$i(this,Nr).pageType!==Dr.PAGE_DEFAULT){const t={width:i.width/r*a,height:i.height/r*a},e=n.width/t.width,s=n.height/t.height;if(e<s){const i=t.height*e;d=(n.height-i)/2,l=n.width,h=i}else{const e=t.width*s;c=(n.width-e)/2,l=e,h=n.height}$i(this,Br).set(o,[l/t.width,0,0,h/t.height,c,d])}c+=n.left,d+=n.top;let u=e.width,p=e.height,g=t;if($i(this,Nr).imageScaleFactor){let i=Math.floor(e.width*$i(this,Nr).imageScaleFactor+.5),n=Math.floor(e.height*$i(this,Nr).imageScaleFactor+.5);if(i<1&&(i=1),n<1&&(n=1),i!==u&&n!==p){const e=new lr;await e.initImage({source:t}),await e.resize(i,n),g=(await e.getImage({})).imageData,u=i,p=n,await e.freeReservedData()}}return s=await $i(this,Or).addImageToPages(g,[o],{imageWidth:l,imageHeight:h,position:[c,d]},u,p,1===e.bitDepth),await $i(this,Or).setPageCropBox(o,n.cropLeft,n.cropBottom,n.cropRight,n.cropTop),await $i(this,Or).unloadPage(o),s}async appendRawPdfPages(t,e,i){await $i(this,Or).mergeRawPdfPages(t,e,i)}async replaceRawPdfPages(t,e,i,n){await $i(this,Or).replaceRawPdfPages(t,e,i,n)}async changePageImage(t,e,i){const n=this.convertPageSize(Dr.PAGE_DEFAULT,i);return await $i(this,Or).clearPageObjects(t),await $i(this,Or).addImageToPages(e,[t],{imageWidth:n.width,imageHeight:n.height,position:[n.left,n.top]},i.width,i.height)}async setPageInfo(t){for(const[e,i]of t){const t=this.convertPageSize(Dr.PAGE_DEFAULT,i),{rotation:n}=i;await $i(this,Or).setPageCropBox(e,t.cropLeft,t.cropBottom,t.cropRight,t.cropTop),await $i(this,Or).setPageRotation(e,(n%360+360)%360)}}async setPageRotation(t){for(const[e,i]of t){const t=(i%360+360)%360;await $i(this,Or).setPageRotation(e,t)}}async getPdf(t){if("application/pdf"===(t=t||"application/pdf"))return $i(this,Or).getPdf(ir.RT_AUTO);const e=await $i(this,Or).getPdf(ir.RT_BINARY);return new Blob([e],{type:t})}updateAnnotPoint(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}fixAnnotationPosition(t,e){$i(this,Br).has(t)&&e.forEach(e=>{const i=this.updateAnnotPoint([e.rect[0],e.rect[1]],$i(this,Br).get(t)),n=this.updateAnnotPoint([e.rect[2],e.rect[3]],$i(this,Br).get(t));if(e.rect=[i[0],i[1],n[0],n[1]],"Highlight"===e.type||"StrikeOut"===e.type||"Underline"===e.type||"Squiggly"===e.type)e.quadPoints.forEach((i,n)=>{const s=this.updateAnnotPoint([i[0],i[1]],$i(this,Br).get(t)),o=this.updateAnnotPoint([i[2],i[3]],$i(this,Br).get(t)),r=this.updateAnnotPoint([i[4],i[5]],$i(this,Br).get(t)),a=this.updateAnnotPoint([i[6],i[7]],$i(this,Br).get(t));e.quadPoints[n]=[s[0],s[1],o[0],o[1],r[0],r[1],a[0],a[1]]});else if("Line"===e.type){const i=this.updateAnnotPoint([e.line[0],e.line[1]],$i(this,Br).get(t)),n=this.updateAnnotPoint([e.line[2],e.line[3]],$i(this,Br).get(t));e.line=[i[0],i[1],n[0],n[1]]}else if("Ink"===e.type)e.inkList.forEach(e=>{for(let i=0;i<e.length;i+=2){const[n,s]=this.updateAnnotPoint([e[i],e[i+1]],$i(this,Br).get(t));e[i]=n,e[i+1]=s}});else if("Polygon"===e.type||"PolyLine"===e.type)for(let i=0;i<e.vertices.length;i+=2){const[n,s]=this.updateAnnotPoint([e.vertices[i],e.vertices[i+1]],$i(this,Br).get(t));e.vertices[i]=n,e.vertices[i+1]=s}})}async removePageAnnotations(t){await $i(this,Or).deletePageAnnotationsExceptTypes(t,"Widget")}async setPageAnnotations(t,e,i){let n;return e&&e.length>0&&this.fixAnnotationPosition(t,e),i?e&&e.length>0&&(n=await $i(this,Or).addAnnotationsToPage(t,e)):n=await $i(this,Or).setPageAnnotations(t,e),n}async flattenPageAnnotations(t,e){return e&&e.length>0&&this.fixAnnotationPosition(t,e),await $i(this,Or).flattenPageAnnotations(t,e)}async flattenPage(t){return await $i(this,Or).flattenPage(t)}async redactPageAnnotations(t,e){return e&&e.length>0&&this.fixAnnotationPosition(t,e),await $i(this,Or).redactPage(t,e)}async getFontInfo(t){return await $i(this,Or).getFontInfo(t)}async ifFontsExist(t){return await $i(this,Or).ifFontsExist(t)}}class Fr{constructor(){Yi(this,"imageWriter",void 0),this.imageWriter=new cr}destroy(){var t;null===(t=this.imageWriter)||void 0===t||t.terminate(),this.imageWriter=void 0}async save(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return await this.imageWriter.saveImage(t,{outputType:e.outputType,jpegQuality:e.jpegQuality,returnType:e.returnType,is1Bit:e.is1Bit})}}class Vr{constructor(){Yi(this,"imageWriter",void 0),Yi(this,"tiffCompression",void 0),Yi(this,"tiffQuality",void 0),this.imageWriter=new cr,this.tiffCompression=Lr.get(Ar.TIFF_AUTO)}destroy(){var t;null===(t=this.imageWriter)||void 0===t||t.terminate(),this.imageWriter=void 0}async init(t){if(await this.imageWriter.createTiff(),t&&(this.tiffQuality=t.quality,t.compression&&(this.tiffCompression=Lr.get(t.compression)),t.customTag))for(let e=0;e<t.customTag.length;e++)await this.imageWriter.addTiffTag(t.customTag[e].id,t.customTag[e].content,t.customTag[e].contentIsBase64)}async appendPage(t,e){await this.imageWriter.appendImage(t,{inputType:void 0,tiffFormat:this.tiffCompression,jpegQuality:this.tiffQuality,is1Bit:null==e?void 0:e.is1Bit})}async getTiff(){return this.imageWriter.getTiff()}}class Wr{constructor(t){Yi(this,"uid",void 0),this.uid=t||Us()}equals(t){return null!=t&&void 0!==t&&(this===t||!!function(t){return t instanceof Wr}(t)&&this.uid===t.uid)}}let Hr=class extends Wr{},jr=class{constructor(t){Yi(this,"type",void 0),Yi(this,"uid",void 0),this.type=t,this.uid=Us()}},zr=class t{constructor(e){Yi(this,"bubbles",!0),Yi(this,"cancelBubble",!0),Yi(this,"cancelable",!1),Yi(this,"composed",!1),Yi(this,"currentTarget",void 0),Yi(this,"defaultPrevented",!1),Yi(this,"eventPhase",t.prototype.NONE),Yi(this,"isTrusted",void 0),Yi(this,"returnValue",void 0),Yi(this,"srcElement",void 0),Yi(this,"target",void 0),Yi(this,"timeStamp",void 0),Yi(this,"type",void 0),Yi(this,"detail",void 0),Yi(this,"view",void 0),Yi(this,"which",void 0),Yi(this,"path",void 0),Yi(this,"immediatePropagationStopped",!1),Yi(this,"propagationStopped",!1),Yi(this,"nativeEvent",void 0),Yi(this,"originalEvent",void 0),Yi(this,"eventService",void 0),Yi(this,"NONE",0),Yi(this,"CAPTURING_PHASE",1),Yi(this,"AT_TARGET",2),Yi(this,"BUBBLING_PHASE",3),this.eventService=e}initUIEvent(t,e,i,n,s){}composedPath(){const{path:t,eventService:e,target:i}=this;return!e||t&&t[this.path.length-1]===i||(this.path=i?e.getPropagationPath(i):[]),this.path}bindEvents(t,e,i){}preventDefault(){const{nativeEvent:t}=this;t instanceof Event&&t.cancelable&&t.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.immediatePropagationStopped=!0}stopPropagation(){this.propagationStopped=!0}};function Gr(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which}let Yr=class extends zr{constructor(t,e){super(null),this.type=t,this.detail=e}},$r=class{constructor(){Yi(this,"pubsub",Ws.create())}addEventListener(t,e,i){let n,s=Rs(i)&&i;Es(i)&&(s=i.capture,n=i.once),t=s?`${t}:capture`:t,e=ks(e)?e:e.handleEvent,this.pubsub.on(t,e,this,n)}dispatchEvent(t){const e=this.ownerDocument||this.document;var i;return e&&(t.eventService=(null===(i=e.defaultView)||void 0===i?void 0:i.eventService)||null,t.defaultPrevented=!1,t.path=[],t.target=this,qr(t)),!t.defaultPrevented}removeEventListener(t,e,i){let n=Rs(i)&&i;Es(i)&&(n=i.capture),t=n?`${t}:capture`:t,e=ks(e)?e:e.handleEvent,this.pubsub.off(t,e)}removeAllEventListeners(){this.pubsub.removeAllEventListeners()}getAllEvents(){return this.pubsub.getAllEvents()}};function Xr(t,e){const i=t.currentTarget.getAllEvents()[e]||[];for(let e=0,n=i.length;e<n;e++){if(t.immediatePropagationStopped)return;const{context:n,fn:s}=i[e];s.call(n,t)}}function qr(t,e){var i;if(e=null!==(i=e)&&void 0!==i?i:t.type,t.propagationStopped=!1,t.immediatePropagationStopped=!1,!t.target)return;const n=t.composedPath(),s=n.length;t.eventPhase=t.CAPTURING_PHASE;for(let i=0;i<s-1;i++)if(t.currentTarget=n[i],Xr(t,`${e}:capture`),Zr(t))return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,Xr(t,e),!Zr(t)){t.eventPhase=t.BUBBLING_PHASE;for(let i=s-2;i>=0;i--)if(t.currentTarget=n[i],Xr(t,e),Zr(t))return}}function Zr(t){return t.propagationStopped||t.immediatePropagationStopped}const Jr=t=>t/180*Math.PI,Kr=t=>t/Math.PI*180;let Qr=class t{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;Yi(this,"x",0),Yi(this,"y",0),this.x=t,this.y=e}static fromValue(e,i){return new t(e,i)}static fromPoint(e){return new t(e.x,e.y)}static fromTwoPoint(e,i){var n,s,o,r;return new t((null!==(n=i.x)&&void 0!==n?n:0)-(null!==(s=e.x)&&void 0!==s?s:0),(null!==(o=i.y)&&void 0!==o?o:0)-(null!==(r=e.y)&&void 0!==r?r:0))}static create(){return new t(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0)}setFromVector(t){this.x=t.x,this.y=t.y}clone(){return new t(this.x,this.y)}norm(){return Math.hypot(this.x,this.y)}dot(t){return this.x*t.x+this.y*t.y}projectionTo(t){const e=Math.hypot(t.x,t.y);return this.dot(t)/e}angle(t){const e=this.norm()*Math.hypot(t.x,t.y);return Math.acos(this.dot(t)/e)}equals(t){return this.x===t.x&&this.y===t.y}distance(t){return Math.hypot(this.x-t.x,this.y-t.y)}lerp(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5;const{x:n,y:s}=this;return new t(n+(e.x-n)*i,s+(e.y-s)*i)}normalize(){const t=this.norm();return this.x/=t,this.y/=t,this}negate(){return this.x*=-1,this.y*=-1,this}cross(t){return this.x*t.y-this.y*t.x}add(e){return new t(this.x+e.x,this.y+e.y)}addSelf(t){return this.x+=t.x,this.y+=t.y,this}sub(e){return new t(this.x-e.x,this.y-e.y)}subSelf(t){return this.x-=t.x,this.y-=t.y,this}multiply(e){return new t(this.x*e.x,this.y*e.y)}multiplySelf(t){return this.x*=t.x,this.y*=t.y,this}},ta=class t{constructor(t){Yi(this,"a",1),Yi(this,"b",0),Yi(this,"c",0),Yi(this,"d",1),Yi(this,"e",0),Yi(this,"f",0),Yi(this,"m11",1),Yi(this,"m12",0),Yi(this,"m13",0),Yi(this,"m21",0),Yi(this,"m22",1),Yi(this,"m23",0),Yi(this,"m31",0),Yi(this,"m32",0),Yi(this,"m33",1),t&&this.setFromMatrix(t)}static compose(e,i,n){const s=Jr(n),o=Math.cos(s),r=Math.sin(s),a=i.x*o,l=i.x*r,h=-i.y*r,c=i.y*o,d=e.x,u=e.y;return t.fromMatrix({m11:a,m21:h,m31:d,m12:l,m22:c,m32:u,m13:0,m23:0,m33:1})}static create(e){return new t(e)}static fromMatrix(e){return(new t).setFromMatrix(e)}static createRotationMatrix(e,i){const n=sa(e,i);return t.fromMatrix(n)}static createTranslationMatrix(e){const i=ia(e.x,e.y);return t.fromMatrix(i)}static createScaleMatrix(e){const i=na(e.x,e.y);return t.fromMatrix(i)}setFromMatrix(t){if(Array.isArray(t)){const[e,i,n,s,o,r]=t;this.m11=e,this.m12=i,this.m13=0,this.m21=n,this.m22=s,this.m23=0,this.m31=o,this.m32=r,this.m33=1}else{var e,i,n,s,o,r,a,l,h,c,d,u,p,g,f;this.m11=null!==(e=null!==(i=t.m11)&&void 0!==i?i:t.a)&&void 0!==e?e:1,this.m12=null!==(n=null!==(s=t.m12)&&void 0!==s?s:t.b)&&void 0!==n?n:0,this.m13=null!==(o=t.m13)&&void 0!==o?o:0,this.m21=null!==(r=null!==(a=t.m21)&&void 0!==a?a:t.c)&&void 0!==r?r:0,this.m22=null!==(l=null!==(h=t.m22)&&void 0!==h?h:t.d)&&void 0!==l?l:1,this.m23=null!==(c=t.m23)&&void 0!==c?c:0,this.m31=null!==(d=null!==(u=t.m31)&&void 0!==u?u:t.e)&&void 0!==d?d:0,this.m32=null!==(p=null!==(g=t.m32)&&void 0!==g?g:t.f)&&void 0!==p?p:0,this.m33=null!==(f=t.m33)&&void 0!==f?f:1}return this.a=this.m11,this.b=this.m12,this.c=this.m21,this.d=this.m22,this.e=this.m31,this.f=this.m32,this}clone(){return t.fromMatrix(this)}translate(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this.clone().translateSelf(t,e)}translateSelf(){const t=ia(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0);return this.multiplySelf(t)}multiplySelf(){const t=ea(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return this.setFromMatrix(t)}preMultiplySelf(){const t=ea(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},this);return this.setFromMatrix(t)}multiply(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.clone().multiplySelf(t)}scaleSelf(t,e,i,n){var s,o;void 0===e&&(e=t),null!==(s=i)&&void 0!==s||(i=0),null!==(o=n)&&void 0!==o||(n=0),0===i&&0===n||this.translateSelf(i,n);const r=na(t,e);return this.multiplySelf(r)}scale(t,e,i,n){return this.clone().scaleSelf(t,e,i,n)}rotateSelf(t,e,i){var n,s;null!==(n=e)&&void 0!==n||(e=0),null!==(s=i)&&void 0!==s||(i=0);const o=sa(t,{x:e,y:i});return this.multiplySelf(o)}rotate(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.clone().rotateSelf(t)}invertSelf(){const t=function(t){const{m11:e,m21:i,m31:n,m12:s,m22:o,m32:r}=t,a=1/(e*o-s*i);return{m11:o*a,m21:-i*a,m31:(i*r-o*n)*a,m12:-s*a,m22:e*a,m32:(s*n-e*r)*a,m13:0,m23:0,m33:1}}(this);return this.setFromMatrix(t)}inverse(){return this.clone().invertSelf()}getScaling(){const t=Math.hypot(this.m11,this.m12),e=Math.hypot(this.m21,this.m22);return new Qr(t,e)}getScaleMatrix(){const e=this.getScaling(),i=na(e.x,e.y);return t.fromMatrix(i)}getTranslation(){return new Qr(this.m31,this.m32)}getRotationMatrix(){const e=this.getScaling(),i={m11:this.m11/e.x,m12:this.m12/e.x,m13:0,m21:this.m21/e.y,m22:this.m22/e.y,m23:0,m31:0,m32:0,m33:1};return t.fromMatrix(i)}getRotation(){const t=Math.atan2(this.m12,this.m11);return Kr(t)}decompose(){let{m11:t,m12:e,m21:i,m22:n}=this;const s={x:this.m31,y:this.m32},o={x:Math.hypot(t,e),y:Math.hypot(i,n)};t*n-e*i<0&&(t<n?o.x=-o.x:o.y=-o.y),o.x&&(t/=o.x,e/=o.x),o.y&&(i/=o.y,n/=o.y);const r=Math.atan2(e,t);return{translation:s,scale:o,rotation:Kr(r)}}transformPoint(t){const{m11:e,m12:i,m21:n,m22:s,m31:o,m32:r}=this;return{x:t.x*e+t.y*n+o,y:t.x*i+t.y*s+r}}};function ea(t,e){const i={},{m11:n,m21:s,m31:o,m12:r,m22:a,m32:l,m13:h,m23:c,m33:d}=t,{m11:u,m21:p,m31:g,m12:f,m22:m,m32:v,m13:y,m23:x,m33:w}=e;return i.m11=n*u+s*f+o*y,i.m21=n*p+s*m+o*x,i.m31=n*g+s*v+o*w,i.m12=r*u+a*f+l*y,i.m22=r*p+a*m+l*x,i.m32=r*g+a*v+l*w,i.m13=h*u+c*f+d*y,i.m23=h*p+c*m+d*x,i.m33=h*g+c*v+d*w,i}function ia(){return{m11:1,m21:0,m31:arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,m12:0,m22:1,m32:arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,m13:0,m23:0,m33:1}}function na(){return{m11:arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,m21:0,m31:0,m12:0,m22:arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,m32:0,m13:0,m23:0,m33:1}}function sa(){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{x:0,y:0};const e=Jr(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0),i=Math.cos(e),n=Math.sin(e),{x:s,y:o}=t;return{m11:i,m21:-n,m31:s-s*i+o*n,m12:n,m22:i,m32:o-s*n-o*i,m13:0,m23:0,m33:1}}const oa=new class{recursiveUpdateHierarchy(t){const{transform:e,childNodes:i}=t;e.frozen||(e.frozen=!0,(e.localDirty||e.worldDirty)&&this.updateHierarchy(t),i.forEach(t=>{this.recursiveUpdateHierarchy(t)}))}querySelector(t,e){return t.startsWith("#")?e.find(e=>e.id===t.substring(1)):null}querySelectorAll(t,e){return[]}append(t,e,i){t.parentNode&&this.remove(t),t.parentNode=e;const{childNodes:n,sortable:s}=e;void 0!==i?n.splice(i,0,t):n.push(t),s&&(s.dirty=!0);const{transform:o}=t;o&&this.dirtyWorld(t,o),o.frozen&&this.unfreezeParentToRoot(t)}remove(t){const{parentNode:e}=t;let i=!0;if(!e)return i=!1,i;const{sortable:n}=e;n&&(n.dirty=!0);const{childNodes:s}=e,o=s.indexOf(t);o>-1?(i=!0,s.splice(o,1)):i=!1;const{transform:r}=t;return r&&this.dirtyWorld(t,r),t.parentNode=null,i}isChildExist(t){const{parentNode:e}=t;if(!e)return!1;const{childNodes:i}=e;return!(i.indexOf(t)<0)}setOrigin(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;Ls(e)&&(e=Qr.fromValue(e,i));const{transform:n}=t;n.origin.equals(e)||(n.origin.setFromVector(e),this.dirtyLocal(t,n))}getOrigin(t){return t.transform.origin.clone()}setPosition(t,e){const{transform:i}=t,n=this.getPosition(t);if(n.equals(e))return;let s=this.getWorldTransform(t);if(i.position.setFromVector(e),t.hasParentTransform()){s=ta.create().translateSelf(e.x-n.x,e.y-n.y).multiply(s);const{worldTransform:o}=t.parentNode.transform,r=o.inverse().multiply(s),a=this.getOrigin(t),l=r.getScaleMatrix().inverse(),h=r.translate(a.x,a.y).multiply(l),c=h.getRotationMatrix().inverse(),d=h.multiply(c).getTranslation();d.subSelf(a),i.localPosition.setFromVector(d)}else i.localPosition.setFromVector(e);this.dirtyLocal(t,i)}setLocalPosition(t,e){const{transform:i}=t;i.localPosition.equals(e)||(i.localPosition.setFromVector(e),this.dirtyLocal(t,i))}getPosition(t){const e=this.getWorldTransform(t),{transform:i}=t,n=e.getTranslation();return i.position.setFromVector(n),t.transform.position.clone()}getLocalPosition(t){return t.transform.localPosition.clone()}translate(t,e){if(0===e.x&&0===e.y)return;const i=this.getPosition(t);i.addSelf(e),this.setPosition(t,i)}translateLocal(t,e){const{transform:i}=t;if(0===e.x&&0===e.y)return;const n=Qr.fromPoint(e).multiplySelf(i.localScale),s=ta.createRotationMatrix(i.localRotation).transformPoint(n);i.localPosition.addSelf(s),this.dirtyLocal(t,i)}scaleLocal(t,e){const{transform:i}=t;i.localScale.multiplySelf(e),this.dirtyLocal(t,i)}setLocalScale(t,e){const{transform:i}=t;i.localScale.equals(e)||(i.localScale.setFromVector(e),this.dirtyLocal(t,i))}getScale(t){const{transform:e}=t,i=this.getWorldTransform(t).getScaling();return e.scale.setFromVector(i),e.scale.clone()}getLocalScale(t){return t.transform.localScale.clone()}getRotation(t){const{transform:e}=t,i=this.getWorldTransform(t).getRotation();return e.rotation=i,i}getLocalRotation(t){return t.transform.localRotation}rotate(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(0===e)return;const{transform:i}=t;if(t.hasParentTransform()){const n=this.getRotation(t),s=-this.getRotation(t.parentNode)+e+n;i.localRotation=s,this.dirtyLocal(t,i)}else this.rotateLocal(t,e)}rotateLocal(t,e){const{transform:i}=t;i.localRotation+=e,this.dirtyLocal(t,i)}setAngle(t,e){const{transform:i}=t;if(t.hasParentTransform()){const n=this.getRotation(t.parentNode);i.localRotation=-n+e,this.dirtyLocal(t,i)}else this.setLocalAngle(t,e)}setLocalAngle(t,e){const{transform:i}=t;i.localRotation=e,this.dirtyLocal(t,i)}getAngle(t){return this.getWorldTransform(t).getRotation()}getLocalAngle(t){return this.getLocalRotation(t)}setLocalTransform(t,e){const i=this.getOrigin(t),{rotation:n,scale:s}=e.decompose(),o=ta.createScaleMatrix(s).inverse(),r=e.translate(i.x,i.y).multiply(o).getTranslation();r.subSelf(i),this.setLocalPosition(t,r),this.setLocalAngle(t,n),this.setLocalScale(t,s)}resetLocalTransform(t){this.setLocalScale(t,new Qr(1,1)),this.setLocalPosition(t,new Qr(0,0)),this.setLocalAngle(t,0)}getWorldTransform(t){const{transform:e}=t;if(!e.worldDirty&&!e.localDirty)return e.worldTransform;const{parentNode:i}=t;return i&&i.transform&&this.getWorldTransform(i),this.updateHierarchy(t),e.worldTransform.clone()}getLocalTransform(t){const{transform:e}=t;return e.localDirty&&e.updateLocalTransform(),e.localTransform.clone()}getBounds(t,e){const{renderable:i,childNodes:n}=t;if(e&&!i.renderBoundsDirty&&i)return i.renderBounds;if(!e&&!i.boundsDirty&&i.bounds)return i.bounds;let s=this.getTransformedGeometryBounds(t,e);n.forEach(t=>{const i=this.getBounds(t,e);i&&(s?s.addBounds(i):s=ql.fromBounds(i))});const{clipPath:o}=t.style;if(o){const e=this.getTransformedGeometryBounds(o,!0);let i=null;e&&(i=ql.create(),i.setFromTransformedBounds(this.getWorldTransform(t),e)),s?i&&(s=i.intersection(s)):s=i}return e?(i.renderBoundsDirty=!1,s&&(i.renderBounds=s)):(i.boundsDirty=!1,s&&(i.bounds=s)),s||ql.create()}getLocalBounds(t){const{parentNode:e}=t;if(e){let i=ta.create();e.transform&&(i=this.getWorldTransform(e).inverse());const n=this.getBounds(t);if(!ql.isEmpty(n)){const t=ql.create();return t.setFromTransformedBounds(i,n),t}}return this.getBounds(t)}getGeometryBounds(t,e){const{geometry:i}=t;return(e?i.renderBounds:i.contentBounds)||ql.create()}getBoundingClientRect(t){var e;let i;const n=this.getGeometryBounds(t);ql.isEmpty(n)||(i=ql.create(),i.setFromTransformedBounds(this.getWorldTransform(t),n));const s=null===(e=t.ownerDocument)||void 0===e?void 0:e.defaultView.getContextService().getBoundingClientRect();return i?{x:i.minX+((null==s?void 0:s.left)||0),y:i.minY+((null==s?void 0:s.top)||0),width:i.maxX-i.minX,height:i.maxY-i.minY}:{x:(null==s?void 0:s.left)||0,y:(null==s?void 0:s.top)||0,width:0,height:0}}updateHierarchy(t){const{transform:e}=t;if(e.localDirty&&e.updateLocalTransform(),e.worldDirty){var i;let n=null==t||null===(i=t.parentNode)||void 0===i?void 0:i.transform;t.parentNode&&n||(n=new ha),e.updateWorldTransform(n)}}getTransformedGeometryBounds(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=this.getGeometryBounds(t,e);if(!ql.isEmpty(i)){const e=ql.create();return e.setFromTransformedBounds(this.getWorldTransform(t),i),e}return null}dirtyLocal(t,e){e.localDirty||(e.localDirty=!0,e.worldDirty||this.dirtyWorld(t,e))}dirtyWorld(t,e){e.worldDirty||this.unfreezeParentToRoot(t),this.recursiveDirtyWorld(t,e),function(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=t;for(;i;){const{renderable:t}=i;t&&(t.boundsDirty=!0,t.renderBoundsDirty=!0),i=i.parentNode}const n=new Yr("bounds-changed",{affectChildren:e});t.dispatchEvent(n)}(t,!0)}recursiveDirtyWorld(t,e){if(e.worldDirty)return;e.worldDirty=!0,e.frozen=!1,t.childNodes.forEach(t=>{const{transform:e}=t;e.worldDirty||this.recursiveDirtyWorld(t,e)});const{renderable:i}=t;i&&(i.boundsDirty=!0,i.renderBoundsDirty=!0);const n=new hh("DOMAttrModified",t,null,null,"modelMatrix",hh.MODIFICATION,null,null);t.dispatchEvent(n)}unfreezeParentToRoot(t){let e=t;for(;e;){const{transform:t}=e;t&&(t.frozen=!1),e=e.parentNode}}};let ra=class{constructor(){Yi(this,"contentBounds",void 0),Yi(this,"renderBounds",void 0)}},aa=class{constructor(){Yi(this,"boundsDirty",!0),Yi(this,"bounds",void 0),Yi(this,"renderBoundsDirty",!0),Yi(this,"renderBounds",void 0)}isRenderable(){return this.boundsDirty||this.renderBoundsDirty}toRenderable(){this.boundsDirty=!0,this.renderBoundsDirty=!0}},la=class{constructor(){Yi(this,"renderOrder",0),Yi(this,"lastSortedIndex",void 0),Yi(this,"sorted",void 0),Yi(this,"dirty",!1)}},ha=class{constructor(){Yi(this,"frozen",!0),Yi(this,"worldDirty",!1),Yi(this,"localDirty",!1),Yi(this,"localRotation",0),Yi(this,"rotation",0),Yi(this,"localScale",Qr.create(1,1)),Yi(this,"scale",Qr.create(1,1)),Yi(this,"localPosition",Qr.create(0,0)),Yi(this,"position",Qr.create(0,0)),Yi(this,"localSkew",Qr.create(0,0)),Yi(this,"skew",Qr.create(0,0)),Yi(this,"origin",Qr.create(0,0)),Yi(this,"worldTransform",ta.create()),Yi(this,"localTransform",ta.create())}updateLocalTransform(){const{origin:t,localScale:e,localPosition:i,localRotation:n}=this,s=ta.create();s.translateSelf(t.x,t.y);const o=ta.compose(i,e,n);s.multiplySelf(o),s.translateSelf(-t.x,-t.y),this.localTransform.setFromMatrix(s),this.localDirty=!1}updateWorldTransform(t){const e=t.worldTransform.clone();e.multiplySelf(this.localTransform),this.worldTransform.setFromMatrix(e),this.worldDirty=!1}};function ca(t,e){if(Number.isNaN(e))return{unit:"px",value:0};if(So(e))return{unit:"px",value:0};if(Ls(e))return{unit:"px",value:e};if(e=e.trim().toLowerCase(),Number.isFinite(Number(e))&&"px".search(t)>=0)return{unit:"px",value:Number(e)};const i=[];e=e.replace(t,t=>(i.push(t),`U${t}`));const n=`U(${t.source})`;return i.map(t=>({unit:t,value:Number(e.replace(new RegExp(`U${t}`,"g"),"").replace(new RegExp(n,"g"),"*0"))}))[0]}const da=t=>ca(/px|pt/g,t),ua=t=>ca(/px|%|em/g,t),pa=t=>ca(/deg|rad|grad|turn/g,t);let ga=class t{constructor(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];Yi(this,"r",void 0),Yi(this,"g",void 0),Yi(this,"b",void 0),Yi(this,"alpha",void 0),Yi(this,"isNone",void 0),Yi(this,"formatted",""),this.r=t,this.g=e,this.b=i,this.alpha=n,this.isNone=s,this.formatted=`rgba(${t}, ${e}, ${i}, ${n})`}clone(){return new t(this.r,this.g,this.b,this.alpha)}},fa=class t{constructor(t,e){Yi(this,"type",void 0),Yi(this,"value",void 0),this.type=t,this.value=e}clone(){return new t(this.type,this.value)}};const ma={left:180,top:-90,bottom:90,right:0,"left top":225,"top left":225,"left bottom":135,"bottom left":135,"right top":-45,"top right":-45,"right bottom":45,"bottom right":45},va=t=>{let e;return e="angular"===t.type?Number(t.value):ma[t.value]||0,{value:e,unit:"deg"}};function ya(t){const e=t.replace(/rgba?\(/,"").replace(/\)/,"").replace(/[\s+]/g,"").split(","),i=parseFloat(e[3]||"1"),n=Math.floor(i*parseInt(e[0],10)+255*(1-i)),s=Math.floor(i*parseInt(e[1],10)+255*(1-i)),o=Math.floor(i*parseInt(e[2],10)+255*(1-i));return`#${`0${n.toString(16)}`.slice(-2)}${`0${s.toString(16)}`.slice(-2)}${`0${o.toString(16)}`.slice(-2)}`}function xa(t){return/^hsla?\(.+\)$/i.test(t)}function wa(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(So(t))return null;if("currentColor"===t&&(t="black"),"transparent"===t)return new ga(0,0,0,0);const e=(t=>{if(t.includes("linear")||t.includes("radial"))return to(t).map(t=>{let{type:e,orientation:i,colorStops:n}=t;!function(t){var e;const{length:i}=t;var n;t[i-1].length=null!==(e=t[i-1].length)&&void 0!==e?e:{type:"%",value:"100"},i>1&&(t[0].length=null!==(n=t[0].length)&&void 0!==n?n:{type:"%",value:"0"});let s=0,o=Number(t[0].length.value);for(let e=1;e<i;e++){var r;const i=null===(r=t[e].length)||void 0===r?void 0:r.value;if(!So(i)&&!So(o)){for(let n=1;n<e-s;n++)t[s+n].length={type:"%",value:`${o+(Number(i)-o)*n/(e-s)}`};s=e,o=Number(i)}}}(n);const s=n.map(t=>({offset:{value:t.length.value,unit:"%"},color:Qs(t)}));if("linear-gradient"===e)return new fa(1,{angle:i?va(i):{value:0,unit:"deg"},steps:s});if("radial-gradient"===e){i||(i=[{type:"shape",value:"circle"}]);const t=i[0];if("shape"===(null==t?void 0:t.type)&&"circle"===(null==t?void 0:t.value)){const{cx:i,cy:n}=(t=>{let e=50,i=50,n="%",s="%";if("position"===(null==t?void 0:t.type)){const{x:o,y:r}=t.value;"position-keyword"===(null==o?void 0:o.type)&&("left"===o.value?e=0:"center"===o.value?e=50:"right"===o.value?e=100:"top"===o.value?i=0:"bottom"===o.value&&(i=100)),"position-keyword"===(null==r?void 0:r.type)&&("left"===r.value?e=0:"center"===r.value?i=50:"right"===r.value?e=100:"top"===r.value?i=0:"bottom"===r.value&&(i=100)),"px"!==(null==o?void 0:o.type)&&"%"!==(null==o?void 0:o.type)&&"em"!==(null==o?void 0:o.type)||(n=null==o?void 0:o.type,e=Number(o.value)),"px"!==(null==r?void 0:r.type)&&"%"!==(null==r?void 0:r.type)&&"em"!==(null==r?void 0:r.type)||(s=null==r?void 0:r.type,i=Number(r.value))}return{cx:{value:e,unit:n},cy:{value:i,unit:s}}})(null==t?void 0:t.at);let o;if(null!=t&&t.style){const{type:i,value:n}=t.style;o="extent-keyword"===i?n:{value:n,unit:e}}return new fa(2,{cx:i,cy:n,size:o,steps:s})}}})})(t);if(e)return e;if(xa){const e=document.createElement("div");e.style.color=t,t=e.style.color}const i=(t=>{let e,i;if(t=`${t}`.trim().toLowerCase(),ls.exec(t))switch(e=ls.exec(t),i=e[1].length,e=parseInt(e[1],16),i){case 6:return vs(e);case 3:return new ms(e>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1);case 8:return ys(e>>24&255,e>>16&255,e>>8&255,(255&e)/255);case 4:return ys(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255);default:return null}return hs.exec(t)?(e=hs.exec(t),new ms(e[1],e[2],e[3],1)):cs.exec(t)?(e=cs.exec(t),new ms(255*e[1]/100,255*e[2]/100,255*e[3]/100,1)):ds.exec(t)?(e=ds.exec(t),ys(e[1],e[2],e[3],e[4])):us.exec(t)?(e=us.exec(t),ys(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4])):ps.exec(t)?(e=ps.exec(t),Cs(xs(e[1],e[2]/100,e[3]/100,1))):gs.exec(t)?(e=gs.exec(t),Cs(xs(e[1],e[2]/100,e[3]/100,e[4]))):fs.hasOwnProperty(t)?vs(fs[t]):"transparent"===t?new ms(NaN,NaN,NaN,0):null})(t),n=[0,0,0,0];return null!==i&&(n[0]=parseInt(i.r,10)||0,n[1]=parseInt(i.g,10)||0,n[2]=parseInt(i.b,10)||0,n[3]=parseFloat(i.opacity)),new ga(...n)}function Ca(t){let e=null;Ts(t)&&(e=t),Os(t)&&(e=t.split(" "));for(let t=0;t<3;t++)e[t]?e[t]=da(e[t]).value:e[t]=0;const i=wa(e[3]);return e[3]=i?i.formatted:"black",e.slice(0,4)}function ba(t){const e=[];return Os(t)?t.split(" ").forEach(t=>{const i=da(t);i&&e.push(i.value)}):e.push(...t),1===e.length?[e[0],e[0]]:e}const Sa=t=>{let e=t;if(Os(t)){const i=ua(t);"%"===i.unit&&(e=i.value/100),"px"===i.unit&&(e=i.value)}return e>1&&(e=1),e},Ta={visibility:"visible",x:0,y:0,zIndex:0,anchor:[0,0],lineDash:[0,0],opacity:1,fillOpacity:1,borderOpacity:1,miterLimit:10,lineDashOffset:0,lineJoin:"miter",lineCap:"butt",borderColor:"black",renderBlendMode:"normal"},Ea={color:"rgb(0,0,0)",fontFamily:"Helvetica",fontStyle:"normal",fontWeight:"normal",fontSize:20};function _a(t){const e=[];return t.forEach(t=>{e.push({...Ea,...t,fontSize:da(t.fontSize||Ea.fontSize)})}),e}function Pa(t,e,i,n){const{x:s=0,y:o=0}=i.parsedStyle,{x:r,y:a}=i.getLocalPosition();i.boundsDirty=!0,"x"===n&&s===r||"y"===n&&o===a||i.setLocalPosition(s,o)}function Aa(t,e,i){if(!(i instanceof kl||i instanceof Ml||i instanceof Pl))return;if(t===e)return;i.pathDirty=!0,i.boundsDirty=!0,i.getPath();const{left:n,top:s}=i.getBoundingRect();i.updatePosition(n,s),i.updateOrigin()}function Ia(t,e,i){!(i instanceof Ll)||i instanceof Fl||i instanceof _l||t!==e&&(i.pathDirty=!0,i.boundsDirty=!0,i.getPath(),i.updateOrigin())}function Da(t,e,i){(i instanceof Sl||i instanceof Tl||i instanceof El)&&t!==e&&(i.pathDirty=!0,i.boundsDirty=!0,i.getPath())}function Ra(t,e,i){if(!(i instanceof Bl||i instanceof Ml))return;if(t===e)return;i.pathDirty=!0,i.boundsDirty=!0,i.getPath();const{left:n,top:s}=i.getBoundingRect();i.updatePosition(n,s),i.updateOrigin()}function ka(t,e,i){t!==e&&(i.pathDirty=!0,i.boundsDirty=!0,i.getPath())}function Ma(t,e,i){i instanceof Ol&&t!==e&&(i.pathDirty=!0,i.boundsDirty=!0,i.getPath())}function La(t,e,i,n){var s;if(!(i instanceof Vl))return;if(t===e)return;i.setLimitWidth(i.parsedStyle.width.value),i.pathDirty=!0,i.boundsDirty=!0;const o="freeTextWriter"!==i.textType;if(["x","y"].includes(n)&&null!==(s=i.lines)&&void 0!==s&&s.length){const s=e-t;return"x"===n?i.updateTextLinesForTranslate(s,0):i.updateTextLinesForTranslate(0,s),void i.getPath()}if(o||!o&&["width","textContents"].includes(n)){var r;if(null==i||null===(r=i.textEditEventHandler)||void 0===r||!r.editMode)return void(i.linesDirty=!0);i.calculateTextLines()}i.getPath()}let Oa=class t{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;Yi(this,"x",void 0),Yi(this,"y",void 0),this.x=t,this.y=e}static fromPoint(e){return new t(e.x,e.y)}setFromPoint(t){return this.x=t.x||0,this.y=t.y||0,this}clone(){return new t(this.x,this.y)}equals(t){return this.x===t.x&&this.y===t.y}distanceTo(t){return Math.hypot(this.x-t.x,this.y-t.y)}lerpTo(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5;return new t(this.x+i*(e.x-this.x),this.y+i*(e.y-this.y))}footPointInSegment(e,i){const n=Qr.fromTwoPoint(e,this),s=Qr.fromTwoPoint(e,i),o=s.norm(),r=t.fromPoint(e);if(0===o)return r;const a=n.projectionTo(s)/o;return r.lerpTo(i,a)}perpendicularToSegment(t,e){const i=this.footPointInSegment(t,e);return this.distanceTo(i)}};function Ba(t,e,i){const n=t.x-e.x,s=t.y-e.y;let o=(i.x-t.x)*n+(i.y-t.y)*s;return o/=n*n+s*s,new Oa(t.x+o*n,t.y+o*s)}function Na(t,e,i,n){let s=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),o=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((s^o)>=0&&0!==s&&0!==o||(s=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),o=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(s^o)>=0&&0!==s&&0!==o))}function Ua(t,e){return((t.x-e.x)**2+(t.y-e.y)**2)**.5}function Fa(t,e,i,n,s){const o=s||[],r=t[e],a=t[i];let l=0,h=1;for(let n=e+1;n<i;n++){const e=Ua(Ba(r,a,t[n]),t[n]);e>l&&(l=e,h=n)}return l>=n?(Fa(t,e,h,n,o),Fa(t,h,i,n,o)):(!o.length&&r&&o.push(r),o.push(a)),o}function Va(t,e,i,n,s,o){const r=function(t,e,i,n,s,o){const r=function(t,e,i){const n=Math.cos(t),s=Math.sin(t);return function(t,o){return{x:n*(t-e)+s*(o-i),y:-s*(t-e)+n*(o-i)}}}((p=s-t,g=o-e,Math.atan2(g,p)),(t+s)/2,(e+o)/2),a=r(t,e),l=r(i,n),h=r(s,o),c=Math.abs(a.x),[d,u]=[l.y/2,0].sort((t,e)=>t-e);var p,g;let f,m;return l.x>=a.x&&l.x<=h.y?[f,m]=[a.x,h.x]:l.x>0?[f,m]=[a.x,.5*(l.x+c*c/l.x)]:[f,m]=[.5*(l.x+c*c/l.x),h.x],function(t,e,i){const n=r(t,e);return!(n.x<f-i||n.x>m+i||n.y<d-i||n.y>u+i)}}(t,e,i,n,s,o),{getDistance:a}=function(t,e,i,n,s,o){const r=[i-t,n-e],a=[t-2*i+s,e-2*n+o],l=[2*r[0],2*r[1]],h=1/Ha(a,a),c=h*Ha(r,a),d=c*c,u=Ha(r,r),p=3**.5,g=0===Ha(a,a)?function(t){return 0===u?0:Wa(-Ha(r,t)/2/u,0,1)}:function(t){const e=h*(2*u+Ha(t,a))/3,i=h*Ha(t,r),n=e-d,s=c*(2*d-3*e)+i;let o=s*s+n*n*n*4;if(o>=0){o=Math.sqrt(o);const t=(o-s)/2,e=(-o-s)/2;return Wa(Math.sign(t)*Math.abs(t)**(1/3)+Math.sign(e)*Math.abs(e)**(1/3)-c,0,1)}const l=Math.sqrt(-n),g=Math.acos(s/(n*l*2))/3,f=Math.cos(g),m=Math.sin(g)*p;return[Wa((f+f)*l-c,0,1),Wa((-m-f)*l-c,0,1)]};return{getDistance(i,n){const s=[t-i,e-n],o=g(s);if("number"==typeof o)return Math.sqrt(ja((l[0]+a[0]*o)*o+s[0],(l[1]+a[1]*o)*o+s[1]));const[r,h]=o;return Math.sqrt(Math.min(ja(s[0]+(l[0]+a[0]*r)*r,s[1]+(l[1]+a[1]*r)*r),ja(s[0]+(l[0]+a[0]*h)*h,s[1]+(l[1]+a[1]*h)*h)))}}}(t,e,i,n,s,o);return{isHit:function(t,e){return function(t,e,i){return!!r(t,e,i)&&a(t,e)<=i}(t[0],t[1],e)}}}function Wa(t,e,i){return Math.min(Math.max(t,e),i)}function Ha(t,e){return t[0]*e[0]+t[1]*e[1]}function ja(t,e){return t*t+e*e}function za(t,e,i,n,s){const{PI:o,cos:r,sin:a,min:l,max:h,tan:c}=Math;s-n>2*o&&(s=n+2*o);let d=h(o/12,(s-n)/12);const u=[];for(u.push({x:t+i*r(n),y:e+i*a(n)});n<s;){const o=t+i*r(n),h=e+i*a(n),p=l(s,n+d);d=l(s-n,d);const g=t+i*r(p),f=e+i*a(p),m=i*c(d/3),v={x:o-(h-e)/i*m,y:h+(o-t)/i*m},y={x:g+(f-e)/i*m,y:f-(g-t)/i*m},x={x:g,y:f};u.push(v,y,x),n+=d}return u}function Ga(t,e,i,n){const s=t-i,o=t+i,r=e-n,a=e+n,l=.551915024494,h=l*i,c=l*n,d=[];return d.push({x:o,y:e}),d.push({x:o,y:e+c},{x:t+h,y:a},{x:t,y:a}),d.push({x:t-h,y:a},{x:s,y:e+c},{x:s,y:e}),d.push({x:s,y:e-c},{x:t-h,y:r},{x:t,y:r}),d.push({x:t+h,y:r},{x:o,y:e-c},{x:o,y:e}),d}function Ya(t,e){return{type:t,data:e,close:arguments.length>2&&void 0!==arguments[2]&&arguments[2]}}function $a(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=t.length;if(i<=1)return[];const n=[],[s]=t;n.push(Ya("moveTo",[s]));for(let e=0;e+3<i;e+=3){const i=t[e+1],s=t[e+2],o=t[e+3];n.push(Ya("bezierCurveTo",[i,s,o]))}return e&&t.length>2&&n.push(Ya("lineTo",[s])),n}function Xa(t,e){return Math.sqrt((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y))}function qa(t,e){const i=t.length;if(i<=1)return[];if(2===i)return[{index:0,ops:[Ya("moveTo",[t[0]])]},{index:1,ops:[Ya("lineTo",[t[1]])]}];let n=i-e;i<=e&&(n=0);const s=[];let o=[],r={index:n,ops:[]};if(s.push(r),i<=e){const e=Ya("moveTo",[t[0]]);r.ops.push(e),o=[...t]}else o=t.slice(-e);const a=function(t){const e=[];for(let i=1;i<t.length-1;i++){const n=180*Rl(Il(t[i-1],t[i]),Il(t[i],t[i+1]))/Math.PI;n>=45&&n<=135&&e.push(i)}return e}(o),l=[];for(let e=0;e<o.length;e++)if(a.includes(e)){const i=t[e-1],s=t[e+1],r=Xa(t[e],i),a=Xa(t[e],s);let h,c;r>6&&(h=el(i,t[e],.2),l.push({val:h})),l.push({index:e+n,val:o[e]}),a>6&&(c=el(s,t[e],.2),l.push({val:c}))}else l.push({index:e+n,val:o[e]});for(let t=0;t<l.length;t++){var h,c,d,u,p,g;const e=l[t],i=l[t].val,o=null!==(h=null===(c=l[t-1])||void 0===c?void 0:c.val)&&void 0!==h?h:i,a=null!==(d=null===(u=l[t+1])||void 0===u?void 0:u.val)&&void 0!==d?d:i,f=Za(o,i,a,null!==(p=null===(g=l[t+2])||void 0===g?void 0:g.val)&&void 0!==p?p:a);void 0!==e.index&&(e.index!==n&&(r={index:void 0,ops:[]},s.push(r)),r.index=e.index),r.ops.push(f)}return s}function Za(t,e,i,n){let s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:5;const o=Xa(e,i);let r={x:e.x+(i.x-t.x)/s,y:e.y+(i.y-t.y)/s},a={x:i.x-(n.x-e.x)/s,y:i.y-(n.y-e.y)/s};const l=Xa(r,e),h=Xa(a,i);return l>o&&(r=el(r,e,o)),h>o&&(a=el(a,i,o)),Ya("bezierCurveTo",[r,a,i])}function Ja(t,e,i){const n=(t.x+e.x)/2,s=(t.y+e.y)/2,o=(e.x+i.x)/2,r=(e.y+i.y)/2;return Ya("bezierCurveTo",[{x:n+2*(e.x-n)/3,y:s+2*(e.y-s)/3},{x:o+2*(e.x-o)/3,y:r+2*(e.y-r)/3},e])}function Ka(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=[];let[n]=t;i.push(Ya("moveTo",[n]));for(let e=1;e<t.length;e++)n=t[e],i.push(Ya("lineTo",[n]));return e&&t.length>2&&([n]=t,i.push(Ya("lineTo",[n]))),i}function Qa(t,e){const{data:i,type:n}=e,[s,o,r]=i;switch(n){case"moveTo":t.moveTo(s.x,s.y);break;case"lineTo":t.lineTo(s.x,s.y);break;case"bezierCurveTo":t.bezierCurveTo(s.x,s.y,o.x,o.y,r.x,r.y);break;case"quadraticCurveTo":t.quadraticCurveTo(s.x,s.y,o.x,o.y)}}function tl(t){let{x:e,y:i}=t[0],n=e,s=i;for(let o=1;o<t.length;o++){const{x:r,y:a}=t[o];e=Math.min(e,r),n=Math.max(n,r),i=Math.min(i,a),s=Math.max(s,a)}return{left:e,top:i,right:n,bottom:s,width:n-e,height:s-i}}function el(t,e,i){const n=e.x-t.x,s=e.y-t.y,o=Math.abs(n)/Math.abs(s);let r=Math.sqrt(i*i/(o*o+1)),a=r*o;return 0===n&&(a=0,r=Math.sqrt(i)),0===s&&(r=0,a=Math.sqrt(i)),{x:e.x-(n>=0?a:-a),y:e.y-(s>=0?r:-r)}}function il(t){if(t.length<1)return[];const e=[];let i=[];for(let n=0;n<t.length;n++){const s=t[n];if(0===s.step)n>0&&e.push({step:i,close:t[n-1].close}),i=[],i.push(Ya("moveTo",[{x:s.x,y:s.y}]));else if(1===s.step)i.push(Ya("lineTo",[{x:s.x,y:s.y}]));else if(2===s.step&&n+2<t.length&&2===t[n+1].step&&2===t[n+2].step){const e=t[n+1],o=t[n+2];i.push(Ya("bezierCurveTo",[s,e,o])),n+=2}}return e.push({step:i,close:t[t.length-1].close}),e}function nl(t){return 180*t/Math.PI}function sl(t){return t<0?t%360+360:t%360}function ol(t,e,i,n){return t/(i*i)+e/(n*n)}function rl(t,e,i,n){let s=0,o=0,r=0,a=0;const l=[t,e],h=tl(l),c=function(t,e,i,n){let s=n/2,o=n/2;const r=e.y-t.y,a=e.x-t.x;if(0===r||0===a)return[a,r];const l=-1/((e.y-t.y)/(e.x-t.x)),h=Math.atan(l);return"square"===i?(s=Math.sqrt(2)*n/2,o=Math.sqrt(2)*n/2):"round"===i?(s=n/2,o=n/2):(s=Math.abs(Math.cos(h)*n)/2,o=Math.abs(Math.sin(h)*n)/2),[s,o]}(l[0],l[1],n,i||0);return 0===c[1]?(s=h.left,o=h.top-i/2,r=h.width,a=h.height+i,"square"!==n&&"round"!==n||(s-=i/2,r+=i)):0===c[0]?(s=h.left-i/2,o=h.top,r=h.width+i,a=h.height,"square"!==n&&"round"!==n||(o-=i/2,a+=i)):(s=h.left-c[0],o=h.top-c[1],r=h.width+2*c[0],a=h.height+2*c[1]),{left:s,top:o,width:r,height:a}}function al(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function ll(t,e,i,n){const{x:s,y:o}=t,{x:r,y:a}=e,{x:l,y:h}=n,c=Math.min(s,r),d=Math.max(s,r),u=Math.min(o,a),p=Math.max(o,a),g=i/2;return l>=c-g&&l<=d+g&&h>=u-g&&h<=p+g&&function(t,e,i,n,s,o){const r=[i-t,n-e];if(new Qr(r[0],r[1]).equals({x:0,y:0}))return Math.sqrt((s-t)*(s-t)+(o-e)*(o-e));const a=[-r[1],r[0]],l=new Qr(a[0],a[1]);l.normalize();const h=[s-t,o-e],c=new Qr(h[0],h[1]);return Math.abs(c.dot(l))}(s,o,r,a,l,h)<=i/2}function hl(t,e,i){let n=!1;const s=t.length;if(s<=2)return!1;for(let l=0;l<s;l++){const h=t[l],c=t[(l+1)%s];if(r=c,((a={x:e,y:i}).x-(o=h).x)*(r.y-o.y)==(r.x-o.x)*(a.y-o.y)&&Math.min(o.x,r.x)<=a.x&&a.x<=Math.max(o.x,r.x)&&Math.min(o.y,r.y)<=a.y&&a.y<=Math.max(o.y,r.y))return!0;al(h.y-i)>0!=al(c.y-i)>0&&al(e-(i-h.y)*(h.x-c.x)/(h.y-c.y)-h.x)<0&&(n=!n)}var o,r,a;return n}function cl(t,e,i,n,s){const o=t.length;if(o<2)return!1;for(let s=0;s<o-1;s++)if(ll(t[s],t[s+1],e,{x:i,y:n}))return!0;return!(!s||!ll(t[0],t[o-1],e,{x:i,y:n}))}function dl(t,e,i,n,s,o){return s>=t&&s<=t+i&&o>=e&&o<=e+n}function ul(t,e,i,n,s,o){const r=o;let a=n.x,l=n.y,h=s.x,c=s.y;0===e&&(a=s.x,l=s.y,h=n.x,c=n.y);let d=Math.PI/2;const u=h-a>=0?1:-1,p=c-l>=0?1:-1;a!==h&&(d=Math.atan(Math.abs(c-l)/Math.abs(h-a)));const g=Math.cos(d),f=Math.sin(d),m=i?1:-1,v={x:h+7.8*m*r*g*u-4.5*r*f*u,y:c+7.8*m*r*f*p+4.5*r*g*p,step:0,close:!1},y={x:h,y:c,step:1,close:!1};i&&(y.x=h+r*m*g*u,y.y=c+r*m*f*p);const x={x:h+7.8*m*r*g*u+4.5*r*f*u,y:c+7.8*m*r*f*p-4.5*r*g*p,step:1,close:!1};t.push(v,y,x)}function pl(t,e,i,n,s,o){const r=o;let a=n.x,l=n.y,h=s.x,c=s.y;0===e&&(a=s.x,l=s.y,h=n.x,c=n.y);let d=Math.PI/2;const u=h-a>=0?1:-1,p=c-l>=0?1:-1;a!==h&&(d=Math.atan(Math.abs(c-l)/Math.abs(h-a)));const g=Math.cos(d),f=Math.sin(d),m=i?1:-1,v={x:h+7.8*m*r*g*u-4.5*r*f*u,y:c+7.8*m*r*f*p+4.5*r*g*p,step:0,close:!1},y={x:h,y:c,step:1,close:!1};i&&(y.x=h+r*m*g*u,y.y=c+r*m*f*p);const x={x:h+7.8*m*r*g*u+4.5*r*f*u,y:c+7.8*m*r*f*p-4.5*r*g*p,step:1,close:!0};t.push(v,y,x)}function gl(t,e,i,n,s){const o=s;let r=i.x,a=i.y,l=n.x,h=n.y;0===e&&(r=n.x,a=n.y,l=i.x,h=i.y);let c=Math.PI/2;const d=l-r>=0?1:-1,u=h-a>=0?1:-1;r!==l&&(c=Math.atan(Math.abs(h-a)/Math.abs(l-r)));const p=Math.cos(c),g=Math.sin(c),f={x:l-3*o*g*d,y:h+3*o*p*u,step:0,close:!1},m={x:l+3*o*g*d,y:h-3*o*p*u,step:1,close:!1};t.push(f,m)}function fl(t,e,i,n,s){const o=s;let r=i.x,a=i.y,l=n.x,h=n.y;0===e&&(r=n.x,a=n.y,l=i.x,h=i.y);let c=Math.PI/2;const d=l-r>=0?1:-1,u=h-a>=0?1:-1,p=h>=a&&l>=r||h<=a&&l<=r?-1:1;r!==l&&(c=Math.atan(Math.abs(h-a)/Math.abs(l-r)));const g=Math.cos(c),f=Math.sin(c),m=4.5*Math.sqrt(3)*o,v={x:l+4.5*o*g*d-m*f*d*p,y:h+4.5*o*f*u+m*g*u*p,step:0,close:!1},y={x:l-4.5*o*g*d+m*f*d*p,y:h-4.5*o*f*u-m*g*u*p,step:1,close:!1};t.push(v,y)}function ml(t,e,i,n,s){const o=s;let{x:r,y:a}=n;0===e&&(r=i.x,a=i.y);const l={x:r-3*o,y:a-3*o,step:0,close:!1},h={x:r+3*o,y:a-3*o,step:1,close:!1},c={x:r+3*o,y:a+3*o,step:1,close:!1},d={x:r-3*o,y:a+3*o,step:1,close:!0};t.push(l,h,c,d)}function vl(t,e,i,n,s){const o=s;let{x:r,y:a}=n;0===e&&(r=i.x,a=i.y);const l={x:r-3*o,y:a,step:0,close:!1},h={x:r,y:a-3*o,step:1,close:!1},c={x:r+3*o,y:a,step:1,close:!1},d={x:r,y:a+3*o,step:1,close:!0};t.push(l,h,c,d)}function yl(t,e,i,n,s){const o=s;let{x:r,y:a}=n;0===e&&(r=i.x,a=i.y);const l=3*o-0*o,h=Ga(r,a,l,l);h.forEach((e,i)=>{const n=0===i?0:2,s=i===h.length-1,o={x:e.x,y:e.y,step:n,close:s};t.push(o)})}let xl=class{constructor(t){Yi(this,"lineAlign",void 0),Yi(this,"owner",void 0),this.owner=t,this.reset()}reset(){this.lineAlign=.5}get x(){return this.owner.getAttribute("x")}set x(t){this.owner.setAttribute("x",t)}get y(){return this.owner.getAttribute("y")}set y(t){this.owner.setAttribute("y",t)}get r(){return this.owner.getAttribute("r")}set r(t){this.owner.setAttribute("r",t)}get width(){return this.owner.getAttribute("width")}set width(t){this.owner.setAttribute("width",t)}get height(){return this.owner.getAttribute("height")}set height(t){this.owner.setAttribute("height",t)}get points(){return this.owner.getAttribute("points")}set points(t){this.owner.setAttribute("points",t)}get origin(){return this.owner.getAttribute("origin")}set origin(t){this.owner.setAttribute("origin",t)}get anchor(){return this.owner.getAttribute("anchor")}set anchor(t){this.owner.setAttribute("anchor",t)}get visibility(){return this.owner.getAttribute("visibility")}set visibility(t){this.owner.setAttribute("visibility",t)}get zIndex(){return this.owner.getAttribute("zIndex")}set zIndex(t){this.owner.setAttribute("zIndex",t)}get borderWidth(){return this.owner.getAttribute("borderWidth")}set borderWidth(t){this.owner.setAttribute("borderWidth",t)}get borderColor(){return this.owner.getAttribute("borderColor")}set borderColor(t){this.owner.setAttribute("borderColor",t)}get opacity(){return this.owner.getAttribute("opacity")}set opacity(t){this.owner.setAttribute("opacity",t)}get fillOpacity(){return this.owner.getAttribute("fillOpacity")}set fillOpacity(t){this.owner.setAttribute("fillOpacity",t)}get borderOpacity(){return this.owner.getAttribute("borderOpacity")}set borderOpacity(t){this.owner.setAttribute("borderOpacity",t)}get background(){return this.owner.getAttribute("background")}set background(t){this.owner.setAttribute("background",t)}get clipPath(){return this.owner.getAttribute("clipPath")}set clipPath(t){this.owner.setAttribute("clipPath",t)}get cursor(){return this.owner.getAttribute("cursor")}set cursor(t){this.owner.setAttribute("cursor",t)}get hitArea(){return this.owner.getAttribute("hitArea")}set hitArea(t){this.owner.setAttribute("hitArea",t)}get pointerEvents(){return this.owner.getAttribute("pointerEvents")}set pointerEvents(t){this.owner.setAttribute("pointerEvents",t)}get miterLimit(){return this.owner.getAttribute("miterLimit")}set miterLimit(t){this.owner.setAttribute("miterLimit",t)}get roundedRadius(){return this.owner.getAttribute("roundedRadius")}set roundedRadius(t){this.owner.setAttribute("roundedRadius",t)}get lineCap(){return this.owner.getAttribute("lineCap")}set lineCap(t){this.owner.setAttribute("lineCap",t)}get lineJoin(){return this.owner.getAttribute("lineJoin")}set lineJoin(t){this.owner.setAttribute("lineJoin",t)}get lineDash(){return this.owner.getAttribute("lineDash")}set lineDash(t){this.owner.setAttribute("lineDash",t)}get lineDashOffset(){return this.owner.getAttribute("lineDashOffset")}set lineDashOffset(t){this.owner.setAttribute("lineDashOffset",t)}get shadow(){return this.owner.getAttribute("shadow")}set shadow(t){this.owner.setAttribute("shadow",t)}get shadowOffsetX(){return this.owner.getAttribute("shadowOffsetX")}set shadowOffsetX(t){this.owner.setAttribute("shadowOffsetX",t)}get shadowOffsetY(){return this.owner.getAttribute("shadowOffsetY")}set shadowOffsetY(t){this.owner.setAttribute("shadowOffsetY",t)}get shadowBlur(){return this.owner.getAttribute("shadowBlur")}set shadowBlur(t){this.owner.setAttribute("shadowBlur",t)}get shadowColor(){return this.owner.getAttribute("shadowColor")}set shadowColor(t){this.owner.setAttribute("shadowColor",t)}get startAngle(){return this.owner.getAttribute("startAngle")}set startAngle(t){this.owner.setAttribute("startAngle",t)}get endAngle(){return this.owner.getAttribute("endAngle")}set endAngle(t){this.owner.setAttribute("endAngle",t)}get rx(){return this.owner.getAttribute("rx")}set rx(t){this.owner.setAttribute("rx",t)}get ry(){return this.owner.getAttribute("ry")}set ry(t){this.owner.setAttribute("ry",t)}get img(){return this.owner.getAttribute("img")}set img(t){this.owner.setAttribute("img",t)}get src(){return this.owner.getAttribute("src")}set src(t){this.owner.setAttribute("src",t)}get text(){return this.owner.getAttribute("text")}set text(t){this.owner.setAttribute("text",t)}get wordWarp(){return this.owner.getAttribute("wordWarp")}set wordWarp(t){this.owner.setAttribute("wordWarp",t)}get wordBreak(){return this.owner.getAttribute("wordBreak")}set wordBreak(t){this.owner.setAttribute("wordBreak",t)}get textMaxWidth(){return this.owner.getAttribute("textMaxWidth")}set textMaxWidth(t){this.owner.setAttribute("textMaxWidth",t)}get letterSpacing(){return this.owner.getAttribute("letterSpacing")}set letterSpacing(t){this.owner.setAttribute("letterSpacing",t)}get textBaseLine(){return this.owner.getAttribute("textBaseLine")}set textBaseLine(t){this.owner.setAttribute("textBaseLine",t)}get color(){return this.owner.getAttribute("color")}set color(t){this.owner.setAttribute("color",t)}get fontStyle(){return this.owner.getAttribute("fontStyle")}set fontStyle(t){this.owner.setAttribute("fontStyle",t)}get fontVariant(){return this.owner.getAttribute("fontVariant")}set fontVariant(t){this.owner.setAttribute("fontVariant",t)}get fontWeight(){return this.owner.getAttribute("fontWeight")}set fontWeight(t){this.owner.setAttribute("fontWeight",t)}get fontSize(){return this.owner.getAttribute("fontSize")}set fontSize(t){this.owner.setAttribute("fontSize",t)}get lineHeight(){return this.owner.getAttribute("lineHeight")}set lineHeight(t){this.owner.setAttribute("lineHeight",t)}get fontFamily(){return this.owner.getAttribute("fontFamily")}set fontFamily(t){this.owner.setAttribute("fontFamily",t)}get font(){return this.owner.getAttribute("font")}set font(t){this.owner.setAttribute("font",t)}get startPoint(){return this.owner.getAttribute("startPoint")}set startPoint(t){this.owner.setAttribute("startPoint",t)}get endPoint(){return this.owner.getAttribute("endPoint")}set endPoint(t){this.owner.setAttribute("endPoint",t)}get lineEnding(){return this.owner.getAttribute("lineEnding")}set lineEnding(t){this.owner.setAttribute("lineEnding",t)}get segments(){return this.owner.getAttribute("segments")}set segments(t){this.owner.setAttribute("segments",t)}get stampPoints(){return this.owner.getAttribute("stampPoints")}set stampPoints(t){this.owner.setAttribute("stampPoints",t)}get imageData(){return this.owner.getAttribute("imageData")}set imageData(t){this.owner.setAttribute("imageData",t)}get iconName(){return this.owner.getAttribute("iconName")}set iconName(t){this.owner.setAttribute("iconName",t)}get textContents(){return this.owner.getAttribute("textContents")}set textContents(t){this.owner.setAttribute("textContents",function(t){const e=[];return t.forEach(t=>{t.content.length&&e.push(t)}),e}(t))}get textAlign(){return this.owner.getAttribute("textAlign")}set textAlign(t){this.owner.setAttribute("textAlign",t)}get renderBlendMode(){return this.owner.getAttribute("renderBlendMode")}set renderBlendMode(t){this.owner.setAttribute("renderBlendMode",t)}get lines(){return this.owner.getAttribute("lines")}set lines(t){this.owner.setAttribute("lines",t)}};const wl=new class{constructor(){Yi(this,"parsers",void 0),Yi(this,"updaters",void 0),this.parsers=new Map,this.updaters=new Map,this.initParser(),this.initUpdater()}getStyleParser(t){return this.parsers.get(t)}getStyleUpdaters(t){return this.updaters.get(t)}initParser(){this.bindHandler(["borderWidth","letterSpacing","lineDashOffset","shadowOffsetX","shadowOffsetY","shadowBlur","textMaxWidth","roundedRadius"],da,void 0),this.bindHandler(["startAngle","endAngle"],pa,void 0),this.bindHandler(["r","rx","ry","width","height","fontSize"],da,void 0),this.bindHandler(["borderColor","background","shadowColor","color"],wa,void 0),this.bindHandler(["opacity","fillOpacity","borderOpacity"],Sa,void 0),this.bindHandler(["lineDash"],ba,void 0),this.bindHandler(["shadow"],Ca,void 0),this.bindHandler(["textContents"],_a,void 0)}initUpdater(){this.bindHandler(["borderWidth"],void 0,ka),this.bindHandler(["x","y"],void 0,Pa),this.bindHandler(["width","height"],void 0,Ia),this.bindHandler(["r","rx","ry","startAngle","endAngle"],void 0,Da),this.bindHandler(["points","segments"],void 0,Aa),this.bindHandler(["startPoint","endPoint","lineEnding"],void 0,Ra),this.bindHandler(["stampPoints"],void 0,Ma),this.bindHandler(["x","y","width","height","textContents","textAlign","borderWidth"],void 0,La)}bindHandler(t,e,i){for(let n=0;n<t.length;n++)if(e&&this.parsers.set(t[n],e),i){const e=this.updaters.get(t[n])||[];e.push(i),this.updaters.set(t[n],e)}}};let Cl=class extends $r{constructor(t){super(),Yi(this,"attributes",{}),Yi(this,"id",void 0),Yi(this,"pageUid",void 0),Yi(this,"index",void 0),Yi(this,"name",void 0),Yi(this,"renderable",new aa),Yi(this,"sortable",new la),Yi(this,"geometry",new ra),Yi(this,"transform",new ha),Yi(this,"parsedStyle",{}),Yi(this,"style",void 0),Yi(this,"isDestroyed",!1),Yi(this,"childNodes",[]),Yi(this,"nodeName",""),Yi(this,"nodeType",0),Yi(this,"nodeValue",null),Yi(this,"ownerDocument",null),Yi(this,"parentNode",null),Yi(this,"isConnected",!1),Yi(this,"textContent",void 0),Yi(this,"shapeType",void 0),Yi(this,"config",void 0),Yi(this,"boundsDirty",!0),Yi(this,"bounds",void 0),Yi(this,"path",void 0),Yi(this,"pathDirty",!0),Yi(this,"steps",void 0),Yi(this,"renderClipPath",void 0),Yi(this,"renderClipStep",void 0),Yi(this,"strokePath",void 0),Yi(this,"strokeSteps",void 0),Yi(this,"externalMatrices",[]),Yi(this,"clippable",!1),Yi(this,"imageData",null),this.config=t,this.id=t.id||t.uid||"",this.name=t.name||"",this.index=t.index,this.nodeName=t.type||"container",this.pageUid=t.pageUid||"",(t.className||t.class)&&(this.className=t.className||t.class),this.style=new xl(this),this.initAttributes(t)}static isNode(t){return!!t.childNodes}set className(t){this.setAttribute("class",t)}get className(){return this.getAttribute("class")||""}get classList(){return this.className.split(" ").filter(t=>""!==t)}get tagName(){return this.nodeName}get children(){return this.childNodes}get childElementCount(){return this.childNodes.length}get firstElementChild(){return this.firstChild}get lastElementChild(){return this.lastChild}get firstChild(){return this.childNodes.length>0?this.childNodes[0]:null}get lastChild(){const{childNodes:t}=this;return t.length>0?t[t.length-1]:null}get nextSibling(){const{parentNode:t}=this;if(t){const e=t.childNodes.indexOf(this);return t.childNodes[e+1]}return null}get parentElement(){return this.parentNode}get previousSibling(){const{parentNode:t}=this;if(t){const e=t.childNodes.indexOf(this);return t.childNodes[e-1]}return null}getAttribute(t){const e=this.attributes[t];return null==e?null:e}getElementsByName(t){return oa.querySelectorAll(`[name="${t}"]`,this)}getElementsByClassName(t){return oa.querySelectorAll(`.${t}`,this)}getElementsByTagName(t){return oa.querySelectorAll(t,this)}hasAttribute(t){return Object.keys(this.attributes).indexOf(t)>-1}removeAttribute(t){this.setAttribute(t,null),delete this.attributes[t]}appendChild(t,e){oa.append(t,this,e);const i=new Yr("child-inserted",{child:t});this.dispatchEvent(i);const n=new hh("DOMNodeInserted",this,"","","",0,"","");return t.dispatchEvent(n),t}cloneNode(t){return null}insertBefore(t,e){if(e){const i=this.childNodes.indexOf(e);this.appendChild(t,i-1)}else this.appendChild(t);return t}removeChild(t){const e=new hh("removed",this,"","","",0,"","");t.dispatchEvent(e);const i=new Yr("child-removed",{child:t});return this.dispatchEvent(i),oa.remove(t),t}isChildExist(t){return oa.isChildExist(t)}replaceChild(t,e){const i=this.childNodes.indexOf(e);return this.removeChild(e),this.appendChild(t,i),e}destroy(){const t=new Yr("destroy",{});this.dispatchEvent(t),this.remove(),this.removeAllEventListeners(),this.isDestroyed=!0}after(){const{parentNode:t}=this;if(t){const s=t.childNodes.indexOf(this);for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];i.forEach((e,i)=>{null==t||t.appendChild(e,s+i+1)})}}before(){const{parentNode:t}=this;if(t){const s=t.childNodes.indexOf(this);for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];i.forEach((e,i)=>{null==t||t.appendChild(e,s+i)})}}remove(){this.parentNode&&this.parentNode.removeChild(this)}replaceWith(){this.after(...arguments),this.remove()}append(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];e.forEach(t=>{this.appendChild(t)})}prepend(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];e.forEach((t,e)=>{this.appendChild(t,e)})}querySelector(t){return oa.querySelector(t,this)}querySelectorAll(t){return oa.querySelectorAll(t,this)}find(t){let e=null;return this.recursiveCall(i=>!(i!==this||!t(i)||(e=i,0))),e}findAll(t){const e=[];return this.recursiveCall(i=>{i===this&&t(i)&&e.push(i)}),e}contains(t){let e=t;for(;e&&this!==e;)e=e.parentNode;return!!e}getRootNode(t){return this.parentNode?this.parentNode.getRootNode(t):this}hasChildNodes(){return this.childNodes.length>0}isEqualNode(t){return this===t}isSameNode(t){return this.isEqualNode(t)}normalize(){throw new Error("Method to be implemented")}recursiveCall(t){t(this)||this.childNodes.forEach(e=>{e.recursiveCall(t)})}hasParentTransform(){return!(!this.parentNode||!this.parentNode.transform)}getGeometryBounds(){return oa.getGeometryBounds(this)}getRenderBounds(){return oa.getBounds(this,!0)}getBounds(){return oa.getBounds(this)}getLocalBounds(){return oa.getLocalBounds(this)}getBoundingClientRect(){return oa.getBoundingClientRect(this)}get isVisible(){return"visible"===this.parsedStyle.visibility}get isInteractive(){return"none"!==this.parsedStyle.pointerEvents}get width(){return this.parsedStyle.width.value*Math.abs(this.getScale().x)}get height(){return this.parsedStyle.height.value*Math.abs(this.getScale().y)}initAttributes(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(const e in t)if(To(e,t)){if("style"===e)continue;this.attributes[e]=t[e]}for(const e in t.style)To(e,t.style)&&(this.parseStyleProperty(e,t.style[e]),this.attributes[e]=t.style[e]);this.renderable.toRenderable()}setAttribute(t,e){if(Ps(e))return;const i="x"===t||"y"===t,n=this.attributes[t];(e!==this.attributes[t]||i)&&(this.attributes[t]=e,Object.keys(this.config).includes(t)||(this.parseStyleProperty(t,e),this.updateStyleProperty(t,n,e)))}parseStyleProperty(t,e){const i=wl.getStyleParser(t);this.parsedStyle[t]=i?i(e,this,t):e}updateStyleProperty(t,e,i){const n=wl.getStyleUpdaters(t);n&&n.forEach(n=>{n(e,i,this,t)})}toFront(){const{parentNode:t}=this;if(t){const e=Math.max(...t.children.map(t=>t.style.zIndex));this.style.zIndex=e+1}return this}toBack(){const{parentNode:t}=this;if(t){const e=Math.min(...t.children.map(t=>t.style.zIndex));this.style.zIndex=e-1}return this}setOrigin(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return oa.setOrigin(this,t,e),this}getOrigin(){return oa.getOrigin(this)}setPosition(t){return t=bl(t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0),oa.setPosition(this,t),this}setLocalPosition(t){return t=bl(t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0),oa.setLocalPosition(this,t),this}getPosition(){return oa.getPosition(this)}getLocalPosition(){return oa.getLocalPosition(this)}translate(t){return t=bl(t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0),oa.translate(this,t),this}translateLocal(t){return t=bl(t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0),oa.translateLocal(this,t),this}scale(t,e){return this.scaleLocal(t,e)}scaleLocal(t,e){return Ls(t)&&(t={x:t,y:e=e||t}),oa.scaleLocal(this,t),this}setLocalScale(t,e){return Ls(t)&&(t={x:t,y:e=e||t}),oa.setLocalScale(this,t),this}getScale(){return oa.getScale(this)}getLocalScale(){return oa.getLocalScale(this)}rotate(t){return oa.rotate(this,t),this}rotateLocal(t){return oa.rotateLocal(this,t),this}setAngle(t){return oa.setAngle(this,t),this}setLocalAngle(t){return oa.setLocalAngle(this,t),this}getAngle(){return oa.getAngle(this)}getLocalAngle(){return oa.getLocalAngle(this)}getLocalTransform(){return oa.getLocalTransform(this)}getWorldTransform(){return oa.getWorldTransform(this)}setLocalTransform(t){return oa.setLocalTransform(this,t),this}resetLocalTransform(){return oa.resetLocalTransform(this),this}getPath(){}getBoundingRect(){return{left:0,top:0,width:0,height:0}}isPointInPath(t){return!1}updateStyle(t){Object.keys(t).forEach(e=>{To(e,t)&&(this.style[e]=t[e])})}updatePosition(t,e){this.style.x=t||0,this.style.y=e||0}updateOrigin(){const{width:t,height:e}=this.getBoundingRect();this.setOrigin(t/2,e/2)}getBoundingRectObject(){const{left:t,top:e,width:i,height:n}=this.getBoundingRect();return new Ll({style:{x:t,y:e,width:i,height:n,borderWidth:1,background:"transparent"}})}};function bl(t,e){return Ls(t)?{x:t,y:e}:t}let Sl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"arc",style:{...Ta,r:0,startAngle:0,endAngle:1.5*Math.PI,...t},...e}),Yi(this,"shapeType","arc");const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.updateOrigin()}normAngle(){const{startAngle:t,endAngle:e}=this.style;let i=pa(t).value,n=pa(e).value;if(i>n){const t=i;i=n,n=t}if(Math.abs(n-i)>=2*Math.PI-1e-5&&(i=0,n=2*Math.PI),i<-2*Math.PI||n<-2*Math.PI){const t=Math.max(Math.floor(i/(-2*Math.PI)),Math.floor(n/(-2*Math.PI)));i+=2*Math.PI*t,n+=2*Math.PI*t}if(i>2*Math.PI||n>2*Math.PI){const t=Math.max(Math.floor(i/(2*Math.PI)),Math.floor(n/(2*Math.PI)));i-=2*Math.PI*t,n-=2*Math.PI*t}this.parsedStyle.startAngle=pa(i),this.parsedStyle.endAngle=pa(n)}updateOrigin(){const{width:t,height:e,left:i,top:n}=this.getBoundingRect(),s=i-this.style.x+t/2,o=n-this.style.y+e/2;this.setOrigin(s,o)}getPath(){if(!this.pathDirty)return this.path;this.normAngle();const{r:t,borderWidth:e,startAngle:i,endAngle:n}=this.parsedStyle,s=.5*((null==e?void 0:e.value)||0),o=i.value,r=n.value;return this.path=za(0,0,t.value-s,o,r),this.steps=$a(this.path),this.pathDirty=!1,this.path}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,r:i,startAngle:n,endAngle:s,borderWidth:o}=this.parsedStyle,r=i.value,a=n.value,l=s.value;if(null==o||o.value,n===s)return{left:t-r-0,top:e-r-0,width:2*r+0,height:2*r+0};const{sin:h,cos:c,PI:d}=Math,u=[t+r*c(a),t+r*c(l)],p=[e+r*h(a),e+r*h(l)];return a<0&&l>0&&u.push(t+r),(a<.5*d&&l>.5*d||a<-1.5*d&&l>-1.5*d)&&p.push(e+r),(a<d&&l>d||a<-d&&l>-d)&&u.push(t-r),(a<1.5*d&&l>1.5*d||a<-.5*d&&l>-.5*d)&&p.push(e-r),u.sort((t,e)=>t-e),p.sort((t,e)=>t-e),this.boundsDirty=!1,this.bounds={left:u[0]-0,top:p[0]-0,width:u[u.length-1]-u[0]+0,height:p[p.length-1]-p[0]+0},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.getBoundingRectObject().isPointInPath(t,e))return!1;const{x:i,y:n,r:s,startAngle:o,endAngle:r,background:a,borderWidth:l}=this.parsedStyle,h=sl(nl(o.value)),c=sl(nl(r.value)),d=sl(nl(o.value+r.value)/2),u=Os(this.style.background)&&""!==this.style.background,p=l&&l.value,g=u?0:e,f=(l.value+g||0)/2,m=s.value-f,v=new Oa(i+m*Math.cos(h*Math.PI/180),n+m*Math.sin(h*Math.PI/180)),y=new Oa(i+m*Math.cos(c*Math.PI/180),n+m*Math.sin(c*Math.PI/180)),x=new Oa(i+m*Math.cos(d*Math.PI/180),n+m*Math.sin(d*Math.PI/180)),w=new Oa(t.x,t.y),C=w.distanceTo({x:i,y:n}),b=Na([v.x,v.y],[x.x,x.y],[w.x,w.y],[i,n]),S=Na([y.x,y.y],[x.x,x.y],[w.x,w.y],[i,n]),T=Na([v.x,v.y],[y.x,y.y],[w.x,w.y],[i,n]);if(C>m+f)return!1;const E=ll(v,y,2*f,t);if(c-h<180&&c-h>0||c-h<-180){if(a&&T||E)return!0;if(!a&&p&&C>=m-f&&C<=m+f&&T)return!0}else if(180===Math.abs(c-h)){if(a){if(b||S)return!0;if(function(t,e,i,n){const{x:s,y:o}=t,{x:r,y:a}=e,{x:l,y:h}=i,{x:c,y:d}=n;return!(((c-s)*(a-o)-(d-o)*(r-s))*((l-s)*(a-o)-(h-o)*(r-s))<=0||((c-l)*(a-h)-(d-h)*(r-l))*((s-l)*(a-h)-(o-h)*(r-l))<=0||((c-s)*(h-o)-(d-o)*(l-s))*((r-s)*(h-o)-(a-o)*(l-s))<=0)}(v,x,y,t))return!0}if(!a&&p&&C>=m-f&&C<=m+f&&(b||S))return!0}else{if(a){if(b||S)return!0;if(!T)return!0}if(!a&&p&&C>=m-f&&C<=m+f&&(b||S))return!0}return!!E}},Tl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"circle",style:{...Ta,r:0,anchor:[.5,.5],...t},...e}),Yi(this,"shapeType","circle");const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.updateOrigin()}updateOrigin(){this.setOrigin(0,0)}getPath(){if(!this.pathDirty)return this.path;const{r:t,borderWidth:e}=this.parsedStyle;let i=.5*((null==e?void 0:e.value)||0);return t.value===i&&(i=0),this.path=za(0,0,t.value-i,0,2*Math.PI),this.steps=$a(this.path),this.pathDirty=!1,this.path}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,r:i}=this.parsedStyle,n=i.value;return this.boundsDirty=!1,this.bounds={left:t-n-0,top:e-n-0,width:2*n+0,height:2*n+0},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.getBoundingRectObject().isPointInPath(t,e))return!1;const{x:i,y:n,r:s,background:o,borderWidth:r}=this.parsedStyle,a=Os(this.style.background)&&""!==this.style.background,l=r&&r.value,h=a?0:e,c=(r.value+h||0)/2,d=s.value-c,u=new Oa(t.x,t.y).distanceTo({x:i,y:n});return o&&l?u<=d+c:o?u<=d:!!l&&u>=d-c&&u<=d+c}},El=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"ellipse",style:{...Ta,rx:"",ry:"",borderWidth:0,anchor:[.5,.5],...t},...e}),Yi(this,"shapeType","ellipse");const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.updateOrigin()}updateOrigin(){this.setOrigin(0,0)}getPath(){if(!this.pathDirty)return this.path;const{rx:t,ry:e,borderWidth:i}=this.parsedStyle,n=.5*i.value;return this.path=Ga(0,0,t.value-n,e.value-n),this.steps=$a(this.path),this.pathDirty=!1,this.path}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,rx:i,ry:n}=this.parsedStyle;return this.boundsDirty=!1,this.bounds={left:t-i.value-0,top:e-n.value-0,width:2*i.value+0,height:2*n.value+0},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.getBoundingRectObject().isPointInPath(t,e))return!1;const{x:i,y:n,rx:s,ry:o,borderWidth:r}=this.parsedStyle,a=Os(this.style.background)&&""!==this.style.background,l=r&&r.value,h=a?0:e,c=(r.value||0)/2,d=s.value-c,u=o.value-c,p=(t.x-i)*(t.x-i),g=(t.y-n)*(t.y-n);return a&&l?ol(p,g,d+c,u+c)<=1:a?ol(p,g,d,u)<=1:!!l&&ol(p,g,d-c-h/2,u-c-h/2)>=1&&ol(p,g,d+c+h/2,u+c+h/2)<=1}},_l=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"image",style:{...Ta,width:0,height:0,img:"",...t},...e}),Yi(this,"shapeType","image"),Yi(this,"meteData",void 0),Yi(this,"visiblePartData",void 0),this.meteData=(null==e?void 0:e.metadata)||null;const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.updateOrigin()}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,width:i,height:n}=this.parsedStyle;return this.boundsDirty=!1,this.bounds={left:t,top:e,width:i.value,height:n.value},this.bounds}isPointInPath(t){return this.getBoundingRectObject().isPointInPath(t)}},Pl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"ink",style:{...Ta,segments:[],lineJoin:"round",lineCap:"round",borderWidth:2,miterLimit:10,...t},...e}),Yi(this,"shapeType","ink"),Yi(this,"inkPaths",[]),Yi(this,"inkSteps",[]),Yi(this,"inkRenderPaths",[]),Yi(this,"inkOriginalRenderPath",void 0),Yi(this,"inkRenderSteps",[]),Yi(this,"initialRect",void 0),Yi(this,"douglasPeuckerPoints",[]),Yi(this,"partDirty",!1),Yi(this,"optimizedOpSteps",[]),Yi(this,"positionDirty",!1),this.getPath(),this.initialRect=this.getBoundingRect(),this.updatePosition(this.initialRect.left,this.initialRect.top),this.setOrigin(this.initialRect.width,this.initialRect.height)}addSegment(){const{segments:t}=this.style;t[t.length-1].length&&this.style.segments.push([])}addPoint(t){const e=[...this.style.segments],i=this.style.segments.length,n=e[i-1],s=n[n.length-1];if((null==s?void 0:s.x)!==t.x||(null==s?void 0:s.y)!==t.y){this.partDirty=!0;const n=this.getBoundingRect(),s=this.parsedStyle.borderWidth.value/2;(t.x<n.left+s||t.y<n.top+s)&&(this.positionDirty=!0),e[i-1].push(t),this.style.segments=e;const o=this.getBoundingRect();(t.x<o.left||t.y<o.top||t.x>o.left+o.width||t.y>o.top+o.height)&&(this.boundsDirty=!0)}}getPath(){if(!this.pathDirty&&!this.partDirty)return this.path;const{segments:t}=this.parsedStyle;if(this.partDirty){const e=t.length;if(e>1)for(let i=0;i<e-1;i++){const e=t[i];if(!this.optimizedOpSteps[i]){let t=[...e];1===t.length?t=this.offsetPoints(e[0],.1):(t=Fa(t,0,t.length-1,1),t.length<=3&&t.push({...t[t.length-1]}));const n=qa(t,t.length).map(t=>t.ops).flat(2);this.optimizedOpSteps[i]=n}if(this.positionDirty||!this.inkRenderSteps[i]){const t=this.getRenderStep(this.optimizedOpSteps[i]);this.inkRenderSteps[i]=t}}let i=t[e-1];1===i.length?i=this.offsetPoints(i[0],.1):i.length<=3&&i.push(i[i.length-1]),i=this.getRenderPath(i);const n=function(t){const e=t.length;if(e<=1)return[];if(2===e)return[Ya("moveTo",[t[0]]),Ya("lineTo",[t[1]])];const i=[Ya("moveTo",[t[0]])];for(let n=0;n<e-1;n++){const e=t[n-1]||t[n],s=t[n],o=t[n+1]||t[n];i.push(Ja(e,s,o))}return i}(i);this.inkRenderSteps[e-1]=n}else this.pathDirty&&(this.reset(),t.forEach((t,e)=>{if(0===t.length)return;let i=[...t];1===t.length?i=this.offsetPoints(t[0],.1):(i=Fa(i,0,i.length-1,1),i.length<=3&&i.push({...i[i.length-1]})),this.inkPaths[e]=i;const n=qa(i,i.length);this.inkSteps[e]=n.map(t=>t.ops).flat(2);const s=this.getRenderPath(i),o=qa(s,s.length).map(t=>t.ops).flat(2);this.inkRenderSteps[e]=o}));return this.pathDirty=!1,this.partDirty=!1,this.positionDirty=!1,this.path}offsetPoints(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001;const{x:i,y:n}=t;return[{x:i-e,y:n-e},{x:i+e,y:n-e},{x:i+e,y:n+e},{x:i-e,y:n+e}]}getRenderStep(t){return t.map(t=>({...t,data:this.getRenderPath(t.data)}))}getInkOriginalRenderPath(){if(!this.pathDirty&&this.inkOriginalRenderPath)return;const{segments:t}=this.parsedStyle,e=[];for(let i=0;i<t.length;i++){const n=this.getRenderPath(t[i]);e.push(n)}this.inkOriginalRenderPath=e}getRenderPath(t){const{left:e,top:i}=this.getBoundingRect(),n=[];return t.forEach(t=>{!t||Number.isNaN(t.x)||Number.isNaN(t.y)||n.push({x:t.x-e,y:t.y-i})}),n}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{borderWidth:t}=this.parsedStyle,e=[],i=[];this.parsedStyle.segments.forEach(t=>{t.forEach(t=>{t&&(e.push(t.x),i.push(t.y))})});const{min:n,max:s}=Al(e),{min:o,max:r}=Al(i),a=t.value/2;return this.boundsDirty=!1,this.bounds={left:n-a,top:o-a,width:s-n+2*a,height:r-o+2*a},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.getBoundingRectObject().isPointInPath(t,e))return!1;const{borderWidth:i}=this.parsedStyle;for(let n=0;n<this.inkSteps.length;n++){const s=this.inkSteps[n];for(let n=1;n<s.length;n+=2){const o=s[n-1].data[0],r=s[n].data[0],a=s[n].data[1];if(Va(o.x,o.y,r.x,r.y,a.x,a.y).isHit([t.x,t.y],i.value+e))return!0}}return!1}reset(){this.inkPaths=[],this.inkSteps=[],this.inkRenderPaths=[],this.inkRenderSteps=[]}};function Al(t){if(0===t.length)return{min:void 0,max:void 0};let e=t[0],i=t[0];for(let n=1;n<t.length;n++)t[n]<e&&(e=t[n]),t[n]>i&&(i=t[n]);return{min:e,max:i}}function Il(t,e){return{x:e.x-t.x,y:e.y-t.y}}function Dl(t){return Math.sqrt(t.x*t.x+t.y*t.y)}function Rl(t,e){const i=function(t,e){return t.x*e.x+t.y*e.y}(t,e),n=Dl(t),s=Dl(e);return Math.acos(i/(n*s))}let kl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"polygon",style:{...Ta,points:[{x:0,y:0},{x:10,y:10}],miterLimit:10,borderWidth:2,...t},...e}),Yi(this,"shapeType","polygon"),Yi(this,"renderPath",void 0),Yi(this,"isControls",!1),Yi(this,"basePath",void 0),Yi(this,"baseRenderPath",void 0),this.isControls=e.isControls||!1,0===this.parsedStyle.points.length&&(this.style.points=[{x:0,y:0},{x:10,y:10}]);const{left:i,top:n,width:s,height:o}=this.getBoundingRect();this.updatePosition(i,n),this.setOrigin(s/2,o/2)}addPoint(t){const e=[...this.style.points];e.push(t),this.style.points=e}updatePoints(){const{renderPath:t}=this,e=this.getLocalPosition(),i=[];t.forEach(t=>{i.push({x:t.x+e.x,y:t.y+e.y})}),this.style.points=i}getPath(){if(!this.pathDirty)return this.path;const{left:t,top:e,width:i,height:n}=this.getBoundingRect();return this.path=this.parsedStyle.points,this.basePath=this.path,this.renderPath=this.parsedStyle.points.map(i=>({x:i.x-t,y:i.y-e})),this.baseRenderPath=this.renderPath,this.steps=Ka(this.renderPath,!0),this.isControls||(this.renderClipPath=[{x:0,y:0},{x:i,y:0},{x:i,y:n},{x:0,y:n}],this.renderClipStep=Ka(this.renderClipPath,!0)),this.pathDirty=!1,this.path}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{borderWidth:t,points:e,lineCap:i}=this.parsedStyle;if(2===e.length)return this.boundsDirty=!1,this.bounds=rl(e[0],e[1],t.value,i),this.bounds;const n=tl(e);let s=0;return s=this.isControls?t.value/2||0:t.value||0,this.boundsDirty=!1,this.bounds={left:n.left-s,top:n.top-s,width:n.width+2*s,height:n.height+2*s},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.getBoundingRectObject().isPointInPath(t,e))return!1;const{borderWidth:i,points:n}=this.parsedStyle,s=Os(this.style.background)&&""!==this.style.background,o=s?0:e;let r=!1;return i&&i.value&&(r=cl(n,i.value+o,t.x,t.y,!0)),!r&&s&&(r=hl(n,t.x,t.y)),r}},Ml=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"polyline",style:{...Ta,points:[{x:0,y:0},{x:0,y:0}],lineEnding:null,borderWidth:2,miterLimit:10,...t},...e}),Yi(this,"shapeType","polyline"),Yi(this,"renderPath",void 0),Yi(this,"basePath",void 0),Yi(this,"baseRenderPath",void 0),this.getPath();const{left:i,top:n}=this.getBoundingRect();this.updatePosition(i,n),this.updateOrigin()}initPath(){const{points:t,lineEnding:e}=this.parsedStyle,i=[];if(t.forEach((t,e)=>{0===e?i.push({x:t.x,y:t.y,step:0,close:!1}):i.push({x:t.x,y:t.y,step:1,close:!1})}),this.basePath=[...t],e&&i.length>1)for(let t=0;t<e.length;t++)switch(e[t]){case"OpenArrow":this.addOpenArrow(i,t,!1);break;case"ROpenArrow":this.addOpenArrow(i,t,!0);break;case"ClosedArrow":this.addCloseArrow(i,t,!1);break;case"RClosedArrow":this.addCloseArrow(i,t,!0);break;case"Butt":this.addButt(i,t);break;case"Slash":this.addSlash(i,t);break;case"Square":this.addSquare(i,t);break;case"Diamond":this.addDiamond(i,t);break;case"Circle":this.addCircle(i,t)}return i}getRenderPath(t){const{left:e,top:i}=this.getBoundingRect(),n=[],s=[];return t.forEach((t,o)=>{if(t&&!Number.isNaN(t.x)&&!Number.isNaN(t.y)){const r={x:t.x-e,y:t.y-i,step:t.step,close:t.close};n.push(r),o<this.basePath.length&&s.push(r)}}),this.baseRenderPath=s,n}addPoint(t){const e=[...this.style.points];e.push(t),this.style.points=e}updatePoints(){const{length:t}=this.parsedStyle.points,e=this.getLocalPosition(),i=[];this.renderPath.slice(0,t).forEach(t=>{i.push({x:t.x+e.x,y:t.y+e.y})}),this.style.points=i}updatePoint(){const t=this.getLocalPosition(),e=this.parsedStyle.points.length,i=[];for(let n=0;n<e;n++)i.push({x:this.renderPath[n].x+t.x,y:this.renderPath[n].y+t.y});this.updateStyle({points:i})}getPath(){if(!this.pathDirty)return this.path;this.path=this.initPath(),this.renderPath=this.getRenderPath(this.path),this.steps=il(this.renderPath),this.pathDirty=!1;const{width:t,height:e}=this.getBoundingRect();return this.renderClipPath=[{x:0,y:0},{x:t,y:0},{x:t,y:e},{x:0,y:e}],this.renderClipStep=Ka(this.renderClipPath,!0),this.path}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{borderWidth:t,lineCap:e}=this.parsedStyle;if(2===this.path.length)return this.boundsDirty=!1,this.bounds=rl(this.path[0],this.path[1],t.value,e),this.bounds;const i=tl(this.path),n=t.value||0;return this.boundsDirty=!1,this.bounds={left:i.left-n,top:i.top-n,width:i.width+2*n,height:i.height+2*n},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.getBoundingRectObject().isPointInPath(t,e))return!1;const{borderWidth:i,points:n}=this.parsedStyle;return cl(n,i.value+e,t.x,t.y,!1)}isLineArrow(){const{lineEnding:t}=this.parsedStyle;return!!t&&("None"!==t[0]||"None"!==t[1])}addOpenArrow(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const{points:n,borderWidth:s}=this.parsedStyle,{length:o}=n;let r=n[o-2],a=n[o-1];0===e&&(r={...n[0]},a={...n[1]}),ul(t,e,i,r,a,s.value)}addCloseArrow(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const{points:n,borderWidth:s}=this.parsedStyle,{length:o}=n;let r=n[o-2],a=n[o-1];0===e&&(r={...n[0]},a={...n[1]}),pl(t,e,i,r,a,s.value)}addCircle(t,e){const{points:i,borderWidth:n}=this.parsedStyle,{length:s}=i;yl(t,e,i[0],i[s-1],n.value)}addDiamond(t,e){const{points:i,borderWidth:n}=this.parsedStyle,{length:s}=i;vl(t,e,i[0],i[s-1],n.value)}addSquare(t,e){const{points:i,borderWidth:n}=this.parsedStyle,{length:s}=i;ml(t,e,i[0],i[s-1],n.value)}addSlash(t,e){const{points:i,borderWidth:n}=this.parsedStyle,{length:s}=i;let o=i[s-2],r=i[s-1];0===e&&(o={...i[0]},r={...i[1]}),fl(t,e,o,r,n.value)}addButt(t,e){const{points:i,borderWidth:n}=this.parsedStyle,{length:s}=i;let o=i[s-2],r=i[s-1];0===e&&(o={...i[0]},r={...i[1]}),gl(t,e,o,r,n.value)}},Ll=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"rect",style:{...Ta,width:0,height:0,...t},...e}),Yi(this,"shapeType","rect");const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.updateOrigin()}getPath(){if(!this.pathDirty)return this.path;const{width:t,height:e,borderWidth:i}=this.parsedStyle,n=(null==i?void 0:i.value)||0,s=n,o=n,r=t.value-2*n,a=e.value-2*n;return this.path=[{x:s,y:o},{x:s+r,y:o},{x:s+r,y:o+a},{x:s,y:o+a}],this.steps=Ka(this.path),this.pathDirty=!1,this.path}getStrokePath(){const{width:t,height:e,borderWidth:i}=this.parsedStyle,n=.5*((null==i?void 0:i.value)||0),s=n,o=n,r=t.value-2*n,a=e.value-2*n;this.strokePath=[{x:s,y:o},{x:s+r,y:o},{x:s+r,y:o+a},{x:s,y:o+a}],this.strokeSteps=Ka(this.strokePath)}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,width:i,height:n}=this.parsedStyle;return this.boundsDirty=!1,this.bounds={left:t,top:e,width:i.value,height:n.value},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const{x:i,y:n,borderWidth:s,width:o,height:r}=this.parsedStyle,a=Os(this.style.background)&&""!==this.style.background,l=s&&s.value,h=e/2;return a?dl(i,n,o.value,r.value,t.x,t.y):!!l&&function(t,e,i,n,s,o,r){return dl(t,e,i,s,o,r)||dl(t,e,s,n,o,r)||dl(t,e+n-s,i,s,o,r)||dl(t+i-s,e,s,n,o,r)}(i-h,n-h,o.value+e,r.value+e,s.value+e,t.x,t.y)}},Ol=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"stampPath",style:{...Ta,stampPoints:[],lineJoin:"miter",lineCap:"butt",borderWidth:2,miterLimit:4,...t},...e}),Yi(this,"shapeType","stampPath"),Yi(this,"renderPath",void 0),Yi(this,"clipped",!1),t.clipped&&(this.clipped=!0),this.getPath()}getRenderPath(t){const{left:e,top:i}=this.getBoundingRect(),n=[];return t.forEach(t=>{!t||Number.isNaN(t.x)||Number.isNaN(t.y)||n.push({x:t.x-e,y:t.y-i,step:t.step,close:t.close})}),n}isLinePath(){const t=this.path;if(t.length<2)return!0;let e=!0,i=!0;const n=t[0].x,s=t[0].y;for(let o=1;o<t.length;o++)t[o].x!==n&&(e=!1),t[o].y!==s&&(i=!1);return e||i}getPath(){return this.pathDirty?(this.path=this.parsedStyle.stampPoints,this.renderPath=this.getRenderPath(this.path),this.steps=function(t){if(t.length<1)return[];const e=[];for(let i=0;i<t.length;i++){const n=t[i];if(0===n.step)e.push(Ya("lineTo",[n],n.close));else if(1===n.step){if(i+2<t.length&&1===t[i+1].step&&1===t[i+2].step){const s=t[i+1],o=t[i+2];e.push(Ya("bezierCurveTo",[n,s,o],n.close)),i+=2}}else 2===n.step&&e.push(Ya("moveTo",[n],n.close))}return e}(this.renderPath),this.pathDirty=!1,this.path):this.path}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{borderWidth:t,stampPoints:e,lineCap:i}=this.parsedStyle;if(2===e.length)return this.boundsDirty=!1,this.bounds=rl(e[0],e[1],t.value,i),this.bounds;const n=tl(e),s=t.value/2;return this.boundsDirty=!1,this.bounds={left:n.left-s,top:n.top-s,width:n.width+2*s,height:n.height+2*s},this.bounds}},Bl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"line",style:{...Ta,startPoint:{x:0,y:0},endPoint:{x:0,y:0},lineEnding:["None","None"],borderWidth:2,...t},...e}),Yi(this,"shapeType","line"),Yi(this,"renderPath",void 0),Yi(this,"basePath",void 0),Yi(this,"baseRenderPath",void 0),this.getPath();const{left:i,top:n}=this.getBoundingRect();this.updatePosition(i,n),this.updateOrigin()}initPath(){const{startPoint:t,endPoint:e,lineEnding:i}=this.parsedStyle,n=[{...t,step:0,close:!1},{...e,step:1,close:!1}];if(this.basePath=[...n],i)for(let t=0;t<i.length;t++)switch(i[t]){case"OpenArrow":this.addOpenArrow(n,t,!1);break;case"ROpenArrow":this.addOpenArrow(n,t,!0);break;case"ClosedArrow":this.addCloseArrow(n,t,!1);break;case"RClosedArrow":this.addCloseArrow(n,t,!0);break;case"Butt":this.addButt(n,t);break;case"Slash":this.addSlash(n,t);break;case"Square":this.addSquare(n,t);break;case"Diamond":this.addDiamond(n,t);break;case"Circle":this.addCircle(n,t)}return n}getRenderPath(t){const{left:e,top:i}=this.getBoundingRect(),n=[],s=[];return t.forEach((t,o)=>{if(t&&!Number.isNaN(t.x)&&!Number.isNaN(t.y)){const r={x:t.x-e,y:t.y-i,step:t.step,close:t.close};n.push(r),o<this.basePath.length&&s.push(r)}}),this.baseRenderPath=s,n}updatePoints(){const t=this.getLocalPosition();this.updateStyle({startPoint:{x:this.renderPath[0].x+t.x,y:this.renderPath[0].y+t.y},endPoint:{x:this.renderPath[1].x+t.x,y:this.renderPath[1].y+t.y}})}getPath(){return this.pathDirty?(this.path=this.initPath(),this.renderPath=this.getRenderPath(this.path),this.steps=il(this.renderPath),this.pathDirty=!1,this.path):this.path}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{borderWidth:t,lineCap:e}=this.parsedStyle,i=tl(this.path);if(2===this.path.length)return this.boundsDirty=!1,this.bounds=rl(this.path[0],this.path[1],t.value,e),this.bounds;const n=t.value/2||0;return this.boundsDirty=!1,this.bounds={left:i.left-n,top:i.top-n,width:i.width+2*n,height:i.height+2*n},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.getBoundingRectObject().isPointInPath(t,e))return!1;const{startPoint:i,endPoint:n,borderWidth:s}=this.parsedStyle;return ll(i,n,s.value+e,t)}isLineArrow(){const{lineEnding:t}=this.parsedStyle;return!!t&&("None"!==t[0]||"None"!==t[1])}addCircle(t,e){const{startPoint:i,endPoint:n,borderWidth:s}=this.parsedStyle;yl(t,e,i,n,s.value)}addDiamond(t,e){const{startPoint:i,endPoint:n,borderWidth:s}=this.parsedStyle;vl(t,e,i,n,s.value)}addSquare(t,e){const{startPoint:i,endPoint:n,borderWidth:s}=this.parsedStyle;ml(t,e,i,n,s.value)}addSlash(t,e){const{startPoint:i,endPoint:n,borderWidth:s}=this.parsedStyle;fl(t,e,i,n,s.value)}addButt(t,e){const{startPoint:i,endPoint:n,borderWidth:s}=this.parsedStyle;gl(t,e,i,n,s.value)}addOpenArrow(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const{startPoint:n,endPoint:s,borderWidth:o}=this.parsedStyle;ul(t,e,i,n,s,o.value)}addCloseArrow(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const{startPoint:n,endPoint:s,borderWidth:o}=this.parsedStyle;pl(t,e,i,n,s,o.value)}},Nl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"stampText",style:{...Ta,text:"",color:"black",fontSize:12,fontFamily:"Microsoft YaHei",fontWeight:"normal",fontStyle:"normal",...t},...e}),Yi(this,"shapeType","stampText"),this.setTextFont();const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.updateOrigin()}setTextFont(){const{fontStyle:t,fontWeight:e,fontFamily:i,fontSize:n}=this.parsedStyle,s=""===(null==i?void 0:i.trim())?"sans-serif":i;null!=i&&i.includes(" ")?this.style.font=`${t} ${e} ${n.value}${n.unit} '${s}'`:this.style.font=`${t} ${e} ${n.value}${n.unit} ${s}`}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,text:i,fontSize:n,font:s}=this.parsedStyle,o=document.createElement("canvas").getContext("2d");o.font=s;const{width:r}=o.measureText(i);return this.boundsDirty=!1,this.bounds={left:t,top:e-n.value,width:r,height:n.value},this.bounds}isPointInPath(t){return this.getBoundingRectObject().isPointInPath(t)}},Ul=class extends Ll{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"stamp",style:{...t,background:"transparent",borderColor:"transparent"},...e}),Yi(this,"shapeType","stamp"),Yi(this,"stampConfig",[]),Yi(this,"stampItemShapes",[]),Yi(this,"renderType","stamp"),Yi(this,"initialWidth",0),Yi(this,"initialHeight",0),this.stampConfig=t.stampConfig||[]}initStamp(){this.stampConfig&&(this.renderType="stamp",this.initStampItem(),this.initStampStyle())}initStampItem(){if(!Ts(this.stampConfig))return;this.stampItemShapes=[];const{stampConfig:t,stampItemShapes:e}=this,{renderBlendMode:i}=this.parsedStyle;for(let n=0;n<t.length;n++){let s;"path"===t[n].type&&(s=new Ol({style:{opacity:this.style.opacity,renderBlendMode:i,...t[n]}})),"text"===t[n].type&&(s=new Nl({style:{opacity:this.style.opacity,renderBlendMode:i,...t[n]}})),"image"===t[n].type&&(s=new _l({style:{opacity:this.style.opacity,renderBlendMode:i,...t[n]}})),s&&e.push(s)}}initStampStyle(){if(!Ts(this.stampConfig))return;const t=[],e=[],{stampItemShapes:i}=this,n=i.some(t=>t instanceof Ol);for(const s of i){if(n&&!(s instanceof Ol)){this.appendChild(s);continue}if(s instanceof Ol&&s.clipped){this.appendChild(s);continue}const{left:i,top:o,width:r,height:a}=s.getBoundingRect();t.push(i,i+r),e.push(o,o+a),this.appendChild(s)}this.initialWidth=Math.max(...t)-Math.min(...t),this.initialHeight=Math.max(...e)-Math.min(...e);const s=Math.min(...t),o=Math.min(...e);this.updateStyle({x:s,y:o,width:this.initialWidth,height:this.initialHeight});for(let t=0;t<i.length;t++){const{left:e,top:n}=i[t].getBoundingRect();let s=n-this.style.y;i[t]instanceof Nl&&(s+=i[t].parsedStyle.fontSize.value),i[t].setLocalPosition(e-this.style.x,s)}this.updateOrigin()}isPointInPath(t,e){return super.isPointInPath(t,0)}},Fl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"roundedRect",style:{...Ta,roundedRadius:0,width:0,height:0,...t},...e}),Yi(this,"shapeType","roundedRect");const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.updateOrigin()}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,width:i,height:n}=this.parsedStyle;return this.boundsDirty=!1,this.bounds={left:t,top:e,width:i.value,height:n.value},this.bounds}isPointInPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const{x:i,y:n,width:s,height:o,borderWidth:r}=this.parsedStyle,a=(r.value+e||0)/2;return dl(i-a,n-a,s.value+2*a,o.value+2*a,t.x,t.y)}getCenterPosition(){const{width:t,height:e}=this.parsedStyle,i=new Tl({style:{x:t.value/2,y:e.value/2}});this.appendChild(i);const{x:n,y:s}=i.getPosition();return i.destroy(),{x:n,y:s}}},Vl=class extends Cl{constructor(){let{style:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"freeText",style:{...Ta,width:0,height:0,textAlign:"left",...t},...e}),Yi(this,"shapeType","freeText"),Yi(this,"lines",void 0),Yi(this,"textType","textBox"),Yi(this,"lineHeightOffset",.2),Yi(this,"totalTextHeight",0),Yi(this,"limitWidth",1),Yi(this,"textMaxWidth",0),Yi(this,"borderOffset",0),Yi(this,"padding",1),Yi(this,"linesDirty",!1),this.textType=t.freeTextType||"textBox",this.setLimitWidth(this.parsedStyle.width.value),this.calculateTextLines();const{x:i,y:n}=this.parsedStyle;this.setLocalPosition(i,n),this.boundsDirty=!0,this.updateOrigin()}updateOrigin(){const{width:t,height:e}=this.getBoundingRect();this.setOrigin(t/2,e/2)}organizeLine(){if(0===this.lines.length)return;const{y:t}=this.parsedStyle;let e=t+this.borderOffset+this.padding,i=0,n=0;this.lines.forEach((t,s)=>{n=0,i=Math.max(t.width,i);let o=0,r="";if(0===t.width&&""===t.words[0].text){const e=Wl(" ",t.words[0].style);t.width=e,t.words[0].wordWidth=e,t.words[0].text=" "}if(t.words.forEach(t=>{r+=t.text,o=Math.max(o,t.wordHeight),t.widthWithoutLf=jl(t.text)?Wl(t.text,t.style,!0):t.wordWidth,n+=t.widthWithoutLf}),"textBox"===this.textType&&"justify"===this.style.textAlign&&s!==this.lines.length-1){const e=[],i=/\S+/g;let s,o=0;for(;null!==(s=i.exec(r));)0===e.length&&0!==s.index?e.push(0):e.push(s.index);if(e.length>1){let i=this.limitWidth-n;i<0&&(i=0);const s=i/(e.length-1),r=t=>{for(let i=0;i<e.length;i++)if(e[i]>t)return i;return e.length};t.words.forEach((t,e)=>{e>0&&(t.x+=s*(r(o)-1)),o+=t.text.length}),n=this.limitWidth,t.width=this.limitWidth}}const{lineHeightOffset:a}=this;t.widthWithoutLF=n,t.height=o,t.y=o*(1-a)+e,e+=o,s>0&&(t.y+=this.lines[s-1].height*a,e+=this.lines[s-1].height*a)}),this.textMaxWidth=i}getTextAlignOffset(t){if("freeTextWriter"===this.textType)return 0;const{limitWidth:e}=this,{textAlign:i}=this.parsedStyle,n=t?t.widthWithoutLF:0;let s=0;return"center"===i?s=(Math.max(e,this.textMaxWidth)-n)/2:"right"===i&&(s=Math.max(e,this.textMaxWidth)-n),s}getPath(){var t;if(!this.pathDirty)return this.path;const{width:e,height:i}=this.getBoundingRect(),n=.5*((null===(t=this.parsedStyle.borderWidth)||void 0===t?void 0:t.value)||0),s=n,o=n,r=e-2*n,a=i-2*n;if(this.path=[{x:s,y:o},{x:s+r,y:o},{x:s+r,y:o+a},{x:s,y:o+a}],this.steps=Ka(this.path),"textBox"===this.textType){const t=this.borderOffset/2;this.renderClipPath=[{x:s+t,y:o+t},{x:s+r-t,y:o+t},{x:s+r-t,y:o+a-t},{x:s+t,y:o+a-t}],this.renderClipStep=Ka(this.renderClipPath)}return this.pathDirty=!1,this.path}setLimitWidth(t){const{borderWidth:e,borderColor:i}=this.parsedStyle;"textBox"===this.textType&&e.value&&!i.isNone&&(this.borderOffset=e.value,this.padding=e.value),this.limitWidth=t-2*this.borderOffset-2*this.padding}updateTextLinesForTranslate(t,e){this.lines.forEach(i=>{i.x+=t,i.y+=e,i.words.forEach(e=>{e.x+=t})})}calculateTextLines(){const{textContents:t,x:e}=this.parsedStyle;if(null==t||!t.length||this.limitWidth<=0)return this.lines=[],void this.calculateTotalHeight();const i=e+this.borderOffset+this.padding;this.lines=function(t,e,i){let n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];const s=document.createElement("div"),o=Gl(s,e,t);document.body.appendChild(s);const r=[];let a,l=[],h={};const c=()=>{if(!l.length)return;h.x=i,h.words=l;const t=l.reduce((t,e)=>t+e.wordWidth,0);h.width=t,r.push(h),l=[],h={}},d=(e,s,o,r)=>{const h=t[o];if(n){const n=[],r=/\S+/g;let c;for(;null!==(c=r.exec(e));)0===n.length&&0!==c.index?n.push(0):n.push(c.index);let d=s-(a||0)+i;for(let i=0;i<n.length;i++){const s=n[i],r=i===n.length-1?e.length:n[i+1],a=e.slice(s,r),c=Wl(a,t[o]);l.push({freeContentIndex:o,originText:a,style:h,text:a,wordHeight:h.fontSize.value,wordWidth:c,x:d}),d+=c}}else l.push({freeContentIndex:o,originText:e,style:h,text:e,wordHeight:h.fontSize.value,wordWidth:r,x:s-(a||0)+i})},u=(t,e)=>{d("\n",a||0,t,e),c()};for(let e=0;e<o.length;e++){const i=Yl(o[e]);if(0===i.length)continue;const n=t[e].content.replace(/\r\n/g,"\n"),s=n.length,r=zl(n).length,l=n.slice(r),h=Wl("\n",t[e]);if(r)for(let t=0;t<r;t++)u(e,h);i.length&&Ps(a)&&(a=i[0].x);const p=i.map((t,e)=>({obj:t,index:e,oldIndex:e,minIndex:void 0})).filter(t=>{let{obj:e,index:i}=t;return e.x===a&&0!==i});i.length&&i[0].x===a&&c();const g=i[i.length-1];if(s===i.length)if(p.length){let t=0;p.forEach(s=>{const{index:o}=s,r=n.slice(t,o),a=i[o-1],l=i[t].x;t=o,d(r,l,e,a.x-l+a.width),c()});const s=n.slice(t),o=i[t].x;d(s,o,e,g.x-o+g.width)}else{const t=g.x-i[0].x+g.width;d(n,i[0].x,e,t)}else{const t=$l(l);for(let e=0;e<t.length;e++)p.forEach(i=>{i.index>=t[e]&&(i.index===t[e]&&Ps(null==i?void 0:i.minIndex)&&(i.minIndex=t[e]),i.index+=1)});if(p.length){let n=0,s=0;p.forEach((t,o)=>{const{index:r,oldIndex:a,minIndex:p}=t;let g=0;if(Ps(p)||(g=r-p),g){const t=l.slice(n,r-g+1),o=i[a-1],p=i[s].x,f=o.x-p+o.width+h;d(t,p,e,f),c();for(let t=0;t<g-1;t++)u(e,h)}else{const t=l.slice(n,r),o=i[a-1],h=i[s].x;d(t,h,e,o.x-h+o.width),c()}n=r,s=a});const o=t.filter(t=>t>p[p.length-1].index).length,r=l.slice(n,l.length-o+1),a=i[i.length-1],g=i[p[p.length-1].oldIndex].x,f=o>0?a.x-g+a.width+h:a.x-g+a.width;d(r,g,e,f);for(let t=0;t<o-1;t++)0===t&&c(),u(e,h)}else if(t.length){const n=l.slice(0,l.length-t.length+1),s=g.x-i[0].x+g.width+h;d(n,i[0].x,e,s),c();for(let i=0;i<t.length-1;i++)u(e,h)}else{const t=g.x-i[0].x+g.width;d(l,i[0].x,e,t)}}}return c(),s.remove(),r}(t,this.limitWidth,i,"justify"===this.style.textAlign),this.organizeLine(),this.calculateTotalHeight()}calculateTotalHeight(){const{y:t,height:e}=this.parsedStyle,i=this.lines.length;if(i){const n=this.lines[i-1];let s=n.y+n.height*this.lineHeightOffset-t+2*this.borderOffset;jl(n.words[0].text)&&(s+=n.height*(1+this.lineHeightOffset)),this.totalTextHeight=s>e.value?s:e.value}else this.totalTextHeight=e.value}getBoundingRect(){if(!this.boundsDirty)return this.bounds;const{x:t,y:e,height:i}=this.parsedStyle,n="freeTextWriter"===this.textType?this.totalTextHeight:i.value,s="freeTextWriter"===this.textType?this.textMaxWidth+2*this.borderOffset+2*this.padding:this.parsedStyle.width.value;return this.boundsDirty=!1,this.bounds={left:t,top:e,width:s,height:n},this.bounds}isPointInPath(t){return this.getBoundingRectObject().isPointInPath(t)}getTextEditor(){const t=document.createElement("div");Gl(t,this.parsedStyle.width.value,this.parsedStyle.textContents,!0);const{borderWidth:e,borderColor:i,background:n,textAlign:s,opacity:o}=this.style,{lineDash:r}=this.parsedStyle;if(t.style.pointerEvents="auto",t.style.cursor="text",t.style.lineHeight="0",t.style.opacity=o.toString(),"textBox"===this.textType){const{height:o}=this.getBoundingRect();t.style.padding=`${this.padding}px`,t.style.boxSizing="border-box",t.style.minHeight=`${o}px`,t.style.border=`${e}px ${Fo(r)?"solid":"dashed"} ${i}`,t.style.background=n,t.style.textAlign=s,t.style.height="auto"}else{var a;const e=(null===(a=t.textContent)||void 0===a?void 0:a.replace(/\u200B/g,""))||"";t.style.border="1px solid black",t.style.maxWidth=`${this.parsedStyle.width.value}px`,t.style.border=e.length?"none":"1px solid black",t.style.minWidth="10px",t.style.width="max-content"}return t}};function Wl(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const{fontSize:n,fontStyle:s,fontFamily:o,fontWeight:r}=e,a=document.createElement("canvas").getContext("2d"),l=""===(null==o?void 0:o.trim())?"sans-serif":o;null!=o&&o.includes(" ")?a.font=`${s} ${r} ${n.value}${n.unit} '${l}'`:a.font=`${s} ${r} ${n.value}${n.unit} ${l}`;let h=0;for(let e=0;e<t.length;e++){const n=t.charAt(e);i&&Hl(n)||(h+=a.measureText(n).width)}return h}function Hl(t){return/^[\r\n]+$/.test(t)}function jl(t){return t.endsWith("\n")||t.endsWith("\r")||t.endsWith("\r\n")}function zl(t){const e=t.match(/^(?:\r\n|\r|\n)*/);if(e){const t=e[0];let i=0;for(const e of t)"\n"!==e&&"\r"!==e||(i+=1);return t.includes("\r\n")&&(i-=1),Array.from({length:i},()=>"\n")}return[]}function Gl(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=[],o=document.createDocumentFragment();return t.style.width=`${e}px`,t.style.wordBreak="break-word",t.style.position="absolute",i.forEach(t=>{const{fontSize:e,fontStyle:i,fontFamily:r,fontWeight:a,color:l,content:h,underline:c,lineThrough:d}=t;if(!h.length)return;const u=""===(null==r?void 0:r.trim())?"sans-serif":r,p=null!=r&&r.includes(" ")?`${i} ${a} ${e.value}${e.unit} '${u}'`:`${i} ${a} ${e.value}${e.unit} ${u}`,g=document.createElement("div");if(g.style.font=p,g.style.letterSpacing="0px",g.style.whiteSpace="pre-wrap",g.style.display="inline",g.style.color=l,f=h,new RegExp("([A-Za-z0-9])\\1{9,}").test(f)&&!n)for(let t=0;t<h.length;t++)if("\n"===h[t]||"\r"===h[t]||"\n\r"===h[t])g.appendChild(document.createElement("br"));else if(" "===h[t])g.appendChild(document.createTextNode(" "));else{const e=document.createElement("span");e.style.display="inline-block",e.innerText=h[t],g.appendChild(e)}else g.innerText=h;var f;o.appendChild(g),s.push(g)}),t.appendChild(o),s}function Yl(t){const e=[],i=document.createRange(),n=function(t){const e=[],i=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null);let n;for(;n=i.nextNode();)e.push(n);return e}(t);return n.forEach(t=>{i.selectNodeContents(t);const n=t.nodeValue;for(let s=0;s<n.length;s++){i.setStart(t,s),i.setEnd(t,s+1);const o=i.getClientRects(),r=o.length>1?o[1]:o[0];e.push({text:n[s],x:r.left,y:r.top,width:r.width,height:r.height})}}),function(t){const e=new Map;t.forEach(t=>{var i;e.has(t.y)||e.set(t.y,[]),null===(i=e.get(t.y))||void 0===i||i.push(t)}),e.forEach(t=>{t.sort((t,e)=>t.x-e.x)});const i=[];return e.forEach(t=>{i.push(...t)}),i}(e)}function $l(t){const e=/(\r\n|[\r\n])/g;let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i.index);return n}const Xl=1/0;class ql{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Xl,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1/0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Xl,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1/0;Yi(this,"minX",void 0),Yi(this,"maxX",void 0),Yi(this,"minY",void 0),Yi(this,"maxY",void 0),Yi(this,"rect",void 0),Yi(this,"updateId",void 0),this.minX=t,this.maxX=e,this.minY=i,this.maxY=n,this.rect=null,this.updateId=-1}static isEmpty(t){return t.minX===t.maxX&&t.minY===t.maxY}static fromBounds(t){return(new ql).setFromBounds(t)}static create(){return new ql}setFromBounds(t){return this.minX=t.minX,this.minY=t.minY,this.maxX=t.maxX,this.maxY=t.maxY,this}clear(){return this.minX=Xl,this.maxX=-1/0,this.minY=Xl,this.maxY=-1/0,this}getRect(t){const{minX:e,minY:i,maxX:n,maxY:s}=this;if(e>n||i>s)return new Zs(0,0,0,0);const o=t||new Zs;return o.update(e,i,n-e,s-i),o}addPoint(t){return this.addBounds({minX:t.x,maxX:t.x,minY:t.y,maxY:t.y})}addBounds(t){const e=Jl(this,t);return this.setFromBounds(e)}addBoundsMask(t,e){const i=Zl(t,e);if(i.minX<=i.maxX&&i.minY<=i.maxY){const t=Jl(i,this);this.setFromBounds(t)}return this}intersection(t){if(i=t,!((e=this).minX<=i.maxX&&e.maxX>=i.minX&&e.minY<=i.maxY&&e.maxY>=i.minY))return null;var e,i;const n=Zl(this,t);return ql.fromBounds(n)}union(t){const e=Jl(this,t);return ql.fromBounds(e)}addBoundsArea(t,e){const{x:i,y:n,width:s,height:o}=e,r={minX:i,minY:n,maxX:i+s,maxY:n+o};return this.addBoundsMask(t,r)}addFrame(t,e){return this.setFromTransformedBounds(t.worldTransform,e)}setFromTransformedBounds(t,e){for(let i=0;i<2;i++){const n=t.transformPoint({x:i?e.maxX:e.minX,y:i?e.maxY:e.minY});this.addPoint(n)}return this}addQuad(t){for(let e=0;e<4;e++)this.addPoint({x:t[2*e],y:t[2*e+1]})}}function Zl(t,e){return{minX:t.minX>e.minX?t.minX:e.minX,minY:t.minY>e.minY?t.minY:e.minY,maxX:t.maxX<e.maxX?t.maxX:e.maxX,maxY:t.maxY<e.maxY?t.maxY:e.maxY}}function Jl(t,e){return{minX:t.minX<e.minX?t.minX:e.minX,minY:t.minY<e.minY?t.minY:e.minY,maxX:t.maxX>e.maxX?t.maxX:e.maxX,maxY:t.maxY>e.maxY?t.maxY:e.maxY}}class Kl extends Cl{constructor(){super({}),Yi(this,"name","Document"),Yi(this,"defaultView",void 0),Yi(this,"documentElement",void 0),Yi(this,"timeLine",void 0),this.nodeName="document",this.documentElement=new Cl({name:"Root",id:"root",style:{visibility:"visible"}}),this.documentElement.ownerDocument=this,this.documentElement.parentNode=this,this.childNodes=[this.documentElement]}get children(){return this.childNodes}get childElementCount(){return this.childNodes.length}get firstElementChild(){return this.firstChild}get lastElementChild(){return this.lastChild}createElement(t,e){return new(this.defaultView.customElements.get(t))(e)}getElementById(t){return null}getElementsByName(t){return this.documentElement.getElementsByTagName(t)}getElementsByTagName(t){return this.documentElement.getElementsByTagName(t)}getElementsByClassName(t){return this.documentElement.getElementsByClassName(t)}append(){return this.documentElement.append(...arguments)}prepend(){return this.documentElement.prepend(...arguments)}querySelector(t){return this.documentElement.querySelector(t)}querySelectorAll(t){return this.documentElement.querySelectorAll(t)}find(t){return this.documentElement.find(t)}findAll(t){return this.documentElement.findAll(t)}appendChild(t){return this.documentElement.appendChild(t)}cloneNode(t){return this.documentElement.cloneNode(t)}insertBefore(t,e){return this.documentElement.insertBefore(t,e)}removeChild(t){return this.documentElement.removeChild(t)}replaceChild(t,e){return this.documentElement.replaceChild(t,e)}destroy(){}}class Ql extends zr{constructor(){super(...arguments),Yi(this,"altKey",void 0),Yi(this,"button",void 0),Yi(this,"buttons",void 0),Yi(this,"ctrlKey",void 0),Yi(this,"metaKey",void 0),Yi(this,"shiftKey",void 0),Yi(this,"relatedTarget",void 0),Yi(this,"client",new Oa),Yi(this,"movement",new Oa),Yi(this,"offset",new Oa),Yi(this,"page",new Oa),Yi(this,"screen",new Oa),Yi(this,"global",new Oa),Yi(this,"canvas",new Oa)}initEvent(t,e,i){throw new Error("Method not implemented.")}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.client.x}get y(){return this.client.y}get movementX(){return this.movement.x}get movementY(){return this.movement.x}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get canvasX(){return this.canvas.x}get canvasY(){return this.canvas.y}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,i,n,s,o,r,a,l,h,c,d,u,p,g){throw this.initUIEvent(t,i,i,n,s),new Error("initMouseEvent() DOM API is deprecated.")}}function th(t,e){e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.shiftKey=t.shiftKey,e.relatedTarget=null,e.client.setFromPoint(t.client),e.movement.setFromPoint(t.movement),e.offset.setFromPoint(t.offset),e.page.setFromPoint(t.page),e.screen.setFromPoint(t.screen),e.global.setFromPoint(t.global),e.canvas.setFromPoint(t.canvas)}class eh extends Ql{constructor(){super(...arguments),Yi(this,"deltaMode",void 0),Yi(this,"deltaX",void 0),Yi(this,"deltaY",void 0),Yi(this,"deltaZ",void 0),Yi(this,"DOM_DELTA_PIXEL",0),Yi(this,"DOM_DELTA_LINE",1),Yi(this,"DOM_DELTA_PAGE",2)}}function ih(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}class nh extends Ql{constructor(t){super(t),Yi(this,"height",0),Yi(this,"isPrimary",void 0),Yi(this,"pointerId",void 0),Yi(this,"pointerType",void 0),Yi(this,"pressure",void 0),Yi(this,"tangentialPressure",void 0),Yi(this,"tiltX",void 0),Yi(this,"tiltY",void 0),Yi(this,"twist",void 0),Yi(this,"width",0),Yi(this,"getCoalescedEvents",void 0),Yi(this,"getPredictedEvents",void 0),this.isPrimary=!1,this.height=0,this.width=0}}function sh(t,e){e.isPrimary=t.isPrimary,e.width=t.width,e.height=t.height,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.pointerType=t.pointerType,e.pointerId=t.pointerId,e.pressure=t.pressure,e.twist=t.twist,e.tangentialPressure=t.tangentialPressure}class oh{constructor(t,e){Yi(this,"root",void 0),Yi(this,"cursor","default"),Yi(this,"events",void 0),Yi(this,"trackingData",void 0),Yi(this,"contextService",void 0),this.root=t,this.contextService=e,this.events={},this.trackingData={},this.on("pointerdown",this.onPointerdown.bind(this)),this.on("pointermove",this.onPointermove.bind(this)),this.on("pointerout",this.onPointerout.bind(this)),this.on("pointerleave",this.onPointerout.bind(this)),this.on("pointerover",this.onPointerover.bind(this)),this.on("pointerup",this.onPointerup.bind(this)),this.on("wheel",this.onWheel.bind(this))}clientToCanvas(t){const e=this.contextService.getBoundingClientRect();return new Oa(t.x-(e.x||0),t.y-(e.y||0))}canvasToClient(t){const e=this.root.defaultView.contextService.getBoundingClientRect();return new Oa(t.x+(e.x||0),t.y+(e.y||0))}getPropagationPath(t){const e=[t];for(;Cl.isNode(t)&&t!==this.root;)t=t.parentNode,e.push(t);return e.reverse()}getHitTarget(t,e){const{root:i}=this,{isInteractive:n}=i,s=lh(i,n,new Oa(t,e));return s?s[0]:null}on(t,e){this.events[t]||(this.events[t]=[]),this.events[t].push({fn:e,order:0}),this.events[t].sort((t,e)=>t.order-e.order)}emit(t){if(!this.root)return;const e=this.events[t.type]||[];for(let i=0;i<e.length;i++)e[i].fn(t)}onPointerdown(t){if(!(t instanceof nh))return;const e=this.generatePointerEvent(t);let i;qr(e,"pointerdown"),"touch"===e.pointerType?i="touchstart":rh(e)&&(i=2===e.button?"rightdown":"mousedown"),qr(e,i),this.getTrackingData(t.pointerId).pressTargetsByButton[t.button]=e.composedPath()}onPointermove(t){if(!(t instanceof nh))return;const e=this.generatePointerEvent(t),i=rh(e),n=this.getTrackingData(t.pointerId),s=ah(n.overTargets);if(s&&s!==e.target){const n="mousemove"===t.type?"mouseout":"pointerout",o=this.generatePointerEvent(t,n,s);qr(o,"pointerout"),i&&qr(o,"mouseout");const r=e.composedPath();if(!r.includes(s)){const e=this.generatePointerEvent(t,"pointerleave",s);for(e.eventPhase=e.AT_TARGET;e.target&&!r.includes(e.target);)e.currentTarget=e.target,Xr(e,e.type),i&&Xr(e,"mouseleave"),e.target=e.target.parentNode}}if(s!==e.target){const n="mousemove"===t.type?"mouseover":"pointerover",o=this.clonePointerEvent(e,n);qr(o,"pointerover"),i&&qr(o,"mouseover");let r=Cl.isNode(s)&&(null==s?void 0:s.parentNode);for(;r&&r!==(Cl.isNode(this.root)&&this.root.parentNode)&&r!==e.target;)r=r.parentNode;if(!r||r===this.root.parentNode){const t=this.clonePointerEvent(e,"pointerenter");for(t.eventPhase=t.AT_TARGET;t.target&&t.target!==s&&t.target!==this.root.parentNode;)t.currentTarget=t.target,Xr(t,t.type),i&&Xr(t,"mouseenter"),t.target=t.target.parentNode}}var o;qr(e,"pointermove"),"touch"===e.pointerType&&qr(e,"touchmove"),i&&(qr(e,"mousemove"),this.cursor=null===(o=e.target)||void 0===o?void 0:o.cursor),n.overTargets=e.composedPath()}onPointerup(t){if(!(t instanceof nh))return;const e=performance.now(),i=this.generatePointerEvent(t);qr(i,"pointerup");const{pointerType:n}=i;let s;"touch"===n?s="touchend":rh(i)&&(s=2===i.button?"rightup":"mouseup"),qr(i,s);const o=this.getTrackingData(t.pointerId),r=ah(o.pressTargetsByButton[t.button]);let a=r;const l=i.composedPath();if(r&&!l.includes(r)){let e=r;for(;e&&!l.includes(e);)i.currentTarget=e,Xr(i,"pointerupoutside"),"touch"===n?s="touchendoutside":rh(i)&&(s=2===i.button?"rightupoutside":"mouseupoutside"),Xr(i,s),e=e.parentNode;delete o.pressTargetsByButton[t.button],a=e}if(a){const r=this.clonePointerEvent(i,"click");r.target=a,r.path=null,o.clicksByButton[t.button]||(o.clicksByButton[t.button]={clickCount:0,target:r.target,timeStamp:e});const l=o.clicksByButton[t.button];l.target===r.target&&e-l.timeStamp<200?l.clickCount+=1:l.clickCount=1,l.target=r.target,l.timeStamp=e,r.detail=l.clickCount,s="mouse"===n?"click":"touch"===n?"tap":"pointertap",qr(r,s)}}onPointerout(t){if(!(t instanceof nh))return;const e=this.getTrackingData(t.pointerId);if(e.overTargets){const i=rh(t),n=ah(e.overTargets),s=this.generatePointerEvent(t,"pointerout",n);qr(s),i&&qr(s,"mouseout");const o=this.generatePointerEvent(t,"pointerleave",n);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.root.parentNode;)o.currentTarget=o.target,Xr(o,o.type),i&&Xr(o,"mouseleave"),o.target=o.target.parentNode;e.overTargets=null}this.cursor=null}onPointerover(t){if(!(t instanceof nh))return;const e=this.getTrackingData(t.pointerId),i=this.generatePointerEvent(t),n=rh(t);var s;qr(i,"pointerover"),n&&qr(i,"mouseover"),"mouse"===i.pointerType&&(this.cursor=null===(s=i.target)||void 0===s?void 0:s.cursor);const o=this.clonePointerEvent(i,"pointerenter");for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.root.parentNode;)o.currentTarget=i.target,Xr(o,o.type),n&&Xr(o,"mouseenter"),o.target=o.target.parentNode;e.overTargets=i.composedPath()}onWheel(t){t instanceof eh&&qr(this.generateWheelEvent(t))}generatePointerEvent(t,e,i){const n=new nh(this);return sh(t,n),th(t,n),Gr(t,n),n.nativeEvent=t.nativeEvent,n.originalEvent=t,n.target=null!=i?i:this.getHitTarget(n.globalX,n.globalY),n.type=null!=e?e:n.type,n}generateWheelEvent(t){const e=new eh(this);return ih(t,e),th(t,e),Gr(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.getHitTarget(e.globalX,e.globalY),e}clonePointerEvent(t,e){const i=new nh(this);return sh(t,i),th(t,i),Gr(t,i),i.nativeEvent=t.nativeEvent,i.originalEvent=t,i.target=t.target,i.path=t.composedPath().slice(),i}getTrackingData(t){return this.trackingData[t]||(this.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTargets:null}),this.trackingData[t]}}function rh(t){const{pointerType:e}=t;return"mouse"===e||"pen"===e}function ah(t){if(!t)return null;let e=t[0]||null;for(let i=1,n=t.length;i<n&&t[i].parentNode===e;i++)e=t[i];return e}function lh(t,e,i){if(!t||"visible"!==t.style.visibility)return null;const{hitArea:n}=t.style;if(n){const{x:e,y:s}=t.transform.worldTransform.transformPoint(i);if(!n.contains(e,s))return null}const{clipPath:s}=t.style;if(s&&!s.containPoint(i))return null;if(t.isChildrenInteractive&&t.children){const{children:n}=t;for(let s=n.length-1;s>=0;s--){const o=n[s],r=lh(o,e||o.isInteractive,i);if(r)return(r.length>0||t.isInteractive)&&r.push(t),r}}return e&&t.containPoint(i)?t.isInteractive?[t]:[]:null}Yi(class{constructor(){Yi(this,"canvasConfig",void 0),Yi(this,"contextService",void 0),Yi(this,"renderingContext",void 0),Yi(this,"eventService",void 0),Yi(this,"rootPointerEvent",new nh(null)),Yi(this,"rootWheelEvent",new eh(null)),Yi(this,"autoPreventDefault",!0)}init(t){const{renderingService:e,renderingContext:i,contextService:n,canvasConfig:s}=t;this.eventService=new oh(i.root.parentNode,n),t.eventService=this.eventService,this.renderingContext=i,this.contextService=n,this.canvasConfig=s,e.hooks.wheel.on(this.onWheel),e.hooks.pointerdown.on(this.onPointerdown),e.hooks.pointermove.on(this.onPointermove),e.hooks.pointerup.on(this.onPointerup),e.hooks.pointerout.on(this.onPointermove),e.hooks.pointerover.on(this.onPointermove)}destroy(){}onWheel(t){const e=this.normalizeWheelEvent(t);this.eventService.emit(e)}onPointerdown(t){if(this.isTouchEvent(t))return;const e=this.normalizeToPointerEvent(t);this.autoPreventDefault&&e.isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();const i=this.bootstrapEvent(e,this.rootPointerEvent);this.eventService.emit(i),this.setCursor(this.eventService.cursor)}onPointermove(t){if(this.isTouchEvent(t))return;const e=this.normalizeToPointerEvent(t),i=this.bootstrapEvent(e,this.rootPointerEvent);this.eventService.emit(i),this.setCursor(this.eventService.cursor)}onPointerup(t){if(this.isTouchEvent(t))return;const e=this.contextService.getDomElement(),i=t.target===e?"":"outside",n=this.normalizeToPointerEvent(t),s=this.bootstrapEvent(n,this.rootPointerEvent);s.type+=i,this.eventService.emit(s),this.setCursor(this.eventService.cursor)}setCursor(t){this.contextService.setCursor(t||this.canvasConfig.cursor||"default")}normalizeWheelEvent(t){const e=this.rootWheelEvent;e.nativeEvent=t,this.transferMouseData(t,e),ih(t,e);const i=new Oa(t.clientX,t.clientY),{x:n,y:s}=this.eventService.clientToCanvas(i);return e.canvas.x=n,e.canvas.y=s,e.offset.setFromPoint(e.canvas),e.global.setFromPoint(e.canvas),Gr(t,e),e}normalizeToPointerEvent(t){const e=this.renderingContext.root.ownerDocument.defaultView;if(e.supportTouchEvent&&t instanceof TouchEvent){const e=t;e.isNormalized=!0,e.pointerType="touch"}else if(!MouseEvent||t instanceof MouseEvent&&(!e.supportPointerEvent||!(t instanceof PointerEvent))){const e=t;e.isPrimary=!0,e.width=1,e.height=1,e.tiltX=0,e.tiltY=0,e.pointerType="mouse",e.pointerId=1,e.pressure=.5,e.twist=0,e.tangentialPressure=0,e.isNormalized=!0}return t}bootstrapEvent(t,e){this.renderingContext.root.ownerDocument.defaultView,e.originalEvent=null,e.nativeEvent=t,sh(t,e),this.transferMouseData(t,e);const{x:i,y:n}=this.eventService.clientToCanvas(new Oa(t.clientX,t.clientY));return e.canvas.x=i,e.canvas.y=n,e.offset.setFromPoint(e.canvas),e.global.setFromPoint(e.canvas),Gr(t,e),"pointerleave"===e.type&&(e.type="pointerout"),e.type.startsWith("mouse")&&e.type.replace("mouse","pointer"),e}transferMouseData(t,e){e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.shiftKey=t.shiftKey,e.relatedTarget=null,e.client.x=t.clientX,e.client.y=t.clientY,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.screen.x=t.screenX,e.screen.y=t.screenY}isTouchEvent(t){return this.renderingContext.root.ownerDocument.defaultView.supportTouchEvent&&"touch"===t.pointerType}},"moduleName","Event");class hh extends zr{constructor(t,e,i,n,s,o,r,a){super(null),Yi(this,"relatedNode",void 0),Yi(this,"prevValue",void 0),Yi(this,"newValue",void 0),Yi(this,"attrName",void 0),Yi(this,"attrChange",void 0),Yi(this,"prevParsedValue",void 0),Yi(this,"newParsedValue",void 0),this.type=t,this.relatedNode=e,this.prevValue=i,this.newValue=n,this.attrName=s,this.attrChange=o,this.prevParsedValue=r,this.newParsedValue=a}}Yi(hh,"ADDITION",2),Yi(hh,"MODIFICATION",1),Yi(hh,"REMOVAL",3);class ch{constructor(t){Yi(this,"contextService",void 0),Yi(this,"renderingPlugins",[]),Yi(this,"config",{autoRendering:!0}),Object.assign(this.config,t)}use(t){this.renderingPlugins.includes(t)||this.renderingPlugins.push(t)}initPlugins(t){this.renderingPlugins.forEach(e=>{e.init(t)})}destroyPlugins(){this.renderingPlugins.forEach(t=>{t.destroy()})}getPlugins(){return this.renderingPlugins}getAnnotationConfig(){return this.config}}class dh{constructor(t){Yi(this,"hooks",{init:js.create(),beginFrame:js.create(),beforeRender:js.create(),render:js.create(),afterRender:js.create(),putImageData:js.create(),endFrame:js.create(),destroy:js.create(),pointerdown:js.create(),pointerup:js.create(),pointermove:js.create(),pointerout:js.create(),pointerover:js.create(),pointerCancel:js.create(),wheel:js.create()}),Yi(this,"isInited",!1),Yi(this,"zIndexCounter",0),Yi(this,"renderingContext",void 0),this.renderingContext=t}init(){this.hooks.init.emit(),this.isInited=!0}destroy(){this.isInited=!1,this.hooks.destroy.emit()}render(){const{root:t}=this.renderingContext;this.zIndexCounter=0,oa.recursiveUpdateHierarchy(t),this.isInited&&(this.renderDisplayObject(t),this.renderingContext.dirty&&(this.hooks.endFrame.emit(),this.renderingContext.dirty=!1),this.renderingContext.renderCondition.clear())}renderDisplayObject(t){if(!t.isVisible)return;const{sortable:e}=t;if(e.renderOrder=this.zIndexCounter,this.zIndexCounter+=1,this.renderingContext.dirty||(this.renderingContext.dirty=!0,this.hooks.beginFrame.emit()),t.imageData)return void this.hooks.putImageData.emit(t);this.hooks.beforeRender.emit(t),this.hooks.render.emit(t),this.hooks.afterRender.emit(t);let i=!1;e.dirty&&(e.sorted=t.childNodes.slice().sort(uh),e.dirty=!1,i=!0);let n=e.sorted||t.childNodes;t.isTab?(n=t.visibleChildren,n.sort((t,e)=>t.index-e.index),n.length>1&&n.sort((t,e)=>t.style.zIndex-e.style.zIndex),n.forEach(t=>{this.renderDisplayObject(t)})):(n.sort((t,e)=>t.index-e.index),n.length>1&&n.sort((t,e)=>t.style.zIndex-e.style.zIndex),n.forEach(t=>{this.renderDisplayObject(t)})),n.sort((t,e)=>t.index-e.index),i&&t.recursiveCall(t=>{const e=new Yr("renderOrderChanged",{renderOrder:t.sortable.renderOrder});t.dispatchEvent(e)})}dirty(){this.renderingContext.renderCondition.add(0)}}function uh(t,e){const i=Number(t.style.zIndex),n=Number(e.style.zIndex);if(i===n&&t.parentNode){const{childNodes:i=[]}=t.parentNode;return i.indexOf(t)-i.indexOf(e)}return i-n}class ph extends $r{constructor(t){super(),Yi(this,"document",void 0),Yi(this,"customElements",void 0),Yi(this,"devicePixelRatio",void 0),Yi(this,"eventService",void 0),Yi(this,"renderingService",void 0),Yi(this,"renderingContext",void 0),Yi(this,"canvasConfig",void 0),Yi(this,"renderer",void 0),Yi(this,"supportTouchEvent",void 0),Yi(this,"supportPointerEvent",void 0),Yi(this,"limit1px",!1),Yi(this,"contextService",void 0);const{renderer:e,dpr:i,width:n,height:s,canvas:o,supportPointerEvent:r,supportTouchEvent:a}=t;this.supportPointerEvent=null!=r?r:!!globalThis.PointerEvent,this.supportTouchEvent=null!=a?a:"touchstart"in window;let l=n,h=s,c=i;o&&(c=i||window.devicePixelRatio||1,l=n||o.width/c,h=s||o.height/c),this.canvasConfig={...t,width:l,height:h,dpr:c},this.canvasConfig=t,this.renderer=e,this.document=new Kl,this.document.defaultView=this,this.initRenderingContext(),this.renderingService=new dh(this.renderingContext),this.initRenderer(e)}initRenderingContext(){this.renderingContext={root:this.document.documentElement,force:!1,dirty:!1,renderCondition:new Set},this.document.documentElement.addEventListener("child-inserted",t=>{this.mountChildren(t.detail.child)}),this.document.documentElement.addEventListener("child-removed",t=>{this.unmountChildren(t.detail.child)})}initRenderer(t){this.renderingService.init(),t.initPlugins(this),this.contextService.init(),t.getAnnotationConfig().autoRendering&&this.render(),this.document.documentElement.recursiveCall(t=>{const{renderable:e}=t;e&&(e.boundsDirty=!0,e.renderBoundsDirty=!0)}),this.mountChildren(this.document.documentElement)}render(){const t=new Yr("beforeRender",{});this.dispatchEvent(t),this.contextService.clearCanvas(),this.renderingService.render()}setDPR(t){this.canvasConfig.dpr=t,this.contextService.setDPR(t)}resize(t,e){this.canvasConfig.width=t,this.canvasConfig.height=e,this.contextService.resize(t,e)}getContextService(){return this.contextService}getEventService(){return this.eventService}appendChild(t,e){return this.document.documentElement.appendChild(t,e)}insertBefore(t,e){return this.document.documentElement.insertBefore(t,e)}removeChild(t){return this.document.documentElement.removeChild(t)}getBoundingClientRect(){return this.contextService.getBoundingClientRect()}mountChildren(t){t.recursiveCall(t=>{if(!t.isConnected){t.isConnected=!0,t.ownerDocument=this.document;const e=new Yr("DOMNodeInsertedIntoDocument",{});t.dispatchEvent(e)}})}unmountChildren(t){const e=[];t.recursiveCall(t=>{t.isConnected&&e.push(t)}),e.reverse().forEach(t=>{t.isConnected=!1;const e=new Yr("DOMNodeRemovedFromDocument",{});t.dispatchEvent(e),t!==this.document.documentElement&&(t.ownerDocument=null)})}}class gh{}class fh extends gh{constructor(t){super(),Yi(this,"close",!0),Yi(this,"shape",void 0),Yi(this,"ctx",void 0),Yi(this,"rCanvas",void 0),this.rCanvas=t}render(t,e){const{background:i,borderColor:n,visibility:s}=t.parsedStyle;if("hidden"===s)return;const o=!So(i)&&!i.isNone,r=!So(n)&&!n.isNone;t.renderClipStep&&(e.beginPath(),t.renderClipStep.forEach(t=>{Qa(e,t)}),e.closePath(),e.clip()),this.renderPath(t,e),o&&this.renderFill(t,e),this.renderStrokePath(t,e),r&&this.renderStroke(t,e)}renderPath(t,e){t.getPath(),e.beginPath(),t.steps.forEach(t=>{Qa(e,t)}),this.close&&t.steps.length>2&&e.closePath()}renderStrokePath(t,e){ks(null==t?void 0:t.getStrokePath)&&(t.getStrokePath(),0!==t.strokePath.length&&(e.beginPath(),t.strokeSteps.forEach(t=>{Qa(e,t)}),this.close&&t.strokeSteps.length>2&&e.closePath()))}renderFill(t,e){const{parsedStyle:i}=t,{background:n,opacity:s,fillOpacity:o,renderBlendMode:r}=i;if(e.save(),e.globalAlpha=s*o,"normal"!==r&&(e.globalCompositeOperation=r),Array.isArray(n)){this.setShapeGradientOrigin(t,e);for(let i=0;i<n.length;i++)0===i&&this.setShadow(t,e),e.fillStyle=this.getColor(t,n[i],e),e.fill()}else this.setShadow(t,e),e.fillStyle=n.formatted,e.fill();e.restore()}renderStroke(t,e){const{parsedStyle:i}=t,{borderWidth:n,borderColor:s,opacity:o,lineCap:r,lineJoin:a,miterLimit:l,lineDash:h,lineDashOffset:c,borderOpacity:d,renderBlendMode:u}=i;if(n&&n.value>0){if(e.save(),!So(n)){const i=t.getScale();this.rCanvas.limit1px?e.lineWidth=Math.max(1/i.x,n.value):e.lineWidth=n.value}"normal"!==u&&(e.globalCompositeOperation=u),e.miterLimit=l,e.globalAlpha=o*d,e.lineCap=r,e.lineJoin=a,e.setLineDash(Fo(h)?[0,0]:h),e.lineDashOffset=c.value,Array.isArray(s)?(this.setShapeGradientOrigin(t,e),s.forEach(i=>{e.strokeStyle=this.getColor(t,i,e),e.stroke()})):(e.strokeStyle=s.formatted,e.stroke()),e.restore()}}setShadow(t,e){const{shadow:i,shadowOffsetX:n,shadowOffsetY:s,shadowBlur:o,shadowColor:r}=t.parsedStyle;(i||r)&&(e.shadowOffsetX=(null==n?void 0:n.value)||i[0],e.shadowOffsetY=(null==s?void 0:s.value)||i[1],e.shadowBlur=(null==o?void 0:o.value)||i[2],e.shadowColor=(null==r?void 0:r.formatted)||i[3])}getColor(t,e,i){let n;if(1===e.type||2===e.type){const s=t.getBoundingRect(),{width:o,height:r}=s;n=function(t,e){const{type:i,steps:n,width:s,height:o,angle:r,cx:a,cy:l,size:h}=t;let c=null;if(1===i){const{x1:t,y1:i,x2:n,y2:a}=function(t,e,i){const n=i*Math.PI/180,s=0+t/2,o=0+e/2,r=Math.abs(t*Math.cos(n))+Math.abs(e*Math.sin(n));return{x1:s-Math.cos(n)*r/2,y1:o-Math.sin(n)*r/2,x2:s+Math.cos(n)*r/2,y2:o+Math.sin(n)*r/2}}(s,o,r.value);c=e.createLinearGradient(t,i,n,a)}else if(2===i){const{x:t,y:i,r:n}=function(t,e,i,n,s){let o=i.value,r=n.value;"%"===i.unit&&(o=i.value/100*t),"%"===n.unit&&(r=n.value/100*e);let a=Math.max(Ks({x:0,y:0},{x:o,y:r}),Ks({x:0,y:e},{x:o,y:r}),Ks({x:t,y:e},{x:o,y:r}),Ks({x:t,y:0},{x:o,y:r}));return s&&(Es(s)?a=s.value:Os(s)&&("closest-side"===s?a=Math.min(o,t-o,r,e-r):"farthest-side"===s?a=Math.max(o,t-o,r,e-r):"closest-corner"===s&&(a=Math.min(Ks({x:0,y:0},{x:o,y:r}),Ks({x:0,y:e},{x:o,y:r}),Ks({x:t,y:e},{x:o,y:r}),Ks({x:t,y:0},{x:o,y:r}))))),{x:o,y:r,r:a}}(s,o,a,l,h);c=e.createRadialGradient(t,i,0,t,i,n)}return c&&n.forEach(t=>{let{offset:e,color:i}=t;var n;"%"===e.unit&&(null===(n=c)||void 0===n||n.addColorStop(e.value/100,i.toString()))}),c}({type:e.type,...e.value,width:o,height:r},i)}return n}setShapeGradientOrigin(t,e){const{type:i}=t.config;switch(i){case"circle":case"arc":{const{r:i}=t.parsedStyle;e.translate(0-i.value,0-i.value);break}case"ellipse":{const{rx:i,ry:n}=t.parsedStyle;e.translate(0-i.value,0-n.value);break}default:e.translate(0,0)}}}class mh extends fh{constructor(t){super(t),this.close=!1}}class vh extends fh{}class yh extends fh{}class xh extends fh{async render(t,e){const{width:i,height:n,img:s,opacity:o,visibility:r}=t.parsedStyle;if("hidden"!==r){if(s&&!Os(s)){if(e.save(),e.globalAlpha=o,s instanceof ImageData)e.putImageData(s,0,0);else{e.imageSmoothingEnabled=!0,e.imageSmoothingQuality&&(e.imageSmoothingQuality="high");try{e.drawImage(s,0,0,i.value,n.value)}catch(t){}}e.restore()}if(t.defaultRenderPage&&(e.save(),e.drawImage(t.defaultRenderPage,0,0,i.value,n.value),e.restore()),t.visiblePartData){const{x:i}=t.visiblePartData.visiblePart,{y:n}=t.visiblePartData.visiblePart;e.save();const s=t.visiblePartData.visiblePart.imageScale;e.scale(1/s.x,1/s.y),e.drawImage(t.visiblePartData.data,i,n,t.visiblePartData.visiblePart.width/devicePixelRatio,t.visiblePartData.visiblePart.height/devicePixelRatio),e.restore()}}}}class wh extends fh{constructor(){super(...arguments),Yi(this,"close",!1)}render(t,e){const{visibility:i}=t.parsedStyle;"hidden"!==i&&(this.renderPath(t,e),this.renderStroke(t,e))}renderPath(t,e){t.getPath(),e.beginPath(),t.inkRenderSteps.forEach(t=>{t.forEach(t=>{Qa(e,t)})})}}class Ch extends fh{}class bh extends fh{render(t,e){const{background:i,borderColor:n,visibility:s}=t.parsedStyle;if("hidden"===s)return;const o=!So(i)&&!i.isNone,r=!So(n)&&!n.isNone;t.renderClipStep&&(e.beginPath(),t.renderClipStep.forEach(t=>{Qa(e,t)}),e.closePath(),e.clip()),t.getPath();const a=t.steps.length;for(let i=0;i<a;i++){const n=t.steps[i];e.beginPath(),n.step.forEach(t=>{Qa(e,t)}),n.close&&(e.closePath(),o&&this.renderFill(t,e)),r&&this.renderStroke(t,e)}}}class Sh extends fh{}class Th extends fh{constructor(){super(...arguments),Yi(this,"close",!0)}renderPath(t,e){t.getPath(),e.beginPath(),t.steps.forEach(t=>{Qa(e,t),t.close&&e.closePath()})}}class Eh extends fh{render(t,e){const{background:i,borderColor:n,visibility:s}=t.parsedStyle;if("hidden"===s)return;const o=!So(i)&&!i.isNone,r=!So(n)&&!n.isNone;t.getPath();const a=t.steps.length;for(let i=0;i<a;i++){const n=t.steps[i];e.beginPath(),n.step.forEach(t=>{Qa(e,t)}),n.close&&(e.closePath(),o&&this.renderFill(t,e)),r&&this.renderStroke(t,e)}}}class _h extends fh{render(t,e){const{width:i,height:n,roundedRadius:s,background:o,borderWidth:r,visibility:a}=t.parsedStyle;if("hidden"!==a){for(let t=0;t<4;t++){e.beginPath();const t=s.value;if(0===t)e.rect(0,0,i.value,n.value);else{const{PI:s}=Math;e.arc(t,t,t,s,3*s/2),e.arc(i.value-t,t,t,3*s/2,2*s),e.arc(i.value-t,n.value-t,t,0,s/2),e.arc(t,n.value-t,t,s/2,s)}}e.closePath(),o&&this.renderFill(t,e),r.value>0&&this.renderStroke(t,e)}}}class Ph extends fh{render(t,e){t&&"hidden"!==t.parsedStyle.visibility&&(this.renderBox(t,e),e.save(),t.renderClipStep&&(e.beginPath(),t.renderClipStep.forEach(t=>{Qa(e,t)}),e.closePath(),e.clip()),this.renderText(t,e),e.restore())}renderBox(t,e){const{background:i,borderColor:n}=t.parsedStyle,s="textBox"===t.textType&&!So(i)&&!i.isNone,o="textBox"===t.textType&&!So(n)&&!n.isNone;this.renderPath(t,e),s&&this.renderFill(t,e),o&&this.renderStroke(t,e)}renderText(t,e){const{parsedStyle:i,lines:n}=t,{opacity:s,y:o,x:r}=i;e.globalAlpha=s,n.forEach(i=>{const n=i.height/30,s=t.getTextAlignOffset(i);i.words.forEach(t=>{const{color:a,fontFamily:l,fontSize:h,fontStyle:c,fontWeight:d,lineThrough:u,underline:p}=t.style;e.fillStyle=a;const g=""===l.trim()?"sans-serif":l,f=l.includes(" ")?`'${g}'`:g;e.font=`${c} ${d} ${h.value}${h.unit} ${f}`;let m=t.x-r+s;if(function(t){return/[\u0600-\u06FF]/.test(t)}(t.text))e.fillText(t.text,m,i.y-o);else for(let n=0;n<t.text.length;n++){const s=t.text.charAt(n);e.fillText(s,m,i.y-o),m+=e.measureText(s).width}p&&e.fillRect(t.x-r+s,i.y-o+n,t.widthWithoutLf,n),u&&e.fillRect(t.x-r+s,i.y-t.wordHeight/3-o,t.widthWithoutLf,h.value/30)})})}}class Ah extends fh{render(t,e){t&&"hidden"!==t.parsedStyle.visibility&&this.renderText(t,e)}renderText(t,e){const{parsedStyle:i}=t;t.setTextFont();const{text:n,font:s,opacity:o,color:r,y:a}=i;e.save(),e.globalAlpha=o,e.font=s,e.fillStyle=r.formatted,e.textBaseline="alphabetic",e.fillText(n,0,0),e.restore()}}class Ih{constructor(t){Yi(this,"canvasConfig",void 0),Yi(this,"container",void 0),Yi(this,"canvas",void 0),Yi(this,"dpr",void 0),Yi(this,"context",void 0),Yi(this,"shapeRenderers",{}),this.canvasConfig=t}init(){const{container:t,canvas:e,dpr:i,willReadFrequently:n}=this.canvasConfig;if(e){this.canvas=e;const{parentElement:i}=e;t&&i!==t&&t.appendChild(e),this.container=i,this.canvasConfig.container=i}else if(t&&(this.container=t,Os(t)&&(this.container=document.getElementById(t)),this.container)){const t=document.createElement("canvas");this.container.appendChild(t),this.canvas=t}this.context=this.canvas.getContext("2d",{willReadFrequently:n}),this.dpr=i||ao(),this.resize(this.canvasConfig.width,this.canvasConfig.height)}registerShapeRenderer(t,e){this.shapeRenderers[t]||(this.shapeRenderers[t]=e)}getShapeRenderer(t){return this.shapeRenderers[t]}destroy(){const{canvas:t,container:e}=this;e&&null!=t&&t.parentNode&&e.removeChild(t)}resize(t,e){const{canvas:i,dpr:n}=this;i&&(i.width=t*n,i.height=e*n,this.context.scale(n,n))}getDPR(){return this.dpr}setDPR(t){this.canvasConfig.dpr=t,this.dpr=t}getContext(){return this.context}getDomElement(){return this.canvas}getCanvas(){return this.canvas}setCursor(t){var e;null!=this&&null!==(e=this.container)&&void 0!==e&&e.style&&(this.container.style.cursor=t)}getBoundingClientRect(){var t;return null===(t=this.canvas)||void 0===t?void 0:t.getBoundingClientRect()}clearCanvas(){this.canvas&&(this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.scale(this.dpr,this.dpr))}}class Dh{constructor(){Yi(this,"restoreStack",[])}init(t){const{hooks:e}=t.renderingService;e.endFrame.on(()=>{const{contextService:e}=t,i=e.getContext();this.restoreStack.forEach(()=>{i.restore()}),this.restoreStack=[]}),e.render.on(e=>{this.renderDisplayObject(e,t)}),e.putImageData.on(e=>{if(e.imageData){const{x:i,y:n}=e.getPosition(),s=t.contextService.getContext(),o=t.contextService.getDPR();s.putImageData(e.imageData,Math.floor(i*o+.5),Math.floor(n*o+.5))}})}renderDisplayObject(t,e){if(!t.isVisible)return;const{contextService:i}=e,n=i.getContext();let s=this.restoreStack[this.restoreStack.length-1];for(;s&&t.parentNode!==s;)n.restore(),this.restoreStack.pop(),s=this.restoreStack[this.restoreStack.length-1];n.save(),this.applyTransform(n,t);const{clipPath:o}=t.style;o&&(n.save(),this.applyTransform(n,o),n.restore(),n.clip()),this.useAnchor(n,t);const r=i.getShapeRenderer(t.shapeType);r&&(r.render(t,n),t.clippable&&n.clip()),this.restoreStack.push(t)}applyTransform(t,e){e.externalMatrices.length&&e.externalMatrices.slice().reverse().forEach(e=>{const{a:i,b:n,c:s,d:o,e:r,f:a}=e;t.transform(i,n,s,o,r,a)});const i=e.getLocalTransform(),{a:n,b:s,c:o,d:r,e:a,f:l}=i;t.transform(n,s,o,r,a,l)}applyAttributes(t,e,i){}useAnchor(t,e){const{anchor:i}=e.parsedStyle||{};if(!i||0===i[0]&&0===i[1])return;const n=e.getGeometryBounds().getRect();t.translate(-(i&&i[0]||0)*n.width,-(i&&i[1]||0)*n.height)}destroy(){}}Yi(Dh,"moduleName",void 0);class Rh{init(t){const e=new Ih(t.canvasConfig);t.contextService=e,[{name:"arc",renderer:new mh(t)},{name:"circle",renderer:new vh(t)},{name:"ellipse",renderer:new yh(t)},{name:"line",renderer:new Eh(t)},{name:"image",renderer:new xh(t)},{name:"ink",renderer:new wh(t)},{name:"polygon",renderer:new Ch(t)},{name:"polyline",renderer:new bh(t)},{name:"rect",renderer:new Sh(t)},{name:"stampText",renderer:new Ah(t)},{name:"stampPath",renderer:new Th(t)},{name:"roundedRect",renderer:new _h(t)},{name:"freeText",renderer:new Ph(t)}].forEach(t=>{let{name:i,renderer:n}=t;e.registerShapeRenderer(i,n)})}destroy(){}}class kh extends ch{constructor(t){super(t),this.use(new Rh),this.use(new Dh)}}function Mh(t,e,i){const n=e.x-t.x,s=e.y-t.y,o=i.x-t.x,r=n*(i.y-t.y)-s*o,a=qs(t,e),l=qs(t,i);let h=(a**2+l**2-qs(e,i)**2)/(2*a*l);h<-1&&(h=-1),h>1&&(h=1);let c=180*Math.acos(h)/Math.PI;return c=Math.round(100*c)/100,r<0?-c:c}function Lh(t,e,i){const n=Qr.fromTwoPoint(e,t);return Qr.fromTwoPoint(e,i).angle(n)>Math.PI/2}function Oh(t,e){return(e=t.getWorldTransform().inverse().transformPoint(e)).x+=t.parsedStyle.x,e.y+=t.parsedStyle.y,e}function Bh(t){if(!t)return!1;const{shapeType:e}=t;return"annotationRect"===e||"annotationFreeText"===e&&"textBox"===t.textType||"annotationStamp"===e&&"image"===t.renderType}function Nh(t){return!!t&&("annotationPolyline"===t.shapeType||"annotationPolygon"===t.shapeType||"annotationLine"===t.shapeType)}function Uh(t){return!!t&&("annotationFreeText"===t.shapeType||"annotationTextBox"===t.shapeType)}function Fh(t){return!!t&&("annotationUnderline"===t.shapeType||"annotationStrikeout"===t.shapeType||"annotationHighlight"===t.shapeType)}function Vh(t,e){const i=window.TouchEvent&&e instanceof TouchEvent?e.targetTouches[0]:e,n=t.getBoundingClientRect();return{offsetX:i.pageX-window.scrollX-n.left,offsetY:i.pageY-window.scrollY-n.top}}function Wh(t){return/^[\r\n]+$/.test(t)}function Hh(t,e,i){return t.slice(0,e)+t.slice(i+1)}function jh(t,e){const{textContents:i}=t.style,n=[];return i.forEach(t=>{n.push({...t,...e})}),n}function zh(t,e){const{textContents:i}=t.style,{textSelection:n}=t.textEditEventHandler;if(!n.length)return i;const[s,o]=n,r=s.freeContentIndex,a=o.freeContentIndex,l=i.slice(0,r),h=i.slice(r,a+1),c=i.slice(a+1),d=[];if(s.freeContentIndex===o.freeContentIndex){const{content:t}=h[0],i=t.slice(0,s.indexInFreeContent),n=t.slice(s.indexInFreeContent,o.indexInFreeContent+1),r=t.slice(o.indexInFreeContent+1);i&&d.push({...h[0],content:i}),n&&d.push({...h[0],...e,content:n}),r&&d.push({...h[0],content:r})}else for(let t=0;t<h.length;t++){const i=h[t];0===t?(0!==s.indexInFreeContent&&d.push({...i,content:i.content.slice(0,s.indexInFreeContent)}),d.push({...i,...e,content:i.content.slice(s.indexInFreeContent)})):t===h.length-1?(d.push({...i,...e,content:i.content.slice(0,o.indexInFreeContent+1)}),o.indexInFreeContent+1<i.content.length&&d.push({...i,content:i.content.slice(o.indexInFreeContent+1)})):d.push({...i,...e})}return[...l,...d,...c]}function Gh(t){if(!t)return!1;let e=t,i="visible"===e.parsedStyle.visibility;for(;e;)e.parsedStyle.visibility&&"hidden"===e.parsedStyle.visibility&&(i=!1),e=e.parentNode;return i}var Yh;!function(t){t.REJECTED="SBRejected",t.ACCEPTED="SHAccepted",t.INITIAL_HERE="SHInitialHere",t.SIGN_HERE="SHSignHere",t.WITNESS="SHWitness",t.APPROVED="SBApproved",t.NOT_APPROVED="SBNotApproved",t.DRAFT="SBDraft",t.FINAL="SBFinal",t.COMPLETED="SBCompleted",t.CONFIDENTIAL="SBConfidential",t.VOID="SBVoid"}(Yh||(Yh={}));const $h={border:"1px solid #59626A",background:"transparent",ctrlBorderRadius:"6px",ctrlWidth:"12px",ctrlHeight:"12px",ctrlBorder:"1px solid #59626A",ctrlBackground:"white"},Xh={content:"Insert text here...",fontSize:32,color:"red",lineThrough:!1,underline:!1,fontFamily:"Times New Roman",fontStyle:"normal",fontWeight:"normal"},qh={opacity:1,background:"",borderColor:"red",borderWidth:4,lineDash:[0,0],lineEnding:["None","None"],stampIcon:Yh.DRAFT,imageData:null,textAlign:"left",textContent:{...Xh}},Zh={enableControl:!0,useDefaultControls:!0,enableEdit:!0,enableMove:!0,enableRotate:!0},Jh={showOnTopWhenSelected:!1,enableContinuousDrawing:!1,enableDeleteWithKeyboard:!0,enableMoveWithKeyboard:!0,enableMultipleSelectWidthCtrl:!0,inkCreateDelay:3e3,controlsStyle:$h,defaultStyleConfig:{},eraserStyle:{background:"rgba(0,0,0)",borderColor:"rgba(0,0,0)",opacity:.3,borderWidth:8},selectionStyle:{background:"transparent",borderWidth:2,borderColor:"#59626A",lineDash:[5,5]}};class Kh{constructor(t){Yi(this,"shape",void 0),Yi(this,"startTime",void 0),Yi(this,"startPoint",void 0),Yi(this,"lastPoint",void 0),Yi(this,"limitPosition",void 0),Yi(this,"limitAngle",void 0),Yi(this,"unLimitPosition",void 0),Yi(this,"unLimitScale",void 0),Yi(this,"unLimitStyle",void 0),Yi(this,"limitArea",void 0),this.shape=t}setLimitArea(t){this.limitArea=t}updateShapeByLimitArea(){const{shapeType:t}=this.shape,{left:e,right:i,top:n,bottom:s}=this.isOutOfLimitArea(1,1),o=e||i||n||s,r=Bh(this.shape)||"annotationEllipse"===t;o?(r?this.shape.updateStyle(this.unLimitStyle||{}):this.shape.setLocalScale(this.unLimitScale||this.shape.getLocalScale()),this.shape.setLocalPosition(this.unLimitPosition||this.shape.getLocalPosition())):(r&&(this.unLimitStyle={width:this.shape.style.width,height:this.shape.style.height,rx:this.shape.style.rx,ry:this.shape.style.ry}),this.unLimitPosition=this.shape.getLocalPosition().clone(),this.unLimitScale=this.shape.getLocalScale().clone())}getShapeOriginPosition(){const{left:t,top:e,width:i,height:n}=this.shape.getBoundingRect(),s=new Tl({style:{x:t-this.shape.style.x+i/2,y:e-this.shape.style.y+n/2}});this.shape.appendChild(s);const{x:o,y:r}=s.getPosition();return s.destroy(),{x:o,y:r}}getShapeControlPointPosition(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"vertexes";const{left:e,top:i,width:n,height:s}=this.shape.getBoundingRect(),o=[];for(let r=0;r<4;r++){let a=e-this.shape.style.x,l=i-this.shape.style.y;if("vertexes"===t)switch(r){case 1:a+=n;break;case 2:a+=n,l+=s;break;case 3:l+=s}else switch(r){case 1:a+=n,l+=s/2;break;case 2:a+=n/2,l+=s;break;case 3:l+=s/2;break;default:a+=n/2}const h=new Tl({style:{x:a,y:l}});this.shape.appendChild(h);const{x:c,y:d}=h.getPosition();o.push({x:c,y:d}),h.destroy()}return o}isOutOfLimitArea(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(!this.limitArea)return{left:!1,right:!1,top:!1,bottom:!1};const{left:n,top:s,width:o,height:r}=this.limitArea,a=i||this.getShapeControlPointPosition();let l=!1,h=!1,c=!1,d=!1;for(let i=0;i<4;i++){const{x:u,y:p}=a[i];l=u<n-t||l,h=u>n+o+t||h,c=p<s-e||c,d=p>s+r+e||d}return{left:l,right:h,top:c,bottom:d}}getLimitPosition(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(!this.limitArea)return null;const e=t||this.getShapeControlPointPosition(),{x:i,y:n}=e[0],{left:s,top:o,width:r,height:a}=this.limitArea,l=e[1].x-i,h=e[2].x-i,c=e[3].x-i,d=e[1].y-n,u=e[2].y-n,p=e[3].y-n;let g=s-Math.min(l,h,c),f=s+r-Math.max(l,h,c),m=o-Math.min(d,u,p),v=o+a-Math.max(d,u,p);if(l>=0&&h>=0&&c>=0?g=s:l<=0&&h<=0&&c<=0&&(f=s+r),d>=0&&u>=0&&p>=0?m=o:d<=0&&u<=0&&p<=0&&(v=o+a),(y=this.shape)&&("annotationEllipse"===y.shapeType||"annotationCircle"===y.shapeType)){const{x:t,y:e}=this.getShapeOriginPosition(),s=t-i,o=e-n;g+=s,f+=s,m+=o,v+=o}var y;return{minPosX:g,maxPosX:f,minPosY:m,maxPosY:v}}getLimitRotateAngle(){if(!this.limitArea)return[];const t=function(t,e){const i=t,[n,s,o,r]=i,{left:a,top:l,width:h,height:c}=e,d=a+h,u=l+c,p=(n.x+s.x+o.x+r.x)/4,g=(n.y+s.y+o.y+r.y)/4,f=Math.sqrt((p-n.x)**2+(g-n.y)**2),m=p-f,v=p+f,y=g-f,x=g+f;if(m>a&&y>l&&v<d&&x<u)return[];const w=t=>{const e=f*f-(t-p)**2;return[{x:t,y:g-Math.sqrt(e)},{x:t,y:g+Math.sqrt(e)}]},C=t=>{const e=f*f-(t-g)**2;return[{x:p-Math.sqrt(e),y:t},{x:p+Math.sqrt(e),y:t}]},b=(e,i)=>{const n=[];return e.forEach(e=>{t.forEach(t=>{let s=Mh({x:p,y:g},t,e);0===s&&(s=p>t.x?g>t.y?-0:0:g>t.y?0:-0,"top"!==i&&"bottom"!==i||(s=-s)),n.push(s)})}),n},S=[];if(m<a){const t=w(a);S.push(...b(t,"left"))}if(y<l){const t=C(l);S.push(...b(t,"top"))}if(v>d){const t=w(d);S.push(...b(t,"right"))}if(x>u){const t=C(u);S.push(...b(t,"bottom"))}return S}(this.getShapeControlPointPosition(),this.limitArea);if(0===t.length)return[];let e=0;if(t.forEach(t=>{0===t&&e++}),e>=2)return[0,0];const{maxNegative:i,minPositive:n}=function(t){let e=-1/0,i=1/0;for(let n=0;n<t.length;n++)t[n]<0&&t[n]>e||Object.is(t[n],-0)?e=t[n]:(t[n]>0&&t[n]<i||Object.is(t[n],0))&&(i=t[n]);return e===-1/0&&(e=0),i===1/0&&(i=0),{maxNegative:e,minPositive:i}}(t);return[i,n]}moveByKeyboard(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const{shape:i}=this,{controlsFlags:n}=i.context;if(t.preventDefault(),!n.enableMove)return!1;let s=0,o=0;const r=Math.max(1,Math.round(e*(fo(t)?8:1)));switch(t.key){case"ArrowLeft":s=-r;break;case"ArrowRight":s=r;break;case"ArrowUp":o=-r;break;case"ArrowDown":o=r}const a=i.getPosition();let l=a.x+s,h=a.y+o;const{left:c,right:d,top:u,bottom:p}=this.isOutOfLimitArea(1,1),g=c||d||u||p,f=this.getLimitPosition();if(f&&!g){const{minPosX:t,maxPosX:e,minPosY:i,maxPosY:n}=f;l<t&&(l=t),l>e&&(l=e),h<i&&(h=i),h>n&&(h=n)}return this.shape.setPosition({x:l,y:h}),Nh(i)&&i.pointEventsHandler.updateLineControls(),!0}moveShape(t){const{shape:e,startPoint:i}=this,{lastWorldPosition:n,controlsFlags:s}=e.context;if(!s.enableMove)return;if(new Oa(t.x,t.y).distanceTo(i)<0)return;const o=t.x-i.x,r=t.y-i.y;let a=n.x+o,l=n.y+r;const{left:h,right:c,top:d,bottom:u}=this.isOutOfLimitArea(1,1),p=h||c||d||u;if(this.limitPosition&&!p){const{minPosX:t,maxPosX:e,minPosY:i,maxPosY:n}=this.limitPosition;a<t&&(a=t),a>e&&(a=e),l<i&&(l=i),l>n&&(l=n)}this.shape.setPosition({x:a,y:l})}moveVertex(t){const{shape:e}=this,{context:i,shapeType:n}=e,{hitControlPoint:s,lastLocalScale:o,lastControlsWidth:r,lastControlsHeight:a,keepAspectRatio:l,lastHitControlPoint:h,lastShareAxisYPoint:c,lastShareAxisXPoint:d,lastLocalTransform:u}=i,p=Ba(h,d,t).distanceTo(d)||1;if(Lh(h,d,t))return;let g=p-r,f=p/r;const m=Ba(h,c,t).distanceTo(c)||1;if(Lh(h,c,t))return;let v=m-a,y=m/a;l&&(f<=y?(y=f,v=y*a-a):(f=y,g=f*r-r));const{left:x,right:w,top:C,bottom:b}=this.isOutOfLimitArea(1,1),S=x||w||C||b,T="annotationEllipse"===n;if(Bh(e))this.moveRectVertex(s,g,v);else if(T)this.moveEllipseVertex(s,g,v);else{s<2&&(v=-v),0!==s&&3!==s||(g=-g),e.setLocalTransform(u);const{x:t,y:i}=e.getScale();g/=Math.abs(t),v/=Math.abs(i),e.translateLocal(g/2,v/2),e.setLocalScale(f*o.x,y*o.y)}S||0===e.getAngle()||this.updateShapeByLimitArea()}moveEllipseVertex(t,e,i){const{shape:n}=this,{x:s,y:o}=n.getScale(),{lastShapeWidth:r,lastShapeHeight:a,lastLocalTransform:l}=this.shape.context;e/=Math.abs(s),i/=Math.abs(o),n.style.rx=Math.max(1,(r+e)/2),n.style.ry=Math.max(1,(a+i)/2),t<2&&(i=-i),0!==t&&3!==t||(e=-e),n.setLocalTransform(l),n.translateLocal(e/2,i/2)}moveRectVertex(t,e,i){const{shape:n}=this,{x:s,y:o}=n.getScale(),{lastShapeWidth:r,lastShapeHeight:a,lastWorldPosition:l,lastLocalTransform:h}=this.shape.context;if(e/=Math.abs(s),i/=Math.abs(o),n.style.width=Math.max(r+e,1),n.style.height=Math.max(a+i,1),2===t)n.setPosition(l);else switch(n.setLocalTransform(h),t){case 1:n.translateLocal(0,-i);break;case 3:n.translateLocal(-e,0);break;default:n.translateLocal(-e,-i)}}moveMidpoints(t){const{shape:e}=this,{context:i,shapeType:n}=e,{lastLocalScale:s,lastWorldTransform:o,lastHitControlPoint:r,lastShareAxisPoint:a,hitControlPoint:l,lastWorldPosition:h,lastControlsWidth:c,lastControlsHeight:d,lastHitControlPointCenter:u,lastParentWorldAngle:p}=i,g=l-4,f=Ba(r,a,t).distanceTo(a);if(Lh(r,a,t))return;const m="annotationEllipse"===n,v=f/c*s.x,y=f/d*s.y,{left:x,right:w,top:C,bottom:b}=this.isOutOfLimitArea(1,1),S=x||w||C||b,T={x:t.x-(r.x-u.x),y:t.y-(r.y-u.y)};if(Bh(e))this.moveRectMidPoint(g,T);else if(m)this.moveEllipseMidPoint(g,T);else{const t=o.inverse(),i=t.transformPoint(T),n=t.transformPoint(h),r={...s};0===g?(r.y=y,90===p?n.x=i.x:n.y=i.y):1===g?r.x=v:2===g?r.y=y:3===g&&(r.x=v,90===p?n.y=i.y:n.x=i.x),this.shape.setLocalScale(r);const a=o.transformPoint(n);e.setPosition(a)}S||0===e.getAngle()||this.updateShapeByLimitArea()}moveRectMidPoint(t,e){const{shape:i}=this,{lastShapeHeight:n,lastWorldPosition:s,lastShapeWidth:o}=i.context,r=i.getWorldTransform().clone(),a=r.inverse().transformPoint(e),l=r.inverse().transformPoint(s),h=l;0===t?(i.style.height=n-(a.y-l.y),h.y=a.y):1===t?i.style.width=Math.max(1,a.x-l.x):2===t?i.style.height=Math.max(1,a.y-l.y):3===t&&(i.style.width=o-(a.x-l.x),h.x=a.x);const c=r.transformPoint(h);i.setPosition(c)}moveEllipseMidPoint(t,e){const{shape:i}=this,{lastShapeHeight:n,lastShapeWidth:s,lastWorldPosition:o}=i.context,r=i.getWorldTransform(),a=r.inverse().transformPoint(e),l=r.inverse().transformPoint(o),h=l;if(0===t){const t=(n/2-(a.y-l.y))/2;i.style.ry=t,h.y=a.y+t}else if(1===t){const t=(s/2+(a.x-l.x))/2;i.style.rx=t,h.x=a.x-t}else if(2===t){const t=(n/2+(a.y-l.y))/2;i.style.ry=t,h.y=a.y-t}else if(3===t){const t=(s/2-(a.x-l.x))/2;i.style.rx=t,h.x=a.x+t}const c=r.transformPoint(h);i.setPosition(c)}moveRotationPoint(t){const{startPoint:e,shape:i}=this,{lastOriginWorldPosition:n,lastLocalTransform:s}=i.context,o=Mh(n,e,t);this.shape.setLocalTransform(s),this.shape.rotateLocal(o)}isHit(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{shape:i}=this,{context:n,parsedStyle:s}=i;if("hidden"===s.visibility||!n.controlsFlags.enableControl)return-1;if(n.isGrouped)return n.unHitShape(),-1;let{controls:o}=i,r=!0;o||(r=!1,n.initControls(),n.renderControls(),o=i.controls);let a=o.checkHitArea(t.x,t.y);return Nh(i)&&!i.context.controlsFlags.useDefaultControls&&(8===a?a=-1:a>0&&(a=9),-1!==i.pointEventsHandler.isHitPoint(t)&&(a=0)),Fh(i)&&!i.context.controlsFlags.useDefaultControls&&(8===a?a=-1:a>0&&(a=9),a=i.textAssistEventHandler.isHitPoint(t)),a<0?(e&&(n.unHitShape(),r||i.context.destroyControls()),-1):a}startHandler(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.isHit(t);if(-1===i&&!e)return;-1===i&&e&&(i=9);const{shape:n}=this,{context:s}=n;s.isStart=!0,this.lastPoint={...t},this.startPoint={...t},this.startTime=(new Date).getTime(),Nh(n)&&(n.pointEventsHandler.enableEditMode(),n.pointEventsHandler.editStartHandler(t)),Uh(n)&&n.textEditEventHandler.editStartHandler(t),Fh(n)&&n.textAssistEventHandler.editStartHandler(t);const o=this.getShapeControlPointPosition();if(this.limitPosition=this.getLimitPosition(o),s.controlsFlags.useDefaultControls){if(s.hitShape(),s.hitControlPoint=i,i<4){const{x:e,y:n}=o[i];s.lastHitControlPoint={...t},s.lastHitControlPointCenter={x:e,y:n},s.lastShareAxisYPoint={x:o[3-i].x+t.x-e,y:o[3-i].y+t.y-n},s.lastShareAxisXPoint={x:o[i%2?i-1:i+1].x+t.x-e,y:o[i%2?i-1:i+1].y+t.y-n}}else if(i<8){const e=this.getShapeControlPointPosition("mid"),{x:n,y:o}=e[i-4];s.lastHitControlPoint={...t},s.lastHitControlPointCenter={x:n,y:o},s.lastShareAxisPoint={x:e[(i-2)%4].x+t.x-n,y:e[(i-2)%4].y+t.y-o}}}else s.isHit=!0,s.hitControlPoint=9,s.lastWorldPosition=n.getPosition(),s.lastControlsWorldPosition=n.controls.getPosition()}moveHandler(t,e){const{shape:i}=this,{context:n,controls:s}=i,{isHit:o,isStart:r,hitControlPoint:a}=n;if(!o||!r||!s)return;this.lastPoint={...t};const l=Nh(i);l&&-1!==i.pointEventsHandler.hitIndex?i.pointEventsHandler.editMoveHandler(t):Uh(i)&&i.textEditEventHandler.editMode?i.textEditEventHandler.editMoveHandler(t):Fh(i)&&i.textAssistEventHandler.isEditMode?i.textAssistEventHandler.editMoveHandler(t):a<4?(n.keepAspectRatio=e,this.moveVertex(t)):a<8?this.moveMidpoints(t):a<9?this.moveRotationPoint(t):(this.moveShape(t),l&&i.pointEventsHandler.updateLineControls())}endHandler(t){const{shape:e,startPoint:i,lastPoint:n}=this,{context:s}=e,{isStart:o,isHit:r}=e.context;if(!o||!r)return;const a=(new Date).getTime()-this.startTime,l=n.x-i.x,h=n.y-i.y,c=a<=200&&(l**2+h**2)**.5<2,d=Nh(e),u=Uh(e),p=Fh(e);if(d&&e.pointEventsHandler.editEndHandler(),u&&e.textEditEventHandler.editEndHandler(),p&&e.textAssistEventHandler.editEndHandler(),!s.isActive&&c&&(s.isActive=!0),t){if(u&&e.textEditEventHandler.editMode)return void(s.hitControlPoint=-1);if(p&&e.textAssistEventHandler.isEditMode)return void(s.hitControlPoint=-1);const i=[];e instanceof cc?i.push(...e.shapes):i.push(e);const n=[],o=[];let r=!1,a=!1,l=!1,h=!1;if(8===s.hitControlPoint&&this.shape.getAngle()!==(null==s?void 0:s.lastWorldAngle))o.push("rotated"),r=!0;else{const{lastControlsWorldPosition:t,lastControlsWidth:i,lastControlsHeight:n,lastWorldPosition:r}=s;e.context.renderControls();const{width:c,height:u}=e.controls.getLength(),p=e.controls.getPosition(),g=e.getPosition(),f=e instanceof nc?t:r,m=e instanceof nc?p:g;if(m.x.toFixed(1)===f.x.toFixed(1)&&m.y.toFixed(1)===f.y.toFixed(1)||(o.push("moved"),a=!0),!(e instanceof cc)){const t=d&&-1!==e.pointEventsHandler.hitIndex;if(i&&n&&(c.toFixed(3)!==i.toFixed(3)||u.toFixed(3)!==n.toFixed(3)))o.push("resized"),l=!0;else if(t){const{hitIndex:t,hitPointPos:i}=e.pointEventsHandler,n=e.path[t];n.x.toFixed(2)===i.x.toFixed(2)&&n.y.toFixed(2)===i.y.toFixed(2)||(o.push("resized"),h=!0)}}}if(r||a||l||h){i.forEach(t=>{const e=t.getAnnotationConfig(),i={style:{},transform:_s(e.transform)};(a||l||h)&&(Ps(e.style.x)||(i.style.x=e.style.x),Ps(e.style.y)||(i.style.y=e.style.y),Ps(e.style.points)||(i.style.points=e.style.points),Ps(e.style.segments)||(i.style.segments=e.style.segments),l&&(Ps(e.style.width)||(i.style.width=e.style.width),Ps(e.style.height)||(i.style.height=e.style.height))),(h||a||l)&&(Ps(e.style.startPoint)||(i.style.startPoint=e.style.startPoint),Ps(e.style.endPoint)||(i.style.endPoint=e.style.endPoint)),n.push({shape:t,changedOptions:i})});const e=[...new Set(o)];t.emitModifyAnnotation(e,n)}}s.isHit=!1,s.keepAspectRatio=!1}}class Qh extends Cl{constructor(t,e){super({type:"annotationControls",style:{visibility:"visible"}}),Yi(this,"shapeType","annotationControls"),Yi(this,"container",void 0),Yi(this,"rotationPoint",void 0),Yi(this,"rotationPointOffset",30),Yi(this,"vertexes",[]),Yi(this,"midpoints",[]),Yi(this,"boxRenderPath",[]),Yi(this,"boxRenderSteps",[]),Yi(this,"rotationRenderPath",[]),Yi(this,"rotationRenderSteps",[]),Yi(this,"controlPointsRenderPaths",[]),this.container=t;for(const t in e)To(t,e)&&(this[t]=e[t]);this.updateControlPoints(this.vertexes),this.getPath()}get isVisible(){return"hidden"!==this.parsedStyle.visibility&&Gh(null==this?void 0:this.container)}calculateMidpoints(t){const e=[];for(let i=0,n=t.length;i<n;i++){const s=new Oa((t[i].x+t[(i+1)%n].x)/2,(t[i].y+t[(i+1)%n].y)/2);e.push(s)}return e}calculateRotationPoint(t){const e=t[0].distanceTo(t[2]),i=this.rotationPointOffset/e+1;return t[2].lerpTo(t[0],i)}update(t){this.updateControlPoints(t),this.getPath(),this.updateOrigin()}updateOrigin(){const t=this.midpoints[0].x-this.vertexes[0].x,e=this.midpoints[3].y-this.vertexes[0].y;this.setOrigin(t,e)}updateControlPoints(t){this.vertexes=t,this.midpoints=this.calculateMidpoints(this.vertexes),this.rotationPoint=this.calculateRotationPoint(this.midpoints)}getLength(){const t=this.midpoints[2].y-this.midpoints[0].y;return{width:this.midpoints[1].x-this.midpoints[3].x,height:t}}setVisible(t){this.style.visibility=t}setBoxVisible(t){if("hidden"===t)this.boxRenderPath=[],this.boxRenderSteps=[];else{const t=tl(this.vertexes);this.boxRenderPath=this.vertexes.map(e=>({x:e.x-t.left,y:e.y-t.top})),this.boxRenderSteps=Ka(this.boxRenderPath,!0)}}setRotationPointVisible(t){if("hidden"===t)this.rotationRenderPath=[],this.rotationRenderSteps=[];else{const t=tl(this.vertexes);this.rotationRenderPath=[this.midpoints[0],this.rotationPoint].map(e=>({x:e.x-t.left,y:e.y-t.top})),this.rotationRenderSteps=Ka(this.rotationRenderPath,!0)}}setControlPointVisible(t){if("hidden"===t)this.controlPointsRenderPaths=[];else{const t=tl(this.vertexes);this.controlPointsRenderPaths=[...this.vertexes,...this.midpoints].map(e=>({x:e.x-t.left,y:e.y-t.top}))}}checkHitArea(t,e){const i=this.getWorldTransform().inverse().transformPoint({x:t,y:e}),{x:n,y:s}=this.vertexes[0],o={x:i.x+n,y:i.y+s},{ctrlWidth:r,ctrlHeight:a,ctrlBorderWidth:l,borderWidth:h,background:c}=this.container.context.parsedControlsStyle,d=(l+(Ms()?10:0)||0)/2,u=r/2,p=a/2,g=r+2*d,f=a+2*d,m=(t,e)=>dl(t-u-d,e-p-d,g,f,o.x,o.y);if(this.controlPointsRenderPaths.length){for(let t=0;t<this.vertexes.length;t++)if(m(this.vertexes[t].x,this.vertexes[t].y))return t;for(let t=0;t<this.midpoints.length;t++)if(m(this.midpoints[t].x,this.midpoints[t].y))return this.vertexes.length+t}if(this.rotationRenderPath.length&&m(this.rotationPoint.x,this.rotationPoint.y))return 8;if(this.boxRenderPath.length){const t=tl(this.vertexes);if(o.x<t.left||o.x>t.left+t.width||o.y<t.top||o.y>t.top+t.height)return-1;const e=Os(c)&&""!==c,i=h&&h>0;if(!i&&!e)return-1;let n=!1;if(i&&(n=cl(this.vertexes,h,o.x,o.y,!0)),!n&&e&&(n=hl(this.vertexes,o.x,o.y)),n)return 9}return-1}getPath(){const{enableRotate:t,enableEdit:e}=this.container.context.controlsFlags;this.setBoxVisible("visible"),this.setRotationPointVisible(t?"visible":"hidden"),this.setControlPointVisible(e?"visible":"hidden")}getVertexesPosition(){const t=[],e=this.getWorldTransform();let i=!1;return this.controlPointsRenderPaths.length||(this.setControlPointVisible("visible"),i=!0),this.controlPointsRenderPaths.forEach(i=>{t.push(e.transformPoint(i))}),i&&this.setControlPointVisible("hidden"),t}destroy(){this.parentNode&&(this.parentNode.removeChild(this),this.container.controls=null)}}class tc{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Yi(this,"shape",void 0),Yi(this,"referencePoint",void 0),Yi(this,"controlsStyle",void 0),Yi(this,"controlsFlags",void 0),Yi(this,"parsedControlsStyle",void 0),Yi(this,"tempData",{}),Yi(this,"keepAspectRatio",!1),Yi(this,"isInGroup",!1),Yi(this,"isGrouped",!1),Yi(this,"isActive",!1),Yi(this,"isStart",!1),Yi(this,"isHit",!1),Yi(this,"hitControlPoint",-1),Yi(this,"lastHitControlPoint",void 0),Yi(this,"lastHitControlPointCenter",void 0),Yi(this,"lastLocalTransform",void 0),Yi(this,"lastWorldTransform",void 0),Yi(this,"lastWorldPosition",void 0),Yi(this,"lastLocalScale",void 0),Yi(this,"lastOriginWorldPosition",void 0),Yi(this,"lastWorldAngle",void 0),Yi(this,"lastParentWorldAngle",void 0),Yi(this,"lastControlsWorldPosition",void 0),Yi(this,"lastControlsWidth",void 0),Yi(this,"lastControlsHeight",void 0),Yi(this,"lastShareAxisPoint",void 0),Yi(this,"lastShareAxisXPoint",void 0),Yi(this,"lastShareAxisYPoint",void 0),Yi(this,"lastShapeWidth",void 0),Yi(this,"lastShapeHeight",void 0),this.shape=t,this.controlsStyle={...$h,...e},this.controlsFlags={...Zh},this.parseControlsStyle()}initReferenceBox(){if(this.referencePoint)return void this.updateReferenceBox();const{left:t,top:e}=this.shape.getBoundingRect(),i=t-this.shape.style.x,n=e-this.shape.style.y,s=new Tl({style:{x:i,y:n,r:0}});this.shape.appendChild(s),this.referencePoint=s}updateReferenceBox(){if(!this.referencePoint)return;const{left:t,top:e}=this.shape.getBoundingRect(),i=t-this.shape.style.x,n=e-this.shape.style.y;this.referencePoint.updateStyle({x:i,y:n})}getControlVertexes(){const{shape:t}=this,{left:e,top:i,width:n,height:s}=t.getBoundingRect();return[new Oa(e,i),new Oa(e+n,i),new Oa(e+n,i+s),new Oa(e,i+s)]}getScaledControlVertexes(){const{shape:t}=this,{x:e,y:i}=t.getScale(),{left:n,top:s,width:o,height:r}=t.getBoundingRect(),a=o*Math.abs(e)||1,l=r*Math.abs(i)||1;return[new Oa(n,s),new Oa(n+a,s),new Oa(n+a,s+l),new Oa(n,s+l)]}showControls(){this.initReferenceBox();const{shape:t,referencePoint:e}=this,{x:i,y:n}=e.getPosition(),s=t.getAngle(),o=i,r=n;t.controls.setAngle(s),t.controls.setPosition({x:o,y:r})}parseControlsStyle(){if(!this.controlsStyle)return;this.parsedControlsStyle={};const{background:t,border:e,ctrlWidth:i,ctrlHeight:n,ctrlBackground:s,ctrlBorderRadius:o,ctrlBorder:r}=this.controlsStyle,a=e||$h.border,{borderColor:l,borderStyle:h,borderWidth:c}=lo(a),d=da(c).value,u=r||$h.ctrlBorder,{borderColor:p,borderStyle:g,borderWidth:f}=lo(u),m=da(f).value,v=da(i).value,y=ua(""===o?$h.ctrlBorderRadius:o),x="%"===y.unit?y.value/100*v:y.value;this.parsedControlsStyle={background:t||$h.background,ctrlBackground:s||$h.ctrlBackground,ctrlBorderRadius:x,borderColor:l,borderWidth:d,lineDash:"solid"===h?[0,0]:[2*d,d],ctrlWidth:v,ctrlHeight:da(n).value,ctrlBorderColor:p,ctrlBorderWidth:m,ctrlLineDash:"solid"===g?[0,0]:[2*m,m]}}updateControlsFlags(t){const{enableEdit:e,enableRotate:i,enableControl:n,isVisible:s}=t;this.shape.controls&&(Rs(e)&&this.shape.controls.setControlPointVisible(e?"visible":"hidden"),Rs(i)&&this.shape.controls.setRotationPointVisible(i?"visible":"hidden"),Rs(n)&&!n&&this.destroyControls()),Rs(s)&&(this.shape.style.visibility=s?"visible":"hidden"),this.controlsFlags={...this.controlsFlags,...t}}hitShape(){var t;const{shape:e}=this,{shapeType:i,controls:n}=e;this.isHit=!0,this.lastWorldPosition=e.getPosition(),this.lastLocalTransform=e.getLocalTransform(),this.lastWorldTransform=e.getLocalTransform(),this.lastLocalScale=e.getLocalScale(),this.lastControlsWorldPosition=n.getPosition(),this.lastControlsWidth=n.getLength().width,this.lastControlsHeight=n.getLength().height;const s=e.getBoundingRect();this.lastParentWorldAngle=Math.round(Math.abs(null==e||null===(t=e.parentNode)||void 0===t?void 0:t.getAngle())),this.lastWorldAngle=e.getAngle(),this.lastOriginWorldPosition=e.getWorldTransform().transformPoint({x:s.left-e.style.x+s.width/2,y:s.top-e.style.y+s.height/2}),"annotationEllipse"===i&&(this.lastShapeWidth=2*e.parsedStyle.rx.value,this.lastShapeHeight=2*e.parsedStyle.ry.value),Bh(this.shape)&&(this.lastShapeWidth=e.parsedStyle.width.value,this.lastShapeHeight=e.parsedStyle.height.value)}unHitShape(){const{context:t}=this.shape;t.isStart=!1,t.isHit=!1,t.isActive=!1,t.hitControlPoint=-1,Uh(this.shape)&&this.shape.textEditEventHandler.disableEditMode(),Nh(this.shape)&&this.shape.pointEventsHandler.disableEditMode(),Fh(this.shape)&&this.shape.textAssistEventHandler.disableEditMode()}initControls(){const{shape:t}=this,e=this.getControlVertexes(),i=new Qh(t,{vertexes:e});t.controls=i,t.getRootNode().appendChild(i),this.updateControlsFlags(this.controlsFlags)}updateControls(){var t,e;const{shape:i}=this,n=this.getScaledControlVertexes();JSON.stringify(n)!==JSON.stringify(null===(t=i.controls)||void 0===t?void 0:t.vertexes)&&(null===(e=i.controls)||void 0===e||e.update(n))}renderControls(){const{shape:t,isStart:e,isActive:i,controlsFlags:n,isInGroup:s}=this,{useDefaultControls:o}=n,{controls:r}=t;if(!r)return;let a="hidden";o&&(e||i||s)&&(a="visible"),r&&r.setVisible(a),this.updateControls(),this.showControls()}destroyControls(){var t,e;null===(t=this.referencePoint)||void 0===t||t.destroy(),this.referencePoint=null,null===(e=this.shape.controls)||void 0===e||e.destroy(),this.shape.controls=null}getTransform(){const{parentNode:t}=this.shape,e=t instanceof cc&&this.shape.context.isGrouped;e&&t.delete(this.shape,!1);const i={...this.shape.getLocalPosition()},n=this.shape.getLocalAngle(),s={...this.shape.getLocalScale()};return e&&t.add(this.shape),{angle:n,scale:s,position:i}}setTransform(t){if(t){const{scale:e,angle:i,position:n}=t;n&&this.shape.setLocalPosition(n),Ps(i)||this.shape.setLocalAngle(i),Ps(e)||this.shape.setLocalScale(e)}}getCommonStyleConfig(){const{lineCap:t,lineJoin:e,lineDash:i,background:n,opacity:s,miterLimit:o,borderColor:r,borderWidth:a}=this.shape.attributes;return{lineCap:t,lineJoin:e,lineDash:i,background:n,opacity:s,borderColor:r,borderWidth:a,miterLimit:o}}getRealTimeBoundingBox(){this.shape.boundsDirty=!0;const{left:t,top:e,width:i,height:n}=this.shape.getBoundingRect(),s=[],{useDefaultControls:o,enableRotate:r}=this.shape.context.controlsFlags,a=o&&r?5:4;for(let o=0;o<a;o++){let r=t-this.shape.style.x,a=e-this.shape.style.y;1!==o&&2!==o||(r+=i),2!==o&&3!==o||(a+=n),4===o&&(r+=i/2,a-=30/this.shape.getScale().y);const l=new Tl({style:{x:r,y:a,r:0}});this.shape.appendChild(l);const{x:h,y:c}=l.getPosition();s.push({x:h,y:c}),l.destroy()}return tl(s)}}class ec extends Sl{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationArc",...t}),Yi(this,"shapeType","annotationArc"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.eventHandler=new Kh(this),this.context.setTransform(t)}update(){this.updateOrigin(),this.context.updateControls()}getAnnotationConfig(){const t=this.context.getTransform(),{position:e}=t,{r:i,startAngle:n,endAngle:s}=this.attributes;return{type:"annotationArc",style:{x:e.x,y:e.y,r:i,startAngle:n,endAngle:s,...this.context.getCommonStyleConfig()},transform:t}}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}}class ic extends Tl{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationCircle",...t}),Yi(this,"shapeType","annotationCircle"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.eventHandler=new Kh(this),this.context.setTransform(t)}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}getAnnotationConfig(){const t=this.context.getTransform(),{position:e}=t,{r:i}=this.attributes;return{type:"annotationCircle",style:{x:e.x,y:e.y,r:i,...this.context.getCommonStyleConfig()},transform:t}}}class nc extends El{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationEllipse",...t}),Yi(this,"shapeType","annotationEllipse"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.eventHandler=new Kh(this),this.context.setTransform(t)}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}getAnnotationConfig(){const t=this.context.getTransform(),{rx:e,ry:i}=this.parsedStyle,{position:n}=t;return{type:"annotationEllipse",style:{x:n.x-e.value,y:n.y-i.value,width:2*e.value,height:2*i.value,...this.context.getCommonStyleConfig()},transform:t}}}class sc extends _l{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationImage",...t}),Yi(this,"shapeType","annotationImage"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.eventHandler=new Kh(this),this.context.setTransform(t)}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}getAnnotationConfig(){const{x:t,y:e,img:i,opacity:n,visibility:s,width:o,height:r}=this.attributes;return{type:"annotationImage",style:{x:t,y:e,width:o,height:r,img:i,opacity:n,visibility:s},meteData:this.meteData,transform:this.context.getTransform()}}}class oc extends Pl{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationInk",...t}),Yi(this,"shapeType","annotationInk"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.eventHandler=new Kh(this),this.context.setTransform(t),this.update()}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}setUseDouglasPeucker(t){t&&(this.boundsDirty=!0,this.pathDirty=!0)}getAnnotationConfig(){var t;let e=this.attributes.segments;const i=this.context.getTransform(),n=this.getBoundingRect(),{position:s}=i;return(s.x!==n.left||s.y!==n.top)&&(e=[],this.attributes.segments.forEach(t=>{const i=[];t.forEach(t=>{i.push({x:t.x-n.left+s.x,y:t.y-n.top+s.y})}),e.push(i)}),this.context.isGrouped||(this.style.segments=e)),{type:"annotationInk",style:{renderBlendMode:null==this||null===(t=this.style)||void 0===t?void 0:t.renderBlendMode,segments:e,...this.context.getCommonStyleConfig()},transform:i}}}class rc extends Ll{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationRect",...t}),Yi(this,"shapeType","annotationRect"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.eventHandler=new Kh(this),this.context.setTransform(t)}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}getAnnotationConfig(){const t=this.context.getTransform(),{width:e,height:i}=this.attributes,{position:n}=t;return{type:"annotationRect",id:this.id,style:{x:n.x,y:n.y,width:e,height:i,...this.context.getCommonStyleConfig()},transform:t}}getPath(){if(!this.pathDirty)return this.path;const{width:t,height:e,borderWidth:i}=this.parsedStyle,n=.5*((null==i?void 0:i.value)||0),s=n,o=n,r=t.value-2*n,a=e.value-2*n;return this.path=[{x:s,y:o},{x:s+r,y:o},{x:s+r,y:o+a},{x:s,y:o+a}],this.steps=Ka(this.path),this.pathDirty=!1,this.path}getStrokePath(){return this.strokePath=[],[]}}class ac{constructor(t){Yi(this,"shape",void 0),Yi(this,"textCursor",void 0),Yi(this,"textCursorInitCache",void 0),Yi(this,"inputComposition",!1),Yi(this,"startChar",void 0),Yi(this,"startDirection",void 0),Yi(this,"startPoint",void 0),Yi(this,"textRects",[]),Yi(this,"virtualChar",void 0),Yi(this,"isStart",!1),Yi(this,"canvas",void 0),Yi(this,"textClipboard",[]),Yi(this,"startTextContent",void 0),Yi(this,"oldEnableMove",!0),Yi(this,"lineChars",void 0),Yi(this,"flatChars",void 0),Yi(this,"editMode",void 0),Yi(this,"textarea",void 0),Yi(this,"textSelection",[]),this.shape=t,this.calculateCharPosition()}getLineIndexByMoved(t){const{lines:e,lineHeightOffset:i}=this.shape;let n=0;for(let s=0;s<e.length;s++){const{y:o,height:r}=e[s],a=o-r*(1-i);t.y>a&&(n=s)}return n}getLineIndexByPosition(t){const{lines:e,lineHeightOffset:i}=this.shape,{width:n}=this.shape.bounds;for(let s=0;s<e.length;s++){const o=e[s],{x:r,y:a,height:l,widthWithoutLF:h}=o,c=s===e.length-1?1:1+i;if(new Ll({style:{x:r,y:a-l*(1-i),width:Math.max(n,h),height:l*c,borderWidth:1,background:"transparent"}}).isPointInPath(t))return s}return-1}getCharByPosition(t,e){if(-1===e)return null;const{lineChars:i}=this,{lineHeightOffset:n}=this.shape,s=i[e];for(let e=0;e<s.length;e++){const o=s[e],{x:r,y:a,charWidth:l,charHeight:h}=o,c=o.lineIndex===i.length-1?1:1+n;if(new Ll({style:{x:r,y:a-h*(1-n),width:l,height:h*c,borderWidth:1,background:"transparent"}}).isPointInPath(t))return o}return null}getCharAndDirection(t){const e=this.getLineIndexByPosition(t);let i,n=1;if(-1===e)return i=this.flatChars[this.flatChars.length-1],n=1,{char:i,direction:n};const s="textBox"===this.shape.textType;if(i=this.getCharByPosition(t,e),i){const{x:e,charWidth:s}=i;n=t.x<e+s/2?0:1}else{const o=this.lineChars[e];i=o[o.length-1],n=1,s&&t.x<o[0].x&&(i=o[0],n=0)}return"\r"!==i.text&&"\n"!==i.text&&"\r\n"!==i.text||(n=0),0===n&&0!==i.indexInLine&&(i=this.lineChars[i.lineIndex][i.indexInLine-1],n=1),{char:i,direction:n}}createCursor(t,e,i,n){if(!this.textCursor){const s=document.createElement("div");return s.className="ddv-annotation-cursor",s.style.left=t-.5+"px",s.style.top=`${e}px`,s.style.transform=`rotate(${i}deg)`,s.style.width="1px",s.style.height=`${n}px`,this.canvas.parentNode.appendChild(s),void(this.textCursor=s)}this.textCursor.style.left=t-.5+"px",this.textCursor.style.top=`${e}px`,this.textCursor.style.height=`${n}px`,this.textCursor.style.transform=`rotate(${i}deg)`,this.textCursor.style.animation="none",this.textCursor.offsetWidth,this.textCursor.style.animation=""}showTextCursor(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const{lineHeightOffset:n}=this.shape,s=(t,e)=>{const{x:i,y:s,charWidth:o,charHeight:r,lineIndex:a}=t,l=e?i+o:i,h=s-r*(1-n),c=a>=this.lineChars.length-1?1:1+n;return new Ll({style:{x:l-this.shape.style.x,y:h-this.shape.style.y,borderWidth:"1px",height:r*c}})},o=t=>{this.shape.appendChild(t);const e=this.shape.getScale().y,i=t.getAngle();t.setAngle(0);const{x:n,y:s}=t.getPosition();t.destroy(),this.createCursor(n,s,i,t.parsedStyle.height.value*e)};if(!this.editMode)return void(this.textCursor&&this.hideTextCursor());const{flatChars:r,shape:a}=this;if(!r.length&&this.virtualChar){const{fontSize:t}=this.shape.freeTextContentStyle,e=da(t).value;if(e!==this.virtualChar.charHeight){const{borderOffset:t,padding:i}=this.shape,{y:s}=this.shape.style;this.virtualChar.charHeight=e,this.virtualChar.y=s+t+i+e*(1-n)}return o(s(this.virtualChar,1)),void(this.textCursorInitCache={char:{totalIndex:0},isBack:1})}let l=r[t];if(Ps(t)&&(l=r[0],e=0),!r[t])return;"justify"===a.style.textAlign&&"textBox"===a.textType&&" "===l.text&&e&&r[l.totalIndex+1]&&(l=r[l.totalIndex+1],e=0);const h=r[l.totalIndex+1];let c;Wh(l.text)&&e&&h&&(l=h,e=0),c=Wh(l.text)&&e&&!h?s(this.virtualChar,1):s(l,e),o(c),this.startChar=l,this.startDirection=e,this.textCursorInitCache={char:l,isBack:e},i&&this.shape.hooks.selectTextChars.emit({startChar:l,endChar:l,isBack:!!e,needUpdate:!1})}moveTextCursor(t){const{textSelection:e}=this;let i,n;if(2===e.length){const[s,o]=e;switch(t){case"up":case"left":i=s.totalIndex,n=0;break;default:i=o.totalIndex,n=1}return this.hideTextSelection(),this.shape.hooks.reRenderText.emit(),void this.showTextCursor(i,n)}const s=this.flatChars,o=s.length,{startChar:r,startDirection:a}=this;if(r){if("left"===t){const t=a?r.totalIndex-1:r.totalIndex-2;i=t>=0?t:0,n=t>=0?1:0}else if("right"===t){const t=a?r.totalIndex+1:r.totalIndex;i=t>o-1?o-1:t,n=1}else{const{x:e,charWidth:o,lineIndex:l}=r;if(0===l&&"up"===t)i=0,n=0;else if(l===this.lineChars.length-1&&"down"===t)i=s.length-1,n=1;else{const s=a?e+o:e,r="up"===t?this.lineChars[l-1]:this.lineChars[l+1];i=r[0].totalIndex,n=0,r.forEach(t=>{s>t.x+o/2&&!Wh(t.text)&&(i=t.totalIndex,n=1)})}}this.showTextCursor(i,n)}}hideTextCursor(){this.textCursor&&(this.textCursor.remove(),this.textCursor=null)}showTextSelection(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=[],{lines:s,parsedStyle:o,textType:r,lineHeightOffset:a}=this.shape;if(this.hideTextSelection(),this.textSelection=[t,e],!t||!e)return;const l=["right","justify"].includes(o.textAlign)&&"textBox"===r;if(t.y===e.y){const i=Wh(t.text),o=Wh(e.text);if(i&&o)return;const r=t.x===e.x?t.charWidth:o?e.x-t.x:e.x-t.x+e.charWidth;n.push({left:t.x,top:t.y,lineIndex:t.lineIndex,width:r,height:s[t.lineIndex].height})}else{const i=this.shape.getTextAlignOffset(s[t.lineIndex]),{x:o,height:r}=s[t.lineIndex],a=l?s[t.lineIndex].widthWithoutLF:s[t.lineIndex].width;if(n.push({left:t.x,top:t.y,lineIndex:t.lineIndex,width:o+a+i-t.x,height:r}),e.lineIndex-t.lineIndex>1)for(let i=t.lineIndex+1;i<e.lineIndex;i++){const{x:t,y:e,height:o}=s[i],r=l?s[i].widthWithoutLF:s[i].width,a=this.shape.getTextAlignOffset(s[i]);n.push({left:t+a,top:e,width:r,height:o,lineIndex:i})}const h=this.shape.getTextAlignOffset(s[e.lineIndex]),{x:c,y:d,height:u}=s[e.lineIndex],p=l&&Wh(e.text)?0:e.charWidth;n.push({left:c+h,top:d,width:e.x+p-c-h,height:u,lineIndex:e.lineIndex})}const{x:h,y:c}=this.shape.style;this.hideTextCursor(),n.forEach(t=>{const e=t.lineIndex===this.lineChars.length-1?1:1+a,i=new Ll({style:{x:t.left-h,y:t.top-c-t.height*(1-a),width:t.width,height:t.height*e,background:"rgba(0, 123, 255, 0.5)"}});this.shape.appendChild(i),this.textRects.push(i)}),this.shape.hooks.selectTextChars.emit({startChar:t,endChar:e,isBack:!0,needUpdate:i})}hideTextSelection(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.textRects.forEach(t=>{t.destroy()}),this.textSelection=[],this.textRects=[],t){const{char:t,isBack:e}=this.textCursorInitCache;this.showTextCursor(t.totalIndex,e)}}addText(t,e,i){if(!i||""===i)return;if(!t){const t={...this.shape.freeTextContentStyle,content:i};return this.shape.context.updateControlsFlags({useDefaultControls:!1}),this.shape.updateStyle({textContents:[t]}),this.showTextCursor(i.length-1,1),void this.shape.hooks.textContentUpdatedByChar.emit()}const n=_s(this.shape.style.textContents),{freeContentIndex:s,indexInFreeContent:o}=t,r=n[s];if(!r)return;const a=(null==r?void 0:r.content)||"",l=lc(this.shape.freeTextContentStyle,r),h=()=>({...this.shape.freeTextContentStyle,content:i});if(e&&o===a.length-1)l?r.content+=i:n.splice(s+1,0,h());else if(e||o)if(l){const t=0===e?o:o+1;r.content=a.slice(0,t)+i+a.slice(t)}else{const t=[],i=a.slice(0,e?o+1:o),l=a.slice(e?o+1:o);i&&t.push({...r,content:i}),t.push(h()),l&&t.push({...r,content:l}),n.splice(s,1,...t)}else if(s){const t=n[s-1];lc(this.shape.freeTextContentStyle,t)?n[s-1].content+=i:n.splice(s,0,h())}else l?r.content=i+((null==r?void 0:r.content)||""):n.unshift(h());this.shape.updateStyle({textContents:[...n]}),this.shape.hooks.textContentUpdatedByChar.emit();const{char:c,isBack:d}=this.textCursorInitCache;d?this.showTextCursor(c.totalIndex+i.length,1):this.showTextCursor(c.totalIndex+i.length-1,1)}deleteText(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=_s(this.shape.style.textContents);if(!i.length)return;let n=0;if(2===this.textSelection.length){const[t,e]=this.textSelection;if(t.freeContentIndex===e.freeContentIndex){const n=i[t.freeContentIndex];n.content=Hh(n.content,t.indexInFreeContent,e.indexInFreeContent)}else{const n=i[t.freeContentIndex],s=i[e.freeContentIndex];n.content=n.content.substring(0,t.indexInFreeContent),s.content=s.content.substring(e.indexInFreeContent+1);for(let n=t.freeContentIndex+1;n<e.freeContentIndex;n++)i[n].content=""}n=t.totalIndex-1}else{const{startChar:t,startDirection:o}=this;if(!t)return;let r=o?t:this.flatChars[t.totalIndex-1];if(e){var s;const t=Ps(null===(s=r)||void 0===s?void 0:s.totalIndex)?0:r.totalIndex+1;r=this.flatChars[t]}if(!r)return;const{freeContentIndex:a,indexInFreeContent:l}=r,h=i[a];if(!h.color)return;h.content=Hh(h.content,l,l),n=r.totalIndex-1}this.hideTextSelection(),this.shape.updateStyle({textContents:[...i]}),t&&this.shape.hooks.textContentUpdatedByChar.emit(),-1===n?this.showTextCursor(0,0,!1):this.showTextCursor(n,1,!1),this.shape.hooks.reRenderText.emit()}copyText(){if(!this.textSelection.length)return;this.textClipboard=[];const{textContents:t}=this.shape.style,[e,i]=this.textSelection,n=[],s=e.freeContentIndex,o=i.freeContentIndex;if(s===o){const o=t[s],r=o.content.slice(e.indexInFreeContent,i.indexInFreeContent+1);n.push({...o,content:r})}else for(let r=s;r<=o;r++){const a={...t[r]},l=a.content;r===s?a.content=l.slice(e.indexInFreeContent):r===o&&(a.content=l.slice(0,i.indexInFreeContent+1)),n.push({...a})}this.textClipboard=[...n],function(t){let e="";t.forEach(t=>{e+=t.content});try{navigator.clipboard.writeText(e)}catch(t){}}(n)}pasteText(){this.textSelection.length&&this.deleteText(!1);const{isBack:t,char:e}=this.textCursorInitCache,{textContents:i}=this.shape.style,n=t?e:this.flatChars[e.totalIndex-1];let s=0,o=(null==n?void 0:n.totalIndex)||-1;if(this.textClipboard.forEach(t=>{s+=t.content.length}),n)if(this.flatChars.length){const t=i[e.freeContentIndex];if(t.content.length===n.indexInFreeContent+1)i.splice(e.freeContentIndex+1,0,..._s(this.textClipboard)),this.shape.updateStyle({textContents:[...i]});else{const{content:s}=t,{indexInFreeContent:o}=n,r=[{...t,content:s.slice(0,o+1)},..._s(this.textClipboard),{...t,content:s.slice(o+1)}];i.splice(e.freeContentIndex,1,...r),this.shape.updateStyle({textContents:[...i]})}}else this.shape.updateStyle({textContents:_s(this.textClipboard)}),o=-1;else i.unshift(..._s(this.textClipboard)),this.shape.updateStyle({textContents:i});this.showTextCursor(o+s,1),this.shape.hooks.textContentUpdatedByChar.emit()}selectAllText(){if(!this.flatChars.length)return;const t=this.flatChars[0],e=this.flatChars[this.flatChars.length-1];this.showTextSelection(t,e),this.shape.hooks.reRenderText.emit()}updateTextSelection(){if(!this.textSelection.length)return;const[t,e]=this.textSelection,i=this.flatChars[t.totalIndex],n=this.flatChars[e.totalIndex];this.showTextSelection(i,n,!0),this.shape.hooks.reRenderText.emit()}calculateCharPosition(){const{borderOffset:t,padding:e,lineHeightOffset:i,lines:n}=this.shape,s=[];let o=0,r=0,a=0,l=0;n.forEach((t,e)=>{const i=t.height,n=[],h=this.shape.getTextAlignOffset(t),c=(t,s,a,h,c)=>{const d={text:t,x:s,y:a,charWidth:h,charHeight:i,freeContentIndex:c,lineIndex:e,indexInLine:r,indexInFreeContent:o,totalIndex:l};n.push(d)};r=0,t.words.forEach(e=>{const{wordWidth:i,freeContentIndex:n,x:s,text:d}=e;if(n!==a&&(o=0,a=n),1===e.text.length)c(d,s+h,t.y,i,n),l+=1,r+=1,o+=1;else{let i=e.x+h;for(let s=0;s<d.length;s++){const a=d.charAt(s),h=Wl(a,e.style);c(a,i,t.y,h,n),i+=h,l+=1,o+=1,r+=1}e.text.length!==e.originText.length&&(o+=e.originText.length-e.text.length)}}),s.push(n)});const h=this.shape.getTextAlignOffset();if(this.flatChars=s.flat(),this.lineChars=s,this.virtualChar=null,!n.length){const{x:n,y:s,textAlign:o}=this.shape.parsedStyle,{fontSize:r}=this.shape.freeTextContentStyle,a=da(r).value,l="right"===o?n+e+h:n+t+e+h;return void(this.virtualChar={x:l,y:s+t+e+a*(1-i),charWidth:1,charHeight:a,lineIndex:0})}const c=this.flatChars[this.flatChars.length-1];Wh(c.text)&&(this.virtualChar={x:this.shape.lines[0].x+h,y:c.y+n[c.lineIndex].height*(1+i),charWidth:1,charHeight:c.charHeight,lineIndex:c.lineIndex+1})}updateCursor(){if(!this.textCursor||!this.textCursorInitCache)return;const{char:t,isBack:e}=this.textCursorInitCache;this.showTextCursor(t.totalIndex,e)}enableEditMode(t,e){if(this.editMode)return;"freeTextWriter"===this.shape.textType&&(this.shape.pathDirty=!0,this.shape.boundsDirty=!0,this.shape.calculateTextLines(),this.shape.hooks.reRenderText.emit()),this.calculateCharPosition(),this.editMode=!0,this.canvas=e;let i=!1;if("textBox"===this.shape.textType){const{totalTextHeight:t,textMaxWidth:e}=this.shape,{height:i,width:n}=this.shape.parsedStyle;(t!==i.value||e>n.value)&&(this.shape.boundsDirty=!0,this.shape.pathDirty=!0)}if(this.flatChars.length){const e=Oh(this.shape,t),i=this.getCharAndDirection(e),{char:n,direction:s}=i;this.startChar=n,this.startDirection=s,this.showTextCursor(n.totalIndex,s)}else this.showTextCursor(void 0,void 0),"freeTextWriter"===this.shape.textType&&(i=!0);this.oldEnableMove=this.shape.context.controlsFlags.enableMove,this.shape.context.updateControlsFlags({useDefaultControls:i,enableMove:!1}),this.openTextarea(t),this.resetStartTextContent(),this.shape.hooks.enableTextEditMode.emit()}disableEditMode(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.editMode){if(this.textClipboard=[],this.editMode=!1,this.hideTextCursor(),this.hideTextSelection(),this.shape.lastIsBack=null,this.shape.lastSelectedEndChar=null,this.shape.context.updateControlsFlags({useDefaultControls:!0,enableMove:this.oldEnableMove}),this.textarea&&(this.textarea.blur(),this.textarea.remove()),"textBox"===this.shape.textType){const{totalTextHeight:t,textMaxWidth:e,maxEditWidth:i}=this.shape,{height:n,width:s}=this.shape.parsedStyle;(t!==n.value||e>s.value||i>s.value)&&(this.shape.boundsDirty=!0,this.shape.pathDirty=!0,this.shape.updateOrigin(),this.shape.hooks.reRenderText.emit())}t||(this.shape.maxEditWidth=0,this.shape.hooks.disableTextEditMode.emit(),this.emitTextContentUpdated())}}editStartHandler(t){if(!this.editMode)return;if(!this.flatChars.length)return void this.showTextCursor(void 0,void 0);const e=Oh(this.shape,t),i=this.getCharAndDirection(e);this.hideTextSelection();const{char:n,direction:s}=i;this.showTextCursor(n.totalIndex,s),this.isStart=!0,this.startChar=n,this.startDirection=s,this.startPoint=e,this.shape.hooks.reRenderText.emit()}editMoveHandler(t){if(!this.editMode||!this.isStart)return;const{lineChars:e}=this,i=Oh(this.shape,t),n=this.getLineIndexByMoved(i);let{startChar:s,startDirection:o}=this,r=null;const a=e[n],l=n===this.startChar.lineIndex?i.x>this.startPoint.x:i.y>this.startPoint.y,{lineIndex:h,indexInLine:c}=this.startChar;if(!this.startDirection&&!l){if(0===s.totalIndex)return void this.hideTextSelection(!0);const t=s.lineIndex===e.length-1;if(t&&i.y<this.startPoint.y)s=this.flatChars[s.totalIndex-1],o=1;else if(t)return void this.hideTextSelection(!0)}if(l&&o&&(s=e[h][c+1],o=0,!s))return void this.hideTextSelection(!0);if(l&&i.x<a[0].x+a[0].charWidth/2&&s.lineIndex!==n){const t=e[n-1];return r=t[t.length-1],void this.showTextSelection(s,r)}if(l)a.forEach((t,e)=>{const{x:n,charWidth:s}=t;i.x>n+s/2&&(r=a[e])});else for(let t=a.length-1;t>=0;t--){const{x:e,charWidth:n}=a[t];e+n/2>i.x&&(r=a[t])}if(!r)return void this.hideTextSelection(!0);const{lineIndex:d,indexInLine:u}=s,{lineIndex:p,indexInLine:g}=r;l&&d===p&&u===g+1||!l&&d===p&&u===g-1?this.hideTextSelection(!0):l?this.showTextSelection(s,r):this.showTextSelection(r,s)}editEndHandler(){this.isStart=!1}editClickHandler(t,e){this.editMode&&(this.canvas=e,this.openTextarea(t))}openTextarea(t){if(this.editMode){if(this.textarea)this.canvas.parentNode.appendChild(this.textarea);else{const t=document.createElement("textarea");t.className="ddv-annotation-textarea",this.canvas.parentNode.appendChild(t),this.textarea=t,t.addEventListener("input",t=>{this.inputComposition||this.textareaInput(t)},!1),t.addEventListener("compositionstart",t=>this.textareaCompositionstart(t),!1),t.addEventListener("compositionend",t=>{this.inputComposition=!1,this.textareaInput(t)},!1),t.addEventListener("keydown",t=>this.textareaKeydown(t),!1),t.addEventListener("paste",t=>this.textareaPaste(t),!1)}t&&(this.textarea.style.left="50%",this.textarea.style.top="50%"),this.textarea.value="",this.textarea.focus()}}destroyTextarea(){this.textarea&&(this.textarea.remove(),this.textarea=null)}emitTextContentUpdated(){(function(t,e){let i="",n="";for(let e=0;e<t.length;e++)i+=t[e].content;for(let t=0;t<e.length;t++)n+=e[t].content;return i===n})(this.startTextContent,this.shape.style.textContents)||(this.startTextContent=_s(this.shape.style.textContents),this.shape.hooks.textContentUpdated.emit())}resetStartTextContent(){this.startTextContent=_s(this.shape.style.textContents)}textareaInput(t){const e=this.textarea.value;if(2===this.textSelection.length&&this.deleteText(!1),this.flatChars.length){const{char:t,isBack:i}=this.textCursorInitCache;this.addText(t,i,e)}else this.addText(void 0,void 0,e);this.textarea.value=""}textareaCompositionstart(t){this.inputComposition=!0}textareaKeydown(t){if(this.inputComposition||"Backspace"!==t.key||8!==t.keyCode)if(this.inputComposition||"Delete"!==t.key)switch(po(t)&&("c"===t.key||"C"===t.key?this.copyText():"x"===t.key||"X"===t.key?(this.copyText(),this.textSelection.length&&this.deleteText()):("v"!==t.key&&"V"!==t.key||!this.textClipboard.length)&&("z"===t.key||"Z"===t.key?(t.preventDefault(),t.stopPropagation()):"a"!==t.key&&"A"!==t.key||this.selectAllText())),t.key){case"ArrowLeft":this.moveTextCursor("left");break;case"ArrowRight":this.moveTextCursor("right");break;case"ArrowUp":this.moveTextCursor("up");break;case"ArrowDown":this.moveTextCursor("down")}else this.deleteText(!0,!0);else this.deleteText()}textareaPaste(t){var e;const i=null===(e=t.clipboardData)||void 0===e?void 0:e.getData("text/plain");let n="";this.textClipboard.length&&(n=this.textClipboard.map(t=>t.content).join(""),i!==n?this.textClipboard=[]:(t.preventDefault(),this.pasteText()))}}function lc(t,e){return t.color===e.color&&t.fontFamily===e.fontFamily&&t.fontSize===e.fontSize&&t.fontStyle===e.fontStyle&&t.fontWeight===e.fontWeight&&t.lineThrough===e.lineThrough&&t.underline===e.underline}class hc extends Vl{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"textBox",i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Xh;super({type:"annotationFreeText",id:t.id,style:{freeTextType:e,...t.style}}),Yi(this,"lastSelectedEndChar",void 0),Yi(this,"lastIsBack",void 0),Yi(this,"shapeType","annotationFreeText"),Yi(this,"textEditEventHandler",void 0),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),Yi(this,"freeTextContentStyle",void 0),Yi(this,"inputModeTimer",void 0),Yi(this,"maxEditWidth",0),Yi(this,"hooks",{reRenderText:zs(),selectTextChars:zs(),enableTextEditMode:zs(),disableTextEditMode:zs(),textContentUpdated:zs(),textContentUpdatedByChar:zs(),positionUpdated:zs()}),this.freeTextContentStyle=i,this.init(t.transform,t.selectableStyle),"freeTextWriter"===this.textType&&this.context.updateControlsFlags({enableEdit:!1,enableRotate:!1}),this.hooks.selectTextChars.on(t=>{const e=t.endChar;if(this.isSameChar(e,this.lastSelectedEndChar)&&t.isBack===this.lastIsBack&&!t.needUpdate)return;let i=e.freeContentIndex;e.indexInFreeContent||!e.freeContentIndex||t.isBack||(i-=1);const n=this.style.textContents[i];this.lastSelectedEndChar=e,this.lastIsBack=t.isBack,this.freeTextContentStyle={...n,content:this.freeTextContentStyle.content}})}get isEditMode(){var t;return null===(t=this.textEditEventHandler)||void 0===t?void 0:t.editMode}get hasSelectedChars(){var t;return(null===(t=this.textEditEventHandler)||void 0===t?void 0:t.textSelection.length)>0}init(t,e){this.context=new tc(this,e),this.textEditEventHandler=new ac(this),this.eventHandler=new Kh(this),this.context.setTransform(t)}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.textEditEventHandler.disableEditMode(!0),this.textEditEventHandler.destroyTextarea(),this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}getAnnotationConfig(){const t="textBox"===this.textType?"annotationTextBox":"annotationFreeText",e=this.getPosition();this.updateOrigin(),this.setPosition({...e});const i=this.context.getTransform(),{position:n}=i,{width:s,height:o,textContents:r}=this.attributes,a={type:t,style:{x:n.x,y:n.y,textContents:_s(r),textAlign:this.style.textAlign,...this.context.getCommonStyleConfig(),width:s},transform:i};return"textBox"===this.textType&&(a.style.height=o),a}calculateTotalHeight(){var t,e;const i=da((null===(t=this.freeTextContentStyle)||void 0===t?void 0:t.fontSize)||16);if(null!==(e=this.lines)&&void 0!==e&&e.length)super.calculateTotalHeight();else if("freeTextWriter"===this.textType)this.totalTextHeight=i.value+2*this.borderOffset;else{const{height:t}=this.parsedStyle;this.totalTextHeight=t.value>i.value+2*this.borderOffset?t.value:i.value+2*this.borderOffset+2*this.padding}}getBoundingRect(){var t;if(!this.boundsDirty)return this.bounds;const{x:e,y:i}=this.parsedStyle;if("freeTextWriter"===this.textType&&(null===(t=this.lines)||void 0===t||!t.length)){var n;const t=da((null===(n=this.freeTextContentStyle)||void 0===n?void 0:n.fontSize)||16);return this.boundsDirty=!1,this.bounds={left:e,top:i,width:Wl("  ",{...this.freeTextContentStyle,fontSize:t}),height:t.value+2*this.padding},this.bounds}return super.getBoundingRect(),"textBox"===this.textType&&this.isEditMode&&(this.bounds.height=this.totalTextHeight,this.textMaxWidth>this.bounds.width&&(this.bounds.width=this.textMaxWidth+2*this.borderOffset+2*this.padding),this.maxEditWidth=Math.max(this.maxEditWidth,this.bounds.width),this.maxEditWidth>this.bounds.width&&(this.bounds.width=this.maxEditWidth)),this.bounds}updateFreeTextContentStyle(t){this.freeTextContentStyle=t,this.textEditEventHandler.updateCursor();const{flatChars:e}=this.textEditEventHandler;this.isEditMode&&!e.length&&(this.pathDirty=!0,this.boundsDirty=!0,this.calculateTotalHeight(),this.hooks.reRenderText.emit(),this.hooks.enableTextEditMode.emit())}focusTexture(){const t=Ms();this.isEditMode&&this.textEditEventHandler.textarea&&(t||this.textEditEventHandler.textarea.focus())}updateCursor(){this.textEditEventHandler.updateCursor()}isSameChar(t,e){return!(!t||!e)&&t.charHeight===e.charHeight&&t.charWidth===e.charWidth&&t.freeContentIndex===e.freeContentIndex&&t.indexInFreeContent===e.indexInFreeContent&&t.indexInLine===e.indexInLine&&t.text===e.text&&t.totalIndex===e.totalIndex}}class cc extends Ll{constructor(t){super({id:t,type:"annotationGroup",style:{visibility:"hidden",background:"transparent",borderColor:"transparent"}}),Yi(this,"shapeType","annotationGroup"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),Yi(this,"parent",void 0),Yi(this,"shapes",[]),Yi(this,"clickedShape",null),Yi(this,"state",!1),Yi(this,"groupMode",0),this.context=new tc(this),this.eventHandler=new Kh(this),this.eventHandler.isHit=this.isHit.bind(this),this.groupMode?this.context.updateControlsFlags({enableEdit:!1}):this.context.updateControlsFlags({useDefaultControls:!1})}isHit(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{context:i,parsedStyle:n}=this;let{controls:s}=this;if(!this.state||"hidden"===n.visibility||!i.controlsFlags.enableControl)return this.clickedShape=null,-1;s||(i.initControls(),i.renderControls(),s=this.controls);let o=-1;if(this.groupMode)o=s.checkHitArea(t.x,t.y);else for(let e=0;e<this.shapes.length;e++)if(this.shapes[e].controls||(this.shapes[e].context.initControls(),this.shapes[e].context.renderControls()),this.shapes[e].controls.checkHitArea(t.x,t.y)>=0){this.clickedShape=this.shapes[e],o=9;break}return o<0&&e?(this.clickedShape=null,i.unHitShape(),this.context.destroyControls(),-1):o}init(){this.style.visibility="visible",this.parent.appendChild(this),this.shapes.forEach(t=>{t instanceof hc&&t.isEditMode&&t.textEditEventHandler.disableEditMode(),this.appendChild(t),t.context.isGrouped=!0}),this.update(),this.context.initControls()}add(t){const e=(Array.isArray(t)?t:[t]).filter(t=>"hidden"!==t.parsedStyle.visibility&&!this.shapes.includes(t));if(0!==e.length){if(!this.parent&&e.length>0&&(this.parent=e[0].parentNode),e.forEach(t=>{t.context.isInGroup=!0,this.shapes.push(t)}),this.state){const t=[];for(let e=0;e<this.shapes.length;e++)t.push(this.shapes[e].getWorldTransform().clone());for(let t=0;t<e.length;t++){const i=e[t];i instanceof hc&&i.isEditMode&&i.textEditEventHandler.disableEditMode(),i.context.isGrouped=!0,this.appendChild(i),this.groupMode||this.showAllControls(i)}const i=this.getWorldTransform().inverse();for(let e=0;e<this.shapes.length;e++){const n=i.multiply(t[e]);this.shapes[e].setLocalTransform(n)}this.update()}this.shapes.length>=2&&!1===this.state&&(this.state=!0,this.init())}}update(){let t=-1/0,e=1/0,i=-1/0,n=1/0,s=!0;const o=[];for(let r=0;r<this.shapes.length;r++){const a=this.shapes[r];a.controls||a.context.initControls(),a.context.renderControls(),this.groupMode&&a.context.unHitShape(),a.context.controlsFlags.enableMove||(s=!1);const l=a.controls.getVertexesPosition();for(let s=0;s<l.length;s++){const{x:o,y:r}=l[s];o>t&&(t=o),o<e&&(e=o),r>i&&(i=r),r<n&&(n=r)}o.push(a.getWorldTransform().clone())}this.updateStyle({x:0,y:0,width:t-e,height:i-n}),this.context.updateControlsFlags({enableMove:s}),this.setAngle(180===this.parent.getAngle()?179.99:0),this.setLocalScale(1,1);const{x:r,y:a}=this.getScale();this.scale(1/Math.abs(r),1/Math.abs(a)),this.setPosition({x:e,y:n}),this.updateOrigin(),this.context.updateControls();const l=this.getWorldTransform().inverse();for(let t=0;t<this.shapes.length;t++){const e=l.multiply(o[t]);this.shapes[t].setLocalTransform(e)}}delete(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this.parent||!this.shapes.includes(t))return;const i=t.getWorldTransform().clone();this.parent.appendChild(t);const n=this.parent.getWorldTransform().inverse().multiply(i);t.setLocalTransform(n),t.context.isInGroup=!1,t.context.isGrouped=!1,t.context.isActive=!1,t.context.destroyControls(),"freeTextWriter"!==(null==t?void 0:t.textType)&&(t.context.updateControlsFlags({enableRotate:!Rs(t.context.tempData.enableRotate)||t.context.tempData.enableRotate}),delete t.context.tempData.enableRotate),Nh(t)&&t.pointEventsHandler.disableEditMode(),this.shapes.splice(this.shapes.indexOf(t),1),e&&this.update(),0===this.shapes.length&&this.clear()}clear(){const{length:t}=this.shapes;for(let e=t-1;e>=0;e--)this.delete(this.shapes[e],!1);this.context.destroyControls(),this.reset()}reset(){this.parent&&this.parent.removeChild(this),this.updateStyle({x:0,y:0,width:0,height:0}),this.resetLocalTransform(),this.shapes=[],this.parent=null,this.state=!1,this.style.visibility="hidden"}destroy(){const{length:t}=this.shapes;for(let e=t-1;e>=0;e--)this.shapes[e].destroy();this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy(),this.shapes=[],this.state=!1,this.parent=null,this.style.visibility="hidden",this.updateStyle({x:0,y:0,width:0,height:0})}showAllControls(t){if(!this.state)return;if(this.groupMode)return;const e=t=>{Nh(t)&&t.pointEventsHandler.enableEditMode(),t.controls||t.context.initControls(),t.context.controlsFlags.enableRotate&&(t.context.tempData.enableRotate=t.context.controlsFlags.enableRotate,t.context.updateControlsFlags({enableRotate:!1})),t.context.isActive=!0,t.context.renderControls()};t?e(t):this.shapes.forEach(t=>{e(t)})}getAnnotationConfig(){return{type:"annotationGroup"}}}class dc extends Ll{constructor(t){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),Yi(this,"shapeType","annotationLineControls"),Yi(this,"container",void 0),this.container=t}get isVisible(){return"hidden"!==this.parsedStyle.visibility&&Gh(null==this?void 0:this.container)}checkHitPoint(t,e){const i=this.getWorldTransform().inverse().transformPoint({x:t,y:e}),n={x:i.x+this.style.x,y:i.y+this.style.y},{ctrlWidth:s,ctrlHeight:o,ctrlBorderWidth:r}=this.container.context.parsedControlsStyle,a=(r+(Ms()?10:0)||0)/2,l=this.container.baseRenderPath||[],{x:h,y:c}=this.container.getScale();for(let t=0;t<l.length;t++){const e=l[t];if(dl(e.x*h-s/2-a,e.y*c-o/2-a,s+2*a,o+2*a,n.x,n.y))return t}return-1}}class uc{constructor(t){Yi(this,"shape",void 0),Yi(this,"editMode",void 0),Yi(this,"hitIndex",-1),Yi(this,"hitPointPos",void 0),Yi(this,"startPoint",void 0),Yi(this,"controlsBox",void 0),this.shape=t}initLineControls(){const{shape:t}=this;t.updatePoints();const{x:e,y:i}=this.shape.getScale(),{borderColor:n,borderWidth:s,lineDash:o,background:r}=t.context.parsedControlsStyle,a=this.shape.getBoundingRect();this.controlsBox=new dc(this.shape,{style:{width:a.width*e,height:a.height*i,borderColor:n,borderWidth:s,background:r,lineDash:o}}),this.controlsBox.setAngle(this.shape.getAngle()),this.controlsBox.setPosition(this.shape.getPosition()),this.shape.getRootNode().appendChild(this.controlsBox)}isHitPoint(t){return this.editMode&&this.shape.context.controlsFlags.enableEdit?this.controlsBox.checkHitPoint(t.x,t.y):-1}updateLineControls(){if(!this.controlsBox)return;if(!this.editMode)return;const{x:t,y:e}=this.shape.getScale(),i=this.shape.getBoundingRect();this.controlsBox.updateStyle({width:i.width*t,height:i.height*e}),this.controlsBox.setAngle(this.shape.getAngle()),this.controlsBox.setPosition(this.shape.getPosition()),this.shape.controls&&(this.shape.context.lastControlsWidth=this.shape.controls.getLength().width,this.shape.context.lastControlsHeight=this.shape.controls.getLength().height)}destroyLineControls(){var t;null===(t=this.controlsBox)||void 0===t||t.destroy(),this.controlsBox=null}enableEditMode(){const{shape:t}=this;t.path||this.shape.getPath(),t.path.length>t.pointerLimitCount||(this.editMode||this.initLineControls(),this.editMode=!0,t.context.isHit=!0,t.controls&&(t.context.lastControlsWidth=t.controls.getLength().width,t.context.lastControlsHeight=t.controls.getLength().height))}disableEditMode(){this.destroyLineControls(),this.editMode=!1}editStartHandler(t){if(!this.editMode)return;this.hitIndex=-1;const e=this.isHitPoint(t);-1!==e&&(this.hitIndex=e,this.hitPointPos={...this.shape.path[this.hitIndex]}),this.startPoint=t,this.shape.context.lastLocalTransform=this.shape.getLocalTransform()}editMoveHandler(t){if(!this.editMode||-1===this.hitIndex)return;const{shape:e}=this,i="annotationLine"===e.shapeType,n=i?[...e.path]:[...e.parsedStyle.points],s=Oh(e,t);n[this.hitIndex]=s,i?e.updateStyle({startPoint:{x:n[0].x,y:n[0].y},endPoint:{x:n[1].x,y:n[1].y}}):e.style.points=n,this.updateLineControls()}editEndHandler(){this.editMode&&this.shape.updatePoints()}}class pc extends kl{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationPolygon",...t}),Yi(this,"shapeType","annotationPolygon"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),Yi(this,"pointEventsHandler",void 0),Yi(this,"pointerLimitCount",200),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.pointEventsHandler=new uc(this),this.eventHandler=new Kh(this),this.context.setTransform(t),this.parsedStyle.points.length<this.pointerLimitCount&&this.context.updateControlsFlags({useDefaultControls:!1,enableRotate:!1})}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy(),this.pointEventsHandler.destroyLineControls()}getAnnotationConfig(){const t=this.context.getTransform(),e=this.getBoundingRect(),{position:i}=t,n=i.x!==e.left||i.y!==e.top;let s=this.attributes.points;return n&&(s=[],this.attributes.points.forEach(t=>{s.push({x:t.x-e.left+i.x,y:t.y-e.top+i.y})})),{type:"annotationPolygon",style:{points:s,...this.context.getCommonStyleConfig()},transform:t}}}class gc extends Ml{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationPolyline",...t}),Yi(this,"shapeType","annotationPolyline"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),Yi(this,"pointEventsHandler",void 0),Yi(this,"pointerLimitCount",200),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.pointEventsHandler=new uc(this),this.eventHandler=new Kh(this),this.context.setTransform(t),this.parsedStyle.points.length<this.pointerLimitCount&&this.context.updateControlsFlags({useDefaultControls:!1,enableRotate:!1})}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy(),this.pointEventsHandler.destroyLineControls()}getAnnotationConfig(){const t=this.context.getTransform(),e=this.getBoundingRect(),{position:i}=t,n=i.x!==e.left||i.y!==e.top;let s=this.attributes.points;return n&&(s=[],this.attributes.points.forEach(t=>{s.push({x:t.x-e.left+i.x,y:t.y-e.top+i.y})})),{type:"annotationPolyline",style:{points:s,lineEnding:this.attributes.lineEnding,...this.context.getCommonStyleConfig()},transform:t}}}class fc extends Bl{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super({type:"annotationLine",...t}),Yi(this,"shapeType","annotationLine"),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),Yi(this,"pointEventsHandler",void 0),this.init(t.transform,t.selectableStyle)}init(t,e){this.context=new tc(this,e),this.pointEventsHandler=new uc(this),this.eventHandler=new Kh(this),this.context.setTransform(t),this.context.updateControlsFlags({useDefaultControls:!1,enableRotate:!1})}update(){this.updateOrigin(),this.context.updateControls()}destroy(){this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy(),this.pointEventsHandler.destroyLineControls()}getAnnotationConfig(){const t=this.context.getTransform(),{left:e,top:i}=this.getBoundingRect(),{startPoint:n,endPoint:s,lineEnding:o}=this.attributes,{position:r}=t,a=r.x!==e||r.y!==i;return{type:"annotationLine",style:{startPoint:a?{x:n.x-e+r.x,y:n.y-i+r.y}:n,endPoint:a?{x:s.x-e+r.x,y:s.y-i+r.y}:s,lineEnding:o,...this.context.getCommonStyleConfig()},transform:t}}}const mc=[{type:"path",stampPoints:[{x:417.4818115234375,y:261.32421875,step:2},{x:408.92578125,y:267.67313639322913,step:1},{x:404.0755208333333,y:276.6470947265625,step:1},{x:403.69010416666663,y:277.0937093098958,step:1},{x:403.40885416666663,y:276.3788655598958,step:1},{x:401.96875,y:272.3411458333333,step:1},{x:401.8802083333333,y:270.8835042317708,step:1},{x:399.3177083333333,y:272.16080729166663,step:1},{x:395.36454264322913,y:272.4173583984375,step:1},{x:395.36454264322913,y:272.4173583984375,step:1},{x:395.36454264322913,y:272.4173583984375,step:1},{x:399.7317708333333,y:277.8567708333333,step:1},{x:403.5690511067708,y:284.59375,step:1},{x:403.7773030598958,y:284.56766764322913,step:1},{x:406.17447916666663,y:274.89322916666663,step:1},{x:422.41666666666663,y:265.8476155598958,step:1},{x:418.98832194010413,y:263.60477701822913,step:1},{x:417.4140625,y:261.35746256510413,step:1},{x:417.4818115234375,y:261.32421875,step:1}],borderWidth:0,borderColor:"rgba(0,0,0,1)",background:"linear-gradient(to right bottom, #a9d776, #40691b)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:417.4818115234375,y:261.32421875,step:2},{x:408.92578125,y:267.67313639322913,step:1},{x:404.0755208333333,y:276.6470947265625,step:1},{x:403.69010416666663,y:277.0937093098958,step:1},{x:403.40885416666663,y:276.3788655598958,step:1},{x:401.96875,y:272.3411458333333,step:1},{x:401.8802083333333,y:270.8835042317708,step:1},{x:399.3177083333333,y:272.16080729166663,step:1},{x:395.36454264322913,y:272.4173583984375,step:1},{x:395.36454264322913,y:272.4173583984375,step:1},{x:395.36454264322913,y:272.4173583984375,step:1},{x:399.7317708333333,y:277.8567708333333,step:1},{x:403.5690511067708,y:284.59375,step:1},{x:403.7773030598958,y:284.56766764322913,step:1},{x:406.17447916666663,y:274.89322916666663,step:1},{x:422.41666666666663,y:265.8476155598958,step:1},{x:418.98832194010413,y:263.60477701822913,step:1},{x:417.4140625,y:261.35746256510413,step:1},{x:417.4818115234375,y:261.32421875,step:1}],borderWidth:1.3333333333333333,borderColor:"rgba(65,106,28,1)",background:null,lineDash:[0,0],lineCap:"round",lineJoin:"round",miterLimit:4}],vc=[{type:"path",stampPoints:[{x:424.45703125,y:294.07291666666663,step:2},{x:424.45703125,y:298.47265625,step:1},{x:420.83984375,y:302.07291666666663,step:1},{x:416.4192708333333,y:302.07291666666663,step:1},{x:222.49481201171875,y:302.07291666666663,step:0},{x:218.07421875,y:302.07291666666663,step:1},{x:214.45703125,y:298.47265625,step:1},{x:214.45703125,y:294.07291666666663,step:1},{x:214.45703125,y:252.07291666666666,step:0},{x:214.45703125,y:247.67313639322916,step:1},{x:218.07421875,y:244.07291666666666,step:1},{x:222.49481201171875,y:244.07291666666666,step:1},{x:416.4192708333333,y:244.07291666666666,step:0},{x:420.83984375,y:244.07291666666666,step:1},{x:424.45703125,y:247.67313639322916,step:1},{x:424.45703125,y:252.07291666666666,step:1},{x:424.45703125,y:294.07291666666663,step:0}],borderWidth:0,borderColor:"rgba(0,0,0,0.8509803921568627)",background:"linear-gradient(to right bottom, #f1f6ea, #cedfc5)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:424.0677083333333,y:293.9374593098958,step:2},{x:424.0677083333333,y:298.3358968098958,step:1},{x:420.45048014322913,y:301.9374593098958,step:1},{x:416.02994791666663,y:301.9374593098958,step:1},{x:222.10614013671875,y:301.9374593098958,step:0},{x:217.685546875,y:301.9374593098958,step:1},{x:214.06837972005206,y:298.3358968098958,step:1},{x:214.06837972005206,y:293.9374593098958,step:1},{x:214.06837972005206,y:251.93684895833331,step:0},{x:214.06837972005206,y:247.53715006510416,step:1},{x:217.685546875,y:243.93684895833331,step:1},{x:222.10614013671875,y:243.93684895833331,step:1},{x:416.02994791666663,y:243.93684895833331,step:0},{x:420.45048014322913,y:243.93684895833331,step:1},{x:424.0677083333333,y:247.53715006510416,step:1},{x:424.0677083333333,y:251.93684895833331,step:1},{x:424.0677083333333,y:293.9374593098958,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(41,66,18,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:234.81705729166666,y:280.5859375,step:2},{x:231.83074951171875,y:287.9374593098958,step:0},{x:226.009765625,y:287.9374593098958,step:0},{x:238.44596354166666,y:259.6288655598958,step:0},{x:245.4388224283854,y:259.6288655598958,step:0},{x:248.38736979166666,y:287.9374593098958,step:0},{x:242.67903645833331,y:287.9374593098958,step:0},{x:242.150390625,y:280.5859375,step:0},{x:234.81705729166666,y:280.5859375,step:0},{x:241.9238077799479,y:275.9661458333333,step:2},{x:241.43166097005206,y:269.8769124348958,step:0},{x:241.318359375,y:268.3229573567708,step:1},{x:241.205078125,y:266.0553792317708,step:1},{x:241.0917765299479,y:264.33268229166663,step:1},{x:240.978515625,y:264.33268229166663,step:0},{x:240.33528645833331,y:266.0553792317708,step:1},{x:239.6171671549479,y:268.2389729817708,step:1},{x:238.93684895833331,y:269.8769124348958,step:1},{x:236.44270833333331,y:275.9661458333333,step:0},{x:241.9238077799479,y:275.9661458333333,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:255.87109375,y:260.1335042317708,step:2},{x:257.5345052083333,y:259.67057291666663,step:1},{x:260.06705729166663,y:259.41861979166663,step:1},{x:262.52410888671875,y:259.41861979166663,step:1},{x:264.83009847005206,y:259.41861979166663,step:1},{x:267.43815104166663,y:259.8391927083333,step:1},{x:269.2903645833333,y:261.30924479166663,step:1},{x:271.02931722005206,y:262.56901041666663,step:1},{x:272.0501302083333,y:264.58463541666663,step:1},{x:272.0501302083333,y:267.314453125,step:1},{x:272.0501302083333,y:270.884765625,step:1},{x:270.5755208333333,y:273.6145833333333,step:1},{x:268.61002604166663,y:275.2942708333333,step:1},{x:266.5305989583333,y:277.1015625,step:1},{x:263.544921875,y:277.94010416666663,step:1},{x:260.4446818033854,y:277.94010416666663,step:1},{x:259.5384318033854,y:277.94010416666663,step:1},{x:258.78190104166663,y:277.81510416666663,step:1},{x:258.21486409505206,y:277.7734375,step:1},{x:256.4759114583333,y:287.9374593098958,step:0},{x:251.146484375,y:287.9374593098958,step:0},{x:255.87109375,y:260.1335042317708,step:0},{x:259.0462239583333,y:272.8170979817708,step:2},{x:259.61328125,y:272.9427083333333,step:1},{x:260.2181193033854,y:273.0266927083333,step:1},{x:261.1634318033854,y:273.0266927083333,step:1},{x:264.4140625,y:273.0266927083333,step:1},{x:266.56901041666663,y:270.6751302083333,step:1},{x:266.56901041666663,y:267.861328125,step:1},{x:266.56901041666663,y:265.130859375,step:1},{x:264.7923177083333,y:264.24869791666663,step:1},{x:262.712890625,y:264.24869791666663,step:1},{x:261.6927083333333,y:264.24869791666663,step:1},{x:260.9368489583333,y:264.33268229166663,step:1},{x:260.48307291666663,y:264.4167073567708,step:1},{x:259.0462239583333,y:272.8170979817708,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:277.19010416666663,y:260.1335042317708,step:2},{x:278.85353597005206,y:259.67057291666663,step:1},{x:281.3860677083333,y:259.41861979166663,step:1},{x:283.84246826171875,y:259.41861979166663,step:1},{x:286.14845784505206,y:259.41861979166663,step:1},{x:288.75651041666663,y:259.8391927083333,step:1},{x:290.6087239583333,y:261.30924479166663,step:1},{x:292.34765625,y:262.56901041666663,step:1},{x:293.3685099283854,y:264.58463541666663,step:1},{x:293.3685099283854,y:267.314453125,step:1},{x:293.3685099283854,y:270.884765625,step:1},{x:291.8938802083333,y:273.6145833333333,step:1},{x:289.92836507161456,y:275.2942708333333,step:1},{x:287.84962972005206,y:277.1015625,step:1},{x:284.86328125,y:277.94010416666663,step:1},{x:281.763671875,y:277.94010416666663,step:1},{x:280.8567708333333,y:277.94010416666663,step:1},{x:280.10028076171875,y:277.81510416666663,step:1},{x:279.533203125,y:277.7734375,step:1},{x:277.794921875,y:287.9374593098958,step:0},{x:272.4648234049479,y:287.9374593098958,step:0},{x:277.19010416666663,y:260.1335042317708,step:0},{x:280.36525472005206,y:272.8170979817708,step:2},{x:280.93229166666663,y:272.9427083333333,step:1},{x:281.537109375,y:273.0266927083333,step:1},{x:282.482421875,y:273.0266927083333,step:1},{x:285.732421875,y:273.0266927083333,step:1},{x:287.88736979166663,y:270.6751302083333,step:1},{x:287.88736979166663,y:267.861328125,step:1},{x:287.88736979166663,y:265.130859375,step:1},{x:286.1106974283854,y:264.24869791666663,step:1},{x:284.03192138671875,y:264.24869791666663,step:1},{x:283.0110677083333,y:264.24869791666663,step:1},{x:282.2552286783854,y:264.33268229166663,step:1},{x:281.80145263671875,y:264.4167073567708,step:1},{x:280.36525472005206,y:272.8170979817708,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:298.583984375,y:260.1335042317708,step:2},{x:300.2845052083333,y:259.67057291666663,step:1},{x:302.8548380533854,y:259.41861979166663,step:1},{x:305.3880208333333,y:259.41861979166663,step:1},{x:307.80731201171875,y:259.41861979166663,step:1},{x:310.3020833333333,y:259.79752604166663,step:1},{x:312.078125,y:261.056640625,step:1},{x:313.7415364583333,y:262.1491292317708,step:1},{x:314.9134318033854,y:263.91276041666663,step:1},{x:314.9134318033854,y:266.5592854817708,step:1},{x:314.9134318033854,y:270.7591145833333,step:1},{x:312.41861979166663,y:273.4049072265625,step:1},{x:309.1302083333333,y:274.58072916666663,step:1},{x:309.1302083333333,y:274.70703125,step:0},{x:310.642578125,y:275.46354166666663,step:1},{x:311.322265625,y:277.3098958333333,step:1},{x:311.54949951171875,y:279.8723958333333,step:1},{x:311.88930257161456,y:283.06510416666663,step:1},{x:312.078125,y:286.76041666666663,step:1},{x:312.53190104166663,y:287.9374593098958,step:1},{x:306.93752034505206,y:287.9374593098958,step:0},{x:306.7109375,y:287.18094889322913,step:1},{x:306.4466145833333,y:284.74479166666663,step:1},{x:306.21940104166663,y:281.2591145833333,step:1},{x:305.955078125,y:277.81510416666663,step:1},{x:304.89650472005206,y:276.765625,step:1},{x:302.7415364583333,y:276.765625,step:1},{x:301.07877604166663,y:276.765625,step:0},{x:299.1888020833333,y:287.9374593098958,step:0},{x:293.82096354166663,y:287.9374593098958,step:0},{x:298.583984375,y:260.1335042317708,step:0},{x:301.9101359049479,y:272.22855631510413,step:2},{x:304.1399739583333,y:272.22855631510413,step:0},{x:307.08917236328125,y:272.22855631510413,step:1},{x:309.24346923828125,y:270.25455729166663,step:1},{x:309.24346923828125,y:267.48246256510413,step:1},{x:309.24346923828125,y:265.1731770833333,step:1},{x:307.5423380533854,y:264.16471354166663,step:1},{x:305.35026041666663,y:264.16471354166663,step:1},{x:304.330078125,y:264.16471354166663,step:1},{x:303.6868693033854,y:264.24869791666663,step:1},{x:303.2337239583333,y:264.3749593098958,step:1},{x:301.9101359049479,y:272.22855631510413,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:327.236328125,y:288.3984375,step:2},{x:320.6210734049479,y:288.3984375,step:1},{x:316.91668701171875,y:283.19010416666663,step:1},{x:316.91668701171875,y:276.59635416666663,step:1},{x:316.91668701171875,y:271.47330729166663,step:1},{x:318.61783854166663,y:266.39127604166663,step:1},{x:321.603515625,y:263.19921875,step:1},{x:323.98502604166663,y:260.6790364583333,step:1},{x:327.236328125,y:259.16666666666663,step:1},{x:330.90236409505206,y:259.16666666666663,step:1},{x:337.63087972005206,y:259.16666666666663,step:1},{x:341.18424479166663,y:264.20703125,step:1},{x:341.18424479166663,y:270.9693603515625,step:1},{x:341.18424479166663,y:276.1354573567708,step:1},{x:339.55859375,y:281.17447916666663,step:1},{x:336.6477864583333,y:284.3255208333333,step:1},{x:334.2669270833333,y:286.8880615234375,step:1},{x:331.0540364583333,y:288.3984375,step:1},{x:327.2734375,y:288.3984375,step:1},{x:327.236328125,y:288.3984375,step:0},{x:328.02994791666663,y:283.35941569010413,step:2},{x:329.6555989583333,y:283.35941569010413,step:1},{x:331.12957763671875,y:282.6028645833333,step:1},{x:332.30143229166663,y:281.3021240234375,step:1},{x:334.3040364583333,y:279.0755208333333,step:1},{x:335.40104166666663,y:274.41276041666663,step:1},{x:335.40104166666663,y:271.13736979166663,step:1},{x:335.40104166666663,y:267.6087239583333,step:1},{x:334.2669270833333,y:264.20703125,step:1},{x:330.2597452799479,y:264.20703125,step:1},{x:328.55922444661456,y:264.20703125,step:1},{x:327.04689534505206,y:265.0045166015625,step:1},{x:325.8749796549479,y:266.34891764322913,step:1},{x:323.83400472005206,y:268.57486979166663,step:1},{x:322.69986979166663,y:272.9849853515625,step:1},{x:322.69986979166663,y:276.3880208333333,step:1},{x:322.69986979166663,y:280.3775634765625,step:1},{x:324.3255208333333,y:283.35941569010413,step:1},{x:327.99151611328125,y:283.35941569010413,step:1},{x:328.02994791666663,y:283.35941569010413,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:347.61002604166663,y:287.9374593098958,step:2},{x:344.435546875,y:259.6288655598958,step:0},{x:350.06705729166663,y:259.6288655598958,step:0},{x:351.201171875,y:273.1106770833333,step:0},{x:351.4661458333333,y:276.1354573567708,step:1},{x:351.6549886067708,y:278.8646240234375,step:1},{x:351.80594889322913,y:281.8046468098958,step:1},{x:351.88151041666663,y:281.8046468098958,step:0},{x:352.82682291666663,y:279.03385416666663,step:1},{x:354.03641764322913,y:276.0091552734375,step:1},{x:355.283203125,y:273.068359375,step:1},{x:360.9915771484375,y:259.6288655598958,step:0},{x:367.07743326822913,y:259.6288655598958,step:0},{x:353.9232177734375,y:287.9374593098958,step:0},{x:347.61002604166663,y:287.9374593098958,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:381.7805989583333,y:275.88285319010413,step:2},{x:372.74674479166663,y:275.88285319010413,step:0},{x:371.5755208333333,y:282.7708333333333,step:0},{x:381.7434895833333,y:282.7708333333333,step:0},{x:380.87369791666663,y:287.9374593098958,step:0},{x:365.224609375,y:287.9374593098958,step:0},{x:370.06315104166663,y:259.6288655598958,step:0},{x:385.1451416015625,y:259.6288655598958,step:0},{x:384.2376708984375,y:264.79496256510413,step:0},{x:374.6366780598958,y:264.79496256510413,step:0},{x:373.57877604166663,y:270.8014729817708,step:0},{x:382.68815104166663,y:270.8014729817708,step:0},{x:381.7805989583333,y:275.88285319010413,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:389.52994791666663,y:260.048828125,step:2},{x:391.7220052083333,y:259.6288655598958,step:1},{x:394.103515625,y:259.41861979166663,step:1},{x:396.5989990234375,y:259.41861979166663,step:1},{x:400.5677083333333,y:259.41861979166663,step:1},{x:403.705078125,y:260.42704264322913,step:1},{x:405.8593343098958,y:262.4849853515625,step:1},{x:407.93876139322913,y:264.33268229166663,step:1},{x:409.22391764322913,y:267.146484375,step:1},{x:409.22391764322913,y:271.3470052083333,step:1},{x:409.22391764322913,y:276.8073323567708,step:1},{x:407.1444905598958,y:281.5521240234375,step:1},{x:404.0071614583333,y:284.3671875,step:1},{x:401.05924479166663,y:287.01298014322913,step:1},{x:397.3170166015625,y:288.1458333333333,step:1},{x:391.7981770833333,y:288.1458333333333,step:1},{x:388.73636881510413,y:288.1458333333333,step:1},{x:386.0904541015625,y:287.85282389322913,step:1},{x:384.80533854166663,y:287.5598958333333,step:1},{x:389.52994791666663,y:260.048828125,step:0},{x:391.080078125,y:283.1067708333333,step:2},{x:391.7220052083333,y:283.19010416666663,step:1},{x:392.5162353515625,y:283.2317708333333,step:1},{x:393.4609375,y:283.2317708333333,step:1},{x:396.40946451822913,y:283.2317708333333,step:1},{x:399.017578125,y:282.0573323567708,step:1},{x:400.6809895833333,y:279.9569905598958,step:1},{x:402.4198811848958,y:277.7317708333333,step:1},{x:403.32682291666663,y:274.7916259765625,step:1},{x:403.32682291666663,y:271.38871256510413,step:1},{x:403.32682291666663,y:266.8952229817708,step:1},{x:401.0970052083333,y:264.24869791666663,step:1},{x:396.5989990234375,y:264.24869791666663,step:1},{x:395.6536865234375,y:264.24869791666663,step:1},{x:394.8600667317708,y:264.33268229166663,step:1},{x:394.2923583984375,y:264.458984375,step:1},{x:391.080078125,y:283.1067708333333,step:0}],borderWidth:0,borderColor:"rgba(41,66,18,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],yc=[{type:"path",stampPoints:[{x:523.234375,y:293.9374593098958,step:2},{x:523.234375,y:298.3358968098958,step:1},{x:519.3333333333333,y:301.9374593098958,step:1},{x:514.5638020833333,y:301.9374593098958,step:1},{x:305.404296875,y:301.9374593098958,step:0},{x:300.6360677083333,y:301.9374593098958,step:1},{x:296.73504638671875,y:298.3358968098958,step:1},{x:296.73504638671875,y:293.9374593098958,step:1},{x:296.73504638671875,y:251.93745930989581,step:0},{x:296.73504638671875,y:247.53645833333331,step:1},{x:300.6360677083333,y:243.93745930989581,step:1},{x:305.404296875,y:243.93745930989581,step:1},{x:514.5638020833333,y:243.93745930989581,step:0},{x:519.3333333333333,y:243.93745930989581,step:1},{x:523.234375,y:247.53645833333331,step:1},{x:523.234375,y:251.93745930989581,step:1},{x:523.234375,y:293.9374593098958,step:0}],borderWidth:0,borderColor:"rgba(0,0,0,0.8509803921568627)",background:"linear-gradient(to right bottom, #f1f6ea, #cedfc5)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:523.234375,y:293.9374593098958,step:2},{x:523.234375,y:298.3358968098958,step:1},{x:519.3333333333333,y:301.9374593098958,step:1},{x:514.5638020833333,y:301.9374593098958,step:1},{x:305.404296875,y:301.9374593098958,step:0},{x:300.6360677083333,y:301.9374593098958,step:1},{x:296.73504638671875,y:298.3358968098958,step:1},{x:296.73504638671875,y:293.9374593098958,step:1},{x:296.73504638671875,y:251.93745930989581,step:0},{x:296.73504638671875,y:247.53645833333331,step:1},{x:300.6360677083333,y:243.93745930989581,step:1},{x:305.404296875,y:243.93745930989581,step:1},{x:514.5638020833333,y:243.93745930989581,step:0},{x:519.3333333333333,y:243.93745930989581,step:1},{x:523.234375,y:247.53645833333331,step:1},{x:523.234375,y:251.93745930989581,step:1},{x:523.234375,y:293.9374593098958,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(65,106,28,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:329.54166666666663,y:287.13798014322913,step:2},{x:328.1810099283854,y:287.80985514322913,step:1},{x:325.91276041666663,y:288.35673014322913,step:1},{x:322.8515625,y:288.35673014322913,step:1},{x:316.0852864583333,y:288.35673014322913,step:1},{x:311.58660888671875,y:283.8203125,step:1},{x:311.58660888671875,y:276.3437093098958,step:1},{x:311.58660888671875,y:269.9609375,step:1},{x:314.15690104166663,y:265.046875,step:1},{x:318.0130411783854,y:262.1901448567708,step:1},{x:320.65885416666663,y:260.1745198567708,step:1},{x:323.75844319661456,y:259.2083333333333,step:1},{x:327.349609375,y:259.2083333333333,step:1},{x:330.1087443033854,y:259.2083333333333,step:1},{x:332.18817138671875,y:259.92191569010413,step:1},{x:332.943359375,y:260.38541666666663,step:1},{x:331.43166097005206,y:265.29947916666663,step:0},{x:330.71356201171875,y:264.8802490234375,step:1},{x:329.01236979166663,y:264.3749593098958,step:1},{x:326.8203125,y:264.3749593098958,step:1},{x:324.62760416666663,y:264.3749593098958,step:1},{x:322.5488077799479,y:265.1302083333333,step:1},{x:320.99867757161456,y:266.5598958333333,step:1},{x:318.8821614583333,y:268.4895833333333,step:1},{x:317.4837239583333,y:271.7239583333333,step:1},{x:317.4837239583333,y:275.6718343098958,step:1},{x:317.4837239583333,y:280.16666666666663,step:1},{x:319.78971354166663,y:283.19010416666663,step:1},{x:324.25002034505206,y:283.19010416666663,step:1},{x:326.064453125,y:283.19010416666663,step:1},{x:327.84051513671875,y:282.85416666666663,step:1},{x:329.087890625,y:282.265625,step:1},{x:329.54166666666663,y:287.13798014322913,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:342.9987386067708,y:288.3984375,step:2},{x:336.3841145833333,y:288.3984375,step:1},{x:332.67970784505206,y:283.19010416666663,step:1},{x:332.67970784505206,y:276.59635416666663,step:1},{x:332.67970784505206,y:271.4739990234375,step:1},{x:334.380859375,y:266.390625,step:1},{x:337.3665364583333,y:263.19791666666663,step:1},{x:339.74806722005206,y:260.6796875,step:1},{x:342.9987386067708,y:259.16666666666663,step:1},{x:346.6653645833333,y:259.16666666666663,step:1},{x:353.3938802083333,y:259.16666666666663,step:1},{x:356.94730631510413,y:264.2083333333333,step:1},{x:356.94730631510413,y:270.96875,step:1},{x:356.94730631510413,y:276.1354573567708,step:1},{x:355.3216145833333,y:281.17447916666663,step:1},{x:352.4107666015625,y:284.3255208333333,step:1},{x:350.0292561848958,y:286.8880615234375,step:1},{x:346.8170979817708,y:288.3984375,step:1},{x:343.0364583333333,y:288.3984375,step:1},{x:342.9987386067708,y:288.3984375,step:0},{x:343.79296875,y:283.35941569010413,step:2},{x:345.4185791015625,y:283.35941569010413,step:1},{x:346.892578125,y:282.6015625,step:1},{x:348.0638020833333,y:281.3021240234375,step:1},{x:350.06705729166663,y:279.0755208333333,step:1},{x:351.1634114583333,y:274.4140625,step:1},{x:351.1634114583333,y:271.13798014322913,step:1},{x:351.1634114583333,y:267.609375,step:1},{x:350.0292561848958,y:264.2083333333333,step:1},{x:346.0227864583333,y:264.2083333333333,step:1},{x:344.3216552734375,y:264.2083333333333,step:1},{x:342.8098958333333,y:265.00516764322913,step:1},{x:341.6380208333333,y:266.34891764322913,step:1},{x:339.5970052083333,y:268.5755208333333,step:1},{x:338.46291097005206,y:272.9843343098958,step:1},{x:338.46291097005206,y:276.3880208333333,step:1},{x:338.46291097005206,y:280.3775634765625,step:1},{x:340.087890625,y:283.35941569010413,step:1},{x:343.75455729166663,y:283.35941569010413,step:1},{x:343.79296875,y:283.35941569010413,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:379.5130208333333,y:287.9374593098958,step:2},{x:381.06315104166663,y:276.26041666666663,step:0},{x:381.478515625,y:273.1953125,step:1},{x:382.04557291666663,y:269.33072916666663,step:1},{x:382.76371256510413,y:265.2161865234375,step:1},{x:382.6503499348958,y:265.2161865234375,step:0},{x:381.2519124348958,y:268.8671875,step:1},{x:379.66471354166663,y:272.7734375,step:1},{x:378.26627604166663,y:275.88285319010413,step:1},{x:373.04886881510413,y:287.4739990234375,step:0},{x:368.8157958984375,y:287.4739990234375,step:0},{x:367.908203125,y:276.00785319010413,step:0},{x:367.68168131510413,y:272.90104166666663,step:1},{x:367.4928792317708,y:268.9948323567708,step:1},{x:367.34183756510413,y:265.2161865234375,step:1},{x:367.26627604166663,y:265.2161865234375,step:0},{x:366.54752604166663,y:268.953125,step:1},{x:365.79166666666663,y:273.2369384765625,step:1},{x:365.14908854166663,y:276.26041666666663,step:1},{x:362.6165364583333,y:287.9374593098958,step:0},{x:357.626953125,y:287.9374593098958,step:0},{x:364.0150146484375,y:259.6302083333333,step:0},{x:371.3105061848958,y:259.6302083333333,step:0},{x:372.10416666666663,y:270.42191569010413,step:0},{x:372.255859375,y:273.06766764322913,step:1},{x:372.5201416015625,y:276.26041666666663,step:1},{x:372.5579427083333,y:279.4114583333333,step:1},{x:372.708984375,y:279.4114583333333,step:0},{x:373.69205729166663,y:276.26041666666663,step:1},{x:375.052734375,y:272.9427083333333,step:1},{x:376.1491292317708,y:270.3802083333333,step:1},{x:380.87369791666663,y:259.6302083333333,step:0},{x:388.2447509765625,y:259.6302083333333,step:0},{x:384.80533854166663,y:287.9374593098958,step:0},{x:379.5130208333333,y:287.9374593098958,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:393.99027506510413,y:260.1328125,step:2},{x:395.6536865234375,y:259.6718343098958,step:1},{x:398.1862386067708,y:259.4192708333333,step:1},{x:400.64322916666663,y:259.4192708333333,step:1},{x:402.94921875,y:259.4192708333333,step:1},{x:405.5572509765625,y:259.83854166666663,step:1},{x:407.40946451822913,y:261.3098958333333,step:1},{x:409.1484375,y:262.56766764322913,step:1},{x:410.1692708333333,y:264.5859375,step:1},{x:410.1692708333333,y:267.31510416666663,step:1},{x:410.1692708333333,y:270.8854573567708,step:1},{x:408.6946614583333,y:273.6145833333333,step:1},{x:406.72855631510413,y:275.2942708333333,step:1},{x:404.6503499348958,y:277.1015625,step:1},{x:401.66410319010413,y:277.94010416666663,step:1},{x:398.5644124348958,y:277.94010416666663,step:1},{x:397.656982421875,y:277.94010416666663,step:1},{x:396.9010823567708,y:277.81510416666663,step:1},{x:396.333984375,y:277.7734375,step:1},{x:394.59574381510413,y:287.9374593098958,step:0},{x:389.26566569010413,y:287.9374593098958,step:0},{x:393.99027506510413,y:260.1328125,step:0},{x:397.1659749348958,y:272.8177083333333,step:2},{x:397.73246256510413,y:272.9427083333333,step:1},{x:398.337890625,y:273.02604166666663,step:1},{x:399.28251139322913,y:273.02604166666663,step:1},{x:402.5331624348958,y:273.02604166666663,step:1},{x:404.68815104166663,y:270.6745198567708,step:1},{x:404.68815104166663,y:267.859375,step:1},{x:404.68815104166663,y:265.1302083333333,step:1},{x:402.91141764322913,y:264.25,step:1},{x:400.8326416015625,y:264.25,step:1},{x:399.81180826822913,y:264.25,step:1},{x:399.05533854166663,y:264.3333333333333,step:1},{x:398.60221354166663,y:264.4167073567708,step:1},{x:397.1659749348958,y:272.8177083333333,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:415.421875,y:259.6302083333333,step:2},{x:420.8645833333333,y:259.6302083333333,step:0},{x:416.9348958333333,y:282.64579264322913,step:0},{x:426.7239583333333,y:282.64579264322913,step:0},{x:425.8177083333333,y:287.9374593098958,step:0},{x:410.58329264322913,y:287.9374593098958,step:0},{x:415.421875,y:259.6302083333333,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:445.54947916666663,y:275.88285319010413,step:2},{x:436.515625,y:275.88285319010413,step:0},{x:435.3437093098958,y:282.7708333333333,step:0},{x:445.51041666666663,y:282.7708333333333,step:0},{x:444.6419270833333,y:287.9374593098958,step:0},{x:428.9921875,y:287.9374593098958,step:0},{x:433.83072916666663,y:259.6302083333333,step:0},{x:448.9127197265625,y:259.6302083333333,step:0},{x:448.00516764322913,y:264.7942708333333,step:0},{x:438.4036458333333,y:264.7942708333333,step:0},{x:437.34635416666663,y:270.8021240234375,step:0},{x:446.45572916666663,y:270.8021240234375,step:0},{x:445.54947916666663,y:275.88285319010413,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:457.0780843098958,y:264.92191569010413,step:2},{x:450.3489990234375,y:264.92191569010413,step:0},{x:451.2942708333333,y:259.6302083333333,step:0},{x:470.2317708333333,y:259.6302083333333,step:0},{x:469.32548014322913,y:264.92191569010413,step:0},{x:462.5208333333333,y:264.92191569010413,step:0},{x:458.58988444010413,y:287.9374593098958,step:0},{x:453.1458333333333,y:287.9374593098958,step:0},{x:457.0780843098958,y:264.92191569010413,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:485.0130208333333,y:275.88285319010413,step:2},{x:475.97782389322913,y:275.88285319010413,step:0},{x:474.8059895833333,y:282.7708333333333,step:0},{x:484.9739583333333,y:282.7708333333333,step:0},{x:484.10416666666663,y:287.9374593098958,step:0},{x:468.45572916666663,y:287.9374593098958,step:0},{x:473.2942708333333,y:259.6302083333333,step:0},{x:488.37504069010413,y:259.6302083333333,step:0},{x:487.46875,y:264.7942708333333,step:0},{x:477.8671875,y:264.7942708333333,step:0},{x:476.8098958333333,y:270.8021240234375,step:0},{x:485.9192708333333,y:270.8021240234375,step:0},{x:485.0130208333333,y:275.88285319010413,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:492.76041666666663,y:260.04947916666663,step:2},{x:494.953125,y:259.6302083333333,step:1},{x:497.33463541666663,y:259.4192708333333,step:1},{x:499.8294270833333,y:259.4192708333333,step:1},{x:503.7981770833333,y:259.4192708333333,step:1},{x:506.9348958333333,y:260.42704264322913,step:1},{x:509.0911458333333,y:262.4843343098958,step:1},{x:511.1692708333333,y:264.3333333333333,step:1},{x:512.4544270833333,y:267.14579264322913,step:1},{x:512.4544270833333,y:271.34635416666663,step:1},{x:512.4544270833333,y:276.8073323567708,step:1},{x:510.37504069010413,y:281.5521240234375,step:1},{x:507.2382405598958,y:284.3671875,step:1},{x:504.28910319010413,y:287.01298014322913,step:1},{x:500.546875,y:288.1458333333333,step:1},{x:495.0286865234375,y:288.1458333333333,step:1},{x:491.9661458333333,y:288.1458333333333,step:1},{x:489.3203125,y:287.8515218098958,step:1},{x:488.03641764322913,y:287.5598958333333,step:1},{x:492.76041666666663,y:260.04947916666663,step:0},{x:494.3099365234375,y:283.1067708333333,step:2},{x:494.953125,y:283.19010416666663,step:1},{x:495.7473958333333,y:283.2317708333333,step:1},{x:496.6927083333333,y:283.2317708333333,step:1},{x:499.640625,y:283.2317708333333,step:1},{x:502.2473958333333,y:282.0573323567708,step:1},{x:503.91141764322913,y:279.95572916666663,step:1},{x:505.6510823567708,y:277.7317708333333,step:1},{x:506.5572509765625,y:274.7916259765625,step:1},{x:506.5572509765625,y:271.3880615234375,step:1},{x:506.5572509765625,y:266.8958740234375,step:1},{x:504.32816569010413,y:264.25,step:1},{x:499.8294270833333,y:264.25,step:1},{x:498.8841145833333,y:264.25,step:1},{x:498.0911458333333,y:264.3333333333333,step:1},{x:497.52347819010413,y:264.45829264322913,step:1},{x:494.3099365234375,y:283.1067708333333,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],xc=[{type:"path",stampPoints:[{x:545.5651041666666,y:293.9374593098958,step:2},{x:545.5651041666666,y:298.3358968098958,step:1},{x:540.8880615234375,y:301.9374593098958,step:1},{x:535.1718343098958,y:301.9374593098958,step:1},{x:284.4602864583333,y:301.9374593098958,step:0},{x:278.74416097005206,y:301.9374593098958,step:1},{x:274.06837972005206,y:298.3358968098958,step:1},{x:274.06837972005206,y:293.9374593098958,step:1},{x:274.06837972005206,y:251.93745930989581,step:0},{x:274.06837972005206,y:247.53645833333331,step:1},{x:278.74416097005206,y:243.93745930989581,step:1},{x:284.4602864583333,y:243.93745930989581,step:1},{x:535.1718343098958,y:243.93745930989581,step:0},{x:540.8880615234375,y:243.93745930989581,step:1},{x:545.5651041666666,y:247.53645833333331,step:1},{x:545.5651041666666,y:251.93745930989581,step:1},{x:545.5651041666666,y:293.9374593098958,step:0}],borderWidth:0,borderColor:"rgba(0,0,0,0.8509803921568627)",background:"linear-gradient(to right bottom, #e4f1ff, #c9cee2)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:545.5651041666666,y:293.9374593098958,step:2},{x:545.5651041666666,y:298.3358968098958,step:1},{x:540.8880615234375,y:301.9374593098958,step:1},{x:535.1718343098958,y:301.9374593098958,step:1},{x:284.4602864583333,y:301.9374593098958,step:0},{x:278.74416097005206,y:301.9374593098958,step:1},{x:274.06837972005206,y:298.3358968098958,step:1},{x:274.06837972005206,y:293.9374593098958,step:1},{x:274.06837972005206,y:251.93745930989581,step:0},{x:274.06837972005206,y:247.53645833333331,step:1},{x:278.74416097005206,y:243.93745930989581,step:1},{x:284.4602864583333,y:243.93745930989581,step:1},{x:535.1718343098958,y:243.93745930989581,step:0},{x:540.8880615234375,y:243.93745930989581,step:1},{x:545.5651041666666,y:247.53645833333331,step:1},{x:545.5651041666666,y:251.93745930989581,step:1},{x:545.5651041666666,y:293.9374593098958,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(24,37,100,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:306.875,y:287.13798014322913,step:2},{x:305.51434326171875,y:287.80985514322913,step:1},{x:303.24609375,y:288.35673014322913,step:1},{x:300.1848958333333,y:288.35673014322913,step:1},{x:293.41861979166663,y:288.35673014322913,step:1},{x:288.91994222005206,y:283.8203125,step:1},{x:288.91994222005206,y:276.3437093098958,step:1},{x:288.91994222005206,y:269.9609375,step:1},{x:291.490234375,y:265.046875,step:1},{x:295.34637451171875,y:262.1901448567708,step:1},{x:297.9921875,y:260.1745198567708,step:1},{x:301.0917765299479,y:259.2083333333333,step:1},{x:304.6829427083333,y:259.2083333333333,step:1},{x:307.44207763671875,y:259.2083333333333,step:1},{x:309.52150472005206,y:259.92191569010413,step:1},{x:310.2766927083333,y:260.38541666666663,step:1},{x:308.7649943033854,y:265.29947916666663,step:0},{x:308.04689534505206,y:264.8802490234375,step:1},{x:306.345703125,y:264.3749593098958,step:1},{x:304.1536458333333,y:264.3749593098958,step:1},{x:301.9609375,y:264.3749593098958,step:1},{x:299.88214111328125,y:265.1302083333333,step:1},{x:298.3320109049479,y:266.5598958333333,step:1},{x:296.21549479166663,y:268.4895833333333,step:1},{x:294.81705729166663,y:271.7239583333333,step:1},{x:294.81705729166663,y:275.6718343098958,step:1},{x:294.81705729166663,y:280.16666666666663,step:1},{x:297.123046875,y:283.19010416666663,step:1},{x:301.5833536783854,y:283.19010416666663,step:1},{x:303.3977864583333,y:283.19010416666663,step:1},{x:305.17384847005206,y:282.85416666666663,step:1},{x:306.4212239583333,y:282.265625,step:1},{x:306.875,y:287.13798014322913,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:320.3320109049479,y:288.3984375,step:2},{x:313.71744791666663,y:288.3984375,step:1},{x:310.0130411783854,y:283.19010416666663,step:1},{x:310.0130411783854,y:276.59635416666663,step:1},{x:310.0130411783854,y:271.4739990234375,step:1},{x:311.7141927083333,y:266.390625,step:1},{x:314.69986979166663,y:263.19791666666663,step:1},{x:317.0814005533854,y:260.6796875,step:1},{x:320.3320109049479,y:259.16666666666663,step:1},{x:323.99867757161456,y:259.16666666666663,step:1},{x:330.72721354166663,y:259.16666666666663,step:1},{x:334.28057861328125,y:264.2083333333333,step:1},{x:334.28057861328125,y:270.96875,step:1},{x:334.28057861328125,y:276.1354573567708,step:1},{x:332.65494791666663,y:281.17447916666663,step:1},{x:329.74416097005206,y:284.3255208333333,step:1},{x:327.3626505533854,y:286.8880615234375,step:1},{x:324.150390625,y:288.3984375,step:1},{x:320.36981201171875,y:288.3984375,step:1},{x:320.3320109049479,y:288.3984375,step:0},{x:321.1263020833333,y:283.35941569010413,step:2},{x:322.751953125,y:283.35941569010413,step:1},{x:324.2259114583333,y:282.6015625,step:1},{x:325.39711507161456,y:281.3021240234375,step:1},{x:327.400390625,y:279.0755208333333,step:1},{x:328.49676513671875,y:274.4140625,step:1},{x:328.49676513671875,y:271.13798014322913,step:1},{x:328.49676513671875,y:267.609375,step:1},{x:327.3626505533854,y:264.2083333333333,step:1},{x:323.35611979166663,y:264.2083333333333,step:1},{x:321.65494791666663,y:264.2083333333333,step:1},{x:320.14322916666663,y:265.00516764322913,step:1},{x:318.97135416666663,y:266.34891764322913,step:1},{x:316.93033854166663,y:268.5755208333333,step:1},{x:315.7962443033854,y:272.9843343098958,step:1},{x:315.7962443033854,y:276.3880208333333,step:1},{x:315.7962443033854,y:280.3775634765625,step:1},{x:317.4212239583333,y:283.35941569010413,step:1},{x:321.087890625,y:283.35941569010413,step:1},{x:321.1263020833333,y:283.35941569010413,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:335.56512451171875,y:287.9374593098958,step:2},{x:340.4036458333333,y:259.6302083333333,step:0},{x:346.79166666666663,y:259.6302083333333,step:0},{x:350.1556396484375,y:270.42191569010413,step:0},{x:351.17643229166663,y:274.03385416666663,step:1},{x:351.8573811848958,y:276.9739583333333,step:1},{x:352.46158854166663,y:280.0833740234375,step:1},{x:352.57486979166663,y:280.0833740234375,step:0},{x:352.6888427734375,y:277.18485514322913,step:1},{x:353.06640625,y:274.0755208333333,step:1},{x:353.74674479166663,y:269.9192708333333,step:1},{x:355.4857177734375,y:259.6302083333333,step:0},{x:360.58854166666663,y:259.6302083333333,step:0},{x:355.75,y:287.9374593098958,step:0},{x:350.11783854166663,y:287.9374593098958,step:0},{x:346.5650634765625,y:276.6380208333333,step:0},{x:345.4309895833333,y:272.7734375,step:1},{x:344.75065104166663,y:270.2135823567708,step:1},{x:344.0697021484375,y:266.7682698567708,step:1},{x:343.9563802083333,y:266.7682698567708,step:0},{x:343.69205729166663,y:269.54166666666663,step:1},{x:343.0872395833333,y:273.53129069010413,step:1},{x:342.3313802083333,y:278.0234375,step:1},{x:340.63087972005206,y:287.9374593098958,step:0},{x:335.56512451171875,y:287.9374593098958,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:365.57743326822913,y:259.6302083333333,step:2},{x:380.50846354166663,y:259.6302083333333,step:0},{x:379.6009521484375,y:264.7942708333333,step:0},{x:370.1516927083333,y:264.7942708333333,step:0},{x:368.9798177083333,y:271.42972819010413,step:0},{x:377.86258951822913,y:271.42972819010413,step:0},{x:376.9557698567708,y:276.51298014322913,step:0},{x:368.11063639322913,y:276.51298014322913,step:0},{x:366.1823323567708,y:287.9374593098958,step:0},{x:360.7395833333333,y:287.9374593098958,step:0},{x:365.57743326822913,y:259.6302083333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:390.22265625,y:259.6302083333333,step:2},{x:385.3847249348958,y:287.9374593098958,step:0},{x:379.94071451822913,y:287.9374593098958,step:0},{x:384.7792561848958,y:259.6302083333333,step:0},{x:390.22265625,y:259.6302083333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:395.1737874348958,y:260.04947916666663,step:2},{x:397.36649576822913,y:259.6302083333333,step:1},{x:399.748046875,y:259.4192708333333,step:1},{x:402.24283854166663,y:259.4192708333333,step:1},{x:406.21158854166663,y:259.4192708333333,step:1},{x:409.3489990234375,y:260.42704264322913,step:1},{x:411.50260416666663,y:262.4843343098958,step:1},{x:413.58329264322913,y:264.3333333333333,step:1},{x:414.8671875,y:267.14579264322913,step:1},{x:414.8671875,y:271.34635416666663,step:1},{x:414.8671875,y:276.8073323567708,step:1},{x:412.7890625,y:281.5521240234375,step:1},{x:409.6510823567708,y:284.3671875,step:1},{x:406.7030843098958,y:287.01298014322913,step:1},{x:402.9609375,y:288.1458333333333,step:1},{x:397.4420166015625,y:288.1458333333333,step:1},{x:394.380859375,y:288.1458333333333,step:1},{x:391.734375,y:287.8515218098958,step:1},{x:390.4491780598958,y:287.5598958333333,step:1},{x:395.1737874348958,y:260.04947916666663,step:0},{x:396.7239583333333,y:283.1067708333333,step:2},{x:397.36649576822913,y:283.19010416666663,step:1},{x:398.16015625,y:283.2317708333333,step:1},{x:399.10477701822913,y:283.2317708333333,step:1},{x:402.0540364583333,y:283.2317708333333,step:1},{x:404.662109375,y:282.0573323567708,step:1},{x:406.3249104817708,y:279.95572916666663,step:1},{x:408.0638020833333,y:277.7317708333333,step:1},{x:408.970703125,y:274.7916259765625,step:1},{x:408.970703125,y:271.3880615234375,step:1},{x:408.970703125,y:266.8958740234375,step:1},{x:406.74088541666663,y:264.25,step:1},{x:402.24283854166663,y:264.25,step:1},{x:401.2974853515625,y:264.25,step:1},{x:400.5038655598958,y:264.3333333333333,step:1},{x:399.9368489583333,y:264.45829264322913,step:1},{x:396.7239583333333,y:283.1067708333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:432.7096761067708,y:275.88285319010413,step:2},{x:423.67447916666663,y:275.88285319010413,step:0},{x:422.50260416666663,y:282.7708333333333,step:0},{x:432.6718343098958,y:282.7708333333333,step:0},{x:431.80204264322913,y:287.9374593098958,step:0},{x:416.1536865234375,y:287.9374593098958,step:0},{x:420.9921875,y:259.6302083333333,step:0},{x:436.07291666666663,y:259.6302083333333,step:0},{x:435.16666666666663,y:264.7942708333333,step:0},{x:425.56510416666663,y:264.7942708333333,step:0},{x:424.5077718098958,y:270.8021240234375,step:0},{x:433.61722819010413,y:270.8021240234375,step:0},{x:432.7096761067708,y:275.88285319010413,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:435.69535319010413,y:287.9374593098958,step:2},{x:440.53385416666663,y:259.6302083333333,step:0},{x:446.921875,y:259.6302083333333,step:0},{x:450.2864583333333,y:270.42191569010413,step:0},{x:451.3072509765625,y:274.03385416666663,step:1},{x:451.98697916666663,y:276.9739583333333,step:1},{x:452.59244791666663,y:280.0833740234375,step:1},{x:452.70572916666663,y:280.0833740234375,step:0},{x:452.8190511067708,y:277.18485514322913,step:1},{x:453.1978759765625,y:274.0755208333333,step:1},{x:453.87760416666663,y:269.9192708333333,step:1},{x:455.61722819010413,y:259.6302083333333,step:0},{x:460.71875,y:259.6302083333333,step:0},{x:455.8802083333333,y:287.9374593098958,step:0},{x:450.24869791666663,y:287.9374593098958,step:0},{x:446.6953125,y:276.6380208333333,step:0},{x:445.56119791666663,y:272.7734375,step:1},{x:444.8802083333333,y:270.2135823567708,step:1},{x:444.2005208333333,y:266.7682698567708,step:1},{x:444.0872395833333,y:266.7682698567708,step:0},{x:443.8228759765625,y:269.54166666666663,step:1},{x:443.21875,y:273.53129069010413,step:1},{x:442.4622802734375,y:278.0234375,step:1},{x:440.76041666666663,y:287.9374593098958,step:0},{x:435.69535319010413,y:287.9374593098958,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:469.4127197265625,y:264.92191569010413,step:2},{x:462.6848958333333,y:264.92191569010413,step:0},{x:463.6302490234375,y:259.6302083333333,step:0},{x:482.5677083333333,y:259.6302083333333,step:0},{x:481.65885416666663,y:264.92191569010413,step:0},{x:474.85550944010413,y:264.92191569010413,step:0},{x:470.92447916666663,y:287.9374593098958,step:0},{x:465.4818115234375,y:287.9374593098958,step:0},{x:469.4127197265625,y:264.92191569010413,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:490.9583740234375,y:259.6302083333333,step:2},{x:486.1197509765625,y:287.9374593098958,step:0},{x:480.67704264322913,y:287.9374593098958,step:0},{x:485.51566569010413,y:259.6302083333333,step:0},{x:490.9583740234375,y:259.6302083333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:498.1770833333333,y:280.5859375,step:2},{x:495.1913655598958,y:287.9374593098958,step:0},{x:489.3697509765625,y:287.9374593098958,step:0},{x:501.8072509765625,y:259.6302083333333,step:0},{x:508.79947916666663,y:259.6302083333333,step:0},{x:511.7473958333333,y:287.9374593098958,step:0},{x:506.0403645833333,y:287.9374593098958,step:0},{x:505.51041666666663,y:280.5859375,step:0},{x:498.1770833333333,y:280.5859375,step:0},{x:505.28385416666663,y:275.9661458333333,step:2},{x:504.79166666666663,y:269.87760416666663,step:0},{x:504.6796875,y:268.3229573567708,step:1},{x:504.5650634765625,y:266.05472819010413,step:1},{x:504.4530843098958,y:264.3333333333333,step:1},{x:504.3385009765625,y:264.3333333333333,step:0},{x:503.6966552734375,y:266.05472819010413,step:1},{x:502.9792073567708,y:268.2396240234375,step:1},{x:502.2981770833333,y:269.87760416666663,step:1},{x:499.80204264322913,y:275.9661458333333,step:0},{x:505.28385416666663,y:275.9661458333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:519.3463541666666,y:259.6302083333333,step:2},{x:524.7890625,y:259.6302083333333,step:0},{x:520.8568115234375,y:282.64579264322913,step:0},{x:530.6484375,y:282.64579264322913,step:0},{x:529.7395833333333,y:287.9374593098958,step:0},{x:514.5077718098958,y:287.9374593098958,step:0},{x:519.3463541666666,y:259.6302083333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],wc=[{type:"path",stampPoints:[{x:480.32816569010413,y:291.3645833333333,step:2},{x:480.32816569010413,y:297.2317708333333,step:1},{x:474.28125,y:302.03125,step:1},{x:466.8880615234375,y:302.03125,step:1},{x:350.91019694010413,y:302.03125,step:0},{x:343.51822916666663,y:302.03125,step:1},{x:337.4700724283854,y:297.2317708333333,step:1},{x:337.4700724283854,y:291.3645833333333,step:1},{x:337.4700724283854,y:254.3671875,step:0},{x:337.4700724283854,y:248.50069173177081,step:1},{x:343.51822916666663,y:243.70052083333331,step:1},{x:350.91019694010413,y:243.70052083333331,step:1},{x:466.8880615234375,y:243.70052083333331,step:0},{x:474.28125,y:243.70052083333331,step:1},{x:480.32816569010413,y:248.50069173177081,step:1},{x:480.32816569010413,y:254.3671875,step:1},{x:480.32816569010413,y:291.3645833333333,step:0}],borderWidth:0,borderColor:"rgba(0,0,0,0.8509803921568627)",background:"linear-gradient(to right bottom, #e4f1ff, #c9cee2)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:480.32816569010413,y:291.3645833333333,step:2},{x:480.32816569010413,y:297.2317708333333,step:1},{x:474.28125,y:302.03125,step:1},{x:466.8880615234375,y:302.03125,step:1},{x:350.91019694010413,y:302.03125,step:0},{x:343.51822916666663,y:302.03125,step:1},{x:337.4700724283854,y:297.2317708333333,step:1},{x:337.4700724283854,y:291.3645833333333,step:1},{x:337.4700724283854,y:254.3671875,step:0},{x:337.4700724283854,y:248.50069173177081,step:1},{x:343.51822916666663,y:243.70052083333331,step:1},{x:350.91019694010413,y:243.70052083333331,step:1},{x:466.8880615234375,y:243.70052083333331,step:0},{x:474.28125,y:243.70052083333331,step:1},{x:480.32816569010413,y:248.50069173177081,step:1},{x:480.32816569010413,y:254.3671875,step:1},{x:480.32816569010413,y:291.3645833333333,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(24,37,100,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:356.54886881510413,y:260.048828125,step:2},{x:358.7415364583333,y:259.6288655598958,step:1},{x:361.12308756510413,y:259.41861979166663,step:1},{x:363.61722819010413,y:259.41861979166663,step:1},{x:367.5865478515625,y:259.41861979166663,step:1},{x:370.7239583333333,y:260.42704264322913,step:1},{x:372.8782552083333,y:262.4849853515625,step:1},{x:374.9577229817708,y:264.33268229166663,step:1},{x:376.24283854166663,y:267.146484375,step:1},{x:376.24283854166663,y:271.3470052083333,step:1},{x:376.24283854166663,y:276.8073323567708,step:1},{x:374.1634114583333,y:281.5521240234375,step:1},{x:371.0267333984375,y:284.3671875,step:1},{x:368.07743326822913,y:287.01298014322913,step:1},{x:364.3352864583333,y:288.1458333333333,step:1},{x:358.8170979817708,y:288.1458333333333,step:1},{x:355.7552083333333,y:288.1458333333333,step:1},{x:353.10868326822913,y:287.85282389322913,step:1},{x:351.8235677083333,y:287.5598958333333,step:1},{x:356.54886881510413,y:260.048828125,step:0},{x:358.0989990234375,y:283.1067708333333,step:2},{x:358.7415364583333,y:283.19010416666663,step:1},{x:359.53515625,y:283.2317708333333,step:1},{x:360.47977701822913,y:283.2317708333333,step:1},{x:363.4284261067708,y:283.2317708333333,step:1},{x:366.0370686848958,y:282.0573323567708,step:1},{x:367.69986979166663,y:279.9569905598958,step:1},{x:369.4388020833333,y:277.7317708333333,step:1},{x:370.34574381510413,y:274.7916259765625,step:1},{x:370.34574381510413,y:271.38871256510413,step:1},{x:370.34574381510413,y:266.8952229817708,step:1},{x:368.1158447265625,y:264.24869791666663,step:1},{x:363.61722819010413,y:264.24869791666663,step:1},{x:362.67252604166663,y:264.24869791666663,step:1},{x:361.8782552083333,y:264.33268229166663,step:1},{x:361.31180826822913,y:264.458984375,step:1},{x:358.0989990234375,y:283.1067708333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:382.3288167317708,y:260.1335042317708,step:2},{x:384.0292561848958,y:259.67057291666663,step:1},{x:386.599609375,y:259.41861979166663,step:1},{x:389.1321614583333,y:259.41861979166663,step:1},{x:391.5520833333333,y:259.41861979166663,step:1},{x:394.0462239583333,y:259.79752604166663,step:1},{x:395.8228759765625,y:261.056640625,step:1},{x:397.48636881510413,y:262.1491292317708,step:1},{x:398.658203125,y:263.91276041666663,step:1},{x:398.658203125,y:266.5592854817708,step:1},{x:398.658203125,y:270.7591145833333,step:1},{x:396.1634114583333,y:273.4049072265625,step:1},{x:392.8743489583333,y:274.58072916666663,step:1},{x:392.8743489583333,y:274.70703125,step:0},{x:394.38671875,y:275.46354166666663,step:1},{x:395.06705729166663,y:277.3098958333333,step:1},{x:395.2942708333333,y:279.8723958333333,step:1},{x:395.6341145833333,y:283.06510416666663,step:1},{x:395.8228759765625,y:286.76041666666663,step:1},{x:396.2766927083333,y:287.9374593098958,step:1},{x:390.6823323567708,y:287.9374593098958,step:0},{x:390.45572916666663,y:287.18094889322913,step:1},{x:390.1907552083333,y:284.74479166666663,step:1},{x:389.96415201822913,y:281.2591145833333,step:1},{x:389.69921875,y:277.81510416666663,step:1},{x:388.6412353515625,y:276.765625,step:1},{x:386.486328125,y:276.765625,step:1},{x:384.8236083984375,y:276.765625,step:0},{x:382.9329427083333,y:287.9374593098958,step:0},{x:377.5657958984375,y:287.9374593098958,step:0},{x:382.3288167317708,y:260.1335042317708,step:0},{x:385.6549886067708,y:272.22855631510413,step:2},{x:387.88541666666663,y:272.22855631510413,step:0},{x:390.833984375,y:272.22855631510413,step:1},{x:392.9876708984375,y:270.25455729166663,step:1},{x:392.9876708984375,y:267.48246256510413,step:1},{x:392.9876708984375,y:265.1731770833333,step:1},{x:391.287109375,y:264.16471354166663,step:1},{x:389.0950520833333,y:264.16471354166663,step:1},{x:388.07421875,y:264.16471354166663,step:1},{x:387.431640625,y:264.24869791666663,step:1},{x:386.978515625,y:264.3749593098958,step:1},{x:385.6549886067708,y:272.22855631510413,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:406.9739583333333,y:280.5859375,step:2},{x:403.9876302083333,y:287.9374593098958,step:0},{x:398.1659749348958,y:287.9374593098958,step:0},{x:410.6028645833333,y:259.6288655598958,step:0},{x:417.59635416666663,y:259.6288655598958,step:0},{x:420.5442708333333,y:287.9374593098958,step:0},{x:414.8359375,y:287.9374593098958,step:0},{x:414.30729166666663,y:280.5859375,step:0},{x:406.9739583333333,y:280.5859375,step:0},{x:414.08072916666663,y:275.9661458333333,step:2},{x:413.58854166666663,y:269.8769124348958,step:0},{x:413.4753011067708,y:268.3229573567708,step:1},{x:413.36197916666663,y:266.0553792317708,step:1},{x:413.24869791666663,y:264.33268229166663,step:1},{x:413.1353759765625,y:264.33268229166663,step:0},{x:412.4921468098958,y:266.0553792317708,step:1},{x:411.7734375,y:268.2389729817708,step:1},{x:411.0937093098958,y:269.8769124348958,step:1},{x:408.599609375,y:275.9661458333333,step:0},{x:414.08072916666663,y:275.9661458333333,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:428.1419677734375,y:259.6288655598958,step:2},{x:443.07291666666663,y:259.6288655598958,step:0},{x:442.1653645833333,y:264.79496256510413,step:0},{x:432.71610514322913,y:264.79496256510413,step:0},{x:431.5442708333333,y:271.4309895833333,step:0},{x:440.42704264322913,y:271.4309895833333,step:0},{x:439.51822916666663,y:276.51298014322913,step:0},{x:430.67447916666663,y:276.51298014322913,step:0},{x:428.7460530598958,y:287.9374593098958,step:0},{x:423.3033447265625,y:287.9374593098958,step:0},{x:428.1419677734375,y:259.6288655598958,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:451.1614583333333,y:264.9206136067708,step:2},{x:444.43229166666663,y:264.9206136067708,step:0},{x:445.37760416666663,y:259.6288655598958,step:0},{x:464.3151448567708,y:259.6288655598958,step:0},{x:463.40885416666663,y:264.9206136067708,step:0},{x:456.6041259765625,y:264.9206136067708,step:0},{x:452.6731770833333,y:287.9374593098958,step:0},{x:447.22916666666663,y:287.9374593098958,step:0},{x:451.1614583333333,y:264.9206136067708,step:0}],borderWidth:0,borderColor:"rgba(24,37,100,1)",background:"rgba(24,37,100,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],Cc=[{type:"path",stampPoints:[{x:470.0130208333333,y:291.0103759765625,step:2},{x:470.0130208333333,y:296.87760416666663,step:1},{x:464.83203125,y:301.67704264322913,step:1},{x:458.4973958333333,y:301.67704264322913,step:1},{x:359.1308186848958,y:301.67704264322913,step:0},{x:352.7974853515625,y:301.67704264322913,step:1},{x:347.61588541666663,y:296.87760416666663,step:1},{x:347.61588541666663,y:291.0103759765625,step:1},{x:347.61588541666663,y:254.01236979166666,step:0},{x:347.61588541666663,y:248.14583333333331,step:1},{x:352.7974853515625,y:243.345703125,step:1},{x:359.1308186848958,y:243.345703125,step:1},{x:458.4973958333333,y:243.345703125,step:0},{x:464.83203125,y:243.345703125,step:1},{x:470.0130208333333,y:248.14583333333331,step:1},{x:470.0130208333333,y:254.01236979166666,step:1},{x:470.0130208333333,y:291.0103759765625,step:0}],borderWidth:0,borderColor:"rgba(0,0,0,0.8509803921568627)",background:"linear-gradient(to right bottom, #f1f6ea, #cedfc5)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:470.0130208333333,y:291.0103759765625,step:2},{x:470.0130208333333,y:296.87760416666663,step:1},{x:464.83203125,y:301.67704264322913,step:1},{x:458.4973958333333,y:301.67704264322913,step:1},{x:359.1308186848958,y:301.67704264322913,step:0},{x:352.7974853515625,y:301.67704264322913,step:1},{x:347.61588541666663,y:296.87760416666663,step:1},{x:347.61588541666663,y:291.0103759765625,step:1},{x:347.61588541666663,y:254.01302083333331,step:0},{x:347.61588541666663,y:248.14652506510416,step:1},{x:352.7974853515625,y:243.34635416666666,step:1},{x:359.1308186848958,y:243.34635416666666,step:1},{x:458.4973958333333,y:243.34635416666666,step:0},{x:464.83203125,y:243.34635416666666,step:1},{x:470.0130208333333,y:248.14652506510416,step:1},{x:470.0130208333333,y:254.01302083333331,step:1},{x:470.0130208333333,y:291.0103759765625,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(65,106,28,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:365.95768229166663,y:259.62955729166663,step:2},{x:380.888671875,y:259.62955729166663,step:0},{x:379.9810791015625,y:264.79496256510413,step:0},{x:370.5318603515625,y:264.79496256510413,step:0},{x:369.36002604166663,y:271.431640625,step:0},{x:378.24283854166663,y:271.431640625,step:0},{x:377.3359375,y:276.51298014322913,step:0},{x:368.4908447265625,y:276.51298014322913,step:0},{x:366.5625,y:287.9374593098958,step:0},{x:361.1197509765625,y:287.9374593098958,step:0},{x:365.95768229166663,y:259.62955729166663,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:390.6028645833333,y:259.62955729166663,step:2},{x:385.76493326822913,y:287.9374593098958,step:0},{x:380.3210042317708,y:287.9374593098958,step:0},{x:385.1595052083333,y:259.62955729166663,step:0},{x:390.6028645833333,y:259.62955729166663,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:390.79166666666663,y:287.9374593098958,step:2},{x:395.62955729166663,y:259.62955729166663,step:0},{x:402.01822916666663,y:259.62955729166663,step:0},{x:405.3822021484375,y:270.423828125,step:0},{x:406.4030354817708,y:274.03641764322913,step:1},{x:407.0833333333333,y:276.9739583333333,step:1},{x:407.68815104166663,y:280.0833740234375,step:1},{x:407.8013916015625,y:280.0833740234375,step:0},{x:407.91471354166663,y:277.18485514322913,step:1},{x:408.29300944010413,y:274.078125,step:1},{x:408.97330729166663,y:269.91861979166663,step:1},{x:410.7109375,y:259.62955729166663,step:0},{x:415.81510416666663,y:259.62955729166663,step:0},{x:410.97660319010413,y:287.9374593098958,step:0},{x:405.34440104166663,y:287.9374593098958,step:0},{x:401.79166666666663,y:276.6380208333333,step:0},{x:400.6569417317708,y:272.775390625,step:1},{x:399.9771728515625,y:270.212890625,step:1},{x:399.2962239583333,y:266.7689208984375,step:1},{x:399.18290201822913,y:266.7689208984375,step:0},{x:398.9185791015625,y:269.541015625,step:1},{x:398.31315104166663,y:273.53129069010413,step:1},{x:397.5579427083333,y:278.0260823567708,step:1},{x:395.8567708333333,y:287.9374593098958,step:0},{x:390.79166666666663,y:287.9374593098958,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:422.9974365234375,y:280.5859375,step:2},{x:420.0103759765625,y:287.9374593098958,step:0},{x:414.1888427734375,y:287.9374593098958,step:0},{x:426.625,y:259.62955729166663,step:0},{x:433.61722819010413,y:259.62955729166663,step:0},{x:436.5677083333333,y:287.9374593098958,step:0},{x:430.859375,y:287.9374593098958,step:0},{x:430.3294270833333,y:280.5859375,step:0},{x:422.9974365234375,y:280.5859375,step:0},{x:430.1028645833333,y:275.9661458333333,step:2},{x:429.61197916666663,y:269.8769124348958,step:0},{x:429.4973958333333,y:268.322265625,step:1},{x:429.38541666666663,y:266.0553792317708,step:1},{x:429.27079264322913,y:264.33268229166663,step:1},{x:429.15751139322913,y:264.33268229166663,step:0},{x:428.515625,y:266.0553792317708,step:1},{x:427.796875,y:268.2389729817708,step:1},{x:427.1171468098958,y:269.8769124348958,step:1},{x:424.6223958333333,y:275.9661458333333,step:0},{x:430.1028645833333,y:275.9661458333333,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:444.1640625,y:259.62955729166663,step:2},{x:449.6068115234375,y:259.62955729166663,step:0},{x:445.67704264322913,y:282.64579264322913,step:0},{x:455.4661458333333,y:282.64579264322913,step:0},{x:454.5598958333333,y:287.9374593098958,step:0},{x:439.32548014322913,y:287.9374593098958,step:0},{x:444.1640625,y:259.62955729166663,step:0}],borderWidth:0,borderColor:"rgba(65,106,28,1)",background:"rgba(65,106,28,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],bc=[{type:"path",stampPoints:[{x:347.4140625,y:272.89908854166663,step:2},{x:369.1386311848958,y:288.7083333333333,step:0},{x:463.5677490234375,y:288.7083333333333,step:0},{x:468.39322916666663,y:288.7083333333333,step:1},{x:472.33984375,y:285.10941569010413,step:1},{x:472.33984375,y:280.7083333333333,step:1},{x:472.33984375,y:264.2591145833333,step:0},{x:472.33984375,y:259.8587239583333,step:1},{x:468.39322916666663,y:256.2591145833333,step:1},{x:463.5677490234375,y:256.2591145833333,step:1},{x:369.1386311848958,y:256.2591145833333,step:0},{x:347.4140625,y:272.89908854166663,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(65,50,130,1)",background:"linear-gradient(to right bottom, #ccc2ff, #8677c7)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:386.35221354166663,y:267.82421875,step:2},{x:384.50846354166663,y:278.6067708333333,step:0},{x:382.435546875,y:278.6067708333333,step:0},{x:384.27799479166663,y:267.82421875,step:0},{x:386.35221354166663,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:386.4237874348958,y:278.6067708333333,step:2},{x:388.2669677734375,y:267.82421875,step:0},{x:390.7005208333333,y:267.82421875,step:0},{x:391.982421875,y:271.935546875,step:0},{x:392.37113444010413,y:273.3118489583333,step:1},{x:392.6302490234375,y:274.4322509765625,step:1},{x:392.8606770833333,y:275.6145833333333,step:1},{x:392.9036458333333,y:275.6145833333333,step:0},{x:392.94730631510413,y:274.51298014322913,step:1},{x:393.0911458333333,y:273.32816569010413,step:1},{x:393.3503011067708,y:271.744140625,step:1},{x:394.0124104817708,y:267.82421875,step:0},{x:395.9563802083333,y:267.82421875,step:0},{x:394.1132405598958,y:278.6067708333333,step:0},{x:391.9680989583333,y:278.6067708333333,step:0},{x:390.61393229166663,y:274.3046468098958,step:0},{x:390.1823323567708,y:272.83203125,step:1},{x:389.9232177734375,y:271.8561604817708,step:1},{x:389.66410319010413,y:270.5435791015625,step:1},{x:389.6204833984375,y:270.5435791015625,step:0},{x:389.52018229166663,y:271.599609375,step:1},{x:389.28971354166663,y:273.11979166666663,step:1},{x:389.0013020833333,y:274.83203125,step:1},{x:388.353515625,y:278.6067708333333,step:0},{x:386.4237874348958,y:278.6067708333333,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:399.88736979166663,y:267.82421875,step:2},{x:398.0442708333333,y:278.6067708333333,step:0},{x:395.970703125,y:278.6067708333333,step:0},{x:397.8138020833333,y:267.82421875,step:0},{x:399.88736979166663,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:403.2141927083333,y:269.83984375,step:2},{x:400.65104166666663,y:269.83984375,step:0},{x:401.0110677083333,y:267.82421875,step:0},{x:408.22526041666663,y:267.82421875,step:0},{x:407.87955729166663,y:269.83984375,step:0},{x:405.28776041666663,y:269.83984375,step:0},{x:403.7897542317708,y:278.6067708333333,step:0},{x:401.71610514322913,y:278.6067708333333,step:0},{x:403.2141927083333,y:269.83984375,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:411.421875,y:267.82421875,step:2},{x:409.5780843098958,y:278.6067708333333,step:0},{x:407.50455729166663,y:278.6067708333333,step:0},{x:409.3489990234375,y:267.82421875,step:0},{x:411.421875,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:414.1718343098958,y:275.80729166666663,step:2},{x:413.0338948567708,y:278.6067708333333,step:0},{x:410.8177490234375,y:278.6067708333333,step:0},{x:415.55472819010413,y:267.82421875,step:0},{x:418.21875,y:267.82421875,step:0},{x:419.3411458333333,y:278.6067708333333,step:0},{x:417.16666666666663,y:278.6067708333333,step:0},{x:416.9661458333333,y:275.80729166666663,step:0},{x:414.1718343098958,y:275.80729166666663,step:0},{x:416.8802083333333,y:274.04691569010413,step:2},{x:416.6927083333333,y:271.7278645833333,step:0},{x:416.6484375,y:271.1360677083333,step:1},{x:416.6054280598958,y:270.2714436848958,step:1},{x:416.5625,y:269.61588541666663,step:1},{x:416.5181884765625,y:269.61588541666663,step:0},{x:416.27347819010413,y:270.2714436848958,step:1},{x:416,y:271.1034749348958,step:1},{x:415.7421875,y:271.7278645833333,step:1},{x:414.79166666666663,y:274.04691569010413,step:0},{x:416.8802083333333,y:274.04691569010413,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:422.2357177734375,y:267.82421875,step:2},{x:424.3099365234375,y:267.82421875,step:0},{x:422.81254069010413,y:276.5911458333333,step:0},{x:426.5417073567708,y:276.5911458333333,step:0},{x:426.19535319010413,y:278.6067708333333,step:0},{x:420.39322916666663,y:278.6067708333333,step:0},{x:422.2357177734375,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:433.97135416666663,y:267.82421875,step:2},{x:433.25260416666663,y:272.0163167317708,step:0},{x:436.76566569010413,y:272.0163167317708,step:0},{x:437.48441569010413,y:267.82421875,step:0},{x:439.5729573567708,y:267.82421875,step:0},{x:437.7292073567708,y:278.6067708333333,step:0},{x:435.65629069010413,y:278.6067708333333,step:0},{x:436.4192708333333,y:274.0638020833333,step:0},{x:432.8905843098958,y:274.0638020833333,step:0},{x:432.12760416666663,y:278.6067708333333,step:0},{x:430.05472819010413,y:278.6067708333333,step:0},{x:431.8983968098958,y:267.82421875,step:0},{x:433.97135416666663,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:445.9530843098958,y:274.015625,step:2},{x:442.5103759765625,y:274.015625,step:0},{x:442.06510416666663,y:276.640625,step:0},{x:445.9374593098958,y:276.640625,step:0},{x:445.6068115234375,y:278.6067708333333,step:0},{x:439.6458740234375,y:278.6067708333333,step:0},{x:441.48832194010413,y:267.82421875,step:0},{x:447.234375,y:267.82421875,step:0},{x:446.8880615234375,y:269.7916259765625,step:0},{x:443.23173014322913,y:269.7916259765625,step:0},{x:442.828125,y:272.08011881510413,step:0},{x:446.29691569010413,y:272.08011881510413,step:0},{x:445.9530843098958,y:274.015625,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:448.9192708333333,y:268.0163167317708,step:2},{x:449.5677490234375,y:267.83984375,step:1},{x:450.546875,y:267.744140625,step:1},{x:451.51041666666663,y:267.744140625,step:1},{x:452.43229166666663,y:267.744140625,step:1},{x:453.3827718098958,y:267.8880615234375,step:1},{x:454.0598958333333,y:268.36783854166663,step:1},{x:454.6927083333333,y:268.78385416666663,step:1},{x:455.1405843098958,y:269.45572916666663,step:1},{x:455.1405843098958,y:270.46354166666663,step:1},{x:455.1405843098958,y:272.0638020833333,step:1},{x:454.1888427734375,y:273.07157389322913,step:1},{x:452.9375,y:273.5208333333333,step:1},{x:452.9375,y:273.5677083333333,step:0},{x:453.5130208333333,y:273.8567708333333,step:1},{x:453.77079264322913,y:274.5598958333333,step:1},{x:453.8580322265625,y:275.5364583333333,step:1},{x:453.98697916666663,y:276.75260416666663,step:1},{x:454.0598958333333,y:278.1588948567708,step:1},{x:454.2317708333333,y:278.6067708333333,step:1},{x:452.1015625,y:278.6067708333333,step:0},{x:452.01566569010413,y:278.3203125,step:1},{x:451.9140625,y:277.3919270833333,step:1},{x:451.828125,y:276.0638020833333,step:1},{x:451.7265625,y:274.75260416666663,step:1},{x:451.32291666666663,y:274.3515218098958,step:1},{x:450.50260416666663,y:274.3515218098958,step:1},{x:449.86979166666663,y:274.3515218098958,step:0},{x:449.1484375,y:278.6067708333333,step:0},{x:447.1041259765625,y:278.6067708333333,step:0},{x:448.9192708333333,y:268.0163167317708,step:0},{x:450.1862386067708,y:272.6236572265625,step:2},{x:451.0364583333333,y:272.6236572265625,step:0},{x:452.15885416666663,y:272.6236572265625,step:1},{x:452.9792073567708,y:271.87174479166663,step:1},{x:452.9792073567708,y:270.8157958984375,step:1},{x:452.9792073567708,y:269.935546875,step:1},{x:452.3307698567708,y:269.5521240234375,step:1},{x:451.4973958333333,y:269.5521240234375,step:1},{x:451.1067708333333,y:269.5521240234375,step:1},{x:450.8620198567708,y:269.583984375,step:1},{x:450.69010416666663,y:269.6314697265625,step:1},{x:450.1862386067708,y:272.6236572265625,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:461.79166666666663,y:274.015625,step:2},{x:458.3515625,y:274.015625,step:0},{x:457.90360514322913,y:276.640625,step:0},{x:461.77860514322913,y:276.640625,step:0},{x:461.44657389322913,y:278.6067708333333,step:0},{x:455.48441569010413,y:278.6067708333333,step:0},{x:457.328125,y:267.82421875,step:0},{x:463.07291666666663,y:267.82421875,step:0},{x:462.7292073567708,y:269.7916259765625,step:0},{x:459.0703125,y:269.7916259765625,step:0},{x:458.66666666666663,y:272.08011881510413,step:0},{x:462.1380208333333,y:272.08011881510413,step:0},{x:461.79166666666663,y:274.015625,step:0}],borderWidth:0,borderColor:"rgba(65,50,130,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],Sc=[{type:"path",stampPoints:[{x:551.4908854166666,y:293.8854573567708,step:2},{x:551.4908854166666,y:298.2864583333333,step:1},{x:546.6080729166666,y:301.8854573567708,step:1},{x:540.6393229166666,y:301.8854573567708,step:1},{x:278.845703125,y:301.8854573567708,step:0},{x:272.87760416666663,y:301.8854573567708,step:1},{x:267.99477132161456,y:298.2864583333333,step:1},{x:267.99477132161456,y:293.8854573567708,step:1},{x:267.99477132161456,y:251.88545735677081,step:0},{x:267.99477132161456,y:247.48502604166666,step:1},{x:272.87760416666663,y:243.88545735677081,step:1},{x:278.845703125,y:243.88545735677081,step:1},{x:540.6393229166666,y:243.88545735677081,step:0},{x:546.6080729166666,y:243.88545735677081,step:1},{x:551.4908854166666,y:247.48502604166666,step:1},{x:551.4908854166666,y:251.88545735677081,step:1},{x:551.4908854166666,y:293.8854573567708,step:0}],borderWidth:0,borderColor:"rgba(0,0,0,0.8509803921568627)",background:"linear-gradient(to right bottom, #f8eae7, #ffc6c6)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:551.4908854166666,y:293.8854573567708,step:2},{x:551.4908854166666,y:298.2864583333333,step:1},{x:546.6080729166666,y:301.8854573567708,step:1},{x:540.6393229166666,y:301.8854573567708,step:1},{x:278.845703125,y:301.8854573567708,step:0},{x:272.87760416666663,y:301.8854573567708,step:1},{x:267.99477132161456,y:298.2864583333333,step:1},{x:267.99477132161456,y:293.8854573567708,step:1},{x:267.99477132161456,y:251.88545735677081,step:0},{x:267.99477132161456,y:247.48502604166666,step:1},{x:272.87760416666663,y:243.88545735677081,step:1},{x:278.845703125,y:243.88545735677081,step:1},{x:540.6393229166666,y:243.88545735677081,step:0},{x:546.6080729166666,y:243.88545735677081,step:1},{x:551.4908854166666,y:247.48502604166666,step:1},{x:551.4908854166666,y:251.88545735677081,step:1},{x:551.4908854166666,y:293.8854573567708,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(145,15,5,0.2)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:551.4908854166666,y:293.8854573567708,step:2},{x:551.4908854166666,y:298.2864583333333,step:1},{x:546.6080729166666,y:301.8854573567708,step:1},{x:540.6393229166666,y:301.8854573567708,step:1},{x:278.845703125,y:301.8854573567708,step:0},{x:272.87760416666663,y:301.8854573567708,step:1},{x:267.99477132161456,y:298.2864583333333,step:1},{x:267.99477132161456,y:293.8854573567708,step:1},{x:267.99477132161456,y:251.88545735677081,step:0},{x:267.99477132161456,y:247.48502604166666,step:1},{x:272.87760416666663,y:243.88545735677081,step:1},{x:278.845703125,y:243.88545735677081,step:1},{x:540.6393229166666,y:243.88545735677081,step:0},{x:546.6080729166666,y:243.88545735677081,step:1},{x:551.4908854166666,y:247.48502604166666,step:1},{x:551.4908854166666,y:251.88545735677081,step:1},{x:551.4908854166666,y:293.8854573567708,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(145,15,5,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:281.60611979166663,y:288,step:2},{x:286.44403076171875,y:259.69205729166663,step:0},{x:292.83270263671875,y:259.69205729166663,step:0},{x:296.1966145833333,y:270.4856770833333,step:0},{x:297.21744791666663,y:274.0989583333333,step:1},{x:297.89711507161456,y:277.0377197265625,step:1},{x:298.50260416666663,y:280.1458333333333,step:1},{x:298.61588541666663,y:280.1458333333333,step:0},{x:298.72914632161456,y:277.2473958333333,step:1},{x:299.10744222005206,y:274.14066569010413,step:1},{x:299.78774007161456,y:269.9817708333333,step:1},{x:301.52604166666663,y:259.69205729166663,step:0},{x:306.62957763671875,y:259.69205729166663,step:0},{x:301.791015625,y:288,step:0},{x:296.15887451171875,y:288,step:0},{x:292.60546875,y:276.70182291666663,step:0},{x:291.47137451171875,y:272.837890625,step:1},{x:290.791015625,y:270.27604166666663,step:1},{x:290.1106974283854,y:266.83203125,step:1},{x:289.99737548828125,y:266.83203125,step:0},{x:289.73305257161456,y:269.6041259765625,step:1},{x:289.12760416666663,y:273.59375,step:1},{x:288.3724161783854,y:278.0885823567708,step:1},{x:286.67057291666663,y:288,step:0},{x:281.60611979166663,y:288,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:318.19596354166663,y:288.4622395833333,step:2},{x:311.58074951171875,y:288.4622395833333,step:1},{x:307.8763020833333,y:283.25394694010413,step:1},{x:307.8763020833333,y:276.66015625,step:1},{x:307.8763020833333,y:271.5364583333333,step:1},{x:309.57682291666663,y:266.4544270833333,step:1},{x:312.56378173828125,y:263.26236979166663,step:1},{x:314.9446614583333,y:260.7421875,step:1},{x:318.19596354166663,y:259.2298177083333,step:1},{x:321.86195882161456,y:259.2298177083333,step:1},{x:328.5911458333333,y:259.2298177083333,step:1},{x:332.14322916666663,y:264.27018229166663,step:1},{x:332.14322916666663,y:271.0325520833333,step:1},{x:332.14322916666663,y:276.1979573567708,step:1},{x:330.51822916666663,y:281.2369384765625,step:1},{x:327.60805257161456,y:284.3880208333333,step:1},{x:325.2265421549479,y:286.9505615234375,step:1},{x:322.0136515299479,y:288.4622395833333,step:1},{x:318.23307291666663,y:288.4622395833333,step:1},{x:318.19596354166663,y:288.4622395833333,step:0},{x:318.9895833333333,y:283.42191569010413,step:2},{x:320.6145833333333,y:283.42191569010413,step:1},{x:322.08854166666663,y:282.66666666666663,step:1},{x:323.26041666666663,y:281.3645833333333,step:1},{x:325.26430257161456,y:279.13798014322913,step:1},{x:326.3606974283854,y:274.4765218098958,step:1},{x:326.3606974283854,y:271.2005208333333,step:1},{x:326.3606974283854,y:267.6718343098958,step:1},{x:325.2265421549479,y:264.27018229166663,step:1},{x:321.2200520833333,y:264.27018229166663,step:1},{x:319.51822916666663,y:264.27018229166663,step:1},{x:318.00649007161456,y:265.06766764322913,step:1},{x:316.83465576171875,y:266.412109375,step:1},{x:314.79361979166663,y:268.6380208333333,step:1},{x:313.65948486328125,y:273.0481770833333,step:1},{x:313.65948486328125,y:276.4505208333333,step:1},{x:313.65948486328125,y:280.44010416666663,step:1},{x:315.28515625,y:283.42191569010413,step:1},{x:318.95182291666663,y:283.42191569010413,step:1},{x:318.9895833333333,y:283.42191569010413,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:340.64906819661456,y:264.98368326822913,step:2},{x:333.92055257161456,y:264.98368326822913,step:0},{x:334.865234375,y:259.69205729166663,step:0},{x:353.8033447265625,y:259.69205729166663,step:0},{x:352.8958740234375,y:264.98368326822913,step:0},{x:346.091796875,y:264.98368326822913,step:0},{x:342.16080729166663,y:288,step:0},{x:336.71744791666663,y:288,step:0},{x:340.64906819661456,y:264.98368326822913,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:366.0124104817708,y:280.64969889322913,step:2},{x:363.02604166666663,y:288,step:0},{x:357.2044270833333,y:288,step:0},{x:369.640625,y:259.69205729166663,step:0},{x:376.6341145833333,y:259.69205729166663,step:0},{x:379.58203125,y:288,step:0},{x:373.8743489583333,y:288,step:0},{x:373.3450520833333,y:280.64969889322913,step:0},{x:366.0124104817708,y:280.64969889322913,step:0},{x:373.11844889322913,y:276.0299886067708,step:2},{x:372.626953125,y:269.94010416666663,step:0},{x:372.513671875,y:268.38602701822913,step:1},{x:372.400390625,y:266.1184895833333,step:1},{x:372.2864583333333,y:264.3958333333333,step:1},{x:372.1731770833333,y:264.3958333333333,step:0},{x:371.5305989583333,y:266.1184895833333,step:1},{x:370.81254069010413,y:268.3020833333333,step:1},{x:370.1321614583333,y:269.94010416666663,step:1},{x:367.63736979166663,y:276.0299886067708,step:0},{x:373.11844889322913,y:276.0299886067708,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:387.06640625,y:260.1966552734375,step:2},{x:388.7292073567708,y:259.7337239583333,step:1},{x:391.2624104817708,y:259.4818115234375,step:1},{x:393.71940104166663,y:259.4818115234375,step:1},{x:396.0247395833333,y:259.4818115234375,step:1},{x:398.63346354166663,y:259.90234375,step:1},{x:400.4856770833333,y:261.3723958333333,step:1},{x:402.22391764322913,y:262.6321614583333,step:1},{x:403.2447509765625,y:264.6477864583333,step:1},{x:403.2447509765625,y:267.37760416666663,step:1},{x:403.2447509765625,y:270.94791666666663,step:1},{x:401.77079264322913,y:273.6783447265625,step:1},{x:399.8052978515625,y:275.35807291666663,step:1},{x:397.7259114583333,y:277.1640625,step:1},{x:394.7395833333333,y:278.00394694010413,step:1},{x:391.6399739583333,y:278.00394694010413,step:1},{x:390.73307291666663,y:278.00394694010413,step:1},{x:389.9771728515625,y:277.87760416666663,step:1},{x:389.41015625,y:277.8359375,step:1},{x:387.6712239583333,y:288,step:0},{x:382.3411458333333,y:288,step:0},{x:387.06640625,y:260.1966552734375,step:0},{x:390.2415364583333,y:272.8802490234375,step:2},{x:390.80863444010413,y:273.0058186848958,step:1},{x:391.4134114583333,y:273.0898030598958,step:1},{x:392.35807291666663,y:273.0898030598958,step:1},{x:395.609375,y:273.0898030598958,step:1},{x:397.763671875,y:270.7382405598958,step:1},{x:397.763671875,y:267.92447916666663,step:1},{x:397.763671875,y:265.19401041666663,step:1},{x:395.98697916666663,y:264.3118489583333,step:1},{x:393.908203125,y:264.3118489583333,step:1},{x:392.8880615234375,y:264.3118489583333,step:1},{x:392.13151041666663,y:264.3958333333333,step:1},{x:391.67838541666663,y:264.4798177083333,step:1},{x:390.2415364583333,y:272.8802490234375,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:408.3847249348958,y:260.1966552734375,step:2},{x:410.0481770833333,y:259.7337239583333,step:1},{x:412.58072916666663,y:259.4818115234375,step:1},{x:415.0378011067708,y:259.4818115234375,step:1},{x:417.3437093098958,y:259.4818115234375,step:1},{x:419.9517822265625,y:259.90234375,step:1},{x:421.8033447265625,y:261.3723958333333,step:1},{x:423.5417073567708,y:262.6321614583333,step:1},{x:424.5638020833333,y:264.6477864583333,step:1},{x:424.5638020833333,y:267.37760416666663,step:1},{x:424.5638020833333,y:270.94791666666663,step:1},{x:423.08854166666663,y:273.6783447265625,step:1},{x:421.12369791666663,y:275.35807291666663,step:1},{x:419.0442708333333,y:277.1640625,step:1},{x:416.05729166666663,y:278.00394694010413,step:1},{x:412.9583740234375,y:278.00394694010413,step:1},{x:412.0520833333333,y:278.00394694010413,step:1},{x:411.2956136067708,y:277.87760416666663,step:1},{x:410.7292073567708,y:277.8359375,step:1},{x:408.9896240234375,y:288,step:0},{x:403.66019694010413,y:288,step:0},{x:408.3847249348958,y:260.1966552734375,step:0},{x:411.5598958333333,y:272.8802490234375,step:2},{x:412.12760416666663,y:273.0058186848958,step:1},{x:412.7317708333333,y:273.0898030598958,step:1},{x:413.67704264322913,y:273.0898030598958,step:1},{x:416.9270833333333,y:273.0898030598958,step:1},{x:419.08203125,y:270.7382405598958,step:1},{x:419.08203125,y:267.92447916666663,step:1},{x:419.08203125,y:265.19401041666663,step:1},{x:417.3059895833333,y:264.3118489583333,step:1},{x:415.2265625,y:264.3118489583333,step:1},{x:414.20572916666663,y:264.3118489583333,step:1},{x:413.45048014322913,y:264.3958333333333,step:1},{x:412.9974365234375,y:264.4798177083333,step:1},{x:411.5598958333333,y:272.8802490234375,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:429.77860514322913,y:260.1966552734375,step:2},{x:431.4792073567708,y:259.7337239583333,step:1},{x:434.0494384765625,y:259.4818115234375,step:1},{x:436.58329264322913,y:259.4818115234375,step:1},{x:439.00260416666663,y:259.4818115234375,step:1},{x:441.4973958333333,y:259.8606770833333,step:1},{x:443.2734375,y:261.11979166666663,step:1},{x:444.9362386067708,y:262.2122395833333,step:1},{x:446.10807291666663,y:263.9759114583333,step:1},{x:446.10807291666663,y:266.6223958333333,step:1},{x:446.10807291666663,y:270.82230631510413,step:1},{x:443.6145833333333,y:273.46879069010413,step:1},{x:440.3255208333333,y:274.64322916666663,step:1},{x:440.3255208333333,y:274.7708333333333,step:0},{x:441.83719889322913,y:275.5260823567708,step:1},{x:442.5181884765625,y:277.37369791666663,step:1},{x:442.7447509765625,y:279.93619791666663,step:1},{x:443.08463541666663,y:283.12760416666663,step:1},{x:443.2734375,y:286.82425944010413,step:1},{x:443.7265625,y:288,step:1},{x:438.1328125,y:288,step:0},{x:437.90625,y:287.24479166666663,step:1},{x:437.640625,y:284.8073323567708,step:1},{x:437.4140625,y:281.3229573567708,step:1},{x:437.1497395833333,y:277.87760416666663,step:1},{x:436.0911458333333,y:276.82816569010413,step:1},{x:433.9374593098958,y:276.82816569010413,step:1},{x:432.27347819010413,y:276.82816569010413,step:0},{x:430.3841145833333,y:288,step:0},{x:425.01566569010413,y:288,step:0},{x:429.77860514322913,y:260.1966552734375,step:0},{x:433.1054280598958,y:272.2916259765625,step:2},{x:435.3359375,y:272.2916259765625,step:0},{x:438.2838948567708,y:272.2916259765625,step:1},{x:440.43876139322913,y:270.31766764322913,step:1},{x:440.43876139322913,y:267.54557291666663,step:1},{x:440.43876139322913,y:265.2362874348958,step:1},{x:438.73697916666663,y:264.2279052734375,step:1},{x:436.5442708333333,y:264.2279052734375,step:1},{x:435.5247395833333,y:264.2279052734375,step:1},{x:434.88151041666663,y:264.3118489583333,step:1},{x:434.42838541666663,y:264.4381103515625,step:1},{x:433.1054280598958,y:272.2916259765625,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:458.43094889322913,y:288.4622395833333,step:2},{x:451.81510416666663,y:288.4622395833333,step:1},{x:448.1119384765625,y:283.25394694010413,step:1},{x:448.1119384765625,y:276.66015625,step:1},{x:448.1119384765625,y:271.5364583333333,step:1},{x:449.8125,y:266.4544270833333,step:1},{x:452.79947916666663,y:263.26236979166663,step:1},{x:455.1796468098958,y:260.7421875,step:1},{x:458.43094889322913,y:259.2298177083333,step:1},{x:462.09765625,y:259.2298177083333,step:1},{x:468.8255208333333,y:259.2298177083333,step:1},{x:472.3802083333333,y:264.27018229166663,step:1},{x:472.3802083333333,y:271.0325520833333,step:1},{x:472.3802083333333,y:276.1979573567708,step:1},{x:470.75390625,y:281.2369384765625,step:1},{x:467.8437093098958,y:284.3880208333333,step:1},{x:465.4622802734375,y:286.9505615234375,step:1},{x:462.24869791666663,y:288.4622395833333,step:1},{x:458.4687093098958,y:288.4622395833333,step:1},{x:458.43094889322913,y:288.4622395833333,step:0},{x:459.22391764322913,y:283.42191569010413,step:2},{x:460.85026041666663,y:283.42191569010413,step:1},{x:462.32421875,y:282.66666666666663,step:1},{x:463.49609375,y:281.3645833333333,step:1},{x:465.5,y:279.13798014322913,step:1},{x:466.59635416666663,y:274.4765218098958,step:1},{x:466.59635416666663,y:271.2005208333333,step:1},{x:466.59635416666663,y:267.6718343098958,step:1},{x:465.4622802734375,y:264.27018229166663,step:1},{x:461.45572916666663,y:264.27018229166663,step:1},{x:459.75390625,y:264.27018229166663,step:1},{x:458.2421875,y:265.06766764322913,step:1},{x:457.0703125,y:266.412109375,step:1},{x:455.0286865234375,y:268.6380208333333,step:1},{x:453.8958333333333,y:273.0481770833333,step:1},{x:453.8958333333333,y:276.4505208333333,step:1},{x:453.8958333333333,y:280.44010416666663,step:1},{x:455.5208740234375,y:283.42191569010413,step:1},{x:459.1875,y:283.42191569010413,step:1},{x:459.22391764322913,y:283.42191569010413,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:478.8046875,y:288,step:2},{x:475.6302490234375,y:259.69205729166663,step:0},{x:481.2630208333333,y:259.69205729166663,step:0},{x:482.3958740234375,y:273.1737874348958,step:0},{x:482.6614583333333,y:276.1979573567708,step:1},{x:482.8489990234375,y:278.9284261067708,step:1},{x:483.0013020833333,y:281.8684895833333,step:1},{x:483.07682291666663,y:281.8684895833333,step:0},{x:484.0208740234375,y:279.09635416666663,step:1},{x:485.23173014322913,y:276.07291666666663,step:1},{x:486.47916666666663,y:273.13151041666663,step:1},{x:492.1862386067708,y:259.69205729166663,step:0},{x:498.27213541666663,y:259.69205729166663,step:0},{x:485.1171468098958,y:288,step:0},{x:478.8046875,y:288,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:512.9766031901041,y:275.9466145833333,step:2},{x:503.94266764322913,y:275.9466145833333,step:0},{x:502.7708333333333,y:282.8333333333333,step:0},{x:512.9388020833333,y:282.8333333333333,step:0},{x:512.0690104166666,y:288,step:0},{x:496.4192708333333,y:288,step:0},{x:501.2578125,y:259.69205729166663,step:0},{x:516.3411458333333,y:259.69205729166663,step:0},{x:515.4323323567708,y:264.85807291666663,step:0},{x:505.83203125,y:264.85807291666663,step:0},{x:504.7734375,y:270.8646240234375,step:0},{x:513.8828125,y:270.8646240234375,step:0},{x:512.9766031901041,y:275.9466145833333,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:520.7252604166666,y:260.1119384765625,step:2},{x:522.9166259765625,y:259.69205729166663,step:1},{x:525.2994791666666,y:259.4818115234375,step:1},{x:527.7942708333333,y:259.4818115234375,step:1},{x:531.7630208333333,y:259.4818115234375,step:1},{x:534.8997395833333,y:260.4901936848958,step:1},{x:537.0547281901041,y:262.5482177734375,step:1},{x:539.1340738932291,y:264.3958333333333,step:1},{x:540.4192708333333,y:267.20963541666663,step:1},{x:540.4192708333333,y:271.4101155598958,step:1},{x:540.4192708333333,y:276.86979166666663,step:1},{x:538.33984375,y:281.61588541666663,step:1},{x:535.203125,y:284.4296875,step:1},{x:532.25390625,y:287.0755208333333,step:1},{x:528.5116780598958,y:288.20963541666663,step:1},{x:522.9935302734375,y:288.20963541666663,step:1},{x:519.9309895833333,y:288.20963541666663,step:1},{x:517.2851155598958,y:287.91666666666663,step:1},{x:516,y:287.6223958333333,step:1},{x:520.7252604166666,y:260.1119384765625,step:0},{x:522.2747802734375,y:283.1692708333333,step:2},{x:522.9166259765625,y:283.25394694010413,step:1},{x:523.7109375,y:283.29557291666663,step:1},{x:524.65625,y:283.29557291666663,step:1},{x:527.6041666666666,y:283.29557291666663,step:1},{x:530.2135416666666,y:282.11979166666663,step:1},{x:531.8763020833333,y:280.0208333333333,step:1},{x:533.6145833333333,y:277.7942708333333,step:1},{x:534.5221354166666,y:274.85416666666663,step:1},{x:534.5221354166666,y:271.45182291666663,step:1},{x:534.5221354166666,y:266.95829264322913,step:1},{x:532.2917073567708,y:264.3118489583333,step:1},{x:527.7942708333333,y:264.3118489583333,step:1},{x:526.8489990234375,y:264.3118489583333,step:1},{x:526.0547281901041,y:264.3958333333333,step:1},{x:525.4870198567708,y:264.52213541666663,step:1},{x:522.2747802734375,y:283.1692708333333,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],Tc=[{type:"path",stampPoints:[{x:420.5598958333333,y:265.5247395833333,step:2},{x:416.81119791666663,y:261.8561604817708,step:0},{x:409.3333333333333,y:269.3333333333333,step:0},{x:401.9127197265625,y:261.912109375,step:0},{x:398.3177490234375,y:265.50846354166663,step:0},{x:405.7382405598958,y:272.9290364583333,step:0},{x:398.3151448567708,y:280.3515218098958,step:0},{x:402.0638020833333,y:284.01822916666663,step:0},{x:409.48832194010413,y:276.5989583333333,step:0},{x:416.95703125,y:284.06766764322913,step:0},{x:420.5520833333333,y:280.4713134765625,step:0},{x:413.08203125,y:273.0032552083333,step:0},{x:420.5598958333333,y:265.5247395833333,step:0,close:!0}],borderWidth:0,borderColor:"rgba(0,0,0,1)",background:"linear-gradient(to right bottom, #f89077, #b21f10)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:420.5598958333333,y:265.5247395833333,step:2},{x:416.81119791666663,y:261.8561604817708,step:0},{x:409.3333333333333,y:269.3333333333333,step:0},{x:401.9127197265625,y:261.912109375,step:0},{x:398.3177490234375,y:265.50846354166663,step:0},{x:405.7382405598958,y:272.9290364583333,step:0},{x:398.3151448567708,y:280.3515218098958,step:0},{x:402.0638020833333,y:284.01822916666663,step:0},{x:409.48832194010413,y:276.5989583333333,step:0},{x:416.95703125,y:284.06766764322913,step:0},{x:420.5520833333333,y:280.4713134765625,step:0},{x:413.08203125,y:273.0032552083333,step:0},{x:420.5598958333333,y:265.5247395833333,step:0,close:!0}],borderWidth:1.3333333333333333,borderColor:"rgba(145,15,5,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],Ec=[{type:"path",stampPoints:[{x:347.4140625,y:272.89908854166663,step:2},{x:369.1386311848958,y:288.7083333333333,step:0},{x:463.5677490234375,y:288.7083333333333,step:0},{x:468.39322916666663,y:288.7083333333333,step:1},{x:472.33984375,y:285.10941569010413,step:1},{x:472.33984375,y:280.7083333333333,step:1},{x:472.33984375,y:264.2591145833333,step:0},{x:472.33984375,y:259.8587239583333,step:1},{x:468.39322916666663,y:256.2591145833333,step:1},{x:463.5677490234375,y:256.2591145833333,step:1},{x:369.1386311848958,y:256.2591145833333,step:0},{x:347.4140625,y:272.89908854166663,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(110,0,5,1)",background:"linear-gradient(to right bottom, #f89077, #cc4a31)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:397.2669270833333,y:276.1119384765625,step:2},{x:397.8430989583333,y:276.4791259765625,step:1},{x:398.64908854166663,y:276.78385416666663,step:1},{x:399.556640625,y:276.78385416666663,step:1},{x:400.3483479817708,y:276.78385416666663,step:1},{x:401.08268229166663,y:276.3671875,step:1},{x:401.08268229166663,y:275.5364583333333,step:1},{x:401.08268229166663,y:274.9114583333333,step:1},{x:400.6653645833333,y:274.5286458333333,step:1},{x:399.77274576822913,y:274,step:1},{x:398.75,y:273.3919270833333,step:1},{x:397.77079264322913,y:272.5598958333333,step:1},{x:397.77079264322913,y:271.16796875,step:1},{x:397.77079264322913,y:268.9921875,step:1},{x:399.4700520833333,y:267.6640625,step:1},{x:401.5865478515625,y:267.6640625,step:1},{x:402.75321451822913,y:267.6640625,step:1},{x:403.44462076822913,y:267.95182291666663,step:1},{x:403.86258951822913,y:268.1920979817708,step:1},{x:403.2141927083333,y:270.111328125,step:0},{x:402.8977864583333,y:269.919921875,step:1},{x:402.220703125,y:269.6314697265625,step:1},{x:401.4140625,y:269.6477864583333,step:1},{x:400.4491780598958,y:269.6477864583333,step:1},{x:399.9452718098958,y:270.17582194010413,step:1},{x:399.9452718098958,y:270.767578125,step:1},{x:399.9452718098958,y:271.3919270833333,step:1},{x:400.53580729166663,y:271.775390625,step:1},{x:401.35611979166663,y:272.28776041666663,step:1},{x:402.53776041666663,y:272.9759114583333,step:1},{x:403.2720947265625,y:273.83984375,step:1},{x:403.2720947265625,y:275.13541666666663,step:1},{x:403.2720947265625,y:277.5364583333333,step:1},{x:401.48636881510413,y:278.7682698567708,step:1},{x:399.34049479166663,y:278.7682698567708,step:1},{x:398.0013020833333,y:278.75260416666663,step:1},{x:397.0221761067708,y:278.3671875,step:1},{x:396.5755208333333,y:278,step:1},{x:397.2669270833333,y:276.1119384765625,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:408.052734375,y:267.82421875,step:2},{x:406.20963541666663,y:278.6067708333333,step:0},{x:404.1361083984375,y:278.6067708333333,step:0},{x:405.97916666666663,y:267.82421875,step:0},{x:408.052734375,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:416.1302083333333,y:278.1119384765625,step:2},{x:415.3958740234375,y:278.3827718098958,step:1},{x:414.2161458333333,y:278.71879069010413,step:1},{x:412.9921875,y:278.71879069010413,step:1},{x:411.66666666666663,y:278.71879069010413,step:1},{x:410.5572509765625,y:278.3358968098958,step:1},{x:409.765625,y:277.5364583333333,step:1},{x:408.98832194010413,y:276.78385416666663,step:1},{x:408.5423177083333,y:275.5833333333333,step:1},{x:408.5423177083333,y:274.2083333333333,step:1},{x:408.5423177083333,y:272.1920979817708,step:1},{x:409.27665201822913,y:270.44791666666663,step:1},{x:410.515625,y:269.279296875,step:1},{x:411.609375,y:268.2714436848958,step:1},{x:413.12109375,y:267.7115478515625,step:1},{x:414.8059895833333,y:267.7115478515625,step:1},{x:416.05859375,y:267.7115478515625,step:1},{x:416.9948323567708,y:267.98368326822913,step:1},{x:417.3697509765625,y:268.1920979817708,step:1},{x:416.75,y:270.1438802083333,step:0},{x:416.3177490234375,y:269.919921875,step:1},{x:415.55472819010413,y:269.69596354166663,step:1},{x:414.69010416666663,y:269.69596354166663,step:1},{x:413.7265625,y:269.69596354166663,step:1},{x:412.8763020833333,y:270,step:1},{x:412.2292073567708,y:270.5598958333333,step:1},{x:411.37890625,y:271.29557291666663,step:1},{x:410.8177490234375,y:272.57621256510413,step:1},{x:410.8177490234375,y:274.04691569010413,step:1},{x:410.8177490234375,y:275.8567708333333,step:1},{x:411.7812093098958,y:276.7682698567708,step:1},{x:413.3072509765625,y:276.7682698567708,step:1},{x:413.796875,y:276.7682698567708,step:1},{x:414.12894694010413,y:276.6875,step:1},{x:414.37504069010413,y:276.5755208333333,step:1},{x:414.7630615234375,y:274.3046468098958,step:0},{x:413.2499593098958,y:274.3046468098958,step:0},{x:413.58203125,y:272.46354166666663,step:0},{x:417.109375,y:272.46354166666663,step:0},{x:416.1302083333333,y:278.1119384765625,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:417.81510416666663,y:278.6067708333333,step:2},{x:419.65885416666663,y:267.82421875,step:0},{x:422.09244791666663,y:267.82421875,step:0},{x:423.37504069010413,y:271.935546875,step:0},{x:423.7630208333333,y:273.3118489583333,step:1},{x:424.0221761067708,y:274.4322509765625,step:1},{x:424.25260416666663,y:275.6145833333333,step:1},{x:424.2956136067708,y:275.6145833333333,step:0},{x:424.3385009765625,y:274.51298014322913,step:1},{x:424.4817708333333,y:273.32816569010413,step:1},{x:424.7421875,y:271.744140625,step:1},{x:425.4036458333333,y:267.82421875,step:0},{x:427.3489990234375,y:267.82421875,step:0},{x:425.50516764322913,y:278.6067708333333,step:0},{x:423.359375,y:278.6067708333333,step:0},{x:422.00516764322913,y:274.3046468098958,step:0},{x:421.5729573567708,y:272.83203125,step:1},{x:421.31510416666663,y:271.8561604817708,step:1},{x:421.05472819010413,y:270.5435791015625,step:1},{x:421.0130208333333,y:270.5435791015625,step:0},{x:420.91141764322913,y:271.599609375,step:1},{x:420.6809895833333,y:273.11979166666663,step:1},{x:420.39322916666663,y:274.83203125,step:1},{x:419.7447509765625,y:278.6067708333333,step:0},{x:417.81510416666663,y:278.6067708333333,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:433.97135416666663,y:267.82421875,step:2},{x:433.25260416666663,y:272.0163167317708,step:0},{x:436.76566569010413,y:272.0163167317708,step:0},{x:437.48441569010413,y:267.82421875,step:0},{x:439.5729573567708,y:267.82421875,step:0},{x:437.7292073567708,y:278.6067708333333,step:0},{x:435.65629069010413,y:278.6067708333333,step:0},{x:436.4192708333333,y:274.0638020833333,step:0},{x:432.8905843098958,y:274.0638020833333,step:0},{x:432.12760416666663,y:278.6067708333333,step:0},{x:430.05472819010413,y:278.6067708333333,step:0},{x:431.8983968098958,y:267.82421875,step:0},{x:433.97135416666663,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:445.9530843098958,y:274.015625,step:2},{x:442.5103759765625,y:274.015625,step:0},{x:442.06510416666663,y:276.640625,step:0},{x:445.9374593098958,y:276.640625,step:0},{x:445.6068115234375,y:278.6067708333333,step:0},{x:439.6458740234375,y:278.6067708333333,step:0},{x:441.48832194010413,y:267.82421875,step:0},{x:447.234375,y:267.82421875,step:0},{x:446.8880615234375,y:269.7916259765625,step:0},{x:443.23173014322913,y:269.7916259765625,step:0},{x:442.828125,y:272.08011881510413,step:0},{x:446.29691569010413,y:272.08011881510413,step:0},{x:445.9530843098958,y:274.015625,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:448.9192708333333,y:268.0163167317708,step:2},{x:449.5677490234375,y:267.83984375,step:1},{x:450.546875,y:267.744140625,step:1},{x:451.51041666666663,y:267.744140625,step:1},{x:452.43229166666663,y:267.744140625,step:1},{x:453.3827718098958,y:267.8880615234375,step:1},{x:454.0598958333333,y:268.36783854166663,step:1},{x:454.6927083333333,y:268.78385416666663,step:1},{x:455.1405843098958,y:269.45572916666663,step:1},{x:455.1405843098958,y:270.46354166666663,step:1},{x:455.1405843098958,y:272.0638020833333,step:1},{x:454.1888427734375,y:273.07157389322913,step:1},{x:452.9375,y:273.5208333333333,step:1},{x:452.9375,y:273.5677083333333,step:0},{x:453.5130208333333,y:273.8567708333333,step:1},{x:453.77079264322913,y:274.5598958333333,step:1},{x:453.8580322265625,y:275.5364583333333,step:1},{x:453.98697916666663,y:276.75260416666663,step:1},{x:454.0598958333333,y:278.1588948567708,step:1},{x:454.2317708333333,y:278.6067708333333,step:1},{x:452.1015625,y:278.6067708333333,step:0},{x:452.01566569010413,y:278.3203125,step:1},{x:451.9140625,y:277.3919270833333,step:1},{x:451.828125,y:276.0638020833333,step:1},{x:451.7265625,y:274.75260416666663,step:1},{x:451.32291666666663,y:274.3515218098958,step:1},{x:450.50260416666663,y:274.3515218098958,step:1},{x:449.86979166666663,y:274.3515218098958,step:0},{x:449.1484375,y:278.6067708333333,step:0},{x:447.1041259765625,y:278.6067708333333,step:0},{x:448.9192708333333,y:268.0163167317708,step:0},{x:450.1862386067708,y:272.6236572265625,step:2},{x:451.0364583333333,y:272.6236572265625,step:0},{x:452.15885416666663,y:272.6236572265625,step:1},{x:452.9792073567708,y:271.87174479166663,step:1},{x:452.9792073567708,y:270.8157958984375,step:1},{x:452.9792073567708,y:269.935546875,step:1},{x:452.3307698567708,y:269.5521240234375,step:1},{x:451.4973958333333,y:269.5521240234375,step:1},{x:451.1067708333333,y:269.5521240234375,step:1},{x:450.8620198567708,y:269.583984375,step:1},{x:450.69010416666663,y:269.6314697265625,step:1},{x:450.1862386067708,y:272.6236572265625,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:461.79166666666663,y:274.015625,step:2},{x:458.3515625,y:274.015625,step:0},{x:457.90360514322913,y:276.640625,step:0},{x:461.77860514322913,y:276.640625,step:0},{x:461.44657389322913,y:278.6067708333333,step:0},{x:455.48441569010413,y:278.6067708333333,step:0},{x:457.328125,y:267.82421875,step:0},{x:463.07291666666663,y:267.82421875,step:0},{x:462.7292073567708,y:269.7916259765625,step:0},{x:459.0703125,y:269.7916259765625,step:0},{x:458.66666666666663,y:272.08011881510413,step:0},{x:462.1380208333333,y:272.08011881510413,step:0},{x:461.79166666666663,y:274.015625,step:0}],borderWidth:0,borderColor:"rgba(110,0,5,1)",background:"rgba(0,0,0,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],_c=[{type:"path",stampPoints:[{x:465.87760416666663,y:290.62760416666663,step:2},{x:465.87760416666663,y:296.4948323567708,step:1},{x:461.0780843098958,y:301.2942708333333,step:1},{x:455.2109375,y:301.2942708333333,step:1},{x:363.1640625,y:301.2942708333333,step:0},{x:357.2974853515625,y:301.2942708333333,step:1},{x:352.4973958333333,y:296.4948323567708,step:1},{x:352.4973958333333,y:290.62760416666663,step:1},{x:352.4973958333333,y:253.63081868489581,step:0},{x:352.4973958333333,y:247.7642822265625,step:1},{x:357.2974853515625,y:242.96415201822916,step:1},{x:363.1640625,y:242.96415201822916,step:1},{x:455.2109375,y:242.96415201822916,step:0},{x:461.0780843098958,y:242.96415201822916,step:1},{x:465.87760416666663,y:247.7642822265625,step:1},{x:465.87760416666663,y:253.63081868489581,step:1},{x:465.87760416666663,y:290.62760416666663,step:0}],borderWidth:0,borderColor:"rgba(0,0,0,0.8509803921568627)",background:"linear-gradient(to right bottom, #f8eae7, #ffc6c6)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:10},{type:"path",stampPoints:[{x:465.87760416666663,y:290.62760416666663,step:2},{x:465.87760416666663,y:296.4948323567708,step:1},{x:461.0780843098958,y:301.2942708333333,step:1},{x:455.2109375,y:301.2942708333333,step:1},{x:363.1640625,y:301.2942708333333,step:0},{x:357.2974853515625,y:301.2942708333333,step:1},{x:352.4973958333333,y:296.4948323567708,step:1},{x:352.4973958333333,y:290.62760416666663,step:1},{x:352.4973958333333,y:253.63081868489581,step:0},{x:352.4973958333333,y:247.7642822265625,step:1},{x:357.2974853515625,y:242.96415201822916,step:1},{x:363.1640625,y:242.96415201822916,step:1},{x:455.2109375,y:242.96415201822916,step:0},{x:461.0780843098958,y:242.96415201822916,step:1},{x:465.87760416666663,y:247.7642822265625,step:1},{x:465.87760416666663,y:253.63081868489581,step:1},{x:465.87760416666663,y:290.62760416666663,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(145,15,5,1)",background:null,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:371.2519124348958,y:286.9765625,step:2},{x:368.0761311848958,y:258.6692708333333,step:0},{x:373.708984375,y:258.6692708333333,step:0},{x:374.84183756510413,y:272.15043131510413,step:0},{x:375.1073811848958,y:275.17447916666663,step:1},{x:375.2962239583333,y:277.90360514322913,step:1},{x:375.447265625,y:280.8450520833333,step:1},{x:375.5228271484375,y:280.8450520833333,step:0},{x:376.46805826822913,y:278.07291666666663,step:1},{x:377.677734375,y:275.0494384765625,step:1},{x:378.923828125,y:272.1087239583333,step:1},{x:384.6321614583333,y:258.6692708333333,step:0},{x:390.71805826822913,y:258.6692708333333,step:0},{x:377.564453125,y:286.9765625,step:0},{x:371.2519124348958,y:286.9765625,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:399.7519124348958,y:287.4388427734375,step:2},{x:393.1373291015625,y:287.4388427734375,step:1},{x:389.4329427083333,y:282.2318115234375,step:1},{x:389.4329427083333,y:275.63798014322913,step:1},{x:389.4329427083333,y:270.51298014322913,step:1},{x:391.1347249348958,y:265.4309895833333,step:1},{x:394.1204427083333,y:262.2389729817708,step:1},{x:396.501953125,y:259.7193603515625,step:1},{x:399.7519124348958,y:258.20768229166663,step:1},{x:403.4185791015625,y:258.20768229166663,step:1},{x:410.14847819010413,y:258.20768229166663,step:1},{x:413.7005615234375,y:263.2473958333333,step:1},{x:413.7005615234375,y:270.0091552734375,step:1},{x:413.7005615234375,y:275.17447916666663,step:1},{x:412.0755208333333,y:280.2161865234375,step:1},{x:409.1634114583333,y:283.3645833333333,step:1},{x:406.7831624348958,y:285.9270833333333,step:1},{x:403.5697021484375,y:287.4388427734375,step:1},{x:399.791015625,y:287.4388427734375,step:1},{x:399.7519124348958,y:287.4388427734375,step:0},{x:400.5462239583333,y:282.3984375,step:2},{x:402.1712239583333,y:282.3984375,step:1},{x:403.646484375,y:281.64322916666663,step:1},{x:404.818359375,y:280.3411458333333,step:1},{x:406.8210042317708,y:278.1145833333333,step:1},{x:407.91727701822913,y:273.453125,step:1},{x:407.91727701822913,y:270.1771240234375,step:1},{x:407.91727701822913,y:266.64908854166663,step:1},{x:406.7831624348958,y:263.2473958333333,step:1},{x:402.7753499348958,y:263.2473958333333,step:1},{x:401.0761311848958,y:263.2473958333333,step:1},{x:399.5631917317708,y:264.044921875,step:1},{x:398.39127604166663,y:265.38871256510413,step:1},{x:396.3509114583333,y:267.6145833333333,step:1},{x:395.21683756510413,y:272.0247395833333,step:1},{x:395.21683756510413,y:275.4270833333333,step:1},{x:395.21683756510413,y:279.4167073567708,step:1},{x:396.84183756510413,y:282.3984375,step:1},{x:400.50846354166663,y:282.3984375,step:1},{x:400.5462239583333,y:282.3984375,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:425.1536458333333,y:258.6692708333333,step:2},{x:420.3151448567708,y:286.9765625,step:0},{x:414.8723958333333,y:286.9765625,step:0},{x:419.7109375,y:258.6692708333333,step:0},{x:425.1536458333333,y:258.6692708333333,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:430.10416666666663,y:259.0892333984375,step:2},{x:432.29691569010413,y:258.6692708333333,step:1},{x:434.6796875,y:258.458984375,step:1},{x:437.1744384765625,y:258.458984375,step:1},{x:441.1431884765625,y:258.458984375,step:1},{x:444.2786458333333,y:259.46683756510413,step:1},{x:446.43485514322913,y:261.5247395833333,step:1},{x:448.51298014322913,y:263.373046875,step:1},{x:449.79947916666663,y:266.1868896484375,step:1},{x:449.79947916666663,y:270.38736979166663,step:1},{x:449.79947916666663,y:275.8463134765625,step:1},{x:447.71875,y:280.59375,step:1},{x:444.58072916666663,y:283.40625,step:1},{x:441.6328125,y:286.0521240234375,step:1},{x:437.8905843098958,y:287.1874593098958,step:1},{x:432.3724365234375,y:287.1874593098958,step:1},{x:429.3098958333333,y:287.1874593098958,step:1},{x:426.6640625,y:286.89322916666663,step:1},{x:425.3802083333333,y:286.5989583333333,step:1},{x:430.10416666666663,y:259.0892333984375,step:0},{x:431.6536865234375,y:282.1458333333333,step:2},{x:432.29691569010413,y:282.2318115234375,step:1},{x:433.0911458333333,y:282.2734375,step:1},{x:434.03641764322913,y:282.2734375,step:1},{x:436.98441569010413,y:282.2734375,step:1},{x:439.59375,y:281.09635416666663,step:1},{x:441.2552083333333,y:278.9973958333333,step:1},{x:442.9948323567708,y:276.7708333333333,step:1},{x:443.90104166666663,y:273.83072916666663,step:1},{x:443.90104166666663,y:270.42899576822913,step:1},{x:443.90104166666663,y:265.9348958333333,step:1},{x:441.6718343098958,y:263.28971354166663,step:1},{x:437.1744384765625,y:263.28971354166663,step:1},{x:436.2292073567708,y:263.28971354166663,step:1},{x:435.4348958333333,y:263.373046875,step:1},{x:434.8671875,y:263.4993489583333,step:1},{x:431.6536865234375,y:282.1458333333333,step:0}],borderWidth:0,borderColor:"rgba(145,15,5,1)",background:"rgba(145,15,5,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}],Pc=[{type:"path",stampPoints:[{x:347.4140625,y:272.89908854166663,step:2},{x:369.1386311848958,y:288.7083333333333,step:0},{x:463.5677490234375,y:288.7083333333333,step:0},{x:468.39322916666663,y:288.7083333333333,step:1},{x:472.33984375,y:285.10941569010413,step:1},{x:472.33984375,y:280.7083333333333,step:1},{x:472.33984375,y:264.2591145833333,step:0},{x:472.33984375,y:259.8587239583333,step:1},{x:468.39322916666663,y:256.2591145833333,step:1},{x:463.5677490234375,y:256.2591145833333,step:1},{x:369.1386311848958,y:256.2591145833333,step:0},{x:347.4140625,y:272.89908854166663,step:0}],borderWidth:1.3333333333333333,borderColor:"rgba(213,177,66,1)",background:"linear-gradient(to right bottom, #f7fc93, #f8fb4f)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:409.1328125,y:278.6067708333333,step:2},{x:408.75846354166663,y:267.82421875,step:0},{x:410.8606770833333,y:267.82421875,step:0},{x:410.8606770833333,y:272.6236572265625,step:0},{x:410.8606770833333,y:273.9348958333333,step:1},{x:410.83203125,y:275.1510009765625,step:1},{x:410.80338541666663,y:276.12760416666663,step:1},{x:410.83203125,y:276.12760416666663,step:0},{x:411.17704264322913,y:275.07157389322913,step:1},{x:411.52347819010413,y:273.9674886067708,step:1},{x:411.96875,y:272.6555989583333,step:1},{x:413.7109375,y:267.82421875,step:0},{x:415.98697916666663,y:267.82421875,step:0},{x:415.9583333333333,y:272.6399739583333,step:0},{x:415.9439697265625,y:273.9348958333333,step:1},{x:415.9140625,y:275.0078125,step:1},{x:415.8567708333333,y:276.0638020833333,step:1},{x:415.88541666666663,y:276.0638020833333,step:0},{x:416.21744791666663,y:274.9427083333333,step:1},{x:416.5780843098958,y:273.7916259765625,step:1},{x:416.9661458333333,y:272.6236572265625,step:1},{x:418.6366780598958,y:267.82421875,step:0},{x:420.8255208333333,y:267.82421875,step:0},{x:416.54947916666663,y:278.6067708333333,step:0},{x:414.28910319010413,y:278.6067708333333,step:0},{x:414.23050944010413,y:274.1927490234375,step:0},{x:414.2161458333333,y:272.912109375,step:1},{x:414.2447509765625,y:271.82421875,step:1},{x:414.3020833333333,y:270.607421875,step:1},{x:414.27347819010413,y:270.607421875,step:0},{x:413.9270833333333,y:271.759765625,step:1},{x:413.58203125,y:272.927734375,step:1},{x:413.1067708333333,y:274.2396240234375,step:1},{x:411.4375,y:278.6067708333333,step:0},{x:409.1328125,y:278.6067708333333,step:0}],borderWidth:0,borderColor:"rgba(213,177,66,1)",background:"rgba(35,31,32,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:424.0234375,y:267.82421875,step:2},{x:422.1796875,y:278.6067708333333,step:0},{x:420.10546875,y:278.6067708333333,step:0},{x:421.9478759765625,y:267.82421875,step:0},{x:424.0234375,y:267.82421875,step:0}],borderWidth:0,borderColor:"rgba(213,177,66,1)",background:"rgba(35,31,32,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:427.3489990234375,y:269.83984375,step:2},{x:424.7851155598958,y:269.83984375,step:0},{x:425.1458333333333,y:267.82421875,step:0},{x:432.359375,y:267.82421875,step:0},{x:432.01432291666663,y:269.83984375,step:0},{x:429.421875,y:269.83984375,step:0},{x:427.92447916666663,y:278.6067708333333,step:0},{x:425.8515218098958,y:278.6067708333333,step:0},{x:427.3489990234375,y:269.83984375,step:0}],borderWidth:0,borderColor:"rgba(213,177,66,1)",background:"rgba(35,31,32,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:431.6823323567708,y:278.6067708333333,step:2},{x:433.52604166666663,y:267.82421875,step:0},{x:435.95963541666663,y:267.82421875,step:0},{x:437.2421875,y:271.935546875,step:0},{x:437.6302490234375,y:273.3118489583333,step:1},{x:437.88932291666663,y:274.4322509765625,step:1},{x:438.1197509765625,y:275.6145833333333,step:1},{x:438.16276041666663,y:275.6145833333333,step:0},{x:438.20572916666663,y:274.51298014322913,step:1},{x:438.3503011067708,y:273.32816569010413,step:1},{x:438.6093343098958,y:271.744140625,step:1},{x:439.27079264322913,y:267.82421875,step:0},{x:441.2161458333333,y:267.82421875,step:0},{x:439.3723958333333,y:278.6067708333333,step:0},{x:437.2265625,y:278.6067708333333,step:0},{x:435.8723958333333,y:274.3046468098958,step:0},{x:435.44010416666663,y:272.83203125,step:1},{x:435.18229166666663,y:271.8561604817708,step:1},{x:434.921875,y:270.5435791015625,step:1},{x:434.8802083333333,y:270.5435791015625,step:0},{x:434.77860514322913,y:271.599609375,step:1},{x:434.5481770833333,y:273.11979166666663,step:1},{x:434.26041666666663,y:274.83203125,step:1},{x:433.61197916666663,y:278.6067708333333,step:0},{x:431.6823323567708,y:278.6067708333333,step:0}],borderWidth:0,borderColor:"rgba(213,177,66,1)",background:"rgba(35,31,32,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:447.58072916666663,y:274.015625,step:2},{x:444.1380208333333,y:274.015625,step:0},{x:443.6927083333333,y:276.640625,step:0},{x:447.56510416666663,y:276.640625,step:0},{x:447.234375,y:278.6067708333333,step:0},{x:441.2734375,y:278.6067708333333,step:0},{x:443.1171468098958,y:267.82421875,step:0},{x:448.8620198567708,y:267.82421875,step:0},{x:448.515625,y:269.7916259765625,step:0},{x:444.859375,y:269.7916259765625,step:0},{x:444.45572916666663,y:272.08011881510413,step:0},{x:447.92578125,y:272.08011881510413,step:0},{x:447.58072916666663,y:274.015625,step:0}],borderWidth:0,borderColor:"rgba(213,177,66,1)",background:"rgba(35,31,32,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:449.1497395833333,y:276.1119384765625,step:2},{x:449.7265625,y:276.4791259765625,step:1},{x:450.5312093098958,y:276.78385416666663,step:1},{x:451.44010416666663,y:276.78385416666663,step:1},{x:452.2317708333333,y:276.78385416666663,step:1},{x:452.9661458333333,y:276.3671875,step:1},{x:452.9661458333333,y:275.5364583333333,step:1},{x:452.9661458333333,y:274.9114583333333,step:1},{x:452.546875,y:274.5286458333333,step:1},{x:451.65629069010413,y:274,step:1},{x:450.6328125,y:273.3919270833333,step:1},{x:449.6536865234375,y:272.5598958333333,step:1},{x:449.6536865234375,y:271.16796875,step:1},{x:449.6536865234375,y:268.9921875,step:1},{x:451.3529052734375,y:267.6640625,step:1},{x:453.46875,y:267.6640625,step:1},{x:454.63541666666663,y:267.6640625,step:1},{x:455.328125,y:267.95182291666663,step:1},{x:455.7447509765625,y:268.1920979817708,step:1},{x:455.09635416666663,y:270.111328125,step:0},{x:454.7812093098958,y:269.919921875,step:1},{x:454.10416666666663,y:269.6314697265625,step:1},{x:453.29691569010413,y:269.6477864583333,step:1},{x:452.33207194010413,y:269.6477864583333,step:1},{x:451.828125,y:270.17582194010413,step:1},{x:451.828125,y:270.767578125,step:1},{x:451.828125,y:271.3919270833333,step:1},{x:452.4192708333333,y:271.775390625,step:1},{x:453.2395833333333,y:272.28776041666663,step:1},{x:454.4192708333333,y:272.9759114583333,step:1},{x:455.1536458333333,y:273.83984375,step:1},{x:455.1536458333333,y:275.13541666666663,step:1},{x:455.1536458333333,y:277.5364583333333,step:1},{x:453.3697509765625,y:278.7682698567708,step:1},{x:451.22391764322913,y:278.7682698567708,step:1},{x:449.8841145833333,y:278.75260416666663,step:1},{x:448.90494791666663,y:278.3671875,step:1},{x:448.4583333333333,y:278,step:1},{x:449.1497395833333,y:276.1119384765625,step:0}],borderWidth:0,borderColor:"rgba(213,177,66,1)",background:"rgba(35,31,32,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4},{type:"path",stampPoints:[{x:456.4934895833333,y:276.1119384765625,step:2},{x:457.0703125,y:276.4791259765625,step:1},{x:457.87504069010413,y:276.78385416666663,step:1},{x:458.7838134765625,y:276.78385416666663,step:1},{x:459.5755208333333,y:276.78385416666663,step:1},{x:460.3099365234375,y:276.3671875,step:1},{x:460.3099365234375,y:275.5364583333333,step:1},{x:460.3099365234375,y:274.9114583333333,step:1},{x:459.8919270833333,y:274.5286458333333,step:1},{x:459,y:274,step:1},{x:457.9765625,y:273.3919270833333,step:1},{x:456.9974365234375,y:272.5598958333333,step:1},{x:456.9974365234375,y:271.16796875,step:1},{x:456.9974365234375,y:268.9921875,step:1},{x:458.6966145833333,y:267.6640625,step:1},{x:460.81254069010413,y:267.6640625,step:1},{x:461.97916666666663,y:267.6640625,step:1},{x:462.6718343098958,y:267.95182291666663,step:1},{x:463.08854166666663,y:268.1920979817708,step:1},{x:462.44010416666663,y:270.111328125,step:0},{x:462.125,y:269.919921875,step:1},{x:461.4478759765625,y:269.6314697265625,step:1},{x:460.6405843098958,y:269.6477864583333,step:1},{x:459.67704264322913,y:269.6477864583333,step:1},{x:459.1718343098958,y:270.17582194010413,step:1},{x:459.1718343098958,y:270.767578125,step:1},{x:459.1718343098958,y:271.3919270833333,step:1},{x:459.7630208333333,y:271.775390625,step:1},{x:460.58329264322913,y:272.28776041666663,step:1},{x:461.7642822265625,y:272.9759114583333,step:1},{x:462.49869791666663,y:273.83984375,step:1},{x:462.49869791666663,y:275.13541666666663,step:1},{x:462.49869791666663,y:277.5364583333333,step:1},{x:460.71354166666663,y:278.7682698567708,step:1},{x:458.5677083333333,y:278.7682698567708,step:1},{x:457.22782389322913,y:278.75260416666663,step:1},{x:456.2499593098958,y:278.3671875,step:1},{x:455.80204264322913,y:278,step:1},{x:456.4934895833333,y:276.1119384765625,step:0}],borderWidth:0,borderColor:"rgba(213,177,66,1)",background:"rgba(35,31,32,1)",lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4}];class Ac extends Ul{constructor(t){var e;super({type:"annotationStamp",...t,style:{...t.style,stampConfig:(null==t||null===(e=t.style)||void 0===e?void 0:e.stampConfig)||Ic(null==t?void 0:t.style.iconName)}}),Yi(this,"shapeType","annotationStamp"),Yi(this,"stampType","base"),Yi(this,"controls",void 0),Yi(this,"eventHandler",void 0),Yi(this,"context",void 0),Yi(this,"shapes",[]),Yi(this,"initialRect",void 0),Yi(this,"iconName",void 0),Yi(this,"imageLoadedByDraw",!1),Yi(this,"initByDraw",!1),Yi(this,"hooks",{reRenderImage:zs()}),this.initByDraw=(null==t?void 0:t.initByDraw)||!1,this.initStamp(),this.init(t.transform,t.selectableStyle),this.initSize(t.style,t.transform)}init(t,e){this.eventHandler=new Kh(this),this.context=new tc(this,e),this.context.setTransform(t),this.initialRect=this.getBoundingRect()}initStamp(){var t;const{imageData:e,width:i,height:n}=this.style;if(this.stampItemShapes.forEach(t=>{t.destroy()}),this.stampItemShapes=[],(null==this||null===(t=this.style)||void 0===t?void 0:t.img)instanceof HTMLImageElement&&this.style.img.src&&URL.revokeObjectURL(this.style.img.src),e){this.renderType="image",this.imageLoadedByDraw=!1;const t=e instanceof Blob?URL.createObjectURL(e):e,s=new Image;s.src=t,this.style.img=s,s.onload=()=>{if(this.initByDraw||!Ls(i)||!Ls(n)){const{width:t,height:e}=s;let i=t,n=e;if(t>400||e>400){const s=Math.max(t/400,e/400);i/=s,n/=s}this.updateStyle({width:i,height:n}),this.setLocalScale(1,1),this.initialWidth=i,this.initialHeight=n,this.initByDraw=!1,this.imageLoadedByDraw=!0}this.hooks.reRenderImage.emit()}}else this.initByDraw=!1,super.initStamp();this.getPath(),this.renderClipStep=this.steps}initSize(t,e){if("image"===this.renderType){const{x:t,y:e}=this.getLocalScale();1===t&&1===e||this.updateSize(this.parsedStyle.width.value,this.parsedStyle.height.value)}const i={},n=this.getAnnotationConfig(),{x:s,y:o}=(null==e?void 0:e.scale)||{x:1,y:1};var r;Ls(null==t?void 0:t.x)&&(null==t?void 0:t.x)!==n.style.x&&(i.x=t.x),Ls(null==t?void 0:t.y)&&(null==t?void 0:t.y)!==n.style.y&&(i.y=t.y),Ls(null==t?void 0:t.width)&&t.width*s!==n.style.width&&(i.width=t.width),Ls(null==t?void 0:t.height)&&t.height*o!==n.style.height&&(i.height=t.height),r=i,(0!==Object.keys(r).length||r.constructor!==Object)&&this.updateStampStyle(i)}update(){this.updateOrigin(),this.context.updateControls()}updateSize(t,e){const{x:i,y:n}=this.getLocalScale(),{x:s,y:o}=this.getPosition();if("image"===this.renderType){const{x:s,y:o}=this.getLocalPosition(),r=this.getAngle(),a=t*i,l=e*n;this.setAngle(0),this.setLocalScale(1,1),this.updateStyle({width:a,height:l});const h=s+(t-a)/2,c=o+(e-l)/2;return this.initialWidth=a,this.initialHeight=l,this.setLocalPosition({x:h,y:c}),void this.setAngle(r)}const{width:r,height:a}=this.parsedStyle,l=t||r.value*i,h=e||a.value*n;this.setLocalScale(l/r.value,h/a.value),this.setPosition({x:s,y:o})}updateStampStyle(t){const{x:e,y:i}=this.getLocalPosition(),{x:n,y:s}=this.getLocalScale(),{width:o,height:r}=this.parsedStyle,{width:a,height:l}=t,{imageData:h,iconName:c}=this.style;let d=e,u=i;h||Ps(null==t?void 0:t.imageData)||this.setLocalScale(1),null!=t&&t.imageData&&t.imageData!==h?(this.style.imageData=t.imageData,this.initStamp()):null!=t&&t.iconName&&t.iconName!==c&&(this.style.imageData=null,this.style.iconName=t.iconName,this.stampConfig=Ic(t.iconName),this.initStamp()),Ls(null==t?void 0:t.opacity)&&(null==t?void 0:t.opacity)!==this.style.opacity&&(this.style.opacity=t.opacity),this.updateSize(Ls(a)?a:o.value*n,Ls(l)?l:r.value*s);const{x:p,y:g}=this.getLocalScale();if(Ls(null==t?void 0:t.x)){const e=this.initialWidth*p;d=t.x-(this.initialWidth-e)/2}if(Ls(null==t?void 0:t.y)){const e=this.initialHeight*g;u=t.y-(this.initialHeight-e)/2}this.setLocalPosition(d,u)}getAnnotationConfig(){const t=this.context.getTransform(),{x:e,y:i}=this.style,n=_s(t);if(n.position.x===e&&n.position.y===i&&1===n.scale.x&&1===n.scale.y&&(delete n.position,delete n.scale),this.style.imageData)return{type:"annotationStamp",style:{x:t.position.x,y:t.position.y,width:this.style.width,height:this.style.height,opacity:this.style.opacity,imageData:this.style.imageData},transform:{...n}};const{initialWidth:s,initialHeight:o}=this,r=s*t.scale.x,a=o*t.scale.y;return{type:"annotationStamp",style:{x:t.position.x+(s-r)/2,y:t.position.y+(o-a)/2,width:r,height:a,opacity:this.style.opacity,stampConfig:[...this.stampConfig],iconName:this.style.iconName},transform:{...n}}}destroy(){var t;(null==this||null===(t=this.style)||void 0===t?void 0:t.img)instanceof HTMLImageElement&&this.style.img.src&&(this.style.img.complete?URL.revokeObjectURL(this.style.img.src):this.style.img.onload=()=>{URL.revokeObjectURL(this.style.img.src)}),this.parentElement&&this.parentElement.removeChild(this),this.controls&&this.controls.destroy()}}function Ic(t){const e=[Yh.REJECTED,Yh.ACCEPTED,Yh.APPROVED,Yh.NOT_APPROVED,Yh.COMPLETED,Yh.DRAFT,Yh.FINAL,Yh.VOID,Yh.CONFIDENTIAL,Yh.INITIAL_HERE,Yh.SIGN_HERE,Yh.WITNESS];return[Tc,mc,vc,Sc,yc,wc,Cc,_c,xc,bc,Ec,Pc][e.indexOf(t)]}class Dc extends Ac{constructor(t){super({...t}),Yi(this,"stampType","raw"),Yi(this,"annotationRaw",void 0),this.annotationRaw=t.style.annotationRaw,this.context.updateControlsFlags({enableControl:!1})}getAnnotationConfig(){const t=super.getAnnotationConfig();return this.annotationRaw&&(t.style.annotationRaw=this.annotationRaw),t}}class Rc{constructor(t){Yi(this,"shape",void 0),Yi(this,"isEditMode",void 0),Yi(this,"controlsBox",void 0),Yi(this,"controlsPoints",[]),this.shape=t}isHitPoint(t){return this.shape.outCtx.isHitPoint(t)}enableEditMode(){this.isEditMode=!0,this.shape.context.isHit=!0,this.shape.outCtx.isCtrlPointOoutOfCropBox()}disableEditMode(){this.destroyControls(),this.isEditMode=!1,this.shape.context.isHit=!1}editStartHandler(t){this.isEditMode&&this.shape.context.isActive&&this.shape.outCtx.startHandler(t)}editMoveHandler(t){this.isEditMode&&this.shape.outCtx.moveHandler(t)}editEndHandler(){this.isEditMode&&this.shape.outCtx.endHandler()}destroyControls(){var t;null===(t=this.controlsBox)||void 0===t||t.destroy(),this.controlsPoints.forEach(t=>{t.destroy(),t=null}),this.controlsBox=null,this.controlsPoints=[]}}class kc extends Cl{constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;i.style={visibility:"visible",borderWidth:"annotationHighlight"===t?0:1,renderBlendMode:"multiply",lineCap:"butt",lineJoin:"miter",lineDash:[0,0],miterLimit:10,...i.style},super({type:t,name:e,...i}),Yi(this,"lines",[]),Yi(this,"textAssistEventHandler",void 0),Yi(this,"eventHandler",void 0),Yi(this,"controls",void 0),Yi(this,"context",void 0),Yi(this,"startTextPosition",void 0),Yi(this,"endTextPosition",void 0),Yi(this,"startCharRect",void 0),Yi(this,"endCharRect",void 0),Yi(this,"isBlankTextAssist",!1),Yi(this,"isMatchText",!1),Yi(this,"outCtx",void 0),Yi(this,"isOutOfCropBox",!1),this.outCtx=n,this.outCtx&&this.outCtx.setShape(this),this.shapeType=t,this.init(i.transform,i.selectableStyle),this.updateLines(i.style.lines),this.updatePosition(0,0)}init(t,e){this.context=new tc(this,e),this.textAssistEventHandler=new Rc(this),this.eventHandler=new Kh(this),this.context.updateControlsFlags({useDefaultControls:!1,enableMove:!1})}update(){}updateStyle(t){super.updateStyle(t),this.updateLines(this.style.lines)}getAnnotationConfig(){const t=this.context.getTransform();return{type:this.shapeType,style:{lines:this.style.lines,...this.context.getCommonStyleConfig()},transform:t,startCharRect:this.startCharRect,endCharRect:this.endCharRect,startTextPosition:this.startTextPosition,endTextPosition:this.endTextPosition}}updateLines(t){this.lines=t,this.updateBoundingBox()}getBoundingRect(){return this.bounds}updateBoundingBox(){let t=1/0,e=1/0,i=-1/0,n=-1/0;for(let s=0;s<this.lines.length;s++){const o=this.lines[s];t=Math.min(t,o.left),e=Math.min(e,o.top),i=Math.max(i,o.left+o.width),n=Math.max(n,o.top+o.height)}this.bounds={left:t,top:e,width:i-t,height:n-e}}isPointInPath(t){var e;return!(null===(e=this.lines)||void 0===e||!e.some(e=>e.left<=t.x&&e.left+e.width>=t.x&&e.top<=t.y&&e.top+e.height>=t.y))}isPointOnActiveShape(t){if(this.context.isActive)if(this.startCharRect){if(this.isPointOnStartCtrl(t))return!0}else if(this.endCharRect&&this.isPointOnEndCtrl(t))return!0;return this.isPointOnBody(t)}isPointOnBody(t){return t.x>=this.bounds.left&&t.x<=this.bounds.left+this.bounds.width&&t.y>=this.bounds.top&&t.y<=this.bounds.top+this.bounds.height}isPointOnStartCtrl(t){if(!this.startCharRect)return!1;if(!this.context.controlsFlags.enableEdit)return!1;if(Mc(t,this.startCharRect))return!0;const e=this.getScale().x,i=this.context.parsedControlsStyle.ctrlBorderRadius/e;return Ua({x:this.startCharRect.left+this.startCharRect.width/2,y:this.startCharRect.top-i},t)<=i}isPointOnEndCtrl(t){if(!this.endCharRect)return!1;if(!this.context.controlsFlags.enableEdit)return!1;if(Mc(t,this.endCharRect))return!0;const e=this.getScale().x,i=this.context.parsedControlsStyle.ctrlBorderRadius/e;return Ua({x:this.endCharRect.left+this.endCharRect.width/2,y:this.endCharRect.top+this.endCharRect.height+i},t)<=i}}function Mc(t,e){return t.x>=e.left&&t.x<=e.left+e.width&&t.y>=e.top&&t.y<=e.top+e.height}class Lc extends kc{constructor(){super("annotationHighlight","AnnotationHighlight",arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:null),Yi(this,"shapeType","annotationHighlight"),Yi(this,"textAssistType","highlight")}}class Oc extends kc{constructor(){super("annotationStrikeout","AnnotationStrikeout",arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:null),Yi(this,"shapeType","annotationStrikeout"),Yi(this,"textAssistType","strikeout")}}class Bc extends kc{constructor(){super("annotationUnderline","AnnotationUnderline",arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:null),Yi(this,"shapeType","annotationUnderline"),Yi(this,"textAssistType","underline")}updateLines(t){this.lines=t,this.updateBoundingBoxForUnderline()}updateBoundingBoxForUnderline(){let t=1/0,e=1/0,i=-1/0,n=-1/0;for(let s=0;s<this.lines.length;s++){const o=this.lines[s];t=Math.min(t,o.left),e=Math.min(e,o.top),i=Math.max(i,o.left+o.width),n=Math.max(n,o.top+o.height)}this.bounds={left:t,top:e,width:i-t,height:n-e}}}const Nc={annotationRect:"rectangle",annotationEllipse:"ellipse",annotationPolygon:"polygon",annotationPolyline:"polyline",annotationLine:"line",annotationInk:"ink",annotationTextBox:"textBox",annotationFreeText:"textTypewriter",annotationStamp:"stamp"};class Uc{constructor(t){Yi(this,"eraserPath",void 0),Yi(this,"erasedShapeIds",[]),Yi(this,"selectionBox",void 0),Yi(this,"startCanvasPoint",void 0),Yi(this,"startLocalPoint",void 0),Yi(this,"lastMovePoint",void 0),Yi(this,"resetActivatedZIndex",!0),Yi(this,"isSeparateText",!1),Yi(this,"lastClickPointerType",""),Yi(this,"drawType","annotationRect"),Yi(this,"isStartEdit",!1),Yi(this,"isStartDraw",!1),Yi(this,"controller",void 0),Yi(this,"eventArea",void 0),Yi(this,"eventMode","none"),Yi(this,"defaultGroup",void 0),Yi(this,"activatedShape",void 0),Yi(this,"activatedZIndex",0),Yi(this,"drawLineShape",!1),Yi(this,"stampPreview",void 0),Yi(this,"inkDelayTimeout",void 0),Yi(this,"drawInkShape",!1),Yi(this,"isArrowKeyDown",!1),Yi(this,"arrowKeyDownSuccessful",!1),this.controller=t,this.defaultGroup=new cc("ddvDefaultGroup"),this.defaultGroup.style.zIndex=1e5}isDefaultGroup(t){return t===this.defaultGroup}getDrawInitStyle(t,e){var i,n;const{defaultStyleConfig:s,eraserStyle:o,selectionStyle:r}=this.controller.interactiveConfig,a={x:e.x,y:e.y};let l=[{...qh.textContent,..."annotationFreeText"===t?null==s||null===(i=s.textTypewriter)||void 0===i?void 0:i.textContent:null==s||null===(n=s.textBox)||void 0===n?void 0:n.textContent}];""===l[0].content&&(l=[]);let h={};switch(t){case"annotationInk":h={lineCap:"round",lineJoin:"round",segments:[[e]]};break;case"annotationPolygon":case"annotationPolyline":h={points:[e]};break;case"annotationLine":h={startPoint:e,endPoint:e};break;case"annotationFreeText":case"annotationTextBox":h={...a,textContents:l};break;default:h=a}let c={...qh,...s[Nc[t]]||{}};return"select"===this.eventMode?c={...r,zIndex:999}:"erase"===this.eventMode&&(c=o),{...c,...h}}getDrawUpdateStyle(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=(e.x+this.startLocalPoint.x)/2,s=(e.y+this.startLocalPoint.y)/2,o=e.x-this.startLocalPoint.x,r=e.y-this.startLocalPoint.y;const a=["annotationCircle","annotationEllipse"].includes(t),l=Math.min(Math.abs(o),Math.abs(r));i&&(o=e.x>=this.startLocalPoint.x?l:-l,r=e.y>=this.startLocalPoint.y?l:-l,a&&(n=(2*this.startLocalPoint.x+o)/2,s=(2*this.startLocalPoint.y+r)/2));let h={};switch(t){case"annotationFreeText":break;case"annotationCircle":case"annotationArc":h={x:n,y:s,r:l};break;case"annotationEllipse":h={x:n,y:s,rx:Math.abs(o)/2,ry:Math.abs(r)/2};break;case"annotationLine":h={endPoint:e};break;default:h={width:o,height:r}}return h}limitPointToEventArea(t,e){if(!this.eventArea)return;const i=this.activatedShape,{left:n,top:s,width:o,height:r}=this.eventArea;let a=0,l=0,h=0;if(e){const{lastHitControlPoint:t,lastHitControlPointCenter:e}=i.context;t&&e&&(l=t.x-e.x,h=t.y-e.y)}else{const{borderWidth:t}=i.parsedStyle;a=Bh(i)?t.value*i.getScale().x:0}t.x<n+a+l&&(t.x=n+a+l),t.y<s+a+h&&(t.y=s+a+h),t.x>n+o+l&&(t.x=n+o+l),t.y>s+r+h&&(t.y=s+r+h)}executeErase(){var t;"erase"===this.eventMode&&(this.erasedShapeIds.length>0&&this.controller.deleteShape(this.erasedShapeIds),this.controller.deleteShape([null===(t=this.eraserPath)||void 0===t?void 0:t.id],!1),this.eraserPath=null,this.activatedShape=null,this.erasedShapeIds=[])}executeBoxSelect(){if("select"!==this.eventMode)return;const{shapeArrMap:t,containerId:e}=this.controller,{width:i,height:n}=this.selectionBox.parsedStyle,s=i.value<2&&n.value<2,o=[],r=t.get(e);if(s){const t=[];r.forEach(e=>{if(!e.isVisible||!e.context.controlsFlags.enableControl||e===this.selectionBox||"annotationGroup"===e.shapeType)return;const i=Oh(e,this.startCanvasPoint);e.isPointInPath(i,this.getHitBorderOffset(e))&&!e.context.isGrouped&&t.push(e)}),t.length&&(t.sort((t,e)=>t.style.zIndex-e.style.zIndex),o.push(t[t.length-1]))}else r.forEach(t=>{"annotationGroup"!==t.shapeType&&t.isVisible&&t.context.controlsFlags.enableControl&&t!==this.selectionBox&&function(t,e){e.controls||e.context.initControls(),e.context.renderControls();const i=[],n=e.controls.getVertexesPosition();i.push(...n);const{x:s,y:o}=t.getPosition(),{width:r,height:a}=t.parsedStyle,l=t.getScale(),h=Math.abs(l.x),c=Math.abs(l.y),d=function(t,e){let i=e[0].x,n=e[0].x,s=e[0].y,o=e[0].y;for(let t=1;t<e.length;t++){const{x:r,y:a}=e[t];r<i&&(i=r),r>n&&(n=r),a<s&&(s=a),a>o&&(o=a)}return!(t.x2<i||n<t.x1)&&!(t.y2<s||o<t.y1)&&function(t,e){const i=t.x1,n=t.y1,s=t.x2,o=t.y2;for(let t=0;t<e.length;t++){const r=e[t],a=e[(t+1)%e.length],l=a.y-r.y,h=r.x-a.x;if(0===l&&0===h)continue;const c=l*i+h*n,d=l*i+h*o,u=l*s+h*n,p=l*s+h*o;let g=c,f=c;d<g?g=d:d>f&&(f=d),u<g?g=u:u>f&&(f=u),p<g?g=p:p>f&&(f=p);let m=l*e[0].x+h*e[0].y,v=m;for(let t=1;t<e.length;t++){const i=l*e[t].x+h*e[t].y;i<m?m=i:i>v&&(v=i)}if(f<m||v<g)return!1}return!0}(t,e)}({x1:s,y1:o,x2:s+r.value*h,y2:o+a.value*c},i);return d}(this.selectionBox,t)&&o.push(t)});1===o.length?this.selectShapes([o[0]]):o.length>1?this.selectShapes(o):(this.activatedShape=null,this.controller.hooks.emitSelectAnnotation(null)),this.controller.deleteShape([this.selectionBox.id],!1),this.selectionBox=null,this.controller.hooks.emitAnnotationRender()}activateShape(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!t||!t.isVisible||!t.context.controlsFlags.enableControl)return;const n=this.activatedShape===t,{showOnTopWhenSelected:s}=this.controller.interactiveConfig;var o;n&&t.context.isActive||(this.activatedShape&&!n&&(e?(s&&(this.activatedShape.style.zIndex=this.activatedZIndex),this.defaultGroup.parent&&this.defaultGroup.parent!==this.controller.container&&this.defaultGroup.clear(),this.isDefaultGroup(this.activatedShape)||this.defaultGroup.shapes.includes(this.activatedShape)||((null===(o=this.activatedShape)||void 0===o?void 0:o.parentNode)===(null==t?void 0:t.parentNode)?this.defaultGroup.add(this.activatedShape):this.inactivateShape())):this.inactivateShape()),this.activatedShape=t,this.activatedShape.context.isActive=!0,s&&(this.resetActivatedZIndex&&(this.activatedZIndex=this.activatedShape.style.zIndex),this.resetActivatedZIndex=!0,this.activatedShape.style.zIndex=99999),this.activatedShape.eventHandler.setLimitArea(this.eventArea),this.activatedShape.controls||t.context.initControls(),t.context.renderControls(),Nh(t)&&t.pointEventsHandler.enableEditMode(),Fh(t)&&t.textAssistEventHandler.enableEditMode(),this.isDefaultGroup(t)&&t.showAllControls(),e||this.controller.hooks.emitSelectAnnotation(t),i&&this.controller.hooks.emitAnnotationRender())}inactivateShape(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this.activatedShape)return;const{showOnTopWhenSelected:i}=this.controller.interactiveConfig;if(i&&!this.isDefaultGroup(this.activatedShape)&&(this.activatedShape.style.zIndex=this.activatedZIndex),this.drawInkShape&&this.activatedShape instanceof oc&&(this.drawInkShape=!1,clearTimeout(this.inkDelayTimeout)),this.activatedShape.context.unHitShape(),this.activatedShape.context.destroyControls(),this.isDefaultGroup(this.activatedShape)&&this.activatedShape.clear(),this.activatedShape instanceof hc&&"freeTextWriter"===this.activatedShape.textType){const{textContents:t}=this.activatedShape.style;let e="";t.forEach(t=>{e+=(null==t?void 0:t.content)||""}),0===e.length&&this.controller.deleteShape([this.activatedShape.id],!0)}if(this.isArrowKeyDown){this.isArrowKeyDown=!1;const t=[];this.activatedShape instanceof cc?t.push(...this.activatedShape.shapes):t.push(this.activatedShape);const e=t.map(t=>{const e=t.getAnnotationConfig(),i={style:{}};return Ps(e.style.x)||(i.style.x=e.style.x),Ps(e.style.y)||(i.style.y=e.style.y),Ps(e.style.points)||(i.style.points=e.style.points),Ps(e.style.segments)||(i.style.segments=e.style.segments),Ps(e.style.startPoint)||(i.style.startPoint=e.style.startPoint),Ps(e.style.endPoint)||(i.style.endPoint=e.style.endPoint),{shape:t,changedOptions:i}});this.controller.hooks.emitModifyAnnotation(["moved"],e),this.controller.hooks.emitAfterAnnotationEdit(this.activatedShape)}this.activatedShape=null,this.controller.hooks.emitAnnotationRender(),t&&this.controller.hooks.emitSelectAnnotation(null,e)}setEventArea(t){this.eventArea=t,this.activatedShape&&this.activatedShape.eventHandler.setLimitArea(this.eventArea)}setEventMode(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"annotationRect";if("draw"===this.eventMode&&this.activatedShape&&("annotationInk"===this.drawType&&this.activatedShape instanceof oc&&this.activatedShape.setUseDouglasPeucker(!0),this.drawLineShape)){const t=[...this.activatedShape.style.points];Ms()||t.pop(),this.activatedShape.style.points=t}this.drawLineShape&&this.controller.hooks.emitAddAnnotation("draw",[this.activatedShape]),(this.drawInkShape||this.drawLineShape)&&(clearTimeout(this.inkDelayTimeout),this.inactivateShape(!1)),this.isStartDraw=!1,this.drawLineShape=!1,this.drawInkShape=!1,this.eventMode=t,this.drawType=e,this.stampPreview&&(this.controller.deleteShape([this.stampPreview.id],!1),this.stampPreview=null,this.controller.hooks.emitAnnotationRender()),"none"!==t&&(this.inactivateShape(!0),"erase"===t&&(this.drawType="annotationInk"),"select"===t&&(this.drawType="annotationRect"))}getFreeTextLimitWidth(t,e,i,n,s,o,r,a){const l=t,h=e,c=Math.round(i),d=Math.round(o);if(!l)return 0;let u=l,p=n;if(d!==c){if(0===d)switch(c){case 90:return s+a/2+r/2;case-180:case 180:return n+r;case-90:u=h,p=s+a/2-r/2}if(-90===d)switch(c){case 0:return s+a/2+r/2;case 90:return n+r;case-180:case 180:u=h,p=s+a/2-r/2}if(180===d||-180===d)switch(c){case 0:return n+r;case-90:return s+a/2+r/2;case 90:u=h,p=s+a/2-r/2}if(90===d)switch(c){case-180:case 180:return s+a/2+r/2;case-90:return n+r;case 0:u=h,p=s+a/2-r/2}}let g=u-p;return g<0&&(g=u),g}selectShapes(t){const e=[];return t.forEach(t=>{"visible"===t.parsedStyle.visibility&&t.context.controlsFlags.enableControl&&e.push(t)}),this.inactivateShape(!t.length),!!e.length&&(this.defaultGroup.clear(),1===e.length?this.activateShape(e[0],!1,!0):(this.defaultGroup.add(e),this.activateShape(this.defaultGroup,!1,!0)),!0)}editStartHandler(t){if("none"!==this.eventMode)return;if(!this.activatedShape)return;const{offsetX:e,offsetY:i}=Vh(this.controller.canvas,t),n={x:e,y:i};this.isStartEdit=!0,180===this.activatedShape.getAngle()&&this.activatedShape.setAngle(179.99),this.activatedShape.eventHandler.startHandler(n,!0),this.controller.hooks.emitBeforeAnnotationEdit(this.activatedShape)}editMoveHandler(t){if(!this.activatedShape||"none"!==this.eventMode||!this.isStartEdit)return;const{offsetX:e,offsetY:i}=Vh(this.controller.canvas,t),n={x:e,y:i};this.limitPointToEventArea(n,!0),this.activatedShape.eventHandler.moveHandler(n,fo(t)),this.controller.hooks.emitAnnotationRender()}editEndHandler(t){this.isStartEdit=!1,this.activatedShape&&"none"===this.eventMode&&(this.activatedShape.eventHandler.endHandler(this.controller.hooks),this.controller.hooks.emitAfterAnnotationEdit(this.activatedShape))}drawStartHandler(t){if(!this.controller.container||"none"===this.eventMode)return;if("draw"===this.eventMode&&"annotationStamp"===this.drawType)return void("touch"!==t.pointerType&&"pen"!==t.pointerType||this.drawStampMoveHandler(t,!1));if(!this.eventArea)return;const{controller:e}=this,{drawType:i,drawLineShape:n,eventMode:s}=this,{offsetX:o,offsetY:r}=Vh(e.canvas,t),{left:a,top:l,width:h,height:c}=this.eventArea;if(o<a||o>a+h||r<l||r>l+c)return;const d={x:o,y:r},u=e.container.getWorldTransform().inverse().transformPoint(d);if(this.isStartDraw=!0,this.startCanvasPoint=d,this.startLocalPoint=u,this.lastMovePoint=null,"select"===s&&(this.inactivateShape(),this.controller.hooks.emitBeforeAnnotationEdit(null)),this.drawInkShape&&clearTimeout(this.inkDelayTimeout),"draw"===s&&(n||this.drawInkShape)){const e=this.activatedShape instanceof oc;return e&&this.activatedShape.addSegment(),this.activatedShape.addPoint(u),void(e||"touch"!==t.pointerType&&"pen"!==t.pointerType||this.controller.hooks.emitAnnotationRender())}-1!==["annotationPolyline","annotationPolygon"].indexOf(i)&&(this.drawLineShape=!0),"draw"===s&&-1!==["annotationInk"].indexOf(i)&&(this.drawInkShape=!0);const p={style:this.getDrawInitStyle(this.drawType,u)};if("annotationFreeText"===this.drawType){const{cropBoxRect:t}=this.controller.container.parentNode.parentNode.parentNode,e=this.getFreeTextLimitWidth(t.width,t.height,this.controller.container.getAngle(),p.style.x-t.left||0,p.style.y-t.top||0,0,0,0);p.style.width=e||p.style.width}const g=this.controller.addShape(this.drawType,p,!1);g.style.zIndex=999;const f=()=>{0!==this.controller.container.getAngle()&&Fc(g)&&(g.setAngle(0),g.setPosition(d))},{container:m}=this.controller;if("draw"===s)this.controller.hooks.emitBeforeAnnotationDraw(g),f();else if("erase"===s){if(g.style.background=null,m){const t=g.style.borderWidth/m.getScale().x;g.style.borderWidth=t}this.eraserPath=g}else{if(m){const t=g.style.borderWidth/m.getScale().x;g.style.borderWidth=t}this.selectionBox=g,f()}this.activatedShape=g,this.controller.hooks.emitAnnotationRender()}drawMoveHandler(t,e){const{activatedShape:i,eventMode:n,isStartDraw:s,drawType:o}=this;if("none"===n)return;if("draw"===n&&"annotationStamp"===o)return void this.drawStampMoveHandler(t,e);if("draw"===n&&"annotationFreeText"===o)return;if(!s)return;const{offsetX:r,offsetY:a}=Vh(this.controller.canvas,t),l={x:r,y:a};this.limitPointToEventArea(l,!1);const h=this.controller.container.getWorldTransform().inverse().transformPoint(l);if("annotationPolyline"===o||"annotationPolygon"===o){const t=_s(i.parsedStyle.points),e=t.length;1===e?t[e]=h:t[e-1]=h,i.style.points=t}else if("annotationInk"===o)i.addPoint(h);else{const e=this.getDrawUpdateStyle(this.drawType,h,fo(t)),n=this.controller.container.getAngle();if(0!==n&&Fc(i)){if(90===Math.abs(Math.round(n))){const t=e.width;e.width=e.height,e.height=t}e.width=l.x-this.startCanvasPoint.x>0?Math.abs(e.width):-Math.abs(e.width),e.height=l.y-this.startCanvasPoint.y>0?Math.abs(e.height):-Math.abs(e.height),i.updateStyle(e),i.setPosition({...this.startCanvasPoint})}else i.updateStyle(e)}this.controller.hooks.emitAnnotationRender()}drawStampMoveHandler(t,e){const{offsetX:i,offsetY:n}=Vh(this.controller.canvas,t),s={x:i,y:n},o=this.controller.container.getRootNode(),r=o.getWorldTransform().inverse().transformPoint(s),a=()=>{if(!this.stampPreview)return;const t=this.stampPreview.getBoundingRect();this.stampPreview.style.visibility=e?"hidden":"visible",this.stampPreview.setLocalPosition(r.x-t.width/2,r.y-t.height/2)};if(!this.stampPreview){const{defaultStyleConfig:t}=this.controller.interactiveConfig,{stamp:e}=t,i=(null==e?void 0:e.stampIcon)||(null==qh?void 0:qh.stampIcon),n=(null==e?void 0:e.imageData)||(null==qh?void 0:qh.imageData),s=(null==e?void 0:e.stampConfig)||null;if(this.stampPreview=this.controller.createShape("annotationStamp",{style:{iconName:s?null:i,imageData:n,stampConfig:s,opacity:Ls(e.opacity)?e.opacity:.5,zIndex:9999},initByDraw:!0}),o.appendChild(this.stampPreview),!n&&i){const{width:t,height:e}=this.stampPreview.parsedStyle;if(e.value>60){const i=e.value/60;this.stampPreview.updateSize(t.value/i,e.value/i)}this.stampPreview.hooks.reRenderImage.on(()=>{this.controller.hooks.emitAnnotationRender()})}else this.stampPreview.hooks.reRenderImage.on(()=>{"visible"===this.stampPreview.style.visibility&&a(),this.controller.hooks.emitAnnotationRender()})}a(),this.controller.hooks.emitAnnotationRender()}eraseMoveHandler(t){const{eraserStyle:e}=this.controller.interactiveConfig,{eventMode:i,isStartDraw:n,erasedShapeIds:s,controller:o}=this;if("erase"!==i||!o.container||!n)return;const r=o.shapeArrMap.get(o.containerId);if(!r.size)return;const{offsetX:a,offsetY:l}=Vh(o.canvas,t),h={x:a,y:l};this.lastMovePoint||(this.lastMovePoint=h),r.forEach(t=>{t!==this.eraserPath&&-1===s.indexOf(t.id)&&"visible"===t.parsedStyle.visibility&&t.context.controlsFlags.enableControl&&function(t,e,i){const n=Oh(t,e),s=qs(e,i),o=t.isPointInPath(n,5);if(o||s<=.9)return o;const r=s/1,a=(e.x-i.x)/r,l=(e.y-i.y)/r;for(let e=0;e<Math.abs(r);e++){const n=Oh(t,{x:i.x+a*e,y:i.y+l*e});if(t.isPointInPath(n,5))return!0}return!1}(t,h,this.lastMovePoint,e.borderWidth)&&(t.style.opacity=.5,s.push(t.id))}),this.lastMovePoint=h}drawEndHandler(t){const{eventMode:e,isStartDraw:i,drawLineShape:n,drawType:s,activatedShape:o,controller:r}=this;if("draw"===e&&"annotationStamp"===s)return void this.drawStampEndHandler(t);if("none"===e||!i||n)return;if(this.isStartDraw=!1,["annotationRect","annotationTextBox"].includes(s)){const{width:t,height:e,borderWidth:i}=o.parsedStyle,{x:n,y:s}=o.getPosition(),{x:r,y:a}=o.getScale(),l=(null==i?void 0:i.value)||0;let h=n,c=s;t.value<0&&(h=n-(-t.value+l)*r,o.style.width=-t.value+2*l),e.value<0&&(c=s-(-e.value+l)*a,o.style.height=-e.value+2*l),o.setPosition({x:h,y:c})}if("annotationEllipse"===s){const t=Math.abs(Math.round(this.controller.container.getAngle()));if(0!==t&&(o.setAngle(0),90===t)){const{rx:t,ry:e}=o.parsedStyle;o.style.rx=e.value,o.style.ry=t.value}}if("draw"===e&&this.drawInkShape){if(o.setUseDouglasPeucker(!0),this.controller.hooks.emitAnnotationRender(),1===this.activatedShape.style.segments.length)r.hooks.emitAddAnnotation("draw",[this.activatedShape]);else{const t={style:{segments:this.activatedShape.getAnnotationConfig().style.segments}};r.hooks.emitModifyAnnotation(["resized"],[{shape:this.activatedShape,changedOptions:t}])}return void(this.inkDelayTimeout=setTimeout(()=>{this.drawInkShape&&(this.drawInkShape=!1,this.activatedShape&&this.activatedShape instanceof oc&&(this.activatedShape.setUseDouglasPeucker(!0),this.inactivateShape(!1,!1)))},this.controller.interactiveConfig.inkCreateDelay))}if("draw"===e&&"annotationFreeText"!==s&&"annotationStamp"!==s){const{offsetX:e,offsetY:i}=Vh(r.canvas,t);((this.startCanvasPoint.x-e)**2+(this.startCanvasPoint.y-i)**2)**.5<2&&"annotationStamp"!==o.shapeType&&(r.deleteShape([o.id],!1),r.hooks.emitAfterAnnotationDraw(null),this.activatedShape=null)}const a=(t,e)=>{if(t instanceof hc){const{enableControl:i}=t.context.controlsFlags;if(!i)return;t.textEditEventHandler.enableEditMode(this.startCanvasPoint,e),"textBox"===t.textType&&this.controller.hooks.emitAnnotationRender(),"freeTextWriter"===t.textType&&setTimeout(()=>{document.activeElement instanceof HTMLTextAreaElement||t.textEditEventHandler.enableEditMode(this.startCanvasPoint,e)},10)}};if("draw"===e&&this.activatedShape){const t=this.activatedShape,{canvas:e}=this.controller;r.hooks.emitAddAnnotation("draw",[this.activatedShape]),r.interactiveConfig.enableContinuousDrawing?o instanceof hc?(this.eventMode="none",this.resetActivatedZIndex=!1,this.activateShape(this.activatedShape,!1,!0),a(o,e)):this.activatedShape=null:(this.controller.setAnnotationMode("none",!0),r.hooks.emitAfterAnnotationDraw(t),this.resetActivatedZIndex=!1,this.activateShape(this.activatedShape,!1,!0),a(o,e))}"erase"===e&&this.executeErase(),"select"===e&&this.executeBoxSelect()}drawStampEndHandler(t){const{offsetX:e,offsetY:i}=Vh(this.controller.canvas,t);if(!this.stampPreview)return;if(!this.eventArea)return;if(this.stampPreview&&"image"===this.stampPreview.renderType&&!this.stampPreview.imageLoadedByDraw)return void(this.stampPreview.style.visibility="hidden");const{left:n,top:s,width:o,height:r}=this.eventArea;if(e<n||e>o+n||i<s||i>r+s)return;const{defaultStyleConfig:a}=this.controller.interactiveConfig,{stamp:l}=a,h=Ls(null==l?void 0:l.opacity)?null==l?void 0:l.opacity:null==qh?void 0:qh.opacity,c=this.stampPreview;c.style.opacity=h;const{containerId:d,container:u,shapeArrMap:p}=this.controller,g={...c.getPosition()},f={...c.getScale()},m=u.getScale(),v=f.x/m.x,y=f.y/m.y;if(p.get(d).set(c.id,c),c.index=p.get(d).size,c.pageUid=d,u.appendChild(c),c.style.imageData){const{width:t,height:e}=c.parsedStyle;c.updateStyle({width:t.value*v,height:e.value*y}),c.setLocalScale(1,1)}else c.setLocalScale(v,y);c.setAngle(0),c.setPosition(g),this.stampPreview=null,this.controller.hooks.emitBeforeAnnotationDraw(c),this.controller.hooks.emitAddAnnotation("draw",[c]),this.controller.interactiveConfig.enableContinuousDrawing?Ms()&&this.createStampPreviewForMobile():(this.resetActivatedZIndex=!1,this.controller.setAnnotationMode("none",!0),this.activateShape(c,!1,!0),this.controller.hooks.emitAfterAnnotationDraw(c))}dblClickHandler(t){const{activatedShape:e,controller:i}=this;if(!e)return;const{shapeType:n}=e;if(this.drawLineShape&&("annotationPolygon"===n||"annotationPolyline"===n)){const t=[...e.style.points],n=t.length;return Ms()?qs(t[n-1],t[n-2])<=15&&t.pop():t.pop(),"mouse"===this.lastClickPointerType&&(t.pop(),this.lastClickPointerType=""),t.length<2?(i.deleteShape([e.id],!1),this.activatedShape=null):(e.style.points=t,this.controller.hooks.emitAddAnnotation("draw",[this.activatedShape])),this.isStartDraw=!1,this.drawLineShape=!1,void(!i.interactiveConfig.enableContinuousDrawing&&this.activatedShape?(this.controller.setAnnotationMode("none",!0),this.controller.hooks.emitAfterAnnotationDraw(e),this.resetActivatedZIndex=!1,this.activateShape(e,!1,!0)):this.activatedShape=null)}if("annotationFreeText"===n&&!this.isSeparateText){const{offsetX:i,offsetY:n}=Vh(this.controller.canvas,t),{textEditEventHandler:s}=e,o={x:i,y:n};if(this.activatedShape instanceof hc&&"freeTextWriter"===this.activatedShape.textType&&!this.activatedShape.isEditMode){const{cropBoxRect:t}=this.controller.container.parentNode.parentNode.parentNode,e=this.activatedShape.getBoundingRect(),i=this.getFreeTextLimitWidth(t.width,t.height,this.controller.container.getAngle(),this.activatedShape.getLocalPosition().x-t.left,this.activatedShape.getLocalPosition().y-t.top,this.activatedShape.getAngle(),e.width,e.height);i!==this.activatedShape.style.width&&(this.activatedShape.style.width=i,this.activatedShape.pathDirty=!0,this.activatedShape.boundsDirty=!0,this.activatedShape.calculateTextLines(),this.activatedShape.getBoundingRect().width!==e.width&&this.controller.hooks.emitModifyAnnotation(["appearanceChanged"],[{shape:this.activatedShape,changedOptions:{style:{width:i}}}]))}s.enableEditMode(o,this.controller.canvas),this.controller.hooks.emitAnnotationRender()}}clickHandler(t,e){const{activatedShape:i,eventMode:n}=this;if(!i)return;const{shapeType:s}=i,o=()=>{if("annotationFreeText"===s){const{offsetX:e,offsetY:n}=Vh(this.controller.canvas,t),{textEditEventHandler:s}=i,o={x:e,y:n};s.editClickHandler(o,this.controller.canvas)}};if(this.lastClickPointerType=null==t?void 0:t.pointerType,this.isSeparateText=!1,"none"===n){const n=po(t);if((n||e&&!n)&&this.controller.interactiveConfig.enableMultipleSelectWidthCtrl){if(this.isDefaultGroup(i)){const{clickedShape:t}=i;this.defaultGroup.delete(t);const{shapes:e}=this.defaultGroup;if(e.length<2&&(this.defaultGroup.context.isActive=!1),1===e.length){const t=e[0];this.activateShape(t,!1,!1),this.isSeparateText=t instanceof hc}}else this.defaultGroup.parent&&this.defaultGroup.parent!==this.controller.container&&this.defaultGroup.clear(),this.defaultGroup.add(this.activatedShape),this.defaultGroup.shapes.length>=2?(this.defaultGroup.context.isActive=!0,this.activateShape(this.defaultGroup,!1,!1)):(this.controller.hooks.emitSelectAnnotation(i),o());return void this.controller.hooks.emitAnnotationRender()}o()}}keyDownHandler(t,e){const{activatedShape:i}=this;if(!i)return;const n=()=>(this.isStartDraw&&(this.isStartDraw=!1),this.drawInkShape?(this.drawLineShape=!1,void this.controller.hooks.emitAnnotationModeChanged("none")):this.drawLineShape?(this.drawLineShape=!1,this.controller.deleteShape([this.activatedShape.id]),void this.controller.hooks.emitAnnotationRender()):(this.inactivateShape(!0),void this.defaultGroup.clear()));switch(t.key){case"Escape":n();break;case"Delete":case"Backspace":if(Uh(i)&&i.textEditEventHandler.editMode)return;if(!this.controller.interactiveConfig.enableDeleteWithKeyboard)return;if(this.drawInkShape||this.drawLineShape)return;t.preventDefault(),this.controller.deleteShape([i.id]),this.inactivateShape();break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":if(!this.controller.interactiveConfig.enableMoveWithKeyboard)return void t.preventDefault();if(i instanceof hc&&i.isEditMode)return;if(this.drawInkShape||this.drawLineShape)return;this.isArrowKeyDown=!0,i.eventHandler.moveByKeyboard(t,e)&&(this.controller.hooks.emitBeforeAnnotationEdit(i),this.arrowKeyDownSuccessful=!0,this.controller.hooks.emitAnnotationRender());break;case"Home":case"End":case"PageUp":case"PageDown":this.controller.interactiveConfig.enableMoveWithKeyboard||t.preventDefault()}}keyUpHandler(t){if(this.isArrowKeyDown&&(this.isArrowKeyDown=!1,["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)&&this.arrowKeyDownSuccessful)){this.arrowKeyDownSuccessful=!1;const t=[];this.activatedShape instanceof cc?t.push(...this.activatedShape.shapes):t.push(this.activatedShape);const e=t.map(t=>{const e=t.getAnnotationConfig(),i={style:{}};return Ps(e.style.x)||(i.style.x=e.style.x),Ps(e.style.y)||(i.style.y=e.style.y),Ps(e.style.points)||(i.style.points=e.style.points),Ps(e.style.segments)||(i.style.segments=e.style.segments),Ps(e.style.startPoint)||(i.style.startPoint=e.style.startPoint),Ps(e.style.endPoint)||(i.style.endPoint=e.style.endPoint),{shape:t,changedOptions:i}});this.controller.hooks.emitModifyAnnotation(["moved"],e),this.controller.hooks.emitAfterAnnotationEdit(this.activatedShape)}}getHitBorderOffset(t){if(!t)return 10;const e=t.getScale();if(e.x<1||e.y<1){const t=Math.min(e.x,e.y);return Math.round(Math.abs(10/t))}return 10}createStampPreviewForMobile(){if(this.stampPreview)return;const{defaultStyleConfig:t}=this.controller.interactiveConfig,{stamp:e}=t,i=(null==e?void 0:e.stampIcon)||(null==qh?void 0:qh.stampIcon),n=(null==e?void 0:e.imageData)||(null==qh?void 0:qh.imageData),s=(null==e?void 0:e.stampConfig)||null,o=this.controller.container.getRootNode();if(this.stampPreview=this.controller.createShape("annotationStamp",{style:{iconName:s?null:i,imageData:n,stampConfig:s,opacity:Ls(e.opacity)?e.opacity:.5,zIndex:9999,visibility:!1},initByDraw:!0}),o.appendChild(this.stampPreview),!n&&i){const{width:t,height:e}=this.stampPreview.parsedStyle;if(e.value>60){const i=e.value/60;this.stampPreview.updateSize(t.value/i,e.value/i)}}}}function Fc(t){return["annotationFreeText","annotationTextBox","annotationRect"].includes(t.shapeType)}var Vc=new WeakMap;class Wc extends Wo{constructor(){super(...arguments),Yi(this,"renderAnnotation",jo(this)),Yi(this,"addAnnotation",jo(this)),Yi(this,"deleteAnnotation",jo(this)),Yi(this,"selectAnnotation",jo(this)),Yi(this,"modifyAnnotation",jo(this)),Yi(this,"annotationModeChanged",jo(this)),Yi(this,"beforeAnnotationEdit",jo(this)),Yi(this,"afterAnnotationEdit",jo(this)),Yi(this,"beforeAnnotationDraw",jo(this)),Yi(this,"afterAnnotationDraw",jo(this)),Yi(this,"annotationTextEditorResized",jo(this)),Yi(this,"annotationTextPositionUpdated",jo(this)),Yi(this,"annotationTextContentUpdated",jo(this)),Yi(this,"selectAnnotationTextChars",jo(this)),Yi(this,"enableAnnotationTextEditMode",jo(this)),Yi(this,"disableAnnotationTextEditMode",jo(this)),rn(this,Vc,{writable:!0,value:[]}),Yi(this,"renderTimer",null)}emitAddAnnotation(t,e){const i=[];e.forEach(t=>{i.push({uid:t.id,shape:t})}),this.addAnnotation.emit({action:t,shapes:i})}emitDeleteAnnotation(t){const e=[];t.forEach(t=>{e.push({uid:t.id,shape:t})}),this.deleteAnnotation.emit({shapes:e})}emitSelectAnnotation(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=[];t instanceof cc?t.shapes.forEach(t=>{i.push(t.id)}):t&&i.push(t.id),(i.length||$i(this,Vc).length)&&(this.selectAnnotation.emit({newAnnotationUids:[...i],oldAnnotationsUids:[...$i(this,Vc)],emitSelected:e}),Xi(this,Vc,i))}emitModifyAnnotation(t,e){this.modifyAnnotation.emit({actions:t,shapes:e})}emitAnnotationModeChanged(t){this.annotationModeChanged.emit(t)}emitBeforeAnnotationEdit(t){t instanceof hc&&t.textEditEventHandler.editMode||this.beforeAnnotationEdit.emit(t)}emitAfterAnnotationEdit(t){this.afterAnnotationEdit.emit(t)}emitAnnotationRender(){this.renderTimer||(this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.renderAnnotation.emit()},17))}emitSelectAnnotationTextChar(t){this.selectAnnotationTextChars.emit(t)}emitBeforeAnnotationDraw(t){this.beforeAnnotationDraw.emit(t)}emitAfterAnnotationDraw(t){this.afterAnnotationDraw.emit(t)}emitEnableAnnotationTextEditMode(t){this.enableAnnotationTextEditMode.emit(t)}emitDisableAnnotationTextEditMode(t){this.disableAnnotationTextEditMode.emit(t)}emitAnnotationTextContentUpdated(t){this.annotationTextContentUpdated.emit(t)}emitAnnotationTextPositionUpdated(t){this.annotationTextPositionUpdated.emit(t)}}class Hc{constructor(t){Yi(this,"shapeArrMap",void 0),Yi(this,"shapeMap",void 0),Yi(this,"annotationMode","none"),Yi(this,"brush","annotationRect"),Yi(this,"tempTextStyle",void 0),Yi(this,"isEnterCtrl",!1),Yi(this,"canvas",void 0),Yi(this,"hooks",void 0),Yi(this,"interactiveConfig",_s(Jh)),Yi(this,"eventService",void 0),Yi(this,"containerId",void 0),Yi(this,"container",void 0),this.canvas=t,this.eventService=new Uc(this),this.hooks=new Wc,this.shapeArrMap=new Map,this.shapeMap=new Map}set drawType(t){this.brush=t,"draw"===this.annotationMode&&this.eventService.setEventMode("draw",t)}get drawType(){return this.brush}clearShapeArrMap(){this.shapeArrMap.forEach(t=>{t.clear()}),this.shapeArrMap.clear()}deleteShapeArrMap(t){this.shapeArrMap.has(t)&&(this.shapeArrMap.get(t).clear(),this.shapeArrMap.delete(t))}bindFreeTextHooks(t){if(!(t instanceof hc))return;const e=t.hooks;e.reRenderText.on(()=>{this.hooks.emitAnnotationRender()}),e.textContentUpdated.on(e=>{this.hooks.emitModifyAnnotation(["contentChanged"],[{shape:t,changedOptions:{style:{textContents:_s(t.style.textContents)}}}])}),e.positionUpdated.on(()=>{this.hooks.emitAnnotationTextPositionUpdated(t)}),e.textContentUpdatedByChar.on(()=>{this.hooks.emitAnnotationTextContentUpdated(t)}),e.selectTextChars.on(e=>{var i;const{freeTextContentStyle:n}=t,s="freeTextWriter"===t.textType?"textTypewriter":"textBox",{defaultStyleConfig:o}=this.interactiveConfig;o[s]||(o[s]={}),o[s].textContent={...n,content:null===(i=o[s])||void 0===i||null===(i=i.textContent)||void 0===i?void 0:i.content},this.hooks.emitSelectAnnotationTextChar(t)}),e.enableTextEditMode.on(e=>{this.tempTextStyle=_s(this.interactiveConfig.defaultStyleConfig["textBox"===t.textType?"textBox":"textTypewriter"]),this.hooks.emitEnableAnnotationTextEditMode(t)}),e.disableTextEditMode.on(e=>{this.interactiveConfig.defaultStyleConfig["textBox"===t.textType?"textBox":"textTypewriter"]=this.tempTextStyle,this.tempTextStyle=null,this.hooks.emitDisableAnnotationTextEditMode(t)})}bindStampHooks(t){t instanceof Ac&&t.hooks.reRenderImage.on(()=>{this.hooks.emitAnnotationRender()})}isHitShape(t){const{offsetX:e,offsetY:i}=Vh(this.canvas,t),{activatedShape:n,defaultGroup:s}=this.eventService,o={x:e,y:i},{shapeArrMap:r,shapeMap:a,containerId:l}=this,h=r.get(l)||a,c=s===this.eventService.activatedShape&&(null==s?void 0:s.parentNode)===this.container;if(n&&(c||h.has(n.id))){const t=n.eventHandler.isHit(o,!1);if(-1!==t)return{isHit:!0,isHitSelected:!0,hitControlPointIndex:t,shape:n}}let d=!1,u=null;const p=Array.from(h.values()).filter(t=>"hidden"!==t.style.visibility&&t.context.controlsFlags.enableControl&&t!==n&&!t.context.isGrouped).sort((t,e)=>e.style.zIndex-t.style.zIndex);for(const t of p){const e=Oh(t,o);if(t.isPointInPath(e,this.eventService.getHitBorderOffset(t))){d=!0,u=t;break}}return{isHit:d,shape:u,isHitSelected:!1,hitControlPointIndex:-1}}isInTextEditMode(){return!!(this.eventService.activatedShape&&this.eventService.activatedShape instanceof hc)&&this.eventService.activatedShape.isEditMode}setAnnotationMode(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.annotationMode=t,this.eventService.setEventMode(t,this.drawType),Ms()&&"draw"===t&&"annotationStamp"===this.drawType&&this.eventService.createStampPreviewForMobile(),"none"!==t&&this.eventService.inactivateShape(),e&&this.hooks.emitAnnotationModeChanged(t)}setAnnotationContainer(t,e){if(e!==this.container){const{activatedShape:t,drawLineShape:e,drawInkShape:i,drawType:n}=this.eventService;if("draw"===this.eventService.eventMode&&t){if(i&&t instanceof oc&&(clearTimeout(this.eventService.inkDelayTimeout),t.setUseDouglasPeucker(!0),this.eventService.drawInkShape=!1),e){const e=[...t.style.points];t.style.points=e,this.eventService.drawLineShape=!1,this.eventService.isStartDraw=!1}"annotationInk"!==n&&(this.hooks.emitAddAnnotation("draw",[t]),this.interactiveConfig.enableContinuousDrawing||(this.setAnnotationMode("none",!0),this.hooks.emitAfterAnnotationDraw(t)),this.eventService.activatedShape=null)}}this.containerId=t,this.container=e,this.shapeArrMap.get(t)||this.shapeArrMap.set(t,new Map)}setAnnotationInteractiveConfig(t){if(this.tempTextStyle){const e=this.eventService.activatedShape;if(e instanceof hc){const i=t.defaultStyleConfig["textBox"===e.textType?"textBox":"textTypewriter"];if(i){const t=this.tempTextStyle.textContent;this.tempTextStyle={...this.tempTextStyle,...i},this.tempTextStyle.textContent={...t,...i.textContent}}}}const e=_s(t),{controlsStyle:i,defaultStyleConfig:n,eraserStyle:s,selectionStyle:o}=this.interactiveConfig;e.defaultStyleConfig=(null==e?void 0:e.defaultStyleConfig)||{};const{stamp:r}=n,{stamp:a}=e.defaultStyleConfig,l=(null==r?void 0:r.stampIcon)||qh.stampIcon,h=null==r?void 0:r.stampConfig,c=(null==r?void 0:r.imageData)||qh.imageData,d=null==a?void 0:a.stampIcon,u=null==a?void 0:a.stampConfig,p=null==a?void 0:a.imageData;this.interactiveConfig={...this.interactiveConfig,...e,controlsStyle:_o((null==e?void 0:e.controlsStyle)||{},i),defaultStyleConfig:_o((null==e?void 0:e.defaultStyleConfig)||{},n),eraserStyle:_o((null==e?void 0:e.eraserStyle)||{},s),selectionStyle:_o((null==e?void 0:e.selectionStyle)||{},o)},(d||u||p)&&(p||(this.interactiveConfig.defaultStyleConfig.stamp.imageData=null),u||(this.interactiveConfig.defaultStyleConfig.stamp.stampConfig=null)),null!=e&&e.controlsStyle&&this.updateAllShapeControlsStyle(this.interactiveConfig.controlsStyle);const{stampPreview:g}=this.eventService;var f;g&&g.style.opacity!==(null==a?void 0:a.opacity)&&(this.eventService.stampPreview.style.opacity=null==a?void 0:a.opacity),l===d&&c===p&&h===u||!this.eventService.stampPreview||(null===(f=this.eventService.stampPreview)||void 0===f||f.destroy(),this.eventService.stampPreview=null)}setAnnotationFlags(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const n=this.getShape(t);if(!(n instanceof Dc)&&n){n!==this.eventService.activatedShape||!1!==e.enableControl&&!1!==e.isVisible||this.eventService.drawInkShape||this.eventService.inactivateShape(!0),n.context.updateControlsFlags({...e});const{isVisible:t,enableControl:s,enableEdit:o}=n.context.controlsFlags;if(n.context.isInGroup&&(!t||!s)){const{defaultGroup:t,activatedShape:e}=this.eventService;t.delete(n),e===t&&1===t.shapes.length&&this.eventService.activateShape(t.shapes[0],!1,!0)}Nh(n)&&n.pointEventsHandler.editMode&&!o&&(n.pointEventsHandler.disableEditMode(),n.pointEventsHandler.enableEditMode()),i&&this.hooks.emitAnnotationRender()}}getShape(t){if("ddvDefaultGroup"===t)return this.eventService.defaultGroup;return this.shapeMap.get(t)||null}getSelectedShapeUids(){const{activatedShape:t}=this.eventService;if(!t)return[];const e=[];return t instanceof cc?t.shapes.forEach(t=>{e.push(t.id)}):e.push(t.id),e}createShape(t,e,i){var n,s;let o;if(e.selectableStyle={...this.interactiveConfig.controlsStyle,...e.selectableStyle},"annotationEllipse"===t){const{style:t}=e;t.x+=t.width/2||0,t.y+=t.height/2||0,t.rx=t.width/2||t.rx,t.ry=t.height/2||t.ry}const{defaultStyleConfig:r}=this.interactiveConfig;switch(t){case"annotationRect":o=new rc(e);break;case"annotationGroup":o=new cc(null==e?void 0:e.id);break;case"annotationArc":o=new ec(e);break;case"annotationCircle":o=new ic(e);break;case"annotationEllipse":o=new nc(e);break;case"annotationLine":o=new fc(e);break;case"annotationInk":o=new oc(e);break;case"annotationPolygon":o=new pc(e);break;case"annotationPolyline":o=new gc(e);break;case"annotationFreeText":o=new hc(e,"freeTextWriter",{...qh.textContent,...null===(n=r.textTypewriter)||void 0===n?void 0:n.textContent});break;case"annotationTextBox":o=new hc(e,"textBox",{...qh.textContent,...null===(s=r.textBox)||void 0===s?void 0:s.textContent});break;case"annotationImage":o=new sc(e);break;case"annotationStamp":o=new Ac(e);break;case"annotationHighlight":o=new Lc(e,i);break;case"annotationUnderline":o=new Bc(e,i);break;case"annotationStrikeout":o=new Oc(e,i);break;default:o=new Dc(e)}return o?(o.id||(o.id=Us()),this.shapeMap.set(o.id,o),o):null}addShape(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(null!=e&&e.id){const t=this.getShape(null==e?void 0:e.id);if(t)return t}const s=this.createShape(t,e,n);return this.containerId&&this.shapeArrMap.get(this.containerId).set(s.id,s),this.container&&(s.index=this.shapeArrMap.get(this.containerId).size,s.pageUid=this.containerId,this.container.appendChild(s),i&&this.hooks.emitAddAnnotation("data",[s])),this.bindFreeTextHooks(s),this.bindStampHooks(s),s}updateShape(t,e){const i=this.getShape(t);if(!i)return!1;const{isGrouped:n}=i.context;if(n&&this.eventService.defaultGroup.delete(i),null!=e&&e.style)if(i instanceof Ac)i.updateStampStyle({...e.style});else{if(i instanceof nc){const{x:t,y:n,width:s,height:o}=e.style,{x:r,y:a}=i.getLocalPosition(),l=i.getAnnotationConfig(),h=s?da(s).value/2:l.style.width/2,c=o?da(o).value/2:l.style.height/2,d=Ls(t)?t+h:r-l.style.width/2+h,u=Ls(n)?n+c:a-l.style.height/2+c,p=h,g=c;e.style={...e.style,x:d,y:u,rx:p,ry:g}}i.updateStyle({...e.style}),i instanceof hc&&i.updateOrigin()}if(null!=e&&e.transform){const{angle:t,scale:n}=e.transform;Ps(t)||i.setLocalAngle(t),Ps(n)||i instanceof Ac||i.setLocalScale(n)}return n&&this.eventService.defaultGroup.add(i),!0}updateAllShapeControlsStyle(t){let e=!1;this.shapeMap.forEach(i=>{i.context.controlsStyle=t,i.context.parseControlsStyle(),i.controls&&(i.controls.isVisible&&(e=!0),i.context.destroyControls(),i.context.initControls(),i.context.renderControls())}),e&&this.hooks.emitAnnotationRender()}updateFreeTextDefaultConfig(){const{defaultStyleConfig:t}=this.interactiveConfig;this.shapeMap.forEach(e=>{if(e instanceof hc){const i=qh.textContent,n="freeTextWriter"===e.textType?"textTypewriter":"textBox",{textContent:s}=t[n]||{};e.updateFreeTextContentStyle({...i,...s,content:i.content})}})}updateLayer(t,e){const i=this.getShape(t);return!!i&&(this.interactiveConfig.showOnTopWhenSelected&&this.eventService.activatedShape===i?this.eventService.activatedZIndex=e:i.updateStyle({zIndex:e}),this.interactiveConfig.showOnTopWhenSelected&&this.interactiveConfig.enableContinuousDrawing&&"draw"===this.eventService.eventMode&&i.updateStyle({zIndex:e}),!0)}deleteShape(t){var e;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const s=[],{eventService:o}=this,r=t.includes(null==o||null===(e=o.activatedShape)||void 0===e?void 0:e.id);if(t.forEach(t=>{const e=this.getShape(t);e&&(e instanceof cc?(s.push(...e.shapes),e.clear()):s.push(e))}),!s.length)return!1;i&&this.hooks.emitDeleteAnnotation(s),s.forEach(t=>{t.context.isInGroup&&this.eventService.defaultGroup.delete(t),this.shapeMap.delete(t.id),this.shapeArrMap.get(t.pageUid)&&this.shapeArrMap.get(t.pageUid).delete(t.id),t.destroy()});const{activatedShape:a,defaultGroup:l}=o,h=a===l&&!l.state;return(r||h)&&this.eventService.inactivateShape(!0,n),!0}selectShape(t){const e=[];return t.forEach(t=>{e.push(this.getShape(t))}),this.eventService.selectShapes(e)}moveShape(t,e,i){t.forEach(t=>{const n=this.getShape(t);if(!n)return;const s=n.pageUid,o=this.shapeArrMap.get(s);o&&o.delete(t),this.shapeArrMap.get(e)||this.shapeArrMap.set(e,new Map),this.shapeArrMap.get(e).set(t,n),n.context.isGrouped&&n.parentNode.delete(n,!0),i.appendChild(n)})}clickHandler(t){this.eventService.clickHandler(t,this.isEnterCtrl)}dblClickHandler(t){this.eventService.dblClickHandler(t)}keyDownHandler(t,e){this.eventService.keyDownHandler(t,e)}keyUpHandler(t){this.eventService.keyUpHandler(t)}startHandler(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=this.isHitShape(t);this.isEnterCtrl=po(t);const n=this.isEnterCtrl&&this.interactiveConfig.enableMultipleSelectWidthCtrl;if("none"===this.annotationMode&&e&&(i.isHit?this.eventService.activateShape(i.shape,n,!0):this.eventService.inactivateShape()),"draw"!==this.annotationMode||i.isHit||this.annotationMode===this.eventService.eventMode){if("draw"===this.annotationMode&&!this.eventService.drawLineShape&&"annotationInk"!==this.brush&&"annotationStamp"!==this.brush&&i.isHit)this.eventService.setEventMode("none"),this.eventService.activateShape(i.shape,n,!0);else if("select"===this.annotationMode){const{isHitSelected:t,isHit:e}=i;t?this.eventService.setEventMode("none"):!t&&e&&n?(this.eventService.setEventMode("none"),this.eventService.activateShape(i.shape,n,!0)):(this.eventService.setEventMode("select"),this.eventService.defaultGroup.clear())}}else this.eventService.setEventMode(this.annotationMode,this.brush);this.eventService.editStartHandler(t),this.eventService.drawStartHandler(t)}moveHandler(t,e){this.eventService.editMoveHandler(t),this.eventService.drawMoveHandler(t,e),this.eventService.eraseMoveHandler(t)}endHandler(t){this.eventService.editEndHandler(t),this.eventService.drawEndHandler(t)}cursorHandler(t){if(!this.container)return null;if("erase"===this.annotationMode)return 12;if("draw"===this.annotationMode){if("annotationInk"===this.drawType||"annotationStamp"===this.drawType)return 3;if(["annotationHighlight","annotationUnderline","annotationStrikeout"].includes(this.drawType))return 16}const e=this.isHitShape(t);if(e.isHit){if(e.isHitSelected){let t=null;switch(e.hitControlPointIndex){case 8:t=11;break;case 9:t=e.shape instanceof hc&&e.shape.isEditMode?16:e.shape.context.controlsFlags.enableMove?4:1;break;case 10:t=16;break;default:t=1}return t}return 13}return"select"===this.annotationMode?2:"draw"===this.annotationMode?3:"none"===this.annotationMode?14:null}}class jc extends fh{render(t,e){"hidden"!==t.parsedStyle.visibility&&(super.render(t,e),t.controls&&t.context.renderControls())}}class zc extends jc{constructor(t){super(t),this.close=!1}}class Gc extends jc{render(t,e){super.render(t,e)}}class Yc extends jc{}class $c extends Eh{render(t,e){"hidden"!==t.parsedStyle.visibility&&(super.render(t,e),t.controls&&(t.pointEventsHandler.updateLineControls(),t.context.renderControls()))}}class Xc extends jc{}class qc extends xh{render(t,e){"hidden"!==t.parsedStyle.visibility&&(super.render(t,e),t.controls&&t.context.renderControls())}}class Zc extends wh{render(t,e){"hidden"!==t.parsedStyle.visibility&&(super.render(t,e),t.controls&&t.context.renderControls())}}class Jc extends jc{render(t,e){"hidden"!==t.parsedStyle.visibility&&(super.render(t,e),t.controls&&(t.pointEventsHandler.updateLineControls(),t.context.renderControls()))}}class Kc extends bh{render(t,e){"hidden"!==t.parsedStyle.visibility&&(super.render(t,e),t.controls&&(t.pointEventsHandler.updateLineControls(),t.context.renderControls()))}}class Qc extends jc{}class td extends fh{render(t,e){if("hidden"!==t.parsedStyle.visibility){if("stamp"===t.renderType)super.render(t,e);else{const{width:i,height:n,img:s,opacity:o}=t.parsedStyle;if(Os(s))return;e.save(),e.globalAlpha=o,e.imageSmoothingEnabled=!0,e.imageSmoothingQuality&&(e.imageSmoothingQuality="high"),e.drawImage(s,0,0,i.value,n.value),e.restore()}t.controls&&t.context.renderControls()}}}class ed extends Ph{render(t,e){"hidden"!==t.parsedStyle.visibility&&(super.render(t,e),t.controls&&t.context.renderControls())}}class id extends fh{render(t,e){if("hidden"===t.parsedStyle.visibility)return;nd(t,e);const{background:i,borderColor:n,borderWidth:s}=t.container.context.parsedControlsStyle,o=i&&""!==i,r=n&&""!==n&&s>0;if(t.boxRenderSteps.length&&(o||r)&&(this.renderSteps(t,e,t.boxRenderSteps),this.renderFill(t,e),this.renderStroke(t,e)),t.rotationRenderSteps.length&&r&&(this.renderSteps(t,e,t.rotationRenderSteps),this.renderStroke(t,e),this.renderControlPoints(t,e,t.rotationRenderPath[1])),t.controlPointsRenderPaths.length)for(const i of t.controlPointsRenderPaths)this.renderControlPoints(t,e,i)}renderSteps(t,e,i){e.beginPath(),i.forEach(t=>{Qa(e,t)}),i.length>2&&e.closePath()}renderFill(t,e){const{background:i}=t.container.context.parsedControlsStyle;i&&""!==i&&(e.save(),e.fillStyle=i,e.fill(),e.restore())}renderStroke(t,e){const{borderColor:i,borderWidth:n,lineDash:s}=t.container.context.parsedControlsStyle;i&&""!==i&&n>0&&(e.save(),e.lineWidth=n,e.strokeStyle=i,e.setLineDash(s),e.stroke(),e.restore())}renderControlPoints(t,e,i){const{ctrlBackground:n,ctrlBorderColor:s,ctrlBorderRadius:o,ctrlBorderWidth:r,ctrlLineDash:a,ctrlWidth:l,ctrlHeight:h}=t.container.context.parsedControlsStyle;for(let t=0;t<4;t++){e.beginPath();const t=o;if(0===t)e.rect(i.x-l/2,i.y-h/2,l,h);else{const{PI:n}=Math;e.arc(i.x-l/2+t,i.y-h/2+t,t,n,3*n/2),e.arc(i.x+l/2-t,i.y-h/2+t,t,3*n/2,2*n),e.arc(i.x+l/2-t,i.y+h/2-t,t,0,n/2),e.arc(i.x-l/2+t,i.y+h/2-t,t,n/2,n)}}e.closePath(),n&&(e.save(),e.fillStyle=n,e.fill(),e.restore()),r>0&&(e.save(),e.lineWidth=r,e.strokeStyle=s,e.setLineDash(a),e.stroke(),e.restore())}}function nd(t,e){const{container:i}=t,n=t.parentNode;if(!n)return;const s=n.getLocalTransform(),{a:o,b:r,c:a,d:l,e:h,f:c}=s;let d=null,u=i.parentNode;for(;!d&&u;)"pageCropBox"===u.name&&(d=u),u=u.parentNode;if(d){const{x:t,y:i,width:n,height:s}=function(t){let{x:e,y:i}=t.getPosition(),{width:n,height:s}=t;const o=(t.parentNode.parentNode.rotation%360+360)%360/90,r=devicePixelRatio;if(1===o?e-=s:2===o?(e-=n,i-=s):3===o&&(i-=n),1===o||3===o){const t=n;n=s,s=t}return{x:e*r,y:i*r,width:n*r,height:s*r}}(d);e.save(),e.setTransform(o,r,a,l,h,c),e.beginPath(),e.moveTo(t,i),e.lineTo(t+n,i),e.lineTo(t+n,i+s),e.lineTo(t,i+s),e.closePath(),e.restore(),e.clip()}}class sd extends fh{render(t,e){if("hidden"===t.parsedStyle.visibility)return;if(nd(t,e),super.render(t,e),!t.container.context.controlsFlags.enableEdit)return;const i=t.container.baseRenderPath||[],{x:n,y:s}=t.container.getScale();for(const o of i){const i={x:o.x*n,y:o.y*s};this.renderControlPoints(t,e,i)}}renderControlPoints(t,e,i){const{ctrlBackground:n,ctrlBorderColor:s,ctrlBorderRadius:o,ctrlBorderWidth:r,ctrlLineDash:a,ctrlWidth:l,ctrlHeight:h}=t.container.context.parsedControlsStyle;for(let t=0;t<4;t++){e.beginPath();const t=o;if(0===t)e.rect(i.x-l/2,i.y-h/2,l,h);else{const{PI:n}=Math;e.arc(i.x-l/2+t,i.y-h/2+t,t,n,3*n/2),e.arc(i.x+l/2-t,i.y-h/2+t,t,3*n/2,2*n),e.arc(i.x+l/2-t,i.y+h/2-t,t,0,n/2),e.arc(i.x-l/2+t,i.y+h/2-t,t,n/2,n)}}e.closePath(),n&&(e.save(),e.fillStyle=n,e.fill(),e.restore()),r>0&&(e.save(),e.lineWidth=r,e.strokeStyle=s,e.setLineDash(a),e.stroke(),e.restore())}}class od{constructor(t){Yi(this,"rCanvas",void 0),this.rCanvas=t}render(t,e){"hidden"!==t.parsedStyle.visibility&&(this.renderTextAssist(t,e),t.controls&&t.context.renderControls())}renderTextAssist(t,e){e.save(),e.globalCompositeOperation=t.parsedStyle.renderBlendMode,e.globalAlpha=t.parsedStyle.opacity;const{background:i,borderColor:n,borderWidth:s}=t.parsedStyle;if("annotationHighlight"===t.shapeType?(e.fillStyle=i.formatted,e.beginPath(),t.lines.forEach(t=>{e.rect(t.left,t.top,t.width,t.height)}),e.fill(),e.closePath()):(e.lineWidth=s.value,e.strokeStyle=n.formatted,"annotationStrikeout"===t.shapeType?(e.beginPath(),t.lines.forEach(t=>{let{left:i,top:n,width:s,height:o}=t;e.moveTo(i,n+o/2),e.lineTo(i+s,n+o/2)}),e.closePath(),e.stroke()):(e.beginPath(),t.lines.forEach(t=>{let{left:i,top:n,width:o,height:r}=t;e.moveTo(i,n+r-s.value/2),e.lineTo(i+o,n+r-s.value/2)}),e.closePath(),e.stroke())),t.context.isActive){e.globalAlpha=1;const{ctrlBorderRadius:i,ctrlBorderWidth:n,ctrlBorderColor:s,ctrlHeight:o,ctrlWidth:r,ctrlBackground:a,ctrlLineDash:l}=t.context.parsedControlsStyle,h=t.getScale().x,{left:c,top:d,width:u,height:p}=t.bounds;if(e.strokeStyle=s,e.fillStyle=a,e.lineWidth=n/h,e.setLineDash(Fo(l)?[0,0]:l),e.strokeRect(c,d,u,p),t.context.controlsFlags.enableEdit&&!t.context.isGrouped){const n=i/h,s=[];if(!t.isOutOfCropBox){if(t.startCharRect){const{startCharRect:e}=t;s.push({x:e.left+e.width/2-r/2/h,y:e.top-o/h})}if(t.endCharRect){const{endCharRect:e}=t;s.push({x:e.left+e.width/2-r/2/h,y:e.top+e.height})}}0===i?s.forEach(t=>{e.beginPath(),e.rect(t.x,t.y,r/h,o/h),e.closePath(),a&&e.fill(),e.stroke()}):s.forEach(t=>{e.beginPath();const{PI:i}=Math;e.arc(t.x+n,t.y+n,n,i,3*i/2),e.arc(t.x+r/h-n,t.y+n,n,3*i/2,2*i),e.arc(t.x+r/h-n,t.y+o/h-n,n,0,i/2),e.arc(t.x+n,t.y+o/h-n,n,i/2,i),e.closePath(),a&&e.fill(),e.stroke()})}}e.restore()}}class rd{init(t){[{name:"annotationArc",renderer:new zc(t)},{name:"annotationCircle",renderer:new Gc(t)},{name:"annotationEllipse",renderer:new Yc(t)},{name:"annotationLine",renderer:new $c(t)},{name:"annotationImage",renderer:new qc(t)},{name:"annotationInk",renderer:new Zc(t)},{name:"annotationPolygon",renderer:new Jc(t)},{name:"annotationPolyline",renderer:new Kc(t)},{name:"annotationRect",renderer:new Qc(t)},{name:"annotationFreeText",renderer:new ed(t)},{name:"annotationGroup",renderer:new Xc(t)},{name:"annotationStamp",renderer:new td(t)},{name:"annotationControls",renderer:new id(t)},{name:"annotationLineControls",renderer:new sd(t)},{name:"annotationHighlight",renderer:new od(t)},{name:"annotationUnderline",renderer:new od(t)},{name:"annotationStrikeout",renderer:new od(t)}].forEach(e=>{let{name:i,renderer:n}=e;t.contextService.registerShapeRenderer(i,n)}),t.renderingService.hooks.beforeRender.on(t=>{if(t instanceof hc&&t.linesDirty){const n=t.lines;if(t.calculateTextLines(),t.pathDirty=!0,t.boundsDirty=!0,"freeTextWriter"===t.textType)if(n.length){const e=t.getPosition(),i=t.getOrigin();t.updateOrigin();const n=t.getOrigin();i.x===n.x&&i.y===n.y||(t.setPosition({...e}),t.hooks.positionUpdated.emit())}else t.updateOrigin();var e,i;t.getPath(),null!=t&&t.textEditEventHandler&&(null==t||null===(e=t.textEditEventHandler)||void 0===e||e.calculateCharPosition(),null==t||null===(i=t.textEditEventHandler)||void 0===i||i.updateTextSelection(),null==t||t.updateCursor()),t.linesDirty=!1}})}destroy(){}}function ad(t,e,i){var n;(i instanceof ic||i instanceof nc||i instanceof ec)&&t!==e&&(null===(n=i.context)||void 0===n||n.updateControls())}function ld(t,e,i){t!==e&&i.childNodes.length>0&&i.childNodes.forEach(t=>{t&&t.style&&(t.style.opacity=e)})}function hd(t,e,i){var n;(i instanceof oc||i instanceof pc||i instanceof gc)&&t!==e&&(null===(n=i.context)||void 0===n||n.updateControls())}function cd(t,e,i){if(!(i instanceof pc||i instanceof gc||i instanceof fc||i instanceof oc))return;if(t===e)return;const{left:n,top:s}=i.getBoundingRect();i.updatePosition(n,s),i.updateOrigin()}function dd(t,e,i){var n;(i instanceof rc||i instanceof hc)&&t!==e&&(null===(n=i.context)||void 0===n||n.updateControls())}function ud(t,e,i){var n;i instanceof fc&&t!==e&&(null==i||null===(n=i.context)||void 0===n||n.updateControls())}function pd(t,e,i){i instanceof hc&&t!==e&&(i.linesDirty||(i.textEditEventHandler.calculateCharPosition(),i.textEditEventHandler.updateTextSelection(),i.updateCursor(),i.hooks.reRenderText.emit()))}function gd(t,e,i){i instanceof hc&&t!==e&&(i.linesDirty||(i.textEditEventHandler.calculateCharPosition(),i.textEditEventHandler.updateTextSelection(),i.hooks.reRenderText.emit()))}function fd(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Cr.displayResolution;const i={left:0,top:0,width:t.imageWidth/t.imageXResolution*e,height:t.imageHeight/t.imageYResolution*e};return{fileIndex:0,mediaBox:i,cropBox:{...i},resource:{data:t.imageData,width:t.imageWidth,height:t.imageHeight,resolutionX:t.imageXResolution,resolutionY:t.imageYResolution,bitDepth:t.imageBitDepth}}}const md=new class extends vr{async handler(t){const[e,i]=t.params;if(t.taskInfo.canceled)return null;const n=new lr;if(await n.initImage({source:e,isRGBA:i.sourceType===er.IT_RGBA,width:i.sourceWidth,height:i.sourceHeight,isBGRA:i.sourceType===er.IT_BGRA}),t.taskInfo.canceled)return n.terminate(),null;if(await n.crop(i.rect),t.taskInfo.canceled)return n.terminate(),null;if(await n.resize(i.width,i.height),t.taskInfo.canceled)return n.terminate(),null;const s=await n.getImage({ifDeleteObject:!0,isRGBA:!0,outputType:er.IT_RGBA,returnType:ir.RT_BINARY});return n.terminate(),{blobType:s.blobType,code:s.code,message:s.message,pageIndex:0,imageData:s.imageData,imageInfo:{imageWidth:s.imageWidth,imageHeight:s.imageHeight,imageXResolution:s.imageXResolution,imageYResolution:s.imageYResolution,imageType:s.imageType,curImageBitDepth:s.curImageBitDepth,imageBitDepth:s.imageBitDepth}}}};class vd extends Wr{constructor(){super(),Yi(this,"type","imageParser"),Yi(this,"once",!1),Yi(this,"imgReader",void 0),Yi(this,"isDestroy",!1),Yi(this,"source",void 0),Yi(this,"parserOptions",void 0),Yi(this,"info",void 0),Yi(this,"rgba",void 0),Yi(this,"count",0),this.imgReader=new hr}initParser(t,e){this.source={fileSource:t},e&&(this.parserOptions=e)}async getPageCount(){return 1}destroy(){var t;null===(t=this.imgReader)||void 0===t||t.destroy(),this.imgReader=null,this.source=null,this.isDestroy=!0}async parse(){if(this.isDestroy)return null;const t=fd(await this.imgReader.readImageInfo(this.source));return this.info={mediaBox:t.mediaBox,cropBox:t.cropBox,resolutionX:t.resource.resolutionX,resolutionY:t.resource.resolutionY,imageWidth:t.resource.width,imageHeight:t.resource.height},[t]}async parseAnnotations(t,e){return[]}async getPage(){var t;if(this.isDestroy)return null;const e={"image/jpeg":er.IT_JPG,"image/png":er.IT_PNG,"image/bmp":er.IT_BMP},{outputType:i,jpegQuality:n,returnBase64:s}=null!==(t=this.parserOptions)&&void 0!==t?t:{},o=await this.imgReader.readImage({source:this.source,outputType:null!=i?i:e[this.source.fileSource.type],jpegQuality:n,returnType:s?ir.RT_BASE64:ir.RT_AUTO});return o?fd(o):null}async getPageInternal(){var t;if(this.isDestroy)return;if(this.rgba)return;const{outputType:e,jpegQuality:i,returnBase64:n}=null!==(t=this.parserOptions)&&void 0!==t?t:{},s=await this.imgReader.readImage({source:this.source,outputType:er.IT_RGBA,jpegQuality:i,returnType:n?ir.RT_BASE64:ir.RT_AUTO});s&&(this.rgba=s.imageData)}cancelGetPage(t){var e;if(this.isDestroy)return;const{outputType:i}=null!==(e=this.parserOptions)&&void 0!==e?e:{};this.imgReader.cancelReadImage(this.source,i)}async renderPage(t,e,i){if(this.isDestroy||!this.source)return null;const n=this.info.resolutionX/Cr.dataResolution,s={left:t.rect[0]*n,top:t.rect[1]*n,width:(t.rect[2]-t.rect[0])*n,height:(t.rect[3]-t.rect[1])*n};if(s.top=this.info.imageHeight-s.top-s.height,s.left=Math.max(0,Math.min(Math.round(s.left),this.info.imageWidth-1)),s.top=Math.max(0,Math.min(Math.round(s.top),this.info.imageHeight-1)),s.width=Math.max(1,Math.min(Math.round(s.width),this.info.imageWidth-s.left)),s.height=Math.max(1,Math.min(Math.round(s.height),this.info.imageHeight-s.top)),this.rgba||await this.getPageInternal(),e.canceled)return null;this.count+=1;let o=await md.createTask("renderImage",[i||this.rgba,{sourceType:er.IT_RGBA,sourceWidth:this.info.imageWidth,sourceHeight:this.info.imageHeight,index:t.index,width:t.width,height:t.height,rect:s,outputType:t.outputType}],e);return this.count-=1,o}cancelRenderPage(t){!this.isDestroy&&this.source&&md.cancelTask("renderImage",[],t)}getPageTexts(t){return null}}class yd{constructor(){Yi(this,"type","tiffParser"),Yi(this,"once",!1),Yi(this,"imgReader",void 0),Yi(this,"parserOptions",void 0),Yi(this,"source",void 0),Yi(this,"isDestroy",!1),Yi(this,"rgbas",[]),Yi(this,"infos",[]),this.imgReader=new hr}initParser(t,e){this.source={fileSource:t},e&&(this.parserOptions=e)}async getPageCount(){return this.imgReader.getTiffPageCount(this.source)}destroy(){var t;null===(t=this.imgReader)||void 0===t||t.destroy(),this.imgReader=void 0,this.source=null,this.isDestroy=!0}async parse(t){if(this.isDestroy||!this.source)return null;const e=await this.imgReader.readTiffPageInfo(this.source,t);return t.forEach((t,i)=>{this.infos[t]=e[i]}),e.map(t=>{const e=fd(t);return e.fileIndex=t.pageIndex,e})}async parseAnnotations(t,e){return[]}async getPage(t){var e;if(this.isDestroy||!this.source)return null;const{outputType:i,returnBase64:n}=null!==(e=this.parserOptions)&&void 0!==e?e:{},s=await this.imgReader.readTiffPage({source:this.source,index:t,outputType:i,returnType:n?ir.RT_BASE64:ir.RT_AUTO});if(s){const t=fd(s);return t.fileIndex=s.pageIndex,t}return null}async getPageInternal(t){var e;if(this.isDestroy||!this.source)return;if(this.rgbas[t])return;const{outputType:i,returnBase64:n}=null!==(e=this.parserOptions)&&void 0!==e?e:{},s=await this.imgReader.readTiffPage({source:this.source,index:t,outputType:er.IT_RGBA,returnType:n?ir.RT_BASE64:ir.RT_AUTO});s&&(this.rgbas[t]=s.imageData)}cancelGetPage(t){!this.isDestroy&&this.source&&this.imgReader.cancelReadTiffPage(this.source,t)}async renderPage(t,e){if(this.isDestroy||!this.source)return null;const i=this.infos[t.index],n=i.imageXResolution/Cr.dataResolution,s={left:t.rect[0]*n,top:t.rect[1]*n,width:(t.rect[2]-t.rect[0])*n,height:(t.rect[3]-t.rect[1])*n};s.top=i.imageHeight-s.top-s.height,s.left=Math.max(0,Math.min(Math.round(s.left),i.imageWidth-1)),s.top=Math.max(0,Math.min(Math.round(s.top),i.imageHeight-1)),s.width=Math.max(1,Math.min(Math.round(s.width),i.imageWidth-s.left)),s.height=Math.max(1,Math.min(Math.round(s.height),i.imageHeight-s.top));let o=this.rgbas[t.index];return o||(await this.getPageInternal(t.index),o=this.rgbas[t.index]),e.canceled?null:await md.createTask("renderImage",[o,{sourceType:er.IT_RGBA,sourceWidth:i.imageWidth,sourceHeight:i.imageHeight,index:t.index,width:t.width,height:t.height,rect:s,outputType:t.outputType}],e)}cancelRenderPage(t){!this.isDestroy&&this.source&&md.cancelTask("renderImage",[],t)}getPageTexts(t){return null}}function xd(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=wa(t),s=e||1;if(Ts(n)&&n[0]&&n[0]instanceof fa){const t=n[0].value.steps,{length:e}=n[0].value.steps,s=[0,0,0];t.forEach(t=>{const e=wa(t.color);s[0]+=e.r,s[1]+=e.g,s[2]+=e.b});const o=[s[0]/e,s[1]/e,s[2]/e];return i&&(o[3]=255),o}const{r:o,g:r,b:a,alpha:l}=n,h=[o,r,a];return i&&(h[3]=Math.floor(l*s*255+.5)),h}function wd(t,e){return{strokeColor:t?xd(t,1,!1):null,fillColor:e?xd(e,1,!1):null}}function Cd(t,e,i){let n,s;return n=t?xd(t,i,!0):null,s=e?xd(e,i,!0):null,{apStrokeColor:n,apFillColor:s}}function bd(t,e,i){const n=t.value?t.value/i:0,s=Ad(e||[],i);return s.length?{width:n,style:"D",dash:s}:{width:n}}function Sd(t){const e=t.getLocalTransform().clone(),{a:i,b:n,c:s,d:o}=e;return[Fd(i),-Fd(n),-Fd(s),Fd(o),0,0]}function Td(t,e){const{min:i,max:n}=Math;let s=t[0][0],o=t[0][1],r=t[0][0],a=t[0][1];for(let e=1;e<t.length;e++){const l=t[e];s=i(s,l[0]),r=n(r,l[0]),a=i(a,l[1]),o=n(o,l[1])}return s===r&&(s-=1,r+=1),a===o&&(a-=1,o+=1),[s-e/2,a-e/2,r+e/2,o+e/2]}function Ed(t,e,i,n,s,o){let r=arguments.length>6&&void 0!==arguments[6]&&arguments[6];const a=[],l=tl(e),h=r?i:i/2,c=[{x:l.left-h*n,y:l.bottom+h*s},{x:l.right+h*n,y:l.bottom+h*s},{x:l.right+h*n,y:l.top-h*s},{x:l.left-h*n,y:l.top-h*s}],d=t.getLocalTransform();return c.forEach(t=>{const e=d.transformPoint({x:t.x,y:t.y});a.push([e.x/n,o-e.y/s])}),Td(a,0)}function _d(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=[],{length:n}=t;if(n>50&&e){const e=Math.floor(n/2),s=Math.floor(n/4);i.push(t[0][0],t[0][1]),i.push(t[s][0],t[s][1]),i.push(t[e][0],t[e][1]),i.push(t[n-s][0],t[n-s][1]),i.push(t[n-1][0],t[n-1][1]),i.push(t[0][0],t[0][1])}else t.forEach(t=>{i.push(t[0],t[1])});return i}function Pd(t){const e=[];for(let i=0;i<t.length;i++){const n=[];t[i].forEach(t=>{n.push(t[0],t[1])}),e.push(n)}return e}function Ad(t,e){return t?2===t.length&&0===t[0]&&0===t[1]?[]:t.map(t=>t/e):[]}function Id(t){return Math.max(["butt","round","square"].indexOf(t),0)}function Dd(t){return Math.max(["miter","round","bevel"].indexOf(t),0)}function Rd(t){const e=[],i=t.getLocalTransform();return t.renderPath.forEach(t=>{const n=i.transformPoint({x:t.x,y:t.y});e.push({x:n.x,y:n.y})}),e}function kd(t,e){const i=wa(t);let n=0,s=0,o=99999,r=99999;if(Ts(i)&&i[0]&&i[0]instanceof fa){const i=(t=>{const e=t.match(/(to\s+\w+\s+\w+)|(#\w+)/g);if(!e)return null;const i=e[0],n=e.slice(1);return{direction:i.replace(/\s+/g," ").trim(),colors:n.map(t=>t.trim())}})(t);e.forEach(t=>{n=Math.max(n,t[0]),o=Math.min(o,t[0]),s=Math.max(s,t[1]),r=Math.min(r,t[1])});const a=[o,s,n,r];i.direction.includes("left")&&(a[0]=n,a[2]=o),i.direction.includes("top")&&(a[1]=r,a[3]=s);const l=wa(i.colors[0]),h=wa(i.colors[1]);return{coords:a,extend:[!0,!0],function:[{bounds:[],domain:[0,1],encode:[0,1],functions:[{c0:[l.r/255,l.g/255,l.b/255],c1:[h.r/255,h.g/255,h.b/255],domain:[0,1],n:1,type:"exponentialInterpolation"}],type:"stitching"}],shadingType:"axial",type:"shading"}}return null}function Md(t){const e=t.map(t=>t.toLowerCase()),i=[];return e.includes("print")&&i.push("print"),e.includes("noview")&&i.push("noview"),e.includes("readonly")&&i.push("readonly"),i}function Ld(t,e,i,n,s){const{width:o,height:r}=t.parsedStyle;let a=o.value,l=r.value;if(t instanceof hc){const{width:e,height:i}=t.getBoundingRect();a=e,l=i}const{x:h,y:c}=t.getLocalPosition(),d=e/2,u=h/i,p=s-c/n,g=a/i,f=l/n;return[[u+d,p-f+d,2,!1],[u+g-d,p-f+d,0,!1],[u+g-d,p-d,0,!1],[u+d,p-d,0,!1],[u+d,p-f+d,0,!0]]}function Od(t,e,i,n){t.renderPath||t.getPath();const{renderPath:s}=t,o=[],{x:r,y:a}=t.getLocalPosition();let l=[];for(let t=0;t<s.length;t++){const{step:h,close:c}=s[t],d=(s[t].x+r)/e,u=n-(s[t].y+a)/i;0!==t?0!==h||0===t?2===h?l.push([d,u,1,c]):l.push([d,u,0,c]):(o.push(l),l=[],l.push([d,u,2,c])):l.push([d,u,2,c])}return o.push(l),o}function Bd(t,e,i,n,s,o){let r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6],a=arguments.length>7&&void 0!==arguments[7]&&arguments[7];const{lineDash:l}=t.parsedStyle,h=Sd(t),c=Td(s,a?2*n:n),d=[];return r&&d.push(Nd(t,s,e,i,n,Ad(l,o))),{bbox:c,matrix:h,transform:c,objs:d,blendMode:Hd(t.style.renderBlendMode)||"Normal"}}function Nd(t,e,i,n,s,o){const{miterLimit:r,lineCap:a,lineJoin:l}=t.parsedStyle;return{dashArray:o,dashPhase:0,fillColor:i||[0,0,0,0],fillType:i?2:0,isStroke:s>0,lineCap:Id(a),lineJoin:Dd(l),blendMode:Hd(t.style.renderBlendMode)||"Normal",lineWidth:s,miterLimit:r,objMatrix:[1,0,0,1,0,0],segments:e,strokeColor:n||[0,0,0,0],type:"path"}}function Ud(t,e,i,n){const{fontSize:s,fontFamily:o,fontWeight:r,fontStyle:a,opacity:l,text:h}=t.parsedStyle,{color:c,borderColor:d}=t.style,{x:u,y:p}=t.getLocalPosition(),{apStrokeColor:g,apFillColor:f}=Cd(d,c,l);return{type:"text",charSpace:0,wordSpace:0,fillColor:f||[0,0,0,255],strokeColor:g||[0,0,0,255],fontName:o,renderMode:0,fontIsBold:Vd(r),fontIsItalic:"italic"===a,fontSize:s.value/e,fontPitchFamily:16,text:h,position:[u/e,p/i],objMatrix:[1,0,0,1,u/e,n-p/i],blendMode:Hd(t.style.renderBlendMode)||"Normal"}}function Fd(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6;const i=t.toFixed(e);return Number.parseFloat(i)}function Vd(t){return"bold"===t||Ls(t)&&t>=600}function Wd(t,e,i){return t.replace(new RegExp(e,"g"),i)}function Hd(t){return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()}function jd(t,e,i,n,s,o){const{segments:r,lineWidth:a,strokeColor:l,fillType:h,fillColor:c,dashArray:d,lineCap:u,lineJoin:p,miterLimit:g,isStroke:f,pattern:m}=t;let v=!1;if(o)for(let t=0;t<r.length;t++){const e=r[t];if(e[0]<o[0]||e[0]>o[2]||e[1]<o[1]||e[1]>o[3]){v=!0;break}}const y={type:"path",stampPoints:qd(r,i,n,s),borderWidth:f?(a||1)*i:0,borderColor:Kd(l,e),background:h>0?Kd(c,e):null,lineDash:Qd(d,i),lineCap:Zd(u),lineJoin:Jd(p),miterLimit:g,clipped:v};return m&&(y.background=function(t,e,i,n){var s,o,r,a;const{coords:l,type:h}=t;if("shading"!==h)return null;const c=l[0]*e,d=n-l[1]*i,u=l[2]*e,p=n-l[3]*i,g=c<u?"right":"left",f=d===p?"":d<p?"bottom":"top";if(!t||null==t||!t.function||null==t||null===(s=t.function[0])||void 0===s||!s.functions)return null;let m=null==t||null===(o=t.function[0])||void 0===o||null===(o=o.functions[0])||void 0===o?void 0:o.c0,v=null==t||null===(r=t.function[0])||void 0===r||null===(r=r.functions[0])||void 0===r?void 0:r.c1;if(!m||!v)return null;const y=(null==t||null===(a=t.function[0])||void 0===a?void 0:a.encode)||[1,0];if(y[0]>y[y.length-1]){const t=v;v=m,m=t}const x=`rgb(${255*m[0]},${255*m[1]},${255*m[2]})`,w=`rgb(${255*v[0]},${255*v[1]},${255*v[2]})`;return`linear-gradient(to ${g} ${f}, ${ya(x)}, ${ya(w)})`}(m,i,n,s)||y.background),y}function zd(t,e,i,n,s){const{text:o,renderMode:r,fontIsBold:a,fontIsItalic:l,fillColor:h,fontSize:c,fontName:d,strokeColor:u,objMatrix:p}=t,g=ta.create(p),{scale:f}=g.decompose(),m=function(t,e,i,n,s){const o=Yd(t,e,[1,0,0,1,0,0]);return[o[0]*i,(s-o[1])*n]}(p[4],p[5],i,n,s);return{type:"text",text:o,color:Kd(h,e),borderWidth:r?i:"0px",borderColor:Kd(u,e),fontWeight:a?"bold":"normal",fontStyle:l?"italic":"normal",fontSize:c*i*Math.abs(f.x),fontFamily:d,textBaseLine:"alphabetic",x:m[0],y:m[1]}}function Gd(t,e,i){const n=function(t){const e=t.replace(/[^A-Za-z0-9\+\/]/g,""),i=e.length,n=3*i+1>>>2,s=new Uint8Array(n);for(let t,o,r=0,a=0,l=0;l<i;l++)if(o=3&l,r|=eu(e.charCodeAt(l))<<18-6*o,3===o||i-l==1){for(t=0;t<3&&a<n;t++,a++)s[a]=r>>>(16>>>t&24)&255;r=0}return s}(t),s=new ImageData(new Uint8ClampedArray(n),e,i);let o=document.createElement("canvas");o.width=e,o.height=i,o.getContext("2d").putImageData(s,0,0);const r=o.toDataURL();return o=null,r}function Yd(t,e,i){return[i[0]*t+i[2]*e+i[4],i[1]*t+i[3]*e+i[5]]}function $d(t,e,i,n,s,o){let r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6],a=!(arguments.length>7&&void 0!==arguments[7])||arguments[7];const l=ta.create(i),h=l.decompose(),c={x:(e[2]+e[0])/2,y:(e[1]+e[3])/2},d=(e[2]-e[0])/2,u=(e[1]-e[3])/2,p=l.transformPoint(c),g={x:(p.x-d)*n,y:(o-p.y+u)*s},f=-h.rotation,m={x:h.scale.x,y:h.scale.y};let v=g;var y;return r&&(v=null!==(y=function(t,e,i,n,s,o){let r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const a=[];let l=!0;if(t.forEach(t=>{let i;"path"===t.type?(i=jd(t,1,n,s,o,e),l=!1,r||(i.clipped=!1)):"text"===t.type&&(i=zd(t,1,n,s,o),l=!1),i&&a.push(i)}),l)return null;if(a.length){const t=function(t,e,i,n,s){const o=e[0]*i,r=(s-e[3])*n,a=[],l=[];if(t.forEach(t=>{if("path"!==t.type)return;if(t.clipped)return;const{borderWidth:e,stampPoints:i,lineCap:n}=t;if(2===i.length){const t=rl(i[0],i[1],da(e).value,n);a.push(t.left,t.left+t.width),l.push(t.top,t.top+t.height)}else{const t=tl(i),n=da(e).value/2,s=t.left-n,o=t.top-n,r=t.width+2*n,h=t.height+2*n;a.push(s,s+r),l.push(o,o+h)}}),0===a.length)return{offsetX:0,offsetY:0};return{offsetX:Math.min(...a)-o,offsetY:Math.min(...l)-r}}(a,e,n,s,o);i.x+=t.offsetX,i.y+=t.offsetY}return i}(t,e,{...g},n,s,o,a))&&void 0!==y?y:v),{position:v,angle:f,scale:m}}function Xd(t,e,i,n){const s=[];return t.forEach(t=>{s.push({x:t[0]*e,y:(n-t[1])*i})}),s}function qd(t,e,i,n){const s=[];return t.forEach(t=>{const o=t[0],r=t[1];s.push({x:o*e,y:(n-r)*i,step:t[2],close:t[3]})}),s}function Zd(t){return["butt","round","square"][null!=t?t:0]}function Jd(t){return["miter","round","bevel"][null!=t?t:0]}function Kd(t,e){if(!t)return null;if((null==t?void 0:t.length)<3)return null;if(4===(null==t?void 0:t.length)){const i=0===e?255:t[3];return`rgba(${t.slice(0,3).join()},${i/255/(e||1)})`}return`rgb(${t.join()})`}function Qd(t,e){return t&&0!==t.length?t.map(t=>t*e):[0,0]}function tu(t){if(!Ts(t))return[null];let e=[];for(let i=0;i<t.length;i++)t[i]instanceof Array?e=e.concat(tu(t[i])):e.push(_s(t[i]));return e}function eu(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:43===t?62:47===t?63:0}function iu(t,e){if(!t)return"";let i="";return t.split(";").forEach(t=>{const n=t.split(":");n[0].trim()===e&&(i=n[1].trim())}),i}function nu(t){if(!t)return{contents:[],textStyle:{}};const e=new DOMParser,i='xmlns="http://www.w3.org/1999/xhtml"';let n=t;t.includes('xmlns="')||(n=t.replace(/<body/,`<body ${i}`)),n=Wd(n,'xmlns=""',i);const s=e.parseFromString(n,"text/xml"),o=s.getElementsByTagName("body")[0],r=s.getElementsByTagName("span"),a=s.getElementsByTagName("p"),l=t=>{for(const e in t)null!==t[e]&&void 0!==t[e]&&""!==t[e]||delete t[e];return t},{color:h,fontFamily:c,fontSize:d,fontWeight:u,fontStyle:p,textDecoration:g}=o.style,f=l({color:h,fontFamily:c,fontSize:d,fontWeight:u,fontStyle:p,lineThrough:g.includes("line-through"),underline:g.includes("word")||g.includes("underline")}),m=[],v=t=>{for(let e=0;e<t.length;e++){const i=t[e],{color:n,fontFamily:s,fontSize:o,fontStyle:r,fontWeight:a}=i.style||{},h=iu(i.getAttribute("style"),"text-decoration"),c=l({content:i.textContent,color:n,fontFamily:s,fontSize:o,fontWeight:a,fontStyle:r,lineThrough:h.includes("line-through")||void 0,underline:h.includes("word")||h.includes("underline")||void 0});m.push(c)}};return r.length?v(r):v(a),{textStyle:f,contents:m}}function su(t,e,i){if(1!==Math.abs(e[0])||1!==Math.abs(e[3])||0!==Math.abs(e[4])||0!==Math.abs(e[5])){const n=Yd(i[0],i[1],e),s=Yd(i[2],i[3],e);t.forEach(t=>{t.segments.forEach(t=>{const i=Yd(t[0],t[1],e);t[0]=i[0],t[1]=i[1]})}),i[0]=n[0],i[1]=n[1],i[2]=s[0],i[3]=s[1];for(let t=0;t<6;t++)e[t]=0===t||3===t?1:0}}function ou(t,e,i,n,s,o){var r;const{objs:a}=t||{},l=t&&(null==a?void 0:a.length)>0&&"path"===a[0].type,h=l?a[0]:null,c=(l?h.strokeColor:e)||[0,0,0],d=(l?h.fillColor:i)||null,u=l?h.fillType>0:!So(d),p=Kd(c,n),g=d?Kd(d,n):"",f=Qd(l?h.dashArray:null==s?void 0:s.dash,o),m=Zd(l?h.lineCap:0),v=Jd(l?h.lineJoin:0),y=l?h.miterLimit:10;let x=(null!==(r=null==s?void 0:s.width)&&void 0!==r?r:1)*o||0;var w;return l&&(x=(null!==(w=null==h?void 0:h.lineWidth)&&void 0!==w?w:1)*o||0),{useObj:l,hasFill:u,borderColor:p,background:g,lineDash:f,lineCap:m,lineJoin:v,miterLimit:y,borderWidth:x}}class ru{constructor(){Yi(this,"pageWidth",void 0),Yi(this,"pageHeight",void 0),Yi(this,"ratioX",0),Yi(this,"ratioY",0)}setParserConfig(t,e,i,n){this.pageWidth=t,this.pageHeight=e,this.ratioX=i,this.ratioY=n}parseAnnotation(t){let e=null;switch(t.type){case"Square":e=this.parseRect(t);break;case"Circle":e=this.parseCircle(t);break;case"Line":e=this.parseLine(t);break;case"Polygon":e=this.parsePolygon(t);break;case"PolyLine":e=this.parsePolyline(t);break;case"Ink":e=this.parseInk(t);break;case"FreeText":e=t.intent&&"freetext"!==t.intent.toLocaleLowerCase()?"freetexttypewriter"===t.intent.toLocaleLowerCase()?this.parseFreeText(t):this.parseIncomplete(t):this.parseTextBox(t);break;case"Stamp":e=this.parseStamp(t);break;case"Highlight":e=this.parseTextAssist(t,"highlight");break;case"StrikeOut":e=this.parseTextAssist(t,"strikeout");break;case"Underline":e=this.parseTextAssist(t,"underline");break;case"Widget":e=this.parseUnknown(t);break;default:e=t.normalAppearance?this.parseIncomplete(t):this.parseUnknown(t)}if(e||(t.normalAppearance?(e=this.parseIncomplete(t),e||(e=this.parseUnknown(t))):e=this.parseUnknown(t)),e){var i;const{opacity:n}=t,s=e.style;if(e.raw=t,s.opacity=Ls(s.opacity)?s.opacity:null!=n?n:1,null!=t&&t.normalAppearance){const{blendMode:i}=t.normalAppearance;e.style.renderBlendMode=i.toLowerCase()}null!==(i=e)&&void 0!==i&&i.transform&&e.transform.angle<0&&(e.transform.angle+=360),e.uid=Us()}return e}isSegmentsRect(t){if(5!==t.length&&4!==t.length)return!1;if(5===t.length&&(t[0][0]!==t[4][0]||t[0][1]!==t[4][1]))return!1;if(t[0][0]===t[2][0]&&t[0][1]===t[2][1]||t[1][0]===t[3][0]&&t[1][1]===t[3][1])return!1;for(let e=1;e<t.length;e++)if(0!==t[e][2])return!1;for(let e=1;e<t.length;e++)if(t[e][0]!==t[e-1][0]&&t[e][1]!==t[e-1][1])return!1;return t[0][0]===t[3][0]||t[0][1]===t[3][1]}parseRect(t){const{normalAppearance:e,interiorColor:i,borderStyle:n,opacity:s,color:o,rect:r}=t,{ratioX:a,ratioY:l,pageHeight:h}=this,{useObj:c,hasFill:d,borderColor:u,background:p,lineDash:g,lineCap:f,lineJoin:m,borderWidth:v}=ou(e,o,i,s,n,a);let y=null,x=0,w=0,C=0,b=0;if(e){const{bbox:t,objs:i,transform:s}=e,{position:o,angle:r,scale:d}=$d(i||null,t,s,a,l,h,!(null==i||!i.length));if(C=o.x,b=o.y,y={angle:r,scale:d},c){const{lineWidth:t,segments:e}=i[0];if(!this.isSegmentsRect(e))return null;x=(e[1][0]-e[0][0]+t)*this.ratioX,w=(e[2][1]-e[0][1]+t)*this.ratioY}else{var S,T;x=(t[2]-t[0]-(null!==(S=null==n?void 0:n.width)&&void 0!==S?S:1))*this.ratioX,w=(t[3]-t[1]-(null!==(T=null==n?void 0:n.width)&&void 0!==T?T:1))*this.ratioY}}else{var E,_,P,A;C=(r[0]+(null!==(E=null==n?void 0:n.width)&&void 0!==E?E:1)/2)*this.ratioX,b=(h-r[3]+(null!==(_=null==n?void 0:n.width)&&void 0!==_?_:1)/2)*this.ratioY,x=(r[2]-r[0]-(null!==(P=null==n?void 0:n.width)&&void 0!==P?P:1))*this.ratioX,w=(r[3]-r[1]-(null!==(A=null==n?void 0:n.width)&&void 0!==A?A:1))*this.ratioY}return{type:"rectangle",style:{x:C,y:b,width:x,height:w,borderWidth:v,borderColor:u,background:d?p:"",lineDash:g,lineCap:f,lineJoin:m},iconColor:d?p:u,transform:y}}parseCircle(t){const{normalAppearance:e,interiorColor:i,borderStyle:n,opacity:s,color:o,rect:r}=t,{ratioX:a,ratioY:l,pageHeight:h}=this,{objs:c}=e||{},{hasFill:d,borderColor:u,background:p,lineDash:g,borderWidth:f}=ou(e,o,i,s,n,a);let m=null,v=0,y=0,x=0,w=0;if(e){const{bbox:t,transform:i}=e,{position:n,angle:s,scale:o}=$d(c||null,t,i,a,l,h,!(null==c||!c.length));x=n.x,w=n.y,m={angle:s,scale:o},v=(t[2]-t[0])*this.ratioX,y=(t[3]-t[1])*this.ratioY}else x=r[0]*this.ratioX,w=(h-r[3])*this.ratioY,v=(r[2]-r[0])*this.ratioX,y=(r[3]-r[1])*this.ratioY;return{type:"ellipse",style:{x:x,y:w,width:v,height:y,borderWidth:f,borderColor:u,background:d?p:"",lineDash:g},transform:m,iconColor:d?p:u}}parseLine(t){if(null!=t&&t.intent&&"linedimension"===t.intent.toLocaleLowerCase())return null;const{normalAppearance:e,interiorColor:i,borderStyle:n,lineEnding:s,opacity:o,color:r,line:a}=t,{ratioX:l,ratioY:h,pageHeight:c}=this,{objs:d}=e||{},{useObj:u,borderColor:p,background:g,lineDash:f,lineCap:m,lineJoin:v,miterLimit:y,borderWidth:x}=ou(e,r,i,o,n,l);let w,C={x:a[0]*this.ratioX,y:(this.pageHeight-a[1])*this.ratioY},b={x:a[2]*this.ratioX,y:(this.pageHeight-a[3])*this.ratioY};if(e){const{bbox:t}=e,{transform:i}=e;if(u){const{segments:e}=d[0];su(d,i,t),C={x:e[0][0]*this.ratioX,y:(this.pageHeight-e[0][1])*this.ratioY},b={x:e[1][0]*this.ratioX,y:(this.pageHeight-e[1][1])*this.ratioY}}const{position:n,angle:s,scale:o}=$d(tu(d),t,i,l,h,c,!(null==d||!d.length));w={position:n,scale:o,angle:s}}return{type:"line",style:{startPoint:C,endPoint:b,lineEnding:s||["None","None"],borderColor:p,borderWidth:x,background:g||"",lineCap:m,lineJoin:v,lineDash:f,miterLimit:y},transform:w,iconColor:p}}parsePolygon(t){const{normalAppearance:e,interiorColor:i,borderStyle:n,opacity:s,color:o,vertices:r,intent:a}=t;if(a&&["polygondimension","polygoncloud"].includes(a.toLocaleLowerCase()))return null;const{ratioX:l,ratioY:h,pageHeight:c}=this,{objs:d}=e||{},{hasFill:u,borderColor:p,background:g,lineDash:f,lineCap:m,lineJoin:v,miterLimit:y,useObj:x,borderWidth:w}=ou(e,o,i,s,n,this.ratioX);let C,b;if(x){const{bbox:t}=e,{transform:i}=e;su(d,i,t),C=$d(tu(d),t,i,l,h,c,!1);const{segments:n}=d[0];b=Xd(n,this.ratioX,this.ratioY,this.pageHeight)}else{const t=[];for(let e=0;e<r.length;e+=2)t.push([r[e],r[e+1]]);b=Xd(t,this.ratioX,this.ratioY,this.pageHeight)}var S,T;return b.length>2&&(S=b[0],T=b[b.length-1],S.x===T.x&&S.y===T.y)&&b.pop(),{type:"polygon",style:{points:b,borderWidth:w,borderColor:p,background:u?g:"",lineDash:f,lineCap:m,lineJoin:v,miterLimit:y},transform:C,iconColor:u?g:p}}parsePolyline(t){const{normalAppearance:e,interiorColor:i,opacity:n,color:s,vertices:o,borderStyle:r,intent:a}=t;if(a&&"polylinedimension"===a.toLocaleLowerCase())return null;const{ratioX:l,ratioY:h,pageHeight:c}=this,{objs:d}=e||{},{borderColor:u,background:p,lineDash:g,lineCap:f,lineJoin:m,miterLimit:v,useObj:y,borderWidth:x}=ou(e,s,i,n,r,this.ratioX);let w,C;if(y){const{bbox:t}=e,{transform:i}=e;su(d,i,t),w=$d(tu(d),t,i,l,h,c,!1);const{segments:n}=d[0];C=Xd(n,this.ratioX,this.ratioY,this.pageHeight)}else{const t=[];for(let e=0;e<o.length;e+=2)t.push([o[e],o[e+1]]);C=Xd(t,this.ratioX,this.ratioY,this.pageHeight)}return{type:"polyline",style:{points:C,borderWidth:x,borderColor:u,background:p,lineDash:g,lineCap:f,lineJoin:m,lineEnding:t.lineEnding||["None","None"],miterLimit:v},transform:w,iconColor:u}}parseInk(t){const{normalAppearance:e,inkList:i,opacity:n,borderStyle:s,interiorColor:o,color:r}=t,{ratioX:a,ratioY:l,pageHeight:h}=this;if(!i)return null;const{borderColor:c,background:d,lineDash:u,lineCap:p,lineJoin:g,miterLimit:f,borderWidth:m}=ou(e,r,o,n,s,this.ratioX),v=[];for(let t=0;t<i.length;t++){const e=i[t],n=[];for(let t=0;t<e.length;t+=2){const i=e[t],s=e[t+1];n.push([i,s,1,!1])}const s=Xd(n,this.ratioX,this.ratioY,this.pageHeight);v.push(s)}let y=null;if(e){const{objs:t,transform:i,bbox:n}=e;for(let e=0;e<t.length;e++)if(!1===t[e].isStroke)return null;y=$d(tu(t),n,i,a,l,h,!(null==t||!t.length),!1)}return{type:"ink",style:{segments:v,borderWidth:m,borderColor:c,background:d,lineDash:u,lineCap:p,lineJoin:g,miterLimit:f},transform:y,iconColor:c}}parseFreeText(t){const{normalAppearance:e,richText:i,rect:n,defaultAppearanceData:s,defaultStyle:o}=t,{ratioX:r,ratioY:a,pageHeight:l}=this;let h,c,d,u,p=0;if(e){const{bbox:t,transform:i,objs:n}=e,{position:s,angle:o,scale:u}=$d(tu(n),t,i,r,a,l,n.length&&"path"===n[0].type);p=o,c=s.x,d=s.y,h={angle:p,scale:u}}else c=n[0]*this.ratioX,d=(l-n[3])*this.ratioY;(Math.round(p)+360)/90%2==0?(u=(n[2]-n[0])*this.ratioX,0===p&&(u+=12),u+c>this.pageWidth*this.ratioX&&(u=this.pageWidth*this.ratioX-c)):(u=(n[3]-n[1])*this.ratioY,u+c>this.pageHeight*this.ratioY&&(u=this.pageHeight*this.ratioY-c));const{fontName:g,fontSize:f,fontColor:m}=s,v={content:"",fontFamily:g,color:iu(o,"color")||`rgb(${m[0]},${m[1]},${m[2]})`,fontSize:f},y=nu(i),x=[];return y.contents.forEach(t=>{const e={...v,...y.textStyle,...t},i=da(e.fontSize);e.fontFamily=e.fontFamily.replace(/^"|"$/g,""),(Ls(e.fontSize)||"pt"===i.unit)&&(e.fontSize=i.value*this.ratioX),x.push(e)}),{type:"textTypewriter",style:{x:c,y:d,width:u,textContents:x},transform:h,iconColor:v.color}}parseTextBox(t){const{normalAppearance:e,richText:i,defaultAppearanceData:n,defaultStyle:s,opacity:o,borderStyle:r,color:a,rect:l}=t,{ratioX:h,ratioY:c,pageHeight:d}=this,{hasFill:u,borderColor:p,background:g,borderWidth:f,lineDash:m,useObj:v}=ou(e,null==n?void 0:n.fontColor,a,o,r,h);let y,x,w,C,b;if(e&&e.objs.length){var S,T;const{bbox:t,transform:i,objs:n}=e,{position:s,angle:o,scale:a}=$d(tu(n),t,i,h,c,d,"path"===n[0].type);y=s.x,x=s.y,b={angle:o,scale:a};const{segments:l,lineWidth:u}=n[0];w=v&&"path"===n[0].type?(l[1][0]-l[0][0]+u)*this.ratioX:(t[2]-t[0]-(null!==(S=null==r?void 0:r.width)&&void 0!==S?S:1))*this.ratioX,C="path"===n[0].type?(l[2][1]-l[0][1]+u)*this.ratioY:(t[3]-t[1]-(null!==(T=null==r?void 0:r.width)&&void 0!==T?T:1))*this.ratioY}else{var E,_,P,A;y=(l[0]+(null!==(E=null==r?void 0:r.width)&&void 0!==E?E:1)/2)*this.ratioX,x=(d-l[3]+(null!==(_=null==r?void 0:r.width)&&void 0!==_?_:1)/2)*this.ratioY,w=(l[2]-l[0]-(null!==(P=null==r?void 0:r.width)&&void 0!==P?P:1))*this.ratioX,C=(l[3]-l[1]-(null!==(A=null==r?void 0:r.width)&&void 0!==A?A:1))*this.ratioY}const{fontName:I,fontSize:D}=n,R={content:"",fontFamily:I,fontSize:D},k=nu(i);let M=iu(i,"text-align")||iu(s,"text-align");"justify-center"===M&&(M="justify");const L=[];if(k.contents.forEach(t=>{const e={...R,...k.textStyle,...t},i=da(e.fontSize);e.fontFamily=e.fontFamily.replace(/^"|"$/g,""),(Ls(e.fontSize)||"pt"===i.unit)&&(e.fontSize=i.value*this.ratioX),L.push(e)}),0===L.length&&t.contents){const e={...R,content:t.contents};Ls(e.fontSize)&&(e.fontSize*=this.ratioX),L.push(e)}return{type:"textBox",style:{x:y,y:x,width:w,height:C,borderWidth:f,borderColor:p,background:u?g:"",lineDash:m,textContents:L,textAlign:M},transform:b,iconColor:R.color}}parseStamp(t){const{icon:e,opacity:i,normalAppearance:n}=t;if(!n)return null;const{objs:s,transform:o,bbox:r}=t.normalAppearance;if(0===s.length)return null;const a=tu(s),l=[],{ratioX:h,ratioY:c,pageHeight:d}=this,{position:u,angle:p,scale:g}=$d(a,r,o,h,c,d),f={position:u,angle:p,scale:g};for(let t=0;t<a.length;t++){let e;if("path"===a[t].type&&(e=jd(a[t],i,this.ratioX,this.ratioY,this.pageHeight,r)),"text"===a[t].type&&(e=zd(a[t],i,this.ratioX,this.ratioY,this.pageHeight)),"image"===a[t].type){const e={type:"stamp",style:{imageData:a[t].jpegBase64?`data:image/jpeg;base64,${a[t].jpegBase64}`:Gd(a[t].RGBABase64,a[t].width,a[t].height),width:(a[t].rect[2]-a[t].rect[0])*this.ratioX,height:(a[t].rect[3]-a[t].rect[1])*this.ratioY},transform:f};return e.transform.position.x+=(a[t].rect[0]-r[0])*this.ratioX,e.transform.position.y-=(a[t].rect[3]-r[3])*this.ratioY,e}e&&l.push(e)}return{type:"stamp",style:{iconName:e,stampConfig:l},transform:f,iconColor:"#868E96"}}parseTextAssist(t,e){const{normalAppearance:i,opacity:n,color:s}=t;if(!i)return null;const o=1e-6;if(t.quadPoints)for(let e=0;e<t.quadPoints.length;e++)if(8===t.quadPoints[e].length&&(Math.abs(t.quadPoints[e][1]-t.quadPoints[e][3])>o||Math.abs(t.quadPoints[e][5]-t.quadPoints[e][7])>o))return null;const{objs:r,transform:a,bbox:l}=t.normalAppearance;if(!r||0===r.length){const i=Kd(s,1);return{type:e,style:{annotationRaw:t,lines:[],borderColor:i,borderWidth:1,background:i,lineCap:"butt",lineJoin:"miter",lineDash:[0,0],miterLimit:10,opacity:n},transform:{angle:0,position:{x:0,y:0},scale:{x:1,y:1}}}}su(r,a,l);const h=tu(r),c=[],{ratioX:d,ratioY:u,pageHeight:p}=this,g=$d(h,l,a,d,u,p,!1);for(let t=0;t<h.length;t++)if("path"===h[t].type){const e=jd(h[t],n,d,u,p);c.push(e)}if(0===c.length)return null;const f=[];let m=0;if(c.forEach(i=>{const n=[];let s=[];for(let t=0;t<i.stampPoints.length;t++)2===i.stampPoints[t].step&&s.length>0&&(n.push(s),s=[]),s.push(i.stampPoints[t]);s.length>0&&(n.push(s),s=[]);const r=i.borderWidth;for(let s=0;s<n.length;s++){const a=n[s],l=t.quadPoints[m];m+=1;const h=l[0]*d,c=(p-l[1])*u,g=l[2]*d,v=(p-l[5])*u;let y;if(i.quadPointsRect={left:h,top:c,width:g-h,height:v-c},"highlight"===e){const t=[];for(let e=0;e<a.length;e++)2===a[e].step?t.push({x:a[e].x,y:a[e].y}):1===a[e].step?e+2<a.length&&1===a[e+2].step&&(t.push({x:a[e+2].x,y:a[e+2].y}),e+=2):e>0&&!(Math.abs(a[e].x-a[e-1].x)<=o&&Math.abs(a[e].y-a[e-1].y)<=o)&&t.push({x:a[e].x,y:a[e].y});if(t.length>=4){let e=1/0,i=1/0,n=-1/0,s=-1/0;t.forEach(t=>{e=Math.min(e,t.x),i=Math.min(i,t.y),n=Math.max(n,t.x),s=Math.max(s,t.y)}),y={left:e,top:i,width:n-e,height:s-i}}}else if("strikeout"===e){if(a.length>=2){const t=i.quadPointsRect.top,e=a[1].y;y={left:a[1].x>a[0].x?a[0].x:a[1].x,top:t,width:a[1].x>a[0].x?a[1].x-a[0].x:a[0].x-a[1].x,height:2*Math.abs(e-t)}}}else if("underline"===e&&a.length>=2){const t=2*(i.quadPointsRect.top+i.quadPointsRect.height/2)-(a[0].y+r/2);y={left:a[1].x>a[0].x?a[0].x:a[1].x,top:t,width:a[1].x>a[0].x?a[1].x-a[0].x:a[0].x-a[1].x,height:a[0].y+r/2-t}}y&&f.push(y)}}),0===f.length)return null;const v=c[0];return{type:e,style:{annotationRaw:t,lines:f,borderColor:v.borderColor,borderWidth:v.borderWidth,background:v.background||"",lineCap:v.lineCap,lineJoin:v.lineJoin,lineDash:v.lineDash,miterLimit:v.miterLimit},transform:g}}parseIncomplete(t){const{normalAppearance:e,opacity:i}=t;if(!e)return null;const{objs:n,transform:s,bbox:o}=t.normalAppearance;if(!n||0===n.length)return null;const r=tu(n),a=[],{ratioX:l,ratioY:h,pageHeight:c}=this,{position:d,angle:u,scale:p}=$d(r,o,s,l,h,c),g={position:d,angle:u,scale:p};for(let e=0;e<r.length;e++){let n;if("path"===r[e].type)n=jd(r[e],i,l,h,c);else if("text"===r[e].type)n=zd(r[e],i,l,h,c);else if("image"===r[e].type){let i;i=r[e].jpegBase64?`data:image/jpeg;base64,${r[e].jpegBase64}`:Gd(r[e].RGBABase64,r[e].width,r[e].height);const n={type:"incomplete",style:{imageData:i,width:(r[e].rect[2]-r[e].rect[0])*this.ratioX,height:(r[e].rect[3]-r[e].rect[1])*this.ratioY,annotationRaw:t},transform:g};return n.transform.position.x+=(r[e].rect[0]-o[0])*this.ratioX,n.transform.position.y-=(r[e].rect[3]-o[3])*this.ratioY,n}n&&a.push(n)}return{type:"incomplete",style:{stampConfig:a,annotationRaw:t},transform:g}}parseUnknown(t){return{type:"unknown",style:{annotationRaw:t}}}}class au{constructor(){Yi(this,"map",new Map),Yi(this,"ratioX",Cr.displayResolution/Cr.pdfResolution),Yi(this,"ratioY",Cr.displayResolution/Cr.pdfResolution)}async toPdfAnnotations(t,e){const i=[],n=[...t];n.sort((t,e)=>t.layer-e.layer);for(let t=0;t<n.length;t++){const s=n[t];if(s){const t=await this.toPdfAnnotation(s,{width:e.width/this.ratioX,height:e.height/this.ratioY});if(t){t.oriIndex=s.oriIndex,t.modified=s.modified;const{flags:e}=s,n=[];["noResize","noMove","noRotate"].forEach(t=>{e.includes(t)&&n.push(t)}),n.length&&(t.customData={...s.customData||{},dynamsoftFlags:n}),i.push(t)}}}return i}async toPdfAnnotation(t,e){if("stamp"===t.type&&t.style.imageData&&(!Ls(t.style.width)||!Ls(t.style.height))){const e=new hr,i=await e.readImageInfo({fileSource:t.style.imageData});let n=i.imageWidth,s=i.imageHeight;if(n>400||s>400){const t=Math.max(n/400,s/400);n/=t,s/=t}t.style.width=n,t.style.height=s}const i=this.createShape(t);let n=null;switch(t.type){case"rectangle":case"ellipse":n=this.toPdfRectOrEllipse(t,e,i);break;case"polyline":case"polygon":n=this.toPdfPolygonal(t,e,i);break;case"line":n=this.toPdfLine(t,e,i);break;case"ink":n=this.toPdfInk(t,e,i);break;case"stamp":n=await this.toPdfStamp(t,e,i);break;case"textBox":n=this.toPdfFreeText(t,e,i,"textBox");break;case"textTypewriter":n=this.toPdfFreeText(t,e,i,"freeTextWriter");break;case"highlight":n=this.toPdfTextAssist(t,"Highlight",e,i);break;case"underline":n=this.toPdfTextAssist(t,"Underline",e,i);break;case"strikeout":n=this.toPdfTextAssist(t,"StrikeOut",e,i);break;case"incomplete":case"unknown":n=t.style.annotationRaw}return n&&(n.title=t.comment.author,n.subject=t.comment.subject,n.creationdate=t.comment.creationDate),i&&i.destroy(),n}toPdfRectOrEllipse(t,e,i){const{borderColor:n,background:s,lineDash:o}=t.style,{borderWidth:r,opacity:a}=i.parsedStyle,{strokeColor:l,fillColor:h}=wd(n,s),{apStrokeColor:c,apFillColor:d}=Cd(n,s,a),u=bd(r,o,this.ratioX),p=u.width,g="rectangle"===t.type?Ld(i,p,this.ratioX,this.ratioY,e.height):function(t,e,i,n){const{x:s,y:o}=t.getLocalPosition();t.path||t.getPath();const{path:r}=t,a=[];for(let t=0;t<r.length;t++){const l=(r[t].x+s)/e,h=n-(r[t].y+o)/i;0===t?(a.push([l,h,2,!1]),a.push([l,h,0,!1])):t===r.length-1?a.push([l,h,1,!0]):a.push([l,h,1,!1])}return a}(i,this.ratioX,this.ratioY,e.height),f=Bd(i,d,c,p,g,this.ratioX);return i.path||i.getPath(),{annotType:"SquareCircle",type:"rectangle"===t.type?"Square":"Circle",normalAppearance:f,interiorColor:h,color:l,borderStyle:u,opacity:a,rect:Ed(i,i.path,p,this.ratioX,this.ratioY,e.height),flags:Md([...t.flags]),date:t.comment.modificationDate,name:t.uid,contents:""}}toPdfPolygonal(t,e,i){const{borderWidth:n,opacity:s}=i.parsedStyle,{borderColor:o,background:r,lineEnding:a,lineDash:l}=t.style,h="polyline"===t.type,{strokeColor:c,fillColor:d}=wd(o,r),{apStrokeColor:u,apFillColor:p}=Cd(o,r,s),g=bd(n,l,this.ratioX),f=g.width;let m,v,y;h?(m=Od(i,this.ratioX,this.ratioY,e.height),v=m.flat(),y=_d(m[0])):(m=function(t,e,i,n){t.renderPath||t.getPath();const{x:s,y:o}=t.getLocalPosition(),{renderPath:r}=t,a=[];for(let t=0;t<r.length;t++){const l=(r[t].x+s)/e,h=n-(r[t].y+o)/i;if(0!==t){if(t===r.length-1){a.push([l,h,0,!0]);break}a.push([l,h,0,!1])}else a.push([l,h,2,!1])}return a}(i,this.ratioX,this.ratioY,e.height),v=m,y=_d(v));const x=Bd(i,p,u,f,v,this.ratioX,!h,!0);if(h){const t=[];m.forEach(e=>{t.push(Nd(i,e,p,u,f,Ad(l,this.ratioX)))}),x.objs=t}const w={annotType:"PolygonPolyLine",type:h?"PolyLine":"Polygon",borderStyle:g,color:c,interiorColor:d,normalAppearance:x,vertices:y,opacity:s,rect:Ed(i,i.renderPath,f,this.ratioX,this.ratioY,e.height,!0),name:t.uid,contents:"",flags:Md([...t.flags]),date:t.comment.modificationDate};return h&&i.isLineArrow()&&(w.lineEnding=a),w}toPdfLine(t,e,i){const{borderWidth:n,opacity:s}=i.parsedStyle,{borderColor:o,background:r,lineEnding:a,lineDash:l}=t.style,{strokeColor:h,fillColor:c}=wd(o,r),{apStrokeColor:d,apFillColor:u}=Cd(o,r,s),p=bd(n,l,this.ratioX),g=p.width,f=Od(i,this.ratioX,this.ratioY,e.height),m=f.flat(),v=[];f.forEach(t=>{v.push(Nd(i,t,u,d,g,Ad(l,this.ratioX)))});const y=Bd(i,u,d,g,m,this.ratioX,!1);y.objs=v;const x={annotType:"Line",type:"Line",line:[m[0][0],m[0][1],m[1][0],m[1][1]],interiorColor:c,color:h,normalAppearance:y,borderStyle:p,opacity:s,rect:Ed(i,i.renderPath,g,this.ratioX,this.ratioY,e.height),name:t.uid,contents:"",flags:Md([...t.flags]),date:t.comment.modificationDate,toJsonString:()=>""};return i.isLineArrow()&&(x.lineEnding=a,x.intent="LineArrow"),x}toPdfInk(t,e,i){const{borderWidth:n,opacity:s}=i.parsedStyle,{borderColor:o,background:r,lineDash:a}=t.style,{strokeColor:l}=wd(o,r),{apStrokeColor:h,apFillColor:c}=Cd(o,r,s),d=bd(n,a,this.ratioX),u=d.width,p=function(t,e,i,n){t.inkOriginalRenderPath||t.getInkOriginalRenderPath();const{x:s,y:o}=t.getLocalPosition(),{inkOriginalRenderPath:r}=t,a=[];for(let t=0;t<r.length;t++){const l=r[t],h=[];for(let t=0;t<l.length;t++){const r=(l[t].x+s)/e,a=n-(l[t].y+o)/i;0===t?h.push([r,a,2,!1]):h.push([r,a,1,!1])}if(h.length&&h.length<4)for(;h.length<4;){const t=h[h.length-1];h.push([...t])}a.push(h)}return a}(i,this.ratioX,this.ratioY,e.height),g=p.flat(),f=[],{x:m,y:v}=i.getLocalPosition();i.getPath();const{inkRenderSteps:y}=i,x=[];y.forEach(t=>{const i=[];t.forEach((t,n)=>{if(0===n){const n=(t.data[0].x+m)/this.ratioX,s=e.height-(t.data[0].y+v)/this.ratioY;i.push([n,s,2,!1])}else t.data.forEach(t=>{const n=(t.x+m)/this.ratioX,s=e.height-(t.y+v)/this.ratioY;i.push([n,s,1,!1])})}),x.push(i)}),x.forEach(t=>{f.push(Nd(i,t,c,h,u,Ad(a,this.ratioX)))});const w=Bd(i,c,h,u,g,this.ratioX,!1);return w.objs=f,{annotType:"Ink",type:"Ink",color:l,normalAppearance:w,borderStyle:d,opacity:s,inkList:Pd(p),rect:Ed(i,i.inkOriginalRenderPath.flat(),u,this.ratioX,this.ratioY,e.height),name:t.uid,contents:"",flags:Md([...t.flags]),date:t.comment.modificationDate}}async toPdfStamp(t,e,i){const{imageData:n,iconName:s,opacity:o}=t.style;if(n)return await this.toPdfStampImage(t,e,i);const r=i.childNodes,{segments:a,unClippedSegments:l}=function(t,e,i,n){const s=t.childNodes,o=[],r=[];for(let t=0;t<s.length;t++){if(!(s[t]instanceof Ol))continue;const a=[],{renderPath:l}=s[t],{x:h,y:c}=s[t].getLocalPosition();l.forEach((t,s)=>{var o;const r=[(t.x+h)/e,n-(t.y+c)/i,t.step,null!==(o=t.close)&&void 0!==o&&o];s===l.length-1&&void 0===t.close&&(r[3]=!0),a.push(r)}),o.push(a),s[t].clipped||r.push(a)}return{segments:o,unClippedSegments:r}}(i,this.ratioX,this.ratioY,e.height),h=[],c=[];let d=0,u=0;for(let i=0;i<r.length;i++){let n;const s=r[i].parsedStyle.opacity;if(r[i].style.opacity=s/(t.style.opacity||1),r[i]instanceof Ol){if(!r[i].clipped){const t=Rd(r[i]);c.push(...t)}const{borderWidth:t,lineDash:e}=r[i].parsedStyle,{borderColor:s,background:l}=r[i].style,{apStrokeColor:p,apFillColor:g}=Cd(s,l,o),f=bd(t,e,this.ratioX).width,m=kd(l,a[d]);u=Math.max(f,u),n=Nd(r[i],a[d],g,p,f,Ad(e,this.ratioX)),m&&(n.pattern=m),d+=1,h.push(n)}r[i]instanceof Nl&&(n=Ud(r[i],this.ratioX,this.ratioY,e.height),h.push(n))}const p=Bd(i,null,null,u,l.flat(),this.ratioX,!1);return p.objs=h,{annotType:"Stamp",type:"Stamp",icon:s,rect:Ed(i,c,u,this.ratioX,this.ratioY,e.height),normalAppearance:p,opacity:o,name:t.uid,contents:"",flags:Md([...t.flags]),date:t.comment.modificationDate}}async toPdfStampImage(t,e,i){const{imageData:n,opacity:s}=t.style;let o=n,r=[];Os(n)&&(r=n.split(","),r[0].match(/:(.*?);/)[1],o=function(t){let e=null;const i=t.split(","),n=i[0].match(/:(.*?);/)[1],s=window.atob(i[1]);let o=s.length;const r=new Uint8Array(o);for(;o--;)r[o]=s.charCodeAt(o);return e=new Blob([r],{type:n}),e}(n));const{width:a,height:l}=i.parsedStyle,h=Sd(i),c=[0,0,a.value/this.ratioX,l.value/this.ratioY],d=await async function(t,e,i,n){const{width:s,height:o}=t.parsedStyle,r=s.value/i,a=o.value/n;let l;if("image/jpeg"===e.type){const t=new hr,i=await t.readImage({source:{fileSource:e},outputType:er.IT_JPG,returnType:ir.RT_BASE64});t.destroy(),l={type:"image",jpegBase64:i.imageData,objMatrix:[r,0,0,a,0,0],rect:[0,0,r,a]}}else{const t=new hr,i=await t.readImage({source:{fileSource:e},outputType:er.IT_RGBA,returnType:ir.RT_BASE64});t.destroy(),l={type:"image",RGBABase64:i.imageData,height:i.imageHeight,width:i.imageWidth,objMatrix:[r,0,0,a,0,0],rect:[0,0,r,a]}}return l}(i,o,this.ratioX,this.ratioY),u=function(t,e,i,n){const{width:s,height:o}=t.parsedStyle,{x:r,y:a}=t.getLocalScale(),{x:l,y:h}=t.getLocalPosition(),c=t.getAngle(),d=l+s.value/2,u=h+o.value/2,p=s.value*r*.5,g=n*i-o.value*a*.5-u;let f=new Ll({style:{x:d-p,y:n*i-o.value*a-g,width:s.value*r,height:o.value*a}});f.setAngle(c),f.getPath();const m=Ed(f,f.path,0,e,i,n);return f=null,m}(i,this.ratioX,this.ratioY,e.height);return{annotType:"Stamp",type:"Stamp",normalAppearance:{bbox:c,matrix:h,objs:[d],transform:h},rect:u,opacity:s,name:t.uid,contents:"",flags:Md([...t.flags]),date:t.comment.modificationDate}}toPdfFreeText(t,e,i,n){const{opacity:s,textContents:o,borderColor:r,background:a,lineDash:l,textAlign:h}=t.style;"freeTextWriter"===n&&(i.style.borderWidth=0);const{borderWidth:c}=i.parsedStyle,{strokeColor:d,fillColor:u}=wd(r,a),{apStrokeColor:p,apFillColor:g}=Cd(r,a,s),f="textBox"===n?bd(c,l,this.ratioX):{width:0},m=f.width,v=Bd(i,g,p,m,Ld(i,m,this.ratioX,this.ratioY,e.height),this.ratioX,"textBox"===n),y=function(t,e,i,n){const{lines:s}=t,{opacity:o}=t.parsedStyle,r=[],a=(t,e,i)=>({type:"path",strokeColor:t,fillColor:t,fillType:0,isStroke:!0,lineCap:0,lineJoin:0,miterLimit:10,lineWidth:i,objMatrix:[1,0,0,1,0,0],segments:e,dashArray:[],dashPhase:0});return s.forEach(s=>{const l=s.height/30,h=t.getTextAlignOffset(s);s.words.forEach(c=>{const{fontFamily:d,fontSize:u,fontStyle:p,fontWeight:g,color:f,underline:m,lineThrough:v}=c.style,y=xd(f,1,!1),x=y?[...y,255*o]:[0,0,0,255],w=(c.x+h)/e,C=n-s.y/i,b={type:"text",charSpace:0,wordSpace:0,renderMode:0,fontPitchFamily:0,strokeColor:[0,0,0,255],fillColor:x,fontName:d,fontIsBold:Vd(g),fontIsItalic:"italic"===p,fontSize:u.value/e,text:(S=c.text,S.replace(/\r?\n?$/,"")),objMatrix:[1,0,0,1,w,C],position:[w,C],blendMode:Hd(t.style.renderBlendMode)||"Normal"};var S;if(r.push(b),m){const t=n-(s.y+l)/i,o=a(x,[[w,t,2,!1],[w+c.widthWithoutLf/e,t,0,!1]],l/i);r.push(o)}if(v){const t=n-(s.y-c.wordHeight/3)/i,o=a(x,[[w,t,2,!1],[w+c.widthWithoutLf/e,t,0,!1]],l/i);r.push(o)}})}),r}(i,this.ratioX,this.ratioY,e.height);"textBox"===n?v.objs.push(...y):v.objs=y;const{defaultAppearance:x,defaultAppearanceData:w,defaultStyle:C}=function(t,e,i,n,s){const o=i[0]||{color:"rgb(0,0,0)",fontFamily:"Times Roman",fontStyle:"normal",fontWeight:"normal",fontSize:"12px"},{fontFamily:r,fontSize:a,fontStyle:l,fontWeight:h,color:c}=o,d=xd(c,1,!1),u=ya(`rgb(${d[0]}, ${d[1]}, ${d[2]})`),p=da(a).value/s,g=Wd(r," ","");return{defaultAppearance:"textBox"===t?`${e[0]/255} ${e[1]/255} ${e[2]/255} rg /${g} ${p} Tf`:`${d[0]/255} ${d[1]/255} ${d[2]/255} rg /${g} ${p} Tf`,defaultStyle:`font:${"bold"===h?"bold":""} ${"italic"===l?"italic":""} '${r}' ${p}pt; text-align:${"justify"===n?"justify-center":n}; color:${u.toLocaleUpperCase()}`,defaultAppearanceData:{fontColor:d,fontSize:p,fontName:r}}}(n,d||[0,0,0],o,"freeTextWriter"===n?"left":h,this.ratioX);i.getPath();const b=Ed(i,i.path,m,this.ratioX,this.ratioY,e.height);let S="";o.forEach(t=>{S+=t.content});const T=function(t,e,i){if(!t||!t.length)return null;const n=document.implementation.createDocument(null,"body",null),s=n.documentElement;s.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),s.setAttribute("xmlns:xfa","http://www.xfa.org/schema/xfa-data/1.0/"),s.setAttribute("xfa:APIVersion","Acrobat:18.11.0"),s.setAttribute("xfa:spec","2.0.2");const o=t=>`font-size:${da(t).value/i}pt;`,r=t=>`font-weight:${"bold"===t?"bold":"normal"};`,a=t=>`font-style:${"italic"===t?"italic":"normal"};`,l=t=>`color:${ya(wa(t).formatted)};`,h=t=>`font-family:'${t}';`,c=t[0],{fontFamily:d,fontSize:u,fontStyle:p,fontWeight:g,color:f}=c,m=wa(f),v=`${o(u)}text-align:${"justify"===e?"justify-center":e};${l(m.formatted)}${r(g)}${a(p)}${h(d)}font-stretch:normal;`;s.setAttribute("style",v);const y=n.createElement("p");y.setAttribute("dir","ltr"),t.forEach(t=>{if(!t.content.length)return;const e=n.createElement("span"),i=n.createTextNode(t.content);e.appendChild(i);let s="";d!==t.fontFamily&&(s+=h(t.fontFamily)),u!==t.fontSize&&(s+=o(t.fontSize)),p!==t.fontStyle&&(s+=a(t.fontStyle)),g!==t.fontWeight&&(s+=r(t.fontWeight)),f!==t.color&&(s+=l(t.color)),(t.lineThrough||t.underline)&&(s+=`text-decoration:${t.underline?"word":""} ${t.lineThrough?"line-through":""}`),s&&e.setAttribute("style",s),y.appendChild(e)}),s.appendChild(y);const x=`<?xml version="1.0"?>${(new XMLSerializer).serializeToString(n)}`,w='xmlns="http://www.w3.org/1999/xhtml"';return x.includes(w)?Wd(x,'xmlns=""',w):Wd(x.replace(/<body/,`<body ${w}`),'xmlns=""',w)}(o,h,this.ratioX),E={borderStyle:f,annotType:"FreeText",type:"FreeText",color:u,normalAppearance:v,defaultAppearance:x,defaultAppearanceData:w,defaultStyle:C,rect:b,name:t.uid,contents:S,opacity:s,flags:Md([...t.flags]),date:t.comment.modificationDate};return"freeTextWriter"===n&&(E.intent="FreeTextTypeWriter"),T&&(E.richText=T),E}toPdfTextAssist(t,e,i,n){const{opacity:s,borderColor:o,background:r}=t.style,{lineDash:a,borderWidth:l,lineCap:h,lineJoin:c,miterLimit:d}=n.parsedStyle,{strokeColor:u,fillColor:p}=wd(o,r),{apStrokeColor:g,apFillColor:f}=Cd(o,r,s),m="Highlight"===e?0:bd(l,a,this.ratioX).width,v={blendMode:Hd(n.style.renderBlendMode),dashArray:Ad(a,this.ratioX),dashPhase:0,fillColor:f||[0,0,0,0],fillType:f||"Highlight"===e?2:0,isStroke:"Highlight"!==e&&m>0,lineCap:Id(h),lineJoin:Dd(c),lineWidth:m,miterLimit:d,objMatrix:[1,0,0,1,0,0],segments:void 0,strokeColor:g||[0,0,0,0],type:"path"},y=[],x=[],w=[1/0,1/0,-1/0,-1/0],C=[];n.lines.forEach(t=>{const e=t.left/this.ratioX,s=(t.left+t.width)/this.ratioX,o=i.height-t.top/this.ratioY,r=i.height-(t.top+t.height)/this.ratioY;let a;"annotationHighlight"===n.shapeType?a=[[e,o,2,!1],[s,o,0,!1],[s,r,0,!1],[e,r,0,!1],[e,o,0,!0]]:"annotationUnderline"===n.shapeType?a=[[e,r+m/2,2,!1],[s,r+m/2,0,!1]]:"annotationStrikeout"===n.shapeType&&(a=[[e,(o+r)/2,2,!1],[s,(o+r)/2,0,!1]]),w[0]=Math.min(w[0],e),w[1]=Math.min(w[1],r),w[2]=Math.max(w[2],s),w[3]=Math.max(w[3],o),C.push(...a),x.push([e,o,s,o,e,r,s,r])});const b=_s(v);return b.segments=C,y.push(b),{annotType:"TextMarkup",type:e,color:"Highlight"===e?p:u,rect:[...w],normalAppearance:{bbox:w,blendMode:Hd(n.style.renderBlendMode),matrix:[1,0,0,1,-w[0],-w[1]],objs:y,transform:[1,0,0,1,0,0]},opacity:s,quadPoints:x,name:t.uid,flags:Md([...t.flags]),date:t.comment.modificationDate}}createShape(t){const{type:e,transform:i,style:n}=_s(t),s={id:t.uid,style:n,transform:i};let o;switch("ellipse"===e&&(n.x+=n.width/2||0,n.y+=n.height/2||0,n.rx=n.width/2||n.rx,n.ry=n.height/2||n.ry),e){case"rectangle":o=new rc(s);break;case"ellipse":o=new nc(s);break;case"line":o=new fc(s);break;case"ink":o=new oc(s);break;case"polygon":o=new pc(s);break;case"polyline":o=new gc(s);break;case"textTypewriter":o=new hc(s,"freeTextWriter",{});break;case"textBox":o=new hc(s,"textBox");break;case"stamp":o=new Ac(s);break;case"highlight":o=new Lc(s);break;case"underline":o=new Bc(s);break;case"strikeout":o=new Oc(s)}return o}}class lu{constructor(){Yi(this,"annotationParser",new ru),Yi(this,"annotationWriter",new au)}getParsedAnnotations(t,e,i){const n=Cr.displayResolution/Cr.pdfResolution;t=t.filter(t=>null!==t),this.annotationParser.setParserConfig(e,i,n,n),this.moveAddReply(t);const s=[];return t.forEach((t,e)=>{var i;if(t){const r=this.annotationParser.parseAnnotation(t);if(r){var n,o;switch(r.flags=this.parseFlags(t.flags||[]),null!=t&&null!==(n=t.customData)&&void 0!==n&&null!==(n=n.dynamsoftFlags)&&void 0!==n&&n.length&&r.flags.push(...t.customData.dynamsoftFlags),r.customData={...t.customData},t.type){case"Underline":case"Highlight":case"StrikeOut":r.flags.push("noMove","noRotate");break;case"FreeText":"freetexttypewriter"===(null==t||null===(i=t.intent)||void 0===i?void 0:i.toLocaleLowerCase())&&r.flags.push("noRotate","noResize");break;case"Line":case"Polygon":case"Polyline":r.flags.push("noRotate")}const a=this.parseReply(t);null!==(o=t.replies)&&void 0!==o&&o.length&&(a.replies=t.replies.map(t=>this.parseReply(t))||[]),r.parsedOriIndex=e,r.comment=a,s.push(r)}}}),s}moveAddReply(t){t.forEach(e=>{if(e&&"Text"===e.type&&!Ps(e.inreplyto)){const i=t[e.inreplyto];"Review"===e.statemodel?(i.reviewStates||(i.reviewStates=[]),i.reviewStates.push(e)):"Marked"===e.statemodel?(i.markedStates||(i.markedStates=[]),i.markedStates.push(e)):(i.replies||(i.replies=[]),i.replies.push(e))}}),t.slice().forEach(e=>{if(!e||"Popup"===e.type||!Ps(e.inreplyto)){const i=t.findIndex(t=>t===e);t.splice(i,1)}})}parseReply(t){var e,i;const n=this.parseCommon(t);return n.subject=t.subject,null!==(e=t.reviewStates)&&void 0!==e&&e.length&&(n.reviewStates=t.reviewStates.map(t=>this.parseState(t))),null!==(i=t.markedStates)&&void 0!==i&&i.length&&(n.markedStates=t.markedStates.map(t=>this.parseState(t))),n}parseFlags(t){const e=[],i={readonly:"readOnly",noview:"noView"};return t.forEach(t=>{e.push(i[t]||t)}),t.includes("hidden")&&!e.includes("noView")&&e.push("noView"),e}parseState(t){return{...this.parseCommon(t),state:t.state,stateModel:t.statemodel}}parseCommon(t){const e=t.creationdate,i=t.date;return{uid:Us(),author:t.title,contents:t.contents,type:t.type,creationDate:e||i,modifiedDate:i||e,flags:t.flags?[...t.flags]:[]}}parseDate(t){if(!t)return;let e=2;if(!t)return"";const i=[4,2,2,2,2,2].map(i=>{const n=t.slice(e,e+i);return e+=i,parseInt(n,10)});i[1]-=1;const n=new Date(...i).getTime();return As("yyyy.MM.dd hh:mm:ss",n)}async getOriginalAnnotations(t,e){return await this.annotationWriter.toPdfAnnotations(t,e)}}var hu,cu;function du(t){return{left:t[0],top:t[1],width:t[2]-t[0],height:t[3]-t[1]}}!function(t){t.CM_RENDERALL="cm/renderall",t.CM_IMAGEONLY="cm/imageonly",t.CM_AUTO="cm/auto"}(hu||(hu={})),function(t){t.NO_ANNOTATIONS="noAnnotations",t.RENDER_ANNOTATIONS="renderAnnotations",t.LOAD_ANNOTATIONS="loadAnnotations"}(cu||(cu={}));var uu=new WeakSet;class pu{constructor(){an(this,uu),Yi(this,"type","pdfParser"),Yi(this,"once",!1),Yi(this,"pdfReader",void 0),Yi(this,"parserOptions",{convertMode:hu.CM_AUTO}),Yi(this,"source",void 0),Yi(this,"isDestroy",!1),Yi(this,"annotationMapper",void 0),Yi(this,"count",0),this.pdfReader=new dr,this.annotationMapper=new lu}initParser(t,e){this.parserOptions=null!=e?e:{convertMode:hu.CM_AUTO},this.source={fileSource:t,password:this.parserOptions.password}}async getPageCount(){return this.pdfReader.getPdfPageCount(this.source,sn(this,uu,gu).call(this))}destroy(){var t;null===(t=this.pdfReader)||void 0===t||t.destroy(),this.pdfReader=null,this.source=null,this.parserOptions=null,this.isDestroy=!0}splitArrayIntoChunks(t,e){const i=[];for(let n=0;n<t.length;n+=e){const s=t.slice(n,n+e);i.push(s)}return i}async parseAnnotations(t,e){var i;const n=[];if(this.parserOptions.convertMode===hu.CM_IMAGEONLY||(null===(i=this.parserOptions.renderOptions)||void 0===i?void 0:i.renderAnnotations)!==cu.LOAD_ANNOTATIONS)return n;for(let i=0;i<t.length;i++){const s=e[t[i]],o=s.nativeMediaBox;if(1===s.realReadMode&&s.pdfOptions.annotCount>0){if(this.isDestroy)return[];const e=await this.pdfReader.readAnnotations(this.source,t[i]),r={pageUid:s.pageUid,fileIndex:t[i],annotations:[]};e.length&&(r.annotations=this.annotationMapper.getParsedAnnotations(e,2*o.left+o.width,2*o.top+o.height),s.pdfOptions.parsedAnnotCount=r.annotations.length,s.annotations=r.annotations),n.push(r)}}return n}async parse(t){const e=[],i=this.parserOptions.convertMode===hu.CM_RENDERALL?[t]:this.splitArrayIntoChunks(t,100);for(let t=0;t<i.length;t++){const o=await this.pdfReader.readPageImageInfos({source:this.source,indices:i[t],readOptions:sn(this,uu,gu).call(this),outputType:er.IT_JPG,isInfoOnly:!1,returnType:ir.RT_BINARY}),{displayResolution:r,pdfResolution:a}=Cr;for(let t=0;t<o.length;++t){var n,s;const i=o[t];i.mediaBox[0]>i.mediaBox[2]&&([i.mediaBox[0],i.mediaBox[2]]=[i.mediaBox[2],i.mediaBox[0]]),i.mediaBox[1]>i.mediaBox[3]&&([i.mediaBox[1],i.mediaBox[3]]=[i.mediaBox[3],i.mediaBox[1]]),i.cropBox[0]>i.cropBox[2]&&([i.cropBox[0],i.cropBox[2]]=[i.cropBox[2],i.mediaBox[0]]),i.cropBox[1]>i.cropBox[3]&&([i.cropBox[1],i.cropBox[3]]=[i.cropBox[3],i.cropBox[1]]);const l=1===i.realReadMode,h=l?du(i.mediaBox):{left:0,top:0,width:i.imageWidth/i.imageXResolution*a,height:i.imageHeight/i.imageYResolution*a},c=l?du([i.cropBox[0],i.mediaBox[1]+i.mediaBox[3]-i.cropBox[3],i.cropBox[2],i.mediaBox[1]+i.mediaBox[3]-i.cropBox[1]]):{...h},d=Bo(h,a,r),u=Bo(c,a,r),p={fileIndex:i.pageIndex,rotation:i.rotation,mediaBox:d,cropBox:u,nativeMediaBox:h,nativeCropBox:c,resource:{width:i.imageWidth,height:i.imageHeight,resolutionX:i.imageXResolution,resolutionY:i.imageYResolution,bitDepth:i.imageBitDepth},pdfOptions:{convertMode:l?hu.CM_RENDERALL:hu.CM_IMAGEONLY,renderOptions:{renderAnnotations:null===(n=this.parserOptions.renderOptions)||void 0===n?void 0:n.renderAnnotations,renderGrayscale:null===(s=this.parserOptions.renderOptions)||void 0===s?void 0:s.renderGrayscale},rotation:i.rotation,mediaBox:{...d},cropBox:{...u},annotCount:i.annotCount},realReadMode:i.realReadMode,annotations:[]};e.push(p)}}return e}async getPage(t){if(this.isDestroy||!this.source)return null;const e=await this.pdfReader.readPage({source:this.source,index:t,readOptions:sn(this,uu,gu).call(this),outputType:er.IT_JPG,isInfoOnly:!1,returnType:ir.RT_AUTO});if(e&&0===e.code){const{displayResolution:t,pdfResolution:i}=Cr,n=e.imageInfos[0];return{fileIndex:e.pageIndex,rotation:e.rotation,mediaBox:Bo(du(e.mediaBox),i,t),cropBox:Bo(du(e.cropBox),i,t),resource:{data:e.imageData,width:n.imageWidth,height:n.imageHeight,resolutionX:n.imageXResolution,resolutionY:n.imageYResolution,bitDepth:n.imageBitDepth}}}return null}async renderPage(t,e){if(this.isDestroy||!this.source)return null;const i=sn(this,uu,gu).call(this).renderOptions;this.count+=1;const n=await this.pdfReader.renderPage({source:this.source,index:t.index,width:t.width,height:t.height,rect:t.rect,renderOptions:i,outputType:t.outputType,isInfoOnly:!1,returnType:ir.RT_BINARY},e);return this.count-=1,n}cancelRenderPage(t){!this.isDestroy&&this.source&&this.pdfReader.cancelRenderPage(t)}async getPageTexts(t){return this.isDestroy||!this.source?null:await this.pdfReader.getCharInfos(this.source,(null==t?void 0:t.slice())||[])}cancelGetPage(t){!this.isDestroy&&this.source&&this.pdfReader.cancelReadPage(this.source,t)}}function gu(){var t,e;if(this.isDestroy)return null;if(!this.parserOptions)return null;const i={[cu.NO_ANNOTATIONS]:0,[cu.RENDER_ANNOTATIONS]:1,[cu.LOAD_ANNOTATIONS]:2};return{convertMode:{[hu.CM_IMAGEONLY]:2,[hu.CM_RENDERALL]:1,[hu.CM_AUTO]:3}[(null===(t=this.parserOptions)||void 0===t?void 0:t.convertMode)||hu.CM_AUTO],renderOptions:{...this.parserOptions.renderOptions||{},renderAnnotations:i[null===(e=this.parserOptions.renderOptions)||void 0===e?void 0:e.renderAnnotations]||0,renderIgnoreCrop:!0,ignorePageRotation:!0}}}class fu{constructor(){Yi(this,"type","rgbaParser"),Yi(this,"once",!1),Yi(this,"processor",void 0),Yi(this,"cachePage",[]),Yi(this,"source",void 0),Yi(this,"parserOptions",void 0),Yi(this,"isDestroy",!1),this.processor=new lr}initParser(t,e){this.source=t,this.parserOptions=e}async getPageCount(){return 1}destroy(){var t;null===(t=this.processor)||void 0===t||t.terminate(),this.processor=void 0,this.source=null}async parse(){var t;const{outputType:e,jpegQuality:i,returnBase64:n,width:s,height:o,bitDepth:r,xResolution:a,yResolution:l}=null!==(t=this.parserOptions)&&void 0!==t?t:{},h=await this.source.arrayBuffer();await this.processor.initImage({source:h,isRGBA:!0,width:s,height:o,isBGRA:!1});const c=await this.processor.getImage({jpegQuality:i,ifDeleteObject:!0,isRGBA:!0,bitDepth:r,xDpi:a,yDpi:l,outputType:e,returnType:ir.RT_AUTO}),d=fd(c);return c.srcBuffer,this.cachePage=[d],this.cachePage}async renderPage(t,e){var i;if(this.isDestroy||!this.source)return null;const n=this.parserOptions.xResolution/Cr.dataResolution,s={left:t.rect[0]*n,top:t.rect[1]*n,width:(t.rect[2]-t.rect[0])*n,height:(t.rect[3]-t.rect[1])*n},{width:o,height:r}=null!==(i=this.parserOptions)&&void 0!==i?i:{};s.top=r-s.top-s.height,s.left=Math.max(0,Math.min(Math.round(s.left),r-1)),s.top=Math.max(0,Math.min(Math.round(s.top),r-1)),s.width=Math.max(1,Math.min(Math.round(s.width),r-s.left)),s.height=Math.max(1,Math.min(Math.round(s.height),r-s.top));const a=await this.source.arrayBuffer();return await md.createTask("renderImage",[a,{sourceType:er.IT_RGBA,sourceWidth:o,sourceHeight:r,index:t.index,width:t.width,height:t.height,rect:s,outputType:t.outputType}],e)}cancelRenderPage(t){!this.isDestroy&&this.source&&md.cancelTask("renderImage",[],t)}async parseAnnotations(t,e){return[]}async getPage(){return Promise.resolve(this.cachePage[0])}cancelGetPage(t){}getPageTexts(t){return null}}class mu{constructor(){Yi(this,"db",void 0),this.db=new Map}saveByMime(t,e){this.db.set(t,e)}hasByMime(t){return this.db.has(t)}deleteConstructorByMime(t){return!!this.hasByMime(t)&&(this.db.delete(t),!0)}getConstructorByMime(t){return this.db.get(t)}has(t){throw new Error("Method not implemented.")}save(t){throw new Error("Method not implemented.")}clear(){this.db.clear()}}const vu=new class{constructor(){Yi(this,"db",void 0),this.db=new Map}saveByFileUid(t,e){this.db.set(t,e)}getParserByFileUid(t){return this.db.get(t)}deleteParserByFileUid(t){return this.db.delete(t)}has(t){throw new Error("Method not implemented.")}save(t){throw new Error("Method not implemented.")}clear(){this.db.clear()}getAllParsers(){return Array.from(this.db.values())}},yu=new mu,xu=new mu,wu=new class{constructor(){Yi(this,"db",void 0),this.db=new Map}getDefaultOptionsByMime(t){return this.db.get(t)}deleteDefaultOptionsByMime(t){return this.db.delete(t)}saveDefaultOptionsByMime(t,e){this.db.set(t,e)}has(t){throw new Error("Method not implemented.")}save(t){throw new Error("Method not implemented.")}clear(){this.db.clear()}},Cu=new class{constructor(t,e,i){Yi(this,"parserRepo",void 0),Yi(this,"parserConstructorRepo",void 0),Yi(this,"customParserConstructorRepo",void 0),this.parserRepo=t,this.parserConstructorRepo=e,this.customParserConstructorRepo=i}getParser(t,e){let i=this.parserRepo.getParserByFileUid(t);return i||(i=new(this.customParserConstructorRepo.getConstructorByMime(e)||this.parserConstructorRepo.getConstructorByMime(e)),i.once||this.parserRepo.saveByFileUid(t,i),i)}}(vu,yu,xu),bu=new class{constructor(t){Yi(this,"parserRepo",void 0),this.parserRepo=t}execute(t){const e=this.parserRepo.getParserByFileUid(t);e&&(e.destroy(),this.parserRepo.deleteParserByFileUid(t))}}(vu),Su=new class{constructor(t,e){Yi(this,"parserService",void 0),Yi(this,"parserRepo",void 0),this.parserService=t,this.parserRepo=e}execute(t){const{fileData:e,mime:i,fileUid:n,indices:s}=t;let o=this.parserRepo.getParserByFileUid(n);return o||(o=this.parserService.getParser(n,i),o.initParser(e)),o.getPageTexts(s)}}(Cu,vu),Tu=new class{constructor(t,e){Yi(this,"parserService",void 0),Yi(this,"parserRepo",void 0),this.parserService=t,this.parserRepo=e}async execute(t){const{fileData:e,mime:i,fileUid:n,fileIndex:s}=t;let o=this.parserRepo.getParserByFileUid(n);return o||(o=this.parserService.getParser(n,i),o.initParser(e)),o.getPage(s)}}(Cu,vu),Eu=new class{constructor(t){Yi(this,"parserRepo",void 0),this.parserRepo=t}execute(t){let{fileIndex:e,fileUid:i}=t;const n=this.parserRepo.getParserByFileUid(i);n&&n.cancelGetPage(e)}}(vu),_u=new class{constructor(t,e){Yi(this,"parserService",void 0),Yi(this,"parserRepo",void 0),this.parserService=t,this.parserRepo=e}async execute(t){const{fileData:e,mime:i,fileUid:n,fileIndex:s}=t;let o=this.parserRepo.getParserByFileUid(n);return o||(o=this.parserService.getParser(n,i),o.initParser(e)),o.renderPage(t.config,t.task)}}(Cu,vu),Pu=new class{constructor(t){Yi(this,"parserRepo",void 0),this.parserRepo=t}execute(t){let{task:e,fileUid:i}=t;e.canceled=!0;const n=this.parserRepo.getParserByFileUid(i);n&&n.cancelRenderPage(e)}}(vu),Au=new class{constructor(t,e){Yi(this,"parserService",void 0),Yi(this,"defaultParserOptionsRepo",void 0),this.parserService=t,this.defaultParserOptionsRepo=e}async execute(t){const{fileData:e,mime:i,fileUid:n,indices:s}=t;let{parseOptions:o}=t;o=o||this.defaultParserOptionsRepo.getDefaultOptionsByMime(i);const r=this.parserService.getParser(n,i);return r.initParser(e,o),r.parse(s)}}(Cu,wu),Iu=new class{constructor(t,e){Yi(this,"parserService",void 0),Yi(this,"defaultParserOptionsRepo",void 0),this.parserService=t,this.defaultParserOptionsRepo=e}async execute(t){const{fileData:e,mime:i,fileUid:n,indices:s,parsedPages:o}=t;let{parseOptions:r}=t;return r=r||this.defaultParserOptionsRepo.getDefaultOptionsByMime(i),this.parserService.getParser(n,i).parseAnnotations(s,o)}}(Cu,wu),Du=new class{constructor(t){Yi(this,"parserConstructorRepo",void 0),this.parserConstructorRepo=t}execute(t){let{mime:e,parser:i}=t;this.parserConstructorRepo.saveByMime(e,i)}}(yu),Ru=new class{constructor(t){Yi(this,"parserConstructorRepo",void 0),this.parserConstructorRepo=t}execute(t){this.parserConstructorRepo.deleteConstructorByMime(t)}}(xu),ku=new class{constructor(t){Yi(this,"customParserConstructorRepo",void 0),this.customParserConstructorRepo=t}execute(t){let{mime:e,parser:i}=t;this.customParserConstructorRepo.saveByMime(e,i)}}(yu),Mu=new class{constructor(t){Yi(this,"customParserConstructorRepo",void 0),this.customParserConstructorRepo=t}execute(t){this.customParserConstructorRepo.deleteConstructorByMime(t)}}(xu),Lu=new class{constructor(t){Yi(this,"defaultParserOptionsRepo",void 0),this.defaultParserOptionsRepo=t}execute(t){return this.defaultParserOptionsRepo.getDefaultOptionsByMime(t)}}(wu),Ou=new class{constructor(t,e,i){Yi(this,"defaultParserOptionsRepo",void 0),Yi(this,"parserConstructorRepo",void 0),Yi(this,"customParserConstructorRepo",void 0),this.defaultParserOptionsRepo=t,this.parserConstructorRepo=e,this.customParserConstructorRepo=i}execute(t){let{mime:e,options:i}=t;return!(!i||!Es(i)||!this.customParserConstructorRepo.hasByMime(e)&&!this.parserConstructorRepo.hasByMime(e)||(this.defaultParserOptionsRepo.saveDefaultOptionsByMime(e,_s(i)),0))}}(wu,yu,xu),Bu=new class{constructor(t){Yi(this,"customParserConstructorRepo",void 0),this.customParserConstructorRepo=t}execute(t){return this.customParserConstructorRepo.getConstructorByMime(t)}}(xu),Nu=new class{constructor(t,e){Yi(this,"parserService",void 0),Yi(this,"defaultParserOptionsRepo",void 0),this.parserService=t,this.defaultParserOptionsRepo=e}async execute(t){var e,i;let{fileData:n,mime:s,fileUid:o,options:r}=t;r=r||this.defaultParserOptionsRepo.getDefaultOptionsByMime(s);const a=this.parserService.getParser(o,s);return a.initParser(n,r),{pageCount:await a.getPageCount(),batchSize:null!==(e=null===(i=r)||void 0===i?void 0:i.batchSize)&&void 0!==e?e:0}}}(Cu,wu);class Uu{constructor(){Yi(this,"type",void 0),Yi(this,"once",!1),Yi(this,"cachedPage",void 0),Yi(this,"parserOptions",void 0)}initParser(t,e){this.parserOptions=e}async getPageCount(){return Promise.resolve(1)}destroy(){}async parse(){const{width:t,height:e,bitDepth:i,resolutionX:n,resolutionY:s}=this.parserOptions,o=fd({imageBitDepth:i,imageHeight:e,imageWidth:t,imageXResolution:n,imageYResolution:s});return this.cachedPage=o,[this.cachedPage]}async parseAnnotations(t,e){return[]}async getPage(){const t=await this.createBlankPage(this.parserOptions.width,this.parserOptions.height);return this.cachedPage.resource.data=t,this.cachedPage}cancelGetPage(){}async createBlankPage(t,e){var i,n,s;const o=new Uint8Array([255,255,255,255]),r=new lr;await r.initImage({source:o.buffer,isRGBA:!0,width:1,height:1,isBGRA:!1}),await r.resize(t,e);const a=await r.getImage({jpegQuality:null!==(i=this.parserOptions.jpegQuality)&&void 0!==i?i:80,ifDeleteObject:!0,isRGBA:!0,bitDepth:24,xDpi:null!==(n=this.parserOptions.resolutionX)&&void 0!==n?n:96,yDpi:null!==(s=this.parserOptions.resolutionY)&&void 0!==s?s:96,outputType:xr[tr.JPEG],returnType:ir.RT_BASE64});return new Blob([a.imageData],{type:a.blobType})}async renderPage(t,e){var i,n,s;const o=new Uint8Array([255,255,255,255]),r=new lr;await r.initImage({source:o.buffer,isRGBA:!0,width:1,height:1,isBGRA:!1}),await r.resize(t.width,t.height);const a=await r.getImage({jpegQuality:null!==(i=this.parserOptions.jpegQuality)&&void 0!==i?i:80,ifDeleteObject:!0,isRGBA:!0,bitDepth:24,xDpi:null!==(n=this.parserOptions.resolutionX)&&void 0!==n?n:96,yDpi:null!==(s=this.parserOptions.resolutionY)&&void 0!==s?s:96,outputType:er.IT_RGBA,returnType:ir.RT_BASE64});return{imageInfo:{imageWidth:t.width,imageHeight:t.height},imageData:a.imageData,pageIndex:t.index}}cancelRenderPage(t){md.cancelTask("renderImage",[],t)}getPageTexts(t){return null}}var Fu;!function(t){t.GOOD="Good",t.AUTO_CAPTURE="AutoCaptured",t.SMALL_SIZE="SmallSize",t.OFF_CENTER="OffCenter",t.SKEW="Skew",t.NOTHING_DETECTED="NothingDetected"}(Fu||(Fu={}));var Vu,Wu=new WeakSet,Hu=new WeakSet,ju=new WeakSet,zu=new WeakSet,Gu=new WeakSet,Yu=new WeakSet,$u=new WeakSet,Xu=new WeakSet,qu=new WeakSet,Zu=new WeakSet;class Ju{constructor(){an(this,Zu),an(this,qu),an(this,Xu),an(this,$u),an(this,Yu),an(this,Gu),an(this,zu),an(this,ju),an(this,Hu),an(this,Wu),Yi(this,"detector",void 0),Yi(this,"succeedDetect",0),Yi(this,"failedDetect",0),Yi(this,"autoCaptureStartTime",0),this.succeedDetect=0,this.failedDetect=0}destroy(){this.clear()}clear(){var t;null===(t=this.detector)||void 0===t||t.terminate(),this.detector=void 0}async detect(t,e){return Promise.resolve({success:!1})}getStatusMsg(t){switch(t){case Fu.AUTO_CAPTURE:return"Auto capture completed.";case Fu.GOOD:return"Capturing your document... Please do not move the camera.";case Fu.SMALL_SIZE:return"The document is too small. Try moving closer.";case Fu.OFF_CENTER:return"Try holding the device at the center of the document.";case Fu.SKEW:return"Please hold the device over a document to start scanning.";case Fu.NOTHING_DETECTED:return"No document is detected."}}processDetectResult(t){if([].concat(...t.location).every(t=>0===t))return{success:!1,confidence:0,status:Fu.NOTHING_DETECTED};let e;const i=this.calculateConfidence(t.location,t.width,t.height);e=Ps(t.confidence)?this.calculateTotalConfidence(i):t.confidence;const n={success:!0,location:t.location,confidence:e},{angleConfidence:s,areaConfidence:o,centerConfidence:r}=i,{config:a}=t;return e>=(null==a?void 0:a.acceptedPolygonConfidence)?(this.succeedDetect+=1,n.status=Fu.GOOD,this.succeedDetect,5===this.succeedDetect||this.succeedDetect,null!=a&&a.enableAutoCapture?this.autoCaptureStartTime<=0?this.autoCaptureStartTime=(new Date).getTime():(new Date).getTime()-this.autoCaptureStartTime>a.autoCaptureDelay&&(this.autoCaptureStartTime=0,n.status=Fu.AUTO_CAPTURE):this.autoCaptureStartTime=0):.45*s+.45*r+10>=(null==a?void 0:a.acceptedPolygonConfidence)?(this.reset(),n.status=Fu.SMALL_SIZE):.45*s+.45*o+10>=(null==a?void 0:a.acceptedPolygonConfidence)?(this.reset(),n.status=Fu.OFF_CENTER):.45*o+.45*r+10>=(null==a?void 0:a.acceptedPolygonConfidence)?(this.reset(),n.status=Fu.SKEW):(n.success=!1,n.status=Fu.NOTHING_DETECTED,this.failedDetect+=1,this.autoCaptureStartTime=0),this.failedDetect>5&&this.reset(),n.statusMsg=this.getStatusMsg(n.status),n}calculateConfidence(t,e,i){return sn(this,ju,Qu).call(this,sn(this,Wu,Ku).call(this,t),e,i)}calculateTotalConfidence(t){const{angleConfidence:e,areaConfidence:i,centerConfidence:n}=t;return e&&i&&n?.3*e+.3*i+.3*n+10:0}reset(){this.succeedDetect=0,this.failedDetect=0,this.autoCaptureStartTime=0}}function Ku(t){return t?[t[0][0],t[0][1],t[1][0],t[1][1],t[2][0],t[2][1],t[3][0],t[3][1]]:[0,0,0,0,0,0,0,0]}function Qu(t,e,i){return{angleConfidence:sn(this,zu,tp).call(this,t),areaConfidence:sn(this,Gu,ep).call(this,t,e,i),centerConfidence:sn(this,Yu,ip).call(this,t,e,i)}}function tp(t){let e=0;const i=sn(this,Xu,sp).call(this,[t[0],t[1]],[t[2],t[3]],[t[4],t[5]]),n=sn(this,Xu,sp).call(this,[t[2],t[3]],[t[4],t[5]],[t[6],t[7]]),s=sn(this,Xu,sp).call(this,[t[4],t[5]],[t[6],t[7]],[t[0],t[1]]),o=sn(this,Xu,sp).call(this,[t[6],t[7]],[t[0],t[1]],[t[2],t[3]]);return e+=Math.abs(i-90),e+=Math.abs(n-90),e+=Math.abs(s-90),e+=Math.abs(o-90),Math.max(0,100*Math.min(1,1-.025*e))}function ep(t,e,i){const n=sn(this,Zu,rp).call(this,t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7]);return Math.min(100,400*Math.max(0,n/(e*i)))}function ip(t,e,i){const n=[(t[0]+t[2]+t[4]+t[6])/4,(t[1]+t[3]+t[5]+t[7])/4],s=sn(this,$u,np).call(this,n,[e/2,i/2]);return Math.max(0,100*Math.min(1,1-s/Math.min(e,i)))}function np(t,e){return Math.sqrt((e[0]-t[0])*(e[0]-t[0])+(e[1]-t[1])*(e[1]-t[1]))}function sp(t,e,i){const n=sn(this,$u,np).call(this,e,t),s=sn(this,$u,np).call(this,e,i),o=sn(this,$u,np).call(this,t,i);return 0===n||0===s?0:Math.acos((n*n+s*s-o*o)/(2*n*s))/Math.PI*180}function op(t,e,i,n,s,o){return(t*n+e*s+i*o-s*n-o*t-i*e)/2}function rp(t,e,i,n,s,o,r,a){return sn(this,qu,op).call(this,t,e,i,n,s,o)+sn(this,qu,op).call(this,t,e,s,o,r,a)}!function(t){t.NONE="none",t.BLACK_AND_WHITE="blackAndWhite",t.GRAY="gray",t.REMOVE_SHADOW="removeShadow",t.SAVE_INK="saveInk",t.ENHANCE="enhance",t.INVERT="invert",t.BRIGHTNESS="brightness",t.CONTRAST="contrast",t.BRIGHTNESS_AND_CONTRAST="brightnessAndContrast"}(Vu||(Vu={}));const ap=new Map([[Vu.NONE,"None"],[Vu.BLACK_AND_WHITE,"toBW"],[Vu.GRAY,"toGray"],[Vu.REMOVE_SHADOW,"removeShadow"],[Vu.SAVE_INK,"toBW"],[Vu.ENHANCE,"enhance"],[Vu.INVERT,"invert"],[Vu.CONTRAST,"brightnessAndContrast"],[Vu.BRIGHTNESS,"brightnessAndContrast"],[Vu.BRIGHTNESS_AND_CONTRAST,"brightnessAndContrast"]]);var lp,hp=new WeakSet,cp=new WeakSet;function dp(t,e){const i={...e||{}};return t===Vu.SAVE_INK&&(i.method="adaptiveThreshold"),i}function up(t){var e,i;return t.bRGBA=t.outputType===er.IT_RGBA,t.returnType=null!==(e=t.returnType)&&void 0!==e?e:ir.RT_AUTO,t.bRGBA&&void 0===t.outputType?t.outputType=er.IT_JPG:t.outputType=null!==(i=t.outputType)&&void 0!==i?i:er.IT_ALL,t.is1BitTo8Bit=$o.isApple,t}class pp{static replaceMessage(t,e,i){let n=t;return e&&(n=n.replace("<%api%>",e)),i&&(n=n.replace("<%param%>",i)),n}static getLastError(){return this.lastError}static clearLastError(){this.lastError=null}static buildError(t,e,i){if(t&&!t.code&&t.cause&&t.cause.code&&t.cause.message)return Os(t.message)&&(t.message=this.replaceMessage(t.message,e,i)),t;const n={code:t.code,message:t.message};null!=t&&t.details&&(n.details=t.details);let s={...t};return n.code>-8e4&&0!==n.code?n.code<=-2e4||(n.code=pp.WASM_ERR.code,n.message=pp.WASM_ERR.message,s.actualCode=s.code,s.code=n.code):n.code?(n.message=this.replaceMessage(n.message,e,i),s={...n},Array.isArray(n.details)&&0!==n.details.length&&(s.details=n.details)):(n.code=pp.EXTERNAL_ERR.code,n.message=pp.EXTERNAL_ERR.message,s.actualCode=t.code,s.message=t.message,t.name&&(s.name=t.name),t.stack&&(s.stack=t.stack),s.code=n.code,s.actualError=t),new Error(n.message,{cause:s})}static warning(t,e,i){const n=pp.buildError(t,e,i);this.lastError=n,this.onWarning.emit(n)}static error(t,e,i){const n=pp.buildError(t,e,i);throw this.lastError=n,this.onError.emit(n),n}static verbose(t,e,i){this.onVerbose.emit(t)}static throw(t,e,i){const n=pp.buildError(t,e,i);throw this.lastError=n,this.onError.emit(n),n}static reject(t,e,i){const n=pp.buildError(t,e,i);return this.lastError=n,this.onError.emit(n),Promise.reject(n)}static buildInfo(t,e){const i={details:e,id:pp.infoObjCount,status:"Pending",timestamp:Date.now(),type:t};return pp.infoObjCount+=1,i}static info(t){t.timestamp=Date.now(),this.onInfo.emit(_s(t))}static on(t,e){"error"===t?this.onError.on(e):"verbose"===t?(this.onVerbose.on(e),0!==this.verboseListenerCount&&$o.hasDebugOutput()||($o.enableDebugOutput(!0,t=>{this.verbose(t)}),this.verboseListenerCount+=1)):"warning"===t?this.onWarning.on(e):"info"===t&&this.onInfo.on(e)}static off(t,e){"error"===t?this.onError.off(e):"verbose"===t?(this.onVerbose.off(e),this.verboseListenerCount-=1,0===this.verboseListenerCount&&$o.enableDebugOutput(!1,void 0)):"warning"===t?this.onWarning.off(e):"info"===t&&this.onInfo.off(e)}}function gp(t,e,i,n){return e?i?`${e}${n?"":"."}${i}`:`${e}`:i?`${t}${n?"":"."}${i}`:`${t}`}Yi(pp,"onError",new js),Yi(pp,"onWarning",new js),Yi(pp,"onVerbose",new js),Yi(pp,"onInfo",new js),Yi(pp,"verboseListenerCount",0),Yi(pp,"infoObjCount",0),Yi(pp,"lastError",void 0),Yi(pp,"LIC_EMPTY",{code:-8e4,message:"No license."}),Yi(pp,"LIC_INVALID",{code:-80001,message:"License string is invalid."}),Yi(pp,"LIC_EXPIRED",{code:-80002,message:"XXX module license has expired."}),Yi(pp,"LIC_MISS_MODULE",{code:-80003,message:"XXX module license is missing."}),Yi(pp,"LIC_VER_NOT_MATCHED",{code:-80004,message:"XXX module license version does not match."}),Yi(pp,"LIC_DOMAIN_NOT_MATCHED",{code:-80005,message:"Domain does not match the domain bound to the XXX module license."}),Yi(pp,"INIT_SHOULD_SET_CONFIG",{code:-80050,message:"DDV.Core.init() has not been set up yet."}),Yi(pp,"INIT_CONFIG_NOT_DONE",{code:-80051,message:"DDV.Core.init() has not been completed."}),Yi(pp,"RESOURCE_NOT_FOUND",{code:-80052,message:"<%api%>: Resource is not found from the specified engineResourcePath."}),Yi(pp,"RESOURCE_NOT_MATCHED",{code:-80053,message:"<%api%>: The resource version at the specified engineResourcePath does not match this version of Dynamsoft Document Viewer."}),Yi(pp,"WASM_ERR",{code:-81e3,message:"WASM Error"}),Yi(pp,"PARAM_INVALID",{code:-80100,message:"<%api%>: '<%param%>' is invalid."}),Yi(pp,"PARAM_OUT_OF_RANGE",{code:-80101,message:"<%api%>: '<%param%>' is out of range."}),Yi(pp,"PARAM_MISS",{code:-80102,message:"<%api%>: '<%param%>' is missing."}),Yi(pp,"PARAM_NOT_SUPPORT",{code:-80103,message:"<%api%>: The value for '<%param%>' is not supported."}),Yi(pp,"DOC_NOT_EXIST",{code:-80104,message:"<%api%>: The specified document(s) do not exist."}),Yi(pp,"PAGE_NOT_EXIST",{code:-80105,message:"<%api%>: The specified page(s) do not exist."}),Yi(pp,"ANNOTATION_NOT_EXIST",{code:-80106,message:"<%api%>: The specified annotation does not exist."}),Yi(pp,"DOC_DESTROYED",{code:-80108,message:"The document has been destroyed."}),Yi(pp,"PAGE_DESTROYED",{code:-80109,message:"The page has been destroyed."}),Yi(pp,"FILE_NOT_SUPPORT",{code:-80200,message:"File type is not supported."}),Yi(pp,"DOC_UID_DUPLICATE",{code:-80201,message:"DocUid does not allow duplicate."}),Yi(pp,"PAGEDATA_DESTROYED",{code:-80205,message:"The pageData has been destroyed."}),Yi(pp,"SEARCHER_DESTROYED",{code:-80206,message:"The DocTextSearcher has been destroyed."}),Yi(pp,"CONTAINER_NOT_EXIST",{code:-80301,message:"The specified container does not exist."}),Yi(pp,"MIN_ZOOM_INVALID",{code:-80302,message:"minZoom value cannot be larger than maxZoom value."}),Yi(pp,"MAX_ZOOM_INVALID",{code:-80303,message:"maxZoom value cannot be smaller than minZoom value."}),Yi(pp,"DOC_NOT_OPEN",{code:-80304,message:"No document opened."}),Yi(pp,"DOC_NO_IMAGE",{code:-80305,message:"There is no image in the current document."}),Yi(pp,"ZOOM_TOO_LARGE",{code:-80306,message:"The value for zoom is larger than maxZoom value."}),Yi(pp,"ZOOM_TOO_SMALL",{code:-80307,message:"The value for zoom is smaller than minZoom value."}),Yi(pp,"ROW_COLUMN_CAN_NOT_CHANGE",{code:-80308,message:"<%api%>: Not available in current displayMode."}),Yi(pp,"RECT_EXCEED_PAGE_BOUND",{code:-80309,message:"The specified rect exceeds the bounds of the current page."}),Yi(pp,"UNDO_NOOP",{code:-80310,message:"No operations to undo."}),Yi(pp,"REDO_NOOP",{code:-80311,message:"No operations to redo."}),Yi(pp,"QUAD_EXCEED_PAGE_BOUND",{code:-80312,message:"The specified quad exceeds the bounds of the current page."}),Yi(pp,"ELEMENT_UNSUPPORTED",{code:-80313,message:"The element '<%param%>' is not supported in <%api%> class."}),Yi(pp,"TOOL_MODE_NOT_AVAILABLE",{code:-80314,message:"<%api%>: Not available in current toolMode."}),Yi(pp,"DOC_DETECT_MISS",{code:-80315,message:"DocumentDetect needs to be configured by Dynamsoft.DDV.setProcessingHandler to enable the document detection feature."}),Yi(pp,"IMG_FILTER_MISS",{code:-80316,message:"ImageFilter needs to be configured by Dynamsoft.DDV.setProcessingHandler to enable the image filter feature."}),Yi(pp,"ANNOTATION_SELECT",{code:-80317,message:"The specified annotation(s) is not on the current page or does not exist."}),Yi(pp,"WASM_FONT_LOSS",{code:-80318,message:"The document contains unsupported fonts, which may result in font loss after saving."}),Yi(pp,"UNSELECTED_READONLY",{code:-80319,message:"ReadOnly annotation or noView annotation cannot be selected."}),Yi(pp,"UNSELECTED_UNKNOWN",{code:-80320,message:"Unknown annotation or incomplete annotation cannot be selected."}),Yi(pp,"UNSELECTED_FLATTENED",{code:-80321,message:"Flattened annotation cannot be selected."}),Yi(pp,"NO_RESULTS_FOUND",{code:-80322,message:"No results found."}),Yi(pp,"CAMERA_NOT_EXIST",{code:-80400,message:"The specified camera does not exist."}),Yi(pp,"CAMERA_OCCUPIED",{code:-80401,message:"The specified camera is occupied."}),Yi(pp,"CAMERA_NO_VIDEO",{code:-80402,message:"No video stream is played."}),Yi(pp,"CAMERA_NEED_HTTPS",{code:-80403,message:"Not HTTPS, failed to play the video stream."}),Yi(pp,"CAMERA_NOT_SUPPORT_TORCH",{code:-80404,message:"The camera does not support a flashlight."}),Yi(pp,"CAMERA_NO_CAMERA",{code:-80405,message:"No camera available."}),Yi(pp,"CAMERA_DENIED",{code:-80406,message:"The selected camera is denied by browser."}),Yi(pp,"CONTAINER_NO_BOUND",{code:-80407,message:"No bound container."}),Yi(pp,"EXTERNAL_ERR",{code:-81100,message:"External Error"});class fp{static makeSureValid(t,e,i,n){const s=this.composeError(i,n);pp.throw(s,t,e)}static output(t,e,i,n,s){let o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];const r=this.composeError(n,s);return 2===t?pp.reject(r,e,i):1===t?(pp.warning(r,e,i),o):0===t?pp.error(r,e,i):3===t?pp.verbose(r,e,i):void 0}static error(t,e,i,n){const s=this.composeError(i,n);pp.throw(s,t,e)}static warning(t,e,i,n){let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const o=this.composeError(i,n);return pp.warning(o,t,e),s}static verbose(t,e,i,n){const s=this.composeError(i,n);pp.verbose(s,t,e)}static reject(t,e,i,n){const s=this.composeError(i,n);return pp.reject(s,t,e)}static composeError(t,e){const i={...Ps(e)?pp.PARAM_INVALID:e};return t&&(i.details=t),i}static formatDetails(t,e){const i=[];if(Rs(e))e||i.push(`'${t}' is invalid.`);else{const{isValid:n,isInRange:s,isSupported:o}=e;!1===n&&i.push(`'${t}' is invalid.`),!1===s&&i.push(`'${t}' is out of range.`),!1===o&&i.push(`'${t}' is not supported.`)}return i}static formatError(t,e){const{isValid:i,isInRange:n,isSupported:s}=t;if(!1===i||!1===n||!1===s){if(e)return e;if(!i)return pp.PARAM_INVALID;if(!n)return pp.PARAM_OUT_OF_RANGE;if(!s)return pp.PARAM_NOT_SUPPORT}return null}static isArrayBufferOrBlob(t){return Is(t)||Ds(t)}static isArrayAndMeetMinLength(t,e){return Ts(t)?Ls(e)?{isValid:0!==t.length,isInRange:t.length>=e}:{isValid:!0}:{isValid:!1}}static isNumberAndIsInRange(t,e,i){return Ls(t)?{isValid:!0,isInRange:!(!Ps(e)&&t<e||!Ps(i)&&t>i)}:{isValid:!1}}static isStringAndNotEmpty(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Os(t)?e?{isValid:!0}:{isValid:0!==t.trim().length}:{isValid:!1}}static isPdfDate(t){if(!Os(t))return{isValid:!1};const e=t.match(/^D:(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:([+-])(\d{2})['’](\d{2})['’]|)$/);let i=!1;if(e){const[,t,n,s,o,r,a,l,h,c]=e,d=new Date(`${t}-${n}-${s}T${o}:${r}:${a}`);if(i=!0,d.getFullYear()===parseInt(t,10)&&d.getMonth()+1===parseInt(n,10)&&d.getDate()===parseInt(s,10)&&d.getHours()===parseInt(o,10)&&d.getMinutes()===parseInt(r,10)&&d.getSeconds()===parseInt(a,10)||(i=!1),i&&l){const t=parseInt(h,10),e=parseInt(c,10);(t<0||t>12||e<0||e>59||"+"!==l&&"-"!==l)&&(i=!1)}}return{isSupported:i}}}!function(t){t[t.BlackAndWhite=1]="BlackAndWhite",t[t.Gray=2]="Gray",t[t.RemoveShadow=3]="RemoveShadow",t[t.Enhance=4]="Enhance",t[t.Invert=5]="Invert",t[t.Brightness=6]="Brightness",t[t.Contrast=7]="Contrast",t[t.BrightnessAndContrast=8]="BrightnessAndContrast",t[t.Perspective=9]="Perspective",t[t.Deskew=10]="Deskew",t[t.Rotate=11]="Rotate",t[t.Flip=12]="Flip",t[t.Resize=13]="Resize",t[t.SetHeight=14]="SetHeight",t[t.SetWidth=15]="SetWidth",t[t.SetDPI=16]="SetDPI",t[t.Crop=17]="Crop",t[t.Erase=18]="Erase",t[t.DrawPolygon=19]="DrawPolygon"}(lp||(lp={}));var mp=new WeakSet,vp=new WeakSet;class yp{constructor(){an(this,vp),an(this,mp)}async process(t,e,i){Ts(e)||(e=[e]),sn(this,mp,xp).call(this,e);const n=new lr,s={inputImageInfo:null,output:null,outputImageInfo:null,outputContentType:"",outputType:null};try{var o,r,a,l;const h=await n.initImage({source:t.data,isRGBA:t.type===tr.RGBA,width:t.width,height:t.height,isBGRA:t.type===tr.BGRA});h.srcBuffer&&(t.data=h.srcBuffer);for(const t of e)sn(this,vp,wp).call(this,n,t);const c=await n.getImage({jpegQuality:null==i||null===(o=i.params)||void 0===o?void 0:o.jpegQuality,ifDeleteObject:!0,isRGBA:t.type===tr.RGBA,bitDepth:null==i||null===(r=i.params)||void 0===r?void 0:r.bitDepth,xDpi:null==i||null===(a=i.params)||void 0===a?void 0:a.xDpi,yDpi:null==i||null===(l=i.params)||void 0===l?void 0:l.yDpi,returnType:ir.RT_BINARY,outputType:xr[null==i?void 0:i.type]});await n.freeReservedData(),s.output=c.imageData,s.outputContentType=c.blobType,s.outputImageInfo={width:c.imageWidth,height:c.imageHeight,bitDepth:c.imageBitDepth,resolutionX:c.imageXResolution,resolutionY:c.imageYResolution},s.outputType=wr[c.imageType]}finally{try{await n.terminate()}catch(t){pp.warning(t)}}return s}}function xp(t){for(const e of t)e.type&&(e.type<=0||(e.type,lp.DrawPolygon),e.params)}async function wp(t,e){var i;const n=null!==(i=e.params)&&void 0!==i?i:{};switch(e.type){case lp.BlackAndWhite:return t.toBinaryLevel(n.saveInk,n.level);case lp.Gray:return t.toGrayscale(n.level);case lp.RemoveShadow:return t.removeShadowLevel(n.level,n.alpha);case lp.Enhance:return t.brighten();case lp.Invert:return t.invert();case lp.Contrast:return t.changeBrightnessAndContrast(void 0,n.contrast);case lp.Brightness:return t.changeBrightnessAndContrast(n.brightness,void 0);case lp.BrightnessAndContrast:return t.changeBrightnessAndContrast(n.brightness,n.contrast);case lp.Perspective:return t.perspective(n.location);case lp.Deskew:{var s;const e=await t.getSkewAngle(n.options);return t.rotate({angle:e,fillColor:n.fillColor,keepSize:null===(s=n.keepSize)||void 0===s||s,mode:n.mode})}case lp.Rotate:return t.rotate({angle:n.angle,fillColor:n.fillColor,keepSize:n.keepSize,mode:n.mode});case lp.Flip:return t.flip();case lp.Resize:{const{newWidth:e,newHeight:i,mode:s}=n;return t.resize(e,i,s)}case lp.SetHeight:{const{newHeight:e,fillColor:i}=n;return t.setImageHeight(e,i)}case lp.SetWidth:{const{newWidth:e,fillColor:i}=n;return t.setImageWidth(e,i)}case lp.SetDPI:return t.setDpi({rawResolutionX:0,rawResolutionY:0,resolutionX:n.xRes,resolutionY:n.yRes,resample:!1});case lp.Crop:return t.crop({left:n.left,top:n.top,width:n.right-n.left,height:n.bottom-n.top});case lp.Erase:return t.erase({left:n.left,top:n.top,width:n.right-n.left,height:n.bottom-n.top},n.fillColor);case lp.DrawPolygon:return t.drawQuadrangle({location:n.location,strokeColor:n.strokeColor,lineWidth:n.lineWidth})}}!Jn&&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")),!Jn&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Cp=async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let s=await n.text();if(!s.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let o=document.createElement("div");o.innerHTML=s;let r=[];for(let t=0;t<o.childElementCount;++t){let e=o.children[t];e instanceof HTMLStyleElement&&(r.push(e),document.head.append(e))}let a=1==o.childElementCount?o.children[0]:o;a.remove();let l,h,c,d,u,p=[a],g=a.children;for(let t of g)p.push(t);for(let t=0;t<p.length;++t)for(let e of p[t].children)p.push(e);for(let t of p)if(!l&&t.classList.contains("dls-license-mask"))l=t,t.addEventListener("click",e=>{if(t==e.target){a.remove();for(let t of r)t.remove()}});else if(!h&&t.classList.contains("dls-license-icon-close"))h=t,t.addEventListener("click",()=>{a.remove();for(let t of r)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-icon-warn"))d=t,"warn"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-msg-content")){u=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),s=e.indexOf("(",n),o=e.indexOf(")",s);if(-1==i||-1==n||-1==s||-1==o){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let r=document.createElement("a"),a=e.substring(i+1,n);r.innerText=a;let l=e.substring(s+1,o);r.setAttribute("href",l),r.setAttribute("target","_blank"),t.appendChild(r),e=e.substring(o+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}};var bp=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(t){return}}();function Sp(t,e){t=t||[],e=e||{};try{return new Blob(t,e)}catch(s){if("TypeError"!==s.name)throw s;for(var i=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n<t.length;n+=1)i.append(t[n]);return i.getBlob(e.type)}}function Tp(t,e){e&&t.then(function(t){e(null,t)},function(t){e(t)})}function Ep(t,e,i){"function"==typeof e&&t.then(e),"function"==typeof i&&t.catch(i)}function _p(t){return"string"!=typeof t&&(t=String(t)),t}function Pp(){if(arguments.length&&"function"==typeof arguments[arguments.length-1])return arguments[arguments.length-1]}const Ap="local-forage-detect-blob-support";let Ip;const Dp={},Rp=Object.prototype.toString,kp="readonly",Mp="readwrite";function Lp(t){var e=Dp[t.name],i={};i.promise=new Promise(function(t,e){i.resolve=t,i.reject=e}),e.deferredOperations.push(i),e.dbReady?e.dbReady=e.dbReady.then(function(){return i.promise}):e.dbReady=i.promise}function Op(t){var e=Dp[t.name].deferredOperations.pop();if(e)return e.resolve(),e.promise}function Bp(t,e){var i=Dp[t.name].deferredOperations.pop();if(i)return i.reject(e),i.promise}function Np(t,e){return new Promise(function(i,n){if(Dp[t.name]=Dp[t.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},t.db){if(!e)return i(t.db);Lp(t),t.db.close()}var s=[t.name];e&&s.push(t.version);var o=bp.open.apply(bp,s);e&&(o.onupgradeneeded=function(e){var i=o.result;try{i.createObjectStore(t.storeName),e.oldVersion<=1&&i.createObjectStore(Ap)}catch(t){if("ConstraintError"!==t.name)throw t}}),o.onerror=function(t){t.preventDefault(),n(o.error)},o.onsuccess=function(){var e=o.result;e.onversionchange=function(t){t.target.close()},i(e),Op(t)}})}function Up(t){return Np(t,!1)}function Fp(t){return Np(t,!0)}function Vp(t,e){if(!t.db)return!0;var i=!t.db.objectStoreNames.contains(t.storeName),n=t.version<t.db.version,s=t.version>t.db.version;if(n&&(t.version,t.version=t.db.version),s||i){if(i){var o=t.db.version+1;o>t.version&&(t.version=o)}return!0}return!1}function Wp(t){var e=this,i=e._initReady().then(function(){var t=Dp[e._dbInfo.name];if(t&&t.dbReady)return t.dbReady});return Ep(i,t,t),i}function Hp(t,e,i,n){void 0===n&&(n=1);try{var s=t.db.transaction(t.storeName,e);i(null,s)}catch(s){if(n>0&&(!t.db||"InvalidStateError"===s.name||"NotFoundError"===s.name))return Promise.resolve().then(()=>{if(!t.db||"NotFoundError"===s.name&&!t.db.objectStoreNames.contains(t.storeName)&&t.version<=t.db.version)return t.db&&(t.version=t.db.version+1),Fp(t)}).then(()=>function(t){Lp(t);for(var e=Dp[t.name],i=e.forages,n=0;n<i.length;n++){const t=i[n];t._dbInfo.db&&(t._dbInfo.db.close(),t._dbInfo.db=null)}return t.db=null,Up(t).then(e=>(t.db=e,Vp(t)?Fp(t):e)).then(n=>{t.db=e.db=n;for(var s=0;s<i.length;s++)i[s]._dbInfo.db=n}).catch(e=>{throw Bp(t,e),e})}(t).then(function(){Hp(t,e,i,n-1)})).catch(i);i(s)}}var jp={_driver:"asyncStorage",_initStorage:function(t){var e=this,i={db:null};if(t)for(var n in t)i[n]=t[n];var s=Dp[i.name];s||(s={forages:[],db:null,dbReady:null,deferredOperations:[]},Dp[i.name]=s),s.forages.push(e),e._initReady||(e._initReady=e.ready,e.ready=Wp);var o=[];function r(){return Promise.resolve()}for(var a=0;a<s.forages.length;a++){var l=s.forages[a];l!==e&&o.push(l._initReady().catch(r))}var h=s.forages.slice(0);return Promise.all(o).then(function(){return i.db=s.db,Up(i)}).then(function(t){return i.db=t,Vp(i,e._defaultConfig.version)?Fp(i):t}).then(function(t){i.db=s.db=t,e._dbInfo=i;for(var n=0;n<h.length;n++){var o=h[n];o!==e&&(o._dbInfo.db=i.db,o._dbInfo.version=i.version)}})},_support:function(){try{if(!bp||!bp.open)return!1;var t="undefined"!=typeof openDatabase&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),e="function"==typeof fetch&&-1!==fetch.toString().indexOf("[native code");return(!t||e)&&"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(t){return!1}}(),getItem:function(t,e){var i=this;t=_p(t);var n=new Promise(function(e,n){i.ready().then(function(){Hp(i._dbInfo,kp,function(s,o){if(s)return n(s);try{var r=o.objectStore(i._dbInfo.storeName).get(t);r.onsuccess=function(){var t=r.result;void 0===t&&(t=null),function(t){return t&&t.__local_forage_encoded_blob}(t)&&(t=function(t){var e=function(t){for(var e=t.length,i=new ArrayBuffer(e),n=new Uint8Array(i),s=0;s<e;s++)n[s]=t.charCodeAt(s);return i}(atob(t.data));return Sp([e],{type:t.type})}(t)),e(t)},r.onerror=function(){n(r.error)}}catch(t){n(t)}})}).catch(n)});return Tp(n,e),n},setItem:function(t,e,i){var n=this;t=_p(t);var s=new Promise(function(i,s){var o;n.ready().then(function(){return o=n._dbInfo,"[object Blob]"===Rp.call(e)?function(t){return"boolean"==typeof Ip?Promise.resolve(Ip):function(t){return new Promise(function(e){var i=t.transaction(Ap,Mp),n=Sp([""]);i.objectStore(Ap).put(n,"key"),i.onabort=function(t){t.preventDefault(),t.stopPropagation(),e(!1)},i.oncomplete=function(){var t=navigator.userAgent.match(/Chrome\/(\d+)/),i=navigator.userAgent.match(/Edge\//);e(i||!t||parseInt(t[1],10)>=43)}}).catch(function(){return!1})}(t).then(function(t){return Ip=t,Ip})}(o.db).then(function(t){return t?e:(i=e,new Promise(function(t,e){var n=new FileReader;n.onerror=e,n.onloadend=function(e){var n=btoa(e.target.result||"");t({__local_forage_encoded_blob:!0,data:n,type:i.type})},n.readAsBinaryString(i)}));var i}):e}).then(function(e){Hp(n._dbInfo,Mp,function(o,r){if(o)return s(o);try{var a=r.objectStore(n._dbInfo.storeName);null===e&&(e=void 0);var l=a.put(e,t);r.oncomplete=function(){void 0===e&&(e=null),i(e)},r.onabort=r.onerror=function(){var t=l.error?l.error:l.transaction.error;s(t)}}catch(t){s(t)}})}).catch(s)});return Tp(s,i),s},removeItem:function(t,e){var i=this;t=_p(t);var n=new Promise(function(e,n){i.ready().then(function(){Hp(i._dbInfo,Mp,function(s,o){if(s)return n(s);try{var r=o.objectStore(i._dbInfo.storeName).delete(t);o.oncomplete=function(){e()},o.onerror=function(){n(r.error)},o.onabort=function(){var t=r.error?r.error:r.transaction.error;n(t)}}catch(t){n(t)}})}).catch(n)});return Tp(n,e),n},clear:function(t){var e=this,i=new Promise(function(t,i){e.ready().then(function(){Hp(e._dbInfo,Mp,function(n,s){if(n)return i(n);try{var o=s.objectStore(e._dbInfo.storeName).clear();s.oncomplete=function(){t()},s.onabort=s.onerror=function(){var t=o.error?o.error:o.transaction.error;i(t)}}catch(t){i(t)}})}).catch(i)});return Tp(i,t),i},length:function(t){var e=this,i=new Promise(function(t,i){e.ready().then(function(){Hp(e._dbInfo,kp,function(n,s){if(n)return i(n);try{var o=s.objectStore(e._dbInfo.storeName).count();o.onsuccess=function(){t(o.result)},o.onerror=function(){i(o.error)}}catch(t){i(t)}})}).catch(i)});return Tp(i,t),i},keys:function(t){var e=this,i=new Promise(function(t,i){e.ready().then(function(){Hp(e._dbInfo,kp,function(n,s){if(n)return i(n);try{var o=s.objectStore(e._dbInfo.storeName).openKeyCursor(),r=[];o.onsuccess=function(){var e=o.result;e?(r.push(e.key),e.continue()):t(r)},o.onerror=function(){i(o.error)}}catch(t){i(t)}})}).catch(i)});return Tp(i,t),i},dropInstance:function(t,e){e=Pp.apply(this,arguments);var i,n=this.config();if((t="function"!=typeof t&&t||{}).name||(t.name=t.name||n.name,t.storeName=t.storeName||n.storeName),t.name){const e=t.name===n.name&&this._dbInfo.db?Promise.resolve(this._dbInfo.db):Up(t).then(e=>{const i=Dp[t.name],n=i.forages;i.db=e;for(var s=0;s<n.length;s++)n[s]._dbInfo.db=e;return e});i=t.storeName?e.then(e=>{if(!e.objectStoreNames.contains(t.storeName))return;const i=e.version+1;Lp(t);const n=Dp[t.name],s=n.forages;e.close();for(let t=0;t<s.length;t++){const e=s[t];e._dbInfo.db=null,e._dbInfo.version=i}const o=new Promise((e,n)=>{const s=bp.open(t.name,i);s.onerror=t=>{s.result.close(),n(t)},s.onupgradeneeded=()=>{s.result.deleteObjectStore(t.storeName)},s.onsuccess=()=>{const t=s.result;t.close(),e(t)}});return o.then(t=>{n.db=t;for(let e=0;e<s.length;e++){const i=s[e];i._dbInfo.db=t,Op(i._dbInfo)}}).catch(e=>{throw(Bp(t,e)||Promise.resolve()).catch(()=>{}),e})}):e.then(e=>{Lp(t);const i=Dp[t.name],n=i.forages;e.close();for(var s=0;s<n.length;s++)n[s]._dbInfo.db=null;const o=new Promise((e,i)=>{var n=bp.deleteDatabase(t.name);n.onerror=()=>{const t=n.result;t&&t.close(),i(n.error)},n.onblocked=()=>{},n.onsuccess=()=>{const t=n.result;t&&t.close(),e(t)}});return o.then(t=>{i.db=t;for(var e=0;e<n.length;e++)Op(n[e]._dbInfo)}).catch(e=>{throw(Bp(t,e)||Promise.resolve()).catch(()=>{}),e})})}else i=Promise.reject("Invalid arguments");return Tp(i,e),i}};const zp=new Map;function Gp(t,e){let i=t.name+"/";return t.storeName!==e.storeName&&(i+=t.storeName+"/"),i}var Yp={_driver:"tempStorageWrapper",_initStorage:async function(t){const e={};if(t)for(let i in t)e[i]=t[i];const i=e.keyPrefix=Gp(t,this._defaultConfig);this._dbInfo=e,zp.has(i)||zp.set(i,new Map)},getItem:function(t,e){t=_p(t);const i=this.ready().then(()=>zp.get(this._dbInfo.keyPrefix).get(t));return Tp(i,e),i},setItem:function(t,e,i){t=_p(t);const n=this.ready().then(()=>(void 0===e&&(e=null),zp.get(this._dbInfo.keyPrefix).set(t,e),e));return Tp(n,i),n},removeItem:function(t,e){t=_p(t);const i=this.ready().then(()=>{zp.get(this._dbInfo.keyPrefix).delete(t)});return Tp(i,e),i},clear:function(t){const e=this.ready().then(()=>{const t=this._dbInfo.keyPrefix;zp.has(t)&&zp.delete(t)});return Tp(e,t),e},length:function(t){const e=this.ready().then(()=>zp.get(this._dbInfo.keyPrefix).size);return Tp(e,t),e},keys:function(t){const e=this.ready().then(()=>[...zp.get(this._dbInfo.keyPrefix).keys()]);return Tp(e,t),e},dropInstance:function(t,e){if(e=Pp.apply(this,arguments),!(t="function"!=typeof t&&t||{}).name){const e=this.config();t.name=t.name||e.name,t.storeName=t.storeName||e.storeName}let i;return i=t.name?new Promise(e=>{t.storeName?e(Gp(t,this._defaultConfig)):e(`${t.name}/`)}).then(t=>{zp.delete(t)}):Promise.reject("Invalid arguments"),Tp(i,e),i}};const $p=(t,e)=>t===e||"number"==typeof t&&"number"==typeof e&&isNaN(t)&&isNaN(e),Xp=(t,e)=>{const i=t.length;let n=0;for(;n<i;){if($p(t[n],e))return!0;n++}return!1},qp=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},Zp={},Jp={},Kp={INDEXEDDB:jp,TEMPSTORAGE:Yp},Qp=[Kp.INDEXEDDB._driver,Kp.TEMPSTORAGE._driver],tg=["dropInstance"],eg=["clear","getItem","keys","length","removeItem","setItem"].concat(tg),ig={description:"",driver:Qp.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ng(t,e){t[e]=function(){const i=arguments;return t.ready().then(function(){return t[e].apply(t,i)})}}function sg(){for(let t=1;t<arguments.length;t++){const e=arguments[t];if(e)for(let t in e)e.hasOwnProperty(t)&&(qp(e[t])?arguments[0][t]=e[t].slice():arguments[0][t]=e[t])}return arguments[0]}class og{constructor(t){for(let t in Kp)if(Kp.hasOwnProperty(t)){const e=Kp[t],i=e._driver;this[t]=i,Zp[i]||this.defineDriver(e)}this._defaultConfig=sg({},ig),this._config=sg({},this._defaultConfig,t),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(()=>{})}config(t){if("object"==typeof t){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let e in t){if("storeName"===e&&(t[e]=t[e].replace(/\W/g,"_")),"version"===e&&"number"!=typeof t[e])return new Error("Database version must be a number.");this._config[e]=t[e]}return!("driver"in t)||!t.driver||this.setDriver(this._config.driver)}return"string"==typeof t?this._config[t]:this._config}defineDriver(t,e,i){const n=new Promise(function(e,i){try{const n=t._driver,s=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!t._driver)return void i(s);const o=eg.concat("_initStorage");for(let e=0,n=o.length;e<n;e++){const n=o[e];if((!Xp(tg,n)||t[n])&&"function"!=typeof t[n])return void i(s)}const r=function(){const e=function(t){return function(){const e=new Error(`Method ${t} is not implemented by the current driver`),i=Promise.reject(e);return Tp(i,arguments[arguments.length-1]),i}};for(let i=0,n=tg.length;i<n;i++){const n=tg[i];t[n]||(t[n]=e(n))}};r();const a=function(i){Zp[n],Zp[n]=t,Jp[n]=i,e()};"_support"in t?t._support&&"function"==typeof t._support?t._support().then(a,i):a(!!t._support):a(!0)}catch(t){i(t)}});return Ep(n,e,i),n}driver(){return this._driver||null}getDriver(t,e,i){const n=Zp[t]?Promise.resolve(Zp[t]):Promise.reject(new Error("Driver not found."));return Ep(n,e,i),n}ready(t){const e=this,i=e._driverSet.then(()=>(null===e._ready&&(e._ready=e._initDriver()),e._ready));return Ep(i,t,t),i}setDriver(t,e,i){const n=this;qp(t)||(t=[t]);const s=this._getSupportedDrivers(t);function o(){n._config.driver=n.driver()}function r(t){return n._extend(t),o(),n._ready=n._initStorage(n._config),n._ready}const a=null!==this._driverSet?this._driverSet.catch(()=>Promise.resolve()):Promise.resolve();return this._driverSet=a.then(()=>{const t=s[0];return n._dbInfo=null,n._ready=null,n.getDriver(t).then(t=>{n._driver=t._driver,o(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(t){return function(){let e=0;return function i(){for(;e<t.length;){let s=t[e];return e++,n._dbInfo=null,n._ready=null,n.getDriver(s).then(r).catch(i)}o();const s=new Error("No available storage method found.");return n._driverSet=Promise.reject(s),n._driverSet}()}}(s)})}).catch(()=>{o();const t=new Error("No available storage method found.");return n._driverSet=Promise.reject(t),n._driverSet}),Ep(this._driverSet,e,i),this._driverSet}supports(t){return!!Jp[t]}_extend(t){sg(this,t)}_getSupportedDrivers(t){const e=[];for(let i=0,n=t.length;i<n;i++){const n=t[i];this.supports(n)&&e.push(n)}return e}_wrapLibraryMethodsWithReady(){for(let t=0,e=eg.length;t<e;t++)ng(this,eg[t])}createInstance(t){return new og(t)}}var rg=new og;Date.prototype.kUtilFormat=function(t){const e={"M+":this.getUTCMonth()+1,"d+":this.getUTCDate(),"H+":this.getUTCHours(),"h+":this.getUTCHours()%12||12,"m+":this.getUTCMinutes(),"s+":this.getUTCSeconds(),"q+":Math.floor((this.getUTCMonth()+3)/3),"S+":this.getUTCMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(this.getUTCFullYear()+"").substr(4-RegExp.$1.length)));for(let i in e)new RegExp("("+i+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?e[i]:("000"+e[i]).substr(("000"+e[i]).length-RegExp.$1.length)));return t},String.prototype.startsWith||(String.prototype.startsWith=function(t){return 0==this.indexOf(t)});var ag;class lg{static init(){Ji(this,lg,ug,void 0),Ji(this,lg,pg,void 0),Ji(this,lg,gg,"init")}static reset(){Ji(this,lg,ug,void 0),Ji(this,lg,pg,void 0),Ji(this,lg,gg,"")}static setLicenseInfo(t){var e;Ji(this,lg,gg,"done"),Ji(this,lg,ug,[]),Ji(this,lg,ug,null!==(e=null==t?void 0:t.modules)&&void 0!==e?e:[])}static setLicenseErr(t){Ji(this,lg,pg,t),Ji(this,lg,gg,"done")}static makeSureLoadLicenseExist(){return Ki(this,lg,cg).call(this,3101,5001)}static makeSureCoreLicenseExist(){return Ki(this,lg,cg).call(this,3101)}static makeSureCameraLicenseExist(){return Ki(this,lg,cg).call(this,3006,8002)}static makeSureAnnotationLicenseExist(){return Ki(this,lg,cg).call(this,15)}static annotationLicenseModuleIsExist(){return Ki(this,lg,dg).call(this,15)}static pdfRLicenseModuleIsExist(){return Ki(this,lg,dg).call(this,5001)}}function hg(t){for(const e of Zi(this,ag,ug))if(e.module===t)return e;return{code:pp.LIC_MISS_MODULE.code,message:pp.LIC_MISS_MODULE.message,module:t}}function cg(t,e){""===Zi(this,ag,gg)&&pp.throw(pp.INIT_SHOULD_SET_CONFIG),"done"!==Zi(this,ag,gg)&&pp.throw(pp.INIT_CONFIG_NOT_DONE),Zi(this,ag,pg)&&pp.throw(Zi(this,ag,pg));const i=Ki(this,ag,hg).call(this,t);0!==i.code&&(!e||e&&0!==Ki(this,ag,hg).call(this,e).code)&&pp.throw({code:i.code,message:i.message})}function dg(t){return 0===Ki(this,ag,hg).call(this,t).code}ag=lg;var ug={writable:!0,value:void 0},pg={writable:!0,value:void 0},gg={writable:!0,value:""};function fg(t){let e;if(t){let i;const n=t.message;i=t.ltsErrorCode,Ls(i)?111===i?i=pp.LIC_EXPIRED.code:106===i||108===i?i=pp.LIC_INVALID.code:i>0&&(i=-(2e4+i)):i=pp.LIC_INVALID.code,e={code:i,message:n}}else e=pp.LIC_INVALID;return e}const mg="3.2.0";var vg;!function(t){t[t.publicTrial=0]="publicTrial",t[t.privateTrial=1]="privateTrial",t[t.normal=2]="normal"}(vg||(vg={}));var yg,xg=new WeakMap,wg=new WeakMap,Cg=new WeakMap,bg=new WeakMap,Sg=new WeakMap,Tg=new WeakMap,Eg=new WeakMap,_g=new WeakMap,Pg=new WeakSet,Ag=new WeakSet,Ig=new WeakSet,Dg=new WeakSet,Rg=new WeakSet,kg=new WeakSet;class Mg{constructor(t){an(this,kg),an(this,Rg),an(this,Dg),an(this,Ig),an(this,Ag),an(this,Pg),rn(this,xg,{writable:!0,value:void 0}),rn(this,wg,{writable:!0,value:void 0}),rn(this,Cg,{writable:!0,value:void 0}),rn(this,bg,{writable:!0,value:void 0}),rn(this,Sg,{writable:!0,value:void 0}),rn(this,Tg,{writable:!0,value:void 0}),rn(this,Eg,{writable:!0,value:void 0}),rn(this,_g,{writable:!0,value:void 0}),Xi(this,wg,void 0),Xi(this,xg,void 0),Xi(this,Cg,""),Xi(this,bg,""),Xi(this,Tg,vg.publicTrial),Xi(this,_g,void 0),Xi(this,Eg,"");const e=function(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=t;if(i._pLoad.isEmpty){let n,s,o,r=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),l=i._sessionPassword,h=0;if(r.startsWith("t")||r.startsWith("f"))h=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))h=1;else{h=2;const e=r.indexOf(":");-1!=e&&(r=r.substring(e+1));const i=r.indexOf("?");if(-1!=i&&(s=r.substring(i+1),r=r.substring(0,i)),r.startsWith("DLC2"))h=0;else{if(r.startsWith("DLS2")){let e;try{let t=r.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(r=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=(t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e<t.length;++e){if(!Jn){let i=document.createElement("a");i.href=t[e],t[e]=i.href}t[e].endsWith("/")||(t[e]+="/")}}return t})(t)}!l&&e.sessionPassword&&(l=e.sessionPassword),n=e.remark}r&&"200001"!==r&&!r.startsWith("200001-")||(h=1)}}if(h&&(e||(Kn.crypto||(o="Please upgrade your browser to support online key."),Kn.crypto.subtle||(o="Require https to use online key in this browser."))),o){if(1!==h)throw new Error(o);h=0,i._lastErrorCode=-1,i._lastErrorString=o}return 1===h&&(r=""),{lt:h,l:r,ls:a,sp:l,rmk:n,cv:s}}throw new Error("Can't preprocess license again is not allowed to change after `createInstance` or `loadWasm` is called.")}({_pLoad:{isEmpty:!0},_license:t,_licenseServer:[]},!0);let i;if(e&&Os(e.l)?(i=e.l.trim(),1===e.lt?Xi(this,Tg,vg.publicTrial):2===e.lt?Xi(this,Tg,vg.privateTrial):Xi(this,Tg,vg.normal)):(i="",Xi(this,Tg,vg.publicTrial)),""===i?Xi(this,xg,i):i.includes("-")?Xi(this,wg,i):Xi(this,xg,i),Ts(e.ls)){e.ls.length>0&&Xi(this,_g,e.ls);const t=$i(this,_g);let n,s;if(t&&t.length>0){for(n=0;n<t.length;n++)s=t[n],s.endsWith("/")||(t[n]=`${s}/`);sn(this,Pg,Lg).call(this,t,i)&&Xi(this,Tg,vg.publicTrial)}}Xi(this,Eg,e.sp)}async init(t,e,i){let n=t;n.endsWith("/")||(n=`${n}/`),$i(this,Sg)||await sn(this,Ig,Bg).call(this,i);try{await sn(this,kg,Fg).call(this,e)}catch(t){const e=fg(t);let i=!1;e.code===pp.LIC_EXPIRED.code?-1!==e.message.toLowerCase().indexOf("trial license")&&(i=!0):this.isPublicTrial()&&(i=!0),i&&Cp({_bNeverShowDialog:!1,engineResourcePath:n,_onLog:console.log},"error",e.message),pp.throw(e)}}getClientUUID(){return $i(this,bg)}getAuthResult(){return $i(this,Cg)}isPublicTrial(){return $i(this,Tg)===vg.publicTrial}setClientUUID(t){Xi(this,bg,t)}setAuthResult(t){Xi(this,Cg,t)}}function Lg(t,e){let i=!0;if(Ts(t)&&t.length>0){const e=t[0];Os(e)&&""!==e&&"mlts.dynamsoft.com"!==new URL(e).hostname&&(i=!1)}return i&&(!e||"200001"===e||e.startsWith("200001-"))}function Og(){return window.location.origin?window.location.origin.startsWith("http")?window.location.origin:"https://localhost":window.location.href.startsWith("http")?window.location.href:"https://localhost"}function Bg(t){const e={dm:sn(this,Ag,Og).call(this),fetch:window.fetch};t&&(e.bd=!0,e.log=console.log),Xi(this,Sg,(t=>{let e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x,w,C,b,S=t.fetch||Kn.fetch,T=t.btoa||Kn.btoa,E=t.atob||Kn.atob,_=t.bd,P=t.dm,A=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"],I=!1,D=Promise.resolve(),R=t.lf,k=t.log&&function(){try{for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];t.log.apply(null,i)}catch(t){setTimeout(()=>{throw t},0)}}||(()=>{}),M=_&&k||(()=>{}),L=t.fol,O=t.sutlcb,B=t.feab,N=t=>E(E(t.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),U=t=>T(String.fromCharCode(97+25*Math.random())+T(t)).replace(/\+/g,"\n").replace(/=/g," "),F=()=>{if(b)return b;if(Kn.crypto){let t=new Uint8Array(36);Kn.crypto.getRandomValues(t);let e="";for(let i=0;i<36;++i){let n=t[i]%36;e+=n<10?n:String.fromCharCode(n+87)}return e}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})};const V=" Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license.";let W,H,j,z,G={dlsErrorAndCacheExpire:"Failed to connect to the Dynamsoft License Server. The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:"Failed to connect to the Dynamsoft License Server: network timed out."+V,networkTimeout:"Failed to connect to the Dynamsoft License Server: network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:"Failed to connect to the Dynamsoft License Server: network connection error."+V,failConnect:"Failed to connect to the Dynamsoft License Server: network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system data and time and try again."},Y=async()=>(W=W||(async()=>{await(async()=>{R||(R=rg)})();{let t=await R.createInstance({name:"dynamjssdkhello"});await t.setItem("dynamjssdkhello","available")}if(m=await R.createInstance({name:"dynamdlsinfo"}),v=b?null:T(T("v2")+String.fromCharCode(P.charCodeAt(P.length/2)+1)+T(P)),!b){try{let t=await m.getItem(v);if(!t){let e=await R.createInstance({name:"dynamltsinfo"});t=await e.getItem(v),t&&await m.setItem(v,t)}t&&([a,p]=JSON.parse(await N(t)))}catch(t){}try{null==a&&(a=F(),m.setItem(v,await U(JSON.stringify([a,null]))))}catch(t){}}})(),W),$=async t=>{j=Date.now(),H||(H=(async()=>{try{let g={pd:e,vm:n,v:i,dt:r||"browser",ed:"javascript",cu:a,ad:P,os:l,fn:h};u&&(g.rmk=u),s&&(-1!=s.indexOf("-")?g.hs=s:g.og=s);let f={};if(p&&!b){let t=await m.getItem(v);t&&([a,p]=JSON.parse(await N(t))),f["lts-time"]=p}d&&(g.sp=d);let x=await Promise.race([(async()=>{let e,i=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");p&&!b&&(m.setItem(v,await U(JSON.stringify([a,i]))),p=i);let n,s="auth/?ext="+encodeURIComponent(T(JSON.stringify(g))),r=!1,l=!1,h=async t=>{if(t&&!t.ok)try{let e=await t.text();if(e){let t=JSON.parse(e);t.errorCode&&(n=t,t.errorCode>100&&t.errorCode<200&&(o=null,r=!0,l=!0))}}catch(t){}};try{e=await S(A[0]+s,{headers:f,cache:t?"reload":"default",mode:"cors",timeout:1e4}),await h(e)}catch(t){}if(!(o||e&&e.ok||r))try{e=await S(A[1]+s,{headers:f,mode:"cors",timeout:3e4})}catch(t){}if(!(o||e&&e.ok||r))try{e=await S(A[0]+s,{headers:f,mode:"cors",timeout:3e4}),await h(e)}catch(t){}n&&151==n.errorCode&&!b&&(m.removeItem(v),m.removeItem(y),a=F(),g.cu=a,p=void 0,s="auth/?ext="+encodeURIComponent(T(JSON.stringify(g))),e=await S(A[0]+s,{headers:f,mode:"cors",timeout:3e4}),await h(e)),(()=>{if(!e||!e.ok){let t;l&&m.setItem(y,""),n?111==n.errorCode?t=n.message:(t=n.message.trim(),t.endsWith(".")||(t+="."),t=c?`An error occurred during authorization: ${t} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${t} Contact the site administrator for more information.`):t=c?G.publicTrialFailConnect:G.failConnect;let e=Error(t);throw n&&n.errorCode&&(e.ltsErrorCode=n.errorCode),e}})();let d=await e.text();try{p||b||(m.setItem(v,await U(JSON.stringify([a,i]))),p=i),m.setItem(y,d)}catch(t){}return d})(),new Promise((t,e)=>{let i;i=c?G.publicTrialNetworkTimeout:G.networkTimeout,setTimeout(()=>e(new Error(i)),o?3e3:15e3)})]);o=x}catch(t){g=t}H=null})()),await H},X=async()=>{z||(z=(async()=>{if(M(a),!o){if(!I)throw k(g.message),g;return}let t={dm:P};_&&(t.bd=!0),t.brtk=!0,t.ls=A[0],s&&(-1!=s.indexOf("-")?t.hs=s:t.og=s),t.cu=a,h&&(t.fn=h),e&&(t.pd=e),i&&(t.v=i),r&&(t.dt=r),l&&(t.os=l),u&&(t.rmk=u),M(o);try{t.ar=o,t.bafc=!!g}catch(t){}M(t);try{await x(t)}catch(t){M("error updl")}await q(),I||(I=!0),z=null})()),await z},q=async()=>{let t=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),e=await C();if(M(e),e&&e<t)throw g?new Error(G.dlsErrorAndCacheExpire):new Error(G.checkLocalTime)},Z=null;const J=new Promise(t=>{Z=()=>{J.isPending=!1,J.isFulfilled=!0,t()}});let K=null,Q=async(t,e)=>(D=D.then(async()=>{try{let i=await f.keys();if(e||(J.isFulfilled?t&&(i=i.filter(e=>e<t)):t&&i.includes(t)?i=[t]:(i=[],M("Unexpected null key"))),!i.length)return;for(let t=0;t<i.length/1e3;++t){let e=i.slice(1e3*t,1e3*(t+1)),n=[];for(let t=0;t<e.length;++t)n.push(await f.getItem(e[t]));if(p=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),!b){let t=await m.getItem(v);t&&([a]=JSON.parse(await N(t))),m.setItem(v,await U(JSON.stringify([a,p])))}try{let t,i,s=A[0]+"verify/v2";p&&!b&&(s+="?ltstime="+encodeURIComponent(p));try{t=S(s,{method:"POST",body:n.join(";"),keepalive:!0})}finally{!J.isFulfilled&&ss&&Z()}try{i=await t}finally{J.isFulfilled||Z()}if(!i.ok)throw new Error("verify failed. Status Code: "+i.status);for(let t=0;t<e.length;++t)await f.removeItem(e[t])}catch(t){throw J.isFulfilled||Z(),L&&(L(t),L=null),t}}O&&O()}catch(t){}}),await D);return{i:async t=>(e=t.pd,i=t.v,n=i.split(".")[0],t.dt&&(r=t.dt),s=t.l||"",l="string"!=typeof t.os?JSON.stringify(t.os):t.os,h=t.fn,"string"==typeof h&&(h=h.substring(0,255)),t.ls&&t.ls.length&&(A=t.ls,1==A.length&&A.push(A[0])),c=!s||"200001"===s||s.startsWith("200001-"),d=t.sp,u=t.rmk,"string"==typeof u&&(u=u.substring(0,255)),t.lf&&(R=t.lf),t.lsu&&(a=b=t.lsu),t.feab&&(B=t.feab),x=t.updl,w=t.mnet,C=t.mxet,t.sutlcb&&(O=t.sutlcb),await Y(),await(async()=>{y=T(String.fromCharCode(s.charCodeAt(0)+10)+T(e)+T(s)+n+T(""+r)),f=await R.createInstance({name:"dynamdlsuns"+T(T("v2"))+T(String.fromCharCode(s.charCodeAt(0)+10)+T(e)+T(s)+n+T(""+r))});try{o=await m.getItem(y)}catch(t){}})(),await $(),await X(),(!g||g.ltsErrorCode>=102&&g.ltsErrorCode<=120)&&Q(null,!0),{ar:o,cu:a}),c:async()=>{let t=new Date;if(t.getTime()<j+36e4)return;let e=t.kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),i=await w(),n=await C();if(n&&n<e)await $(!0),await X();else if(i&&i<e){let e=new Date(t.getTime());e.setMinutes(t.getMinutes()-6);let i=e.kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");p<i&&$().then(()=>X())}},s:async(t,e,i,n)=>{if(e){try{let t;t=e.startsWith("{")&&e.endsWith("}")?await B(e):e,t?(M("bs "+i),await f.setItem(i,t),M("ss "+i)):M("ept ecpt")}catch(t){}n&&(M("bd "+i),await Q(i,2==n),M("sd "+i)),K&&clearTimeout(K),K=setTimeout(async()=>{await Q()},36e4)}else await Q(i)},p:J,u:async()=>(await Y(),a),caret:q}})(e))}function Ng(){return this.isPublicTrial()?"":$i(this,wg)||$i(this,xg)}function Ug(){const t=[];return t.push(ns.browser),t.push(ns.version.toString()),t.push(ns.OS),t.join(" ")}async function Fg(t){if(this.getAuthResult()&&this.getClientUUID())return{ar:this.getAuthResult(),cu:this.getClientUUID()};const e={pd:"ddv",dt:"browser",v:mg,os:sn(this,Rg,Ug).call(this),l:sn(this,Dg,Ng).call(this),ls:$i(this,_g),sp:$i(this,Eg),fn:t||"",mnet(){},mxet(){}};""!==this.getClientUUID()&&(e.lsu=this.getClientUUID()),e.updateLicense=t=>{this.setAuthResult(t.ar),this.getClientUUID()||this.setClientUUID(t.cu)};const i=await $i(this,Sg).i(e);return this.getAuthResult()||this.setAuthResult(i.ar),this.getClientUUID()||this.setClientUUID(i.cu),i}const Vg={scrollToLatest:!1};class Wg{constructor(t){Yi(this,"viewerUids",void 0),Yi(this,"groupUid",void 0),Yi(this,"config",void 0),Yi(this,"isSetScrollToLatest",!1),this.groupUid=t,this.viewerUids=new Set,this.config=_s(Vg)}getViewerUids(){return[...this.viewerUids.values()]}updateConfig(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this.config,t)}}var Hg,jg;!function(t){t.LEFT="left",t.TOP="top",t.RIGHT="right",t.BOTTOM="bottom"}(Hg||(Hg={})),function(t){t.DEFAULT="default",t.CAPTURE="capture",t.PERSPECTIVE="perspective",t.THUMBNAIL="thumbnail"}(jg||(jg={}));class zg{constructor(){Yi(this,"db",void 0),this.db=new Map}async set(t,e){return new Promise((i,n)=>{this.db.has(t)?n(new Error(`The item ${t} already exists.`)):(this.db.set(t,e),i(`Save ${t} to database successful.`))})}async get(t){return new Promise((e,i)=>{this.db.has(t)?e(this.db.get(t)):i(new Error(`The item ${t} does not exist.`))})}async remove(t){return new Promise((e,i)=>{const n=this.db.get(t);this.db.delete(t),e(n)})}async update(t,e){return new Promise((i,n)=>{this.db.has(t)?(this.db.set(t,e),i(`Update ${t} successful.`)):n(new Error(`The item ${t} does not exist.`))})}dispose(){this.db.clear()}reset(){this.db.clear()}}class Gg extends Wo{constructor(){super(),Yi(this,"openDocument",void 0),Yi(this,"closeDocument",void 0),Yi(this,"syncDocument",void 0),Yi(this,"addPagesToDoc",void 0),Yi(this,"deletePages",void 0),Yi(this,"updatePage",void 0),Yi(this,"reorderPages",void 0),Yi(this,"movePages",void 0),Yi(this,"swapPages",void 0),Yi(this,"selectedPageChanged",void 0),Yi(this,"pageChanged",void 0),Yi(this,"pageChangedAfterRender",void 0),Yi(this,"pageExistenceChanged",void 0),Yi(this,"currentPageChanged",void 0),Yi(this,"currentIndexChanged",void 0),Yi(this,"pageRendered",void 0),Yi(this,"pagesDropped",void 0),Yi(this,"pagesDragged",void 0),Yi(this,"tabChanged",void 0),Yi(this,"displayModeChanged",void 0),Yi(this,"fitModeChanged",void 0),Yi(this,"filterChanged",void 0),Yi(this,"toolModeChanged",void 0),Yi(this,"zoomChanged",void 0),Yi(this,"visibleChanged",void 0),Yi(this,"beforeLayout",void 0),Yi(this,"afterLayout",void 0),Yi(this,"beforeRender",void 0),Yi(this,"afterRender",void 0),Yi(this,"destroy",void 0),Yi(this,"resize",void 0),Yi(this,"scroll",void 0),Yi(this,"uiInitCompleted",void 0),Yi(this,"cropRectDrawn",void 0),Yi(this,"cropRectDeleted",void 0),Yi(this,"cropRectModified",void 0),Yi(this,"cropModeChanged",void 0),Yi(this,"beforeCropPages",void 0),Yi(this,"afterCropPages",void 0),Yi(this,"operationsChanged",void 0),Yi(this,"perspectiveQuadChanged",void 0),Yi(this,"quadSelectionStyleChanged",void 0),Yi(this,"autoCaptureChanged",void 0),Yi(this,"autoDetectChanged",void 0),Yi(this,"torchChanged",void 0),Yi(this,"cameraPlayed",void 0),Yi(this,"cameraClosed",void 0),Yi(this,"cameraInit",void 0),Yi(this,"cameraChanged",void 0),Yi(this,"cameraCaptured",void 0),Yi(this,"annotationsUpdated",void 0),Yi(this,"annotationModeChanged",void 0),Yi(this,"annotationDefaultStyleChanged",void 0),Yi(this,"selectedAnnotationsChanged",void 0),Yi(this,"annotationLayerStateChanged",void 0),Yi(this,"beforeAnnotationEdit",void 0),Yi(this,"afterAnnotationEdit",void 0),Yi(this,"beforeAnnotationDraw",void 0),Yi(this,"afterAnnotationDraw",void 0),Yi(this,"annotationTextCharsSelected",void 0),Yi(this,"annotationTextContentUpdated",void 0),Yi(this,"annotationTextEditorResized",void 0),Yi(this,"searchTextChanged",void 0),Yi(this,"searchTextSelected",void 0),Yi(this,"searchTextCleared",void 0),Yi(this,"textSelected",void 0),Yi(this,"beforeTextSelected",void 0),Yi(this,"afterTextSelected",void 0),Yi(this,"layoutReason",void 0),Yi(this,"renderReason",void 0),this.openDocument=jo(this),this.closeDocument=jo(this),this.syncDocument=jo(this),this.addPagesToDoc=jo(this),this.deletePages=jo(this),this.updatePage=jo(this),this.reorderPages=jo(this),this.movePages=jo(this),this.swapPages=jo(this),this.selectedPageChanged=jo(this),this.pageChanged=jo(this),this.pageChangedAfterRender=jo(this),this.pageExistenceChanged=jo(this),this.currentPageChanged=jo(this),this.currentIndexChanged=jo(this),this.pageRendered=jo(this),this.pagesDragged=jo(this),this.pagesDropped=jo(this),this.tabChanged=jo(this),this.displayModeChanged=jo(this),this.fitModeChanged=jo(this),this.filterChanged=jo(this),this.toolModeChanged=jo(this),this.zoomChanged=jo(this),this.visibleChanged=jo(this),this.cropModeChanged=jo(this),this.beforeLayout=jo(this),this.afterLayout=jo(this),this.beforeRender=jo(this),this.afterRender=jo(this),this.resize=jo(this),this.scroll=jo(this),this.uiInitCompleted=jo(this),this.destroy=jo(this),this.cropRectDrawn=jo(this),this.cropRectDeleted=jo(this),this.cropRectModified=jo(this),this.cropModeChanged=jo(this),this.beforeCropPages=jo(this),this.afterCropPages=jo(this),this.operationsChanged=jo(this),this.perspectiveQuadChanged=jo(this),this.quadSelectionStyleChanged=jo(this),this.autoCaptureChanged=jo(this),this.autoDetectChanged=jo(this),this.torchChanged=jo(this),this.cameraPlayed=jo(this),this.cameraClosed=jo(this),this.cameraInit=jo(this),this.cameraChanged=jo(this),this.cameraCaptured=jo(this),this.annotationModeChanged=jo(this),this.selectedAnnotationsChanged=jo(this),this.annotationLayerStateChanged=jo(this),this.annotationDefaultStyleChanged=jo(this),this.beforeAnnotationEdit=jo(this),this.afterAnnotationEdit=jo(this),this.beforeAnnotationDraw=jo(this),this.afterAnnotationDraw=jo(this),this.annotationsUpdated=jo(this),this.annotationTextCharsSelected=jo(this),this.annotationTextContentUpdated=jo(this),this.annotationTextEditorResized=jo(this),this.searchTextChanged=jo(this),this.searchTextSelected=jo(this),this.searchTextCleared=jo(this),this.textSelected=jo(this),this.beforeTextSelected=jo(this),this.afterTextSelected=jo(this),this.layoutReason=jo(this),this.renderReason=jo(this)}}class Yg{static numberArrayIsValid(t,e,i,n,s){return Ki(this,Yg,$g).call(this,t,1,e,i,s,n)}static stringArrayIsValid(t,e){return Ki(this,Yg,$g).call(this,t,2,void 0,void 0,0,e)}static blobArrayIsValid(t,e){return Ki(this,Yg,$g).call(this,t,4,void 0,void 0,void 0,e)}static quadIsValid(t,e){const i=[],n="Quad";Ki(this,Yg,Jg).call(this,i,t,6,Ki(this,Yg,qg).call(this,n,e,void 0),4);let s=0;for(const o of t){const t=`[${s}]`;i.push(...Ki(this,Yg,$g).call(this,o,1,void 0,void 0,2,Ki(this,Yg,qg).call(this,n,e,t,!0))),s+=1}return i}static docDetectConfigIsValid(t,e){const i=[],n="DocumentDetectConfig";return Ki(this,Yg,Jg).call(this,i,t,5,Ki(this,Yg,qg).call(this,n,e)),Ki(this,Yg,Jg).call(this,i,t.autoCaptureDelay,1,Ki(this,Yg,qg).call(this,n,e,"autoCaptureDelay")),Ps(t.acceptedPolygonConfidence)||Ki(this,Yg,Jg).call(this,i,t.acceptedPolygonConfidence,1,Ki(this,Yg,qg).call(this,n,e,"acceptedPolygonConfidence")),Ps(t.enableAutoCapture)||Ki(this,Yg,Jg).call(this,i,t.enableAutoCapture,3,Ki(this,Yg,qg).call(this,n,e,"enableAutoCapture")),i}static docDetectConfIsValid(t,e){const i=[],n="DocumentDetectConfidence";return Ki(this,Yg,Jg).call(this,i,t,5,Ki(this,Yg,qg).call(this,n,e)),Ki(this,Yg,Jg).call(this,i,t.angleConfidence,1,Ki(this,Yg,qg).call(this,n,e,"angleConfidence"),0,100),Ki(this,Yg,Jg).call(this,i,t.areaConfidence,1,Ki(this,Yg,qg).call(this,n,e,"areaConfidence"),0,100),Ki(this,Yg,Jg).call(this,i,t.centerConfidence,1,Ki(this,Yg,qg).call(this,n,e,"centerConfidence"),0,100),i}static imageDataIsValid(t,e){const i=[],n="VImageData";return Ki(this,Yg,Jg).call(this,i,t,5,Ki(this,Yg,qg).call(this,n,e)),Ki(this,Yg,Jg).call(this,i,t.data,8,Ki(this,Yg,qg).call(this,n,e,"data")),Ki(this,Yg,Jg).call(this,i,t.type,9,Ki(this,Yg,qg).call(this,n,e,"type")),Ps(t.height)||Ki(this,Yg,Jg).call(this,i,t.height,1,Ki(this,Yg,qg).call(this,n,e,"height")),Ps(t.width)||Ki(this,Yg,Jg).call(this,i,t.width,1,Ki(this,Yg,qg).call(this,n,e,"width")),i}static filterTypeIsValid(t,e){const i=[];return Ki(this,Yg,Jg).call(this,i,t,10,Ki(this,Yg,qg).call(this,"EnumImageFilterType",e)),i}static imageEncodeOptionIsValid(t,e){const i=[],n="ImageEncodeOption";return Ki(this,Yg,Jg).call(this,i,t,5,Ki(this,Yg,qg).call(this,n,e)),Ki(this,Yg,Jg).call(this,i,t.type,9,Ki(this,Yg,qg).call(this,n,e,"type")),Ps(t.params)||Ki(this,Yg,Jg).call(this,i,t.params,5,Ki(this,Yg,qg).call(this,n,e,"params")),i}static makeSureNumberValid(t,e,i,n,s,o){return Ki(this,Yg,Xg).call(this,Ki(this,Yg,lf).call(this,t,e,i),n,s,o)}static makeSureStringValid(t,e,i,n){return Ki(this,Yg,Xg).call(this,{isValid:Ki(this,Yg,hf).call(this,t)},e,i,n)}static makeSureDetectResultValid(t,e,i,n){const s=[],o="DetectResult";Ki(this,Yg,Jg).call(this,s,t,5,Ki(this,Yg,qg).call(this,o,n)),s.push(...Yg.quadIsValid(null==t?void 0:t.location,o)),Ki(this,Yg,Jg).call(this,s,null==t?void 0:t.width,1,Ki(this,Yg,qg).call(this,o,n,"width"),1,void 0),Ki(this,Yg,Jg).call(this,s,null==t?void 0:t.height,1,Ki(this,Yg,qg).call(this,o,n,"height"),1,void 0),s.push(...Yg.docDetectConfigIsValid(null==t?void 0:t.config,o)),null!=t&&t.confidence&&Ki(this,Yg,Jg).call(this,s,t.confidence,1,Ki(this,Yg,qg).call(this,o,n,"confidence")),this.makeSureValid(s,e,i)}static makeSureValid(t,e,i,n){0!==t.length&&Ki(this,Yg,Zg).call(this,t,e,i,n)}static makeSureMissing(t,e,i){Ps(t)&&Ki(this,Yg,Zg).call(this,void 0,e,i,pp.PARAM_MISS)}static makeSureCameraObject(t,e,i){const n=[],s=i;this.makeSureMissing(t,e,i),Os(t)?this.makeSureStringValid(t,e,i):(Ki(this,Yg,Jg).call(this,n,t,5,Ki(this,Yg,qg).call(this,s)),Ki(this,Yg,Jg).call(this,n,t.deviceId,2,Ki(this,Yg,qg).call(this,s,void 0,"deviceId")),Ki(this,Yg,Jg).call(this,n,t.label,2,Ki(this,Yg,qg).call(this,s,void 0,"label")),this.makeSureValid(n,e,i))}static initTypeCheckMap(){Zi(this,Yg,uf)[7]=Is,Zi(this,Yg,uf)[15]=Os,Zi(this,Yg,uf)[3]=Rs,Zi(this,Yg,uf)[5]=Es,Zi(this,Yg,uf)[4]=Ds,Zi(this,Yg,uf)[2]=Ki(this,Yg,hf),Zi(this,Yg,uf)[8]=Ki(this,Yg,Qg),Zi(this,Yg,uf)[11]=Ki(this,Yg,sf),Zi(this,Yg,uf)[12]=Ki(this,Yg,of),Zi(this,Yg,uf)[13]=Ki(this,Yg,rf),Zi(this,Yg,uf)[14]=Ki(this,Yg,af),Zi(this,Yg,uf)[1]=Ki(this,Yg,lf),Zi(this,Yg,uf)[6]=Ki(this,Yg,tf),Zi(this,Yg,uf)[9]=Ki(this,Yg,ef),Zi(this,Yg,uf)[10]=Ki(this,Yg,nf),Zi(this,Yg,uf)[16]=Ki(this,Yg,cf)}}function $g(t,e,i,n,s,o){const r=[],a="Array";if(Ki(this,yg,Jg).call(this,r,t,6,Ki(this,yg,qg).call(this,a,o),s),r.length>0)return r;let l=0;for(const s of t){const t=`[${l}]`;Ki(this,yg,Jg).call(this,r,s,e,Ki(this,yg,qg).call(this,a,o,t,!0),i,n),l+=1}return r}function Xg(t,e,i,n){const{isValid:s,isInRange:o,isSupported:r}=t,a=!!Ps(s)||s,l=!!Ps(o)||o,h=!!Ps(r)||r;a&&l&&h||(n||(n=a?l?pp.PARAM_NOT_SUPPORT:pp.PARAM_OUT_OF_RANGE:pp.PARAM_INVALID),Ki(this,yg,Zg).call(this,void 0,e,i,n))}function qg(t,e,i,n){return e?i?`${e}${n?"":"."}${i}`:`${e}`:i?`${t}${n?"":"."}${i}`:`${t}`}function Zg(t,e,i,n){const s=Ps(n)?{...pp.PARAM_INVALID}:{...n};t&&(s.details=t),pp.throw(s,e,i)}function Jg(t,e,i,n,s,o){const r=Ki(this,yg,Kg).call(this,e,i,n,s,o);r&&t.push(r)}function Kg(t,e,i,n,s){if(Ps(t))return`${i} is missing.`;const o=Zi(this,yg,uf)[e];if(o){const e=o.bind(this)(t,n,s);if(Rs(e)){if(!e)return`${i} is invalid.`}else if(Es(e)){const{isValid:t,isInRange:n,isSupported:s}=e;if(!1===t)return`${i} is invalid.`;if(!1===n)return`${i} is out of range.`;if(!1===s)return`${i} is not supported.`}}}function Qg(t){return Is(t)||Ds(t)}function tf(t,e){return Ts(t)?Ls(e)&&0===t.length||!Ps(e)&&t.length<e?{isValid:!1}:{isValid:!0,isInRange:!!Ps(e)||t.length>=e}:{isValid:!1}}function ef(t){return Ls(t)?{isValid:!0,isInRange:t>=tr.RGBA&&t<=tr.PNG}:{isValid:!1}}function nf(t){return Os(t)?{isValid:!0,isInRange:(e=t,!!ap.get(e))}:{isValid:!1};var e}function sf(t){return void 0!==Mr.get(t)}function of(t){return void 0!==Lr.get(t)}function rf(t){return void 0!==kr.get(t)}function af(t){if(Os(t)){const e=t.trim();return-1!==Zi(this,yg,df).indexOf(e)}return!1}function lf(t,e,i){let n=!0;return Ls(t)?(Ps(e)||(n=t>=e),!Ps(i)&&n&&(n=t<=i),{isValid:!0,isInRange:n}):{isValid:!1}}function hf(t){return!!Os(t)&&0!==t.trim().length}function cf(t){if(!Ki(this,yg,hf).call(this,t))return{isValid:!1};const e=t.match(/^D:(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:([+-])(\d{2})['’](\d{2})['’]|)$/);let i=!1;if(e){const[,t,n,s,o,r,a,l,h,c]=e,d=new Date(`${t}-${n}-${s}T${o}:${r}:${a}`);if(i=!0,d.getFullYear()===parseInt(t,10)&&d.getMonth()+1===parseInt(n,10)&&d.getDate()===parseInt(s,10)&&d.getHours()===parseInt(o,10)&&d.getMinutes()===parseInt(r,10)&&d.getSeconds()===parseInt(a,10)||(i=!1),i&&l){const t=parseInt(h,10),e=parseInt(c,10);("+"===l&&(t<0||t>12||e<0||e>59)||"-"===l&&(t<0||t>12||e<0||e>59))&&(i=!1)}}return{isSupported:i}}yg=Yg;var df={value:["1.1","1.2","1.3","1.4","1.5","1.6","1.7"]},uf={value:Object.create(null)};Yg.initTypeCheckMap();class pf{constructor(t){Yi(this,"maxConcurrency",void 0),Yi(this,"currentConcurrency",void 0),Yi(this,"queue",void 0),this.maxConcurrency=t,this.currentConcurrency=0,this.queue=[]}async acquire(){return new Promise(t=>{this.currentConcurrency<this.maxConcurrency?(this.currentConcurrency+=1,t(!0)):this.queue.push(t)})}release(){this.queue.length>0?this.queue.shift()():this.currentConcurrency-=1}}class gf{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;Yi(this,"tasks",void 0),Yi(this,"semaphore",void 0),this.tasks=[],this.semaphore=new pf(t)}async process(t){await this.semaphore.acquire();let e=null;try{t.cancelled||(e=await this.handler(t.taskUid))}catch(t){e=null}if(t.completed=!0,this.tasks.includes(t)){const e=this.tasks.indexOf(t);this.tasks.splice(e,1)}t.emitter.emit(t.taskUid,e),this.semaphore.release()}async executeTask(t){return new Promise((e,i)=>{let n=this.tasks.find(e=>e.taskUid===t);n||(n={taskUid:t,emitter:new Ws,completed:!1,cancelled:!1,running:!1},this.tasks.push(n)),n.cancelled=!1,n.emitter.on(t,t=>{e(t)}),n.running||(n.running=!0,this.process(n))})}cancel(t){const e=this.tasks.find(e=>e.taskUid===t);e&&(e.cancelled=!0)}destroy(){this.tasks=[]}async handler(t){return Promise.resolve(null)}}class ff extends gf{async handler(t){return new Promise((e,i)=>{const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>{n.onload=null,n.onerror=null,e(n)},n.onerror=t=>{n.onload=null,n.onerror=null,e(null)},n.src=t})}}class mf extends ff{constructor(t,e){super(),Yi(this,"core",void 0),Yi(this,"imageLoader",void 0),this.core=t,this.imageLoader=e}async handler(t){let e=this.core.pageService.getPage(t);if(!e||e.isDestroyed)return null;let{img:i}=e.raw;if(!i){let{url:n}=e.raw;if(!n){let i=e.raw.data;if(!i){let n=await this.core.imageDataService.getRaw(t);const s=this.core.pageService.getPage(t);if(!s)return null;if(e.isDestroyed&&!s.isDestroyed&&(n=await this.core.imageDataService.getRaw(t,!0)),!n||s.isDestroyed)return null;i=n.data}n=URL.createObjectURL(i),e.raw.url=n}if(i=await this.imageLoader.executeTask(n),e=this.core.pageService.getPage(t),!e||e.isDestroyed)return null;e.raw.img=i}return i}}class vf extends ff{constructor(t,e){super(),Yi(this,"core",void 0),Yi(this,"imageLoader",void 0),this.core=t,this.imageLoader=e}async handler(t){var e;let i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;let n=null===(e=i.original)||void 0===e?void 0:e.img;if(!n){var s;let e=null===(s=i.original)||void 0===s?void 0:s.url;if(!e){var o;let n=null===(o=i.original)||void 0===o?void 0:o.data;if(!n){let e=await this.core.imageDataService.getOriginal(t);const s=this.core.pageService.getPage(t);if(!s)return null;if(i.isDestroyed&&!s.isDestroyed&&(e=await this.core.imageDataService.getRaw(t,!0)),!e||s.isDestroyed)return null;n=e.data}e=URL.createObjectURL(n),i.original.url=e}if(n=await this.imageLoader.executeTask(e),i=this.core.pageService.getPage(t),!i||i.isDestroyed)return null;i.original.img=n}return n}}class yf extends ff{constructor(t,e){super(),Yi(this,"core",void 0),Yi(this,"imageLoader",void 0),this.core=t,this.imageLoader=e}async handler(t){var e;let i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;let n=null===(e=i.display)||void 0===e?void 0:e.img;if(!n){var s;let e=null===(s=i.display)||void 0===s?void 0:s.url;if(!e){var o;let n=null===(o=i.display)||void 0===o?void 0:o.data;if(!n){let e=await this.core.imageDataService.getDisplay(t,!0);const s=this.core.pageService.getPage(t);if(!s)return null;if(i.isDestroyed&&!s.isDestroyed&&(e=await this.core.imageDataService.getDisplay(t,!0)),!e||s.isDestroyed)return null;n=e.data}e=URL.createObjectURL(n),i.display.url=e}const{filter:r}=i;if(n=await this.imageLoader.executeTask(e),i=this.core.pageService.getPage(t),!i||i.isDestroyed)return null;if(r!==i.filter)return this.handler(i.uid);i.display.img=n}return n}}class xf extends ff{constructor(t,e){super(),Yi(this,"core",void 0),Yi(this,"imageLoader",void 0),this.core=t,this.imageLoader=e}async handler(t){var e;let i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;let n=null===(e=i.thumbnail)||void 0===e?void 0:e.img;if(!n){var s;let e=null===(s=i.thumbnail)||void 0===s?void 0:s.url;if(!e){var o;let n=null===(o=i.thumbnail)||void 0===o?void 0:o.data;if(!n){const e=await this.core.imageDataService.getThumbnail(t);if(i=this.core.pageService.getPage(t),!e||i.isDestroyed)return null;n=e.data}e=URL.createObjectURL(n),i.thumbnail.url=e}if(n=await this.imageLoader.executeTask(e),i=this.core.pageService.getPage(t),i.isDestroyed)return null;i.thumbnail.img=n}return n}}class wf{constructor(t){Yi(this,"rawImageLoader",void 0),Yi(this,"originalImageLoader",void 0),Yi(this,"displayImageLoader",void 0),Yi(this,"thumbnailImageLoader",void 0);const e=new ff;this.rawImageLoader=new mf(t,e),this.originalImageLoader=new vf(t,e),this.displayImageLoader=new yf(t,e),this.thumbnailImageLoader=new xf(t,e)}async loadRawImage(t){return this.rawImageLoader.executeTask(t)}cancelLoadRawImage(t){this.rawImageLoader.cancel(t)}async loadOriginalImage(t){return this.originalImageLoader.executeTask(t)}cancelLoadOriginalImage(t){this.originalImageLoader.cancel(t)}async loadDisplayImage(t){return this.displayImageLoader.executeTask(t)}cancelLoadDisplayImage(t){this.displayImageLoader.cancel(t)}async loadThumbnailImage(t){return this.thumbnailImageLoader.executeTask(t)}cancelLoadThumbnailImage(t){this.thumbnailImageLoader.cancel(t)}}class Cf{constructor(t,e,i){Yi(this,"worker",void 0),Yi(this,"id",void 0),Yi(this,"manager",void 0),Yi(this,"callbacks",{}),Yi(this,"busy",!1),Yi(this,"counter",0),Yi(this,"tasks",[]),this.worker=t,this.id=e,this.manager=i,this.worker.addEventListener("message",t=>{this.onMessage(t)},!1)}cancel(t){t.forEach(t=>{const e=this.tasks.findIndex(e=>e.taskUid===t);if(e>=0){const t=this.tasks.splice(e,1)[0];this.callbacks[t.callbackId]&&delete this.callbacks[t.callbackId]}})}setBusy(t){if(this.busy=t,!t)if(this.tasks.length){const t=this.tasks.shift();this.send(t)}else this.worker.terminate(),this.manager.removeActor(this)}isBusy(){return this.busy}getWorker(){return this.worker}onMessage(t){this.setBusy(!1);const{callbackId:e}=t.data,i=e?this.callbacks[e]:null;i&&i(t.data),delete this.callbacks[e]}send(t,e){if(this.busy)return void this.tasks.push({...t});this.setBusy(!0);const i=`${this.id}-${t.action}-cb-${this.counter}`;t.callback&&(this.callbacks[i]=t.callback,this.counter+=1),t.callbackId=i;const n=t.handler(),s={taskUid:t.taskUid,callbackId:i,...n};(e=s.source)?this.worker.postMessage(s,[e.data.buffer]):this.worker.postMessage(s)}}class bf{constructor(t,e){Yi(this,"concurrency",1),Yi(this,"actors",[]),Yi(this,"workerUrl",void 0),this.workerUrl=t,this.concurrency=e}send(t,e){this.getActor().send(t,e)}getActor(){const t=this.actors.filter(t=>!t.isBusy())[0];if(t)return t;if(this.actors.length<this.concurrency){const t=new Worker(this.workerUrl),e=new Cf(t,this.actors.length,this);return this.actors.push(e),e}const e=Math.floor(Math.random()*this.concurrency);return this.actors[e]}removeActor(t){const e=this.actors.indexOf(t);this.actors.splice(e,1)}cancel(t){for(const e of this.actors)e.cancel(t);for(const t of this.actors)t.setBusy(!1)}clear(){for(const t of this.actors)t.getWorker().terminate();this.actors=[]}}function Sf(){onmessage=t=>{const{index:e}=t.data,i=t.data.sourceWidth,n=t.data.sourceHeight,s=t.data.width,o=t.data.height,r=t.data.source.data,a=s*o*4,l=new ArrayBuffer(a);let h=null;try{h=new Uint8ClampedArray(l,0,a)}catch(t){h=new Uint8Array(l,0,a)}for(let t=0;t<o;t++){const e=t*n/o,a=Math.floor(e),l=1-(e-a),c=a,d=(t+1)*n/o,u=Math.floor(d-1e-5),p=d-u,g=u;let f=t*s*4;for(let t=0;t<s;t++){const e=t*i/s,n=Math.floor(e),o=1-(e-n),a=n,d=(t+1)*i/s,u=Math.floor(d-1e-5),m=d-u,v=u;let y=0,x=0,w=0,C=0,b=0;const S=255;let T,E,_=(c+1)*i*4+4*a;for(T=c+1;T<g;++T){const t=S;y+=r[_+2]*o*t,x+=r[_+1]*o*t,w+=r[_]*o*t,C+=r[_+3]*o*t,b+=S*o,_+=4*i}let P=(c+1)*i*4+4*v;for(T=c+1;T<g;++T){const t=S;y+=r[P+2]*m*t,x+=r[P+1]*m*t,w+=r[P]*m*t,C+=r[P+3]*m*t,b+=S*m,P+=4*i}let A=c*i*4+4*(a+1);for(E=a+1;E<v;++E){const t=S;y+=r[A+2]*l*t,x+=r[A+1]*l*t,w+=r[A]*l*t,C+=r[A+3]*l*t,b+=S*l,A+=4}let I=g*i*4+4*(a+1);for(E=a+1;E<v;++E){const t=S;y+=r[I+2]*p*t,x+=r[I+1]*p*t,w+=r[I]*p*t,C+=r[I+3]*p*t,b+=S*p,I+=4}for(T=c+1;T<g;++T){let t=T*i*4+4*(a+1);for(E=a+1;E<v;++E){const e=S;y+=r[t+2]*e,x+=r[t+1]*e,w+=r[t]*e,C+=r[t+3]*e,b+=e,t+=4}}let D=c*i*4+4*a;const R=S;y+=r[D+2]*(l*o)*R,x+=r[D+1]*(l*o)*R,w+=r[D]*(l*o)*R,C+=r[D+3]*(l*o)*R,b+=S*(l*o),D=c*i*4+4*v;const k=S;y+=r[D+2]*(l*m)*k,x+=r[D+1]*(l*m)*k,w+=r[D]*(l*m)*k,C+=r[D+3]*(l*m)*k,b+=S*(l*m),D=g*i*4+4*a;const M=S;y+=r[D+2]*(p*o)*M,x+=r[D+1]*(p*o)*M,w+=r[D]*(p*o)*M,C+=r[D+3]*(p*o)*M,b+=S*(p*o),D=g*i*4+4*v;const L=S;y+=r[D+2]*(p*m)*L,x+=r[D+1]*(p*m)*L,w+=r[D]*(p*m)*L,C+=r[D+3]*(p*m)*L,b+=S*(p*m);let O=C/b,B=0,N=0,U=0;0!==O&&(B=y/b,N=x/b,U=w/b),B+=.5,N+=.5,U+=.5,O+=.5,h[f]=Math.floor(U),f+=1,h[f]=Math.floor(N),f+=1,h[f]=Math.floor(B),f+=1,h[f]=Math.floor(O),f+=1}}let c={index:e,target:h,taskUid:t.data.taskUid,callbackId:t.data.callbackId};try{postMessage(c,[h.buffer])}catch(t){postMessage(c,null)}c=null,h=null,t=null}}let Tf=class{constructor(){Yi(this,"actorSystem",void 0),Yi(this,"concurrency",3);const t=window.URL.createObjectURL(new Blob(["(",Sf.toString(),")()"],{type:"text/plain"}));this.actorSystem=new bf(t,this.concurrency)}cancel(t){this.actorSystem.cancel(t)}optimize(t,e){return new Promise((i,n)=>{const s={taskUid:t,action:"optimize",handler:e,callback(t){i(t)}};this.actorSystem.send(s)})}};class Ef{constructor(){}reset(){}async perspectivePreview(t,e,i,n){var s,o,r;let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const l=new lr,h=await l.initImage({source:t,isRGBA:e===tr.RGBA,width:n.width,height:n.height,isBGRA:e===tr.BGRA});h.srcBuffer&&(t=h.srcBuffer);let c=n.width,d=n.height;const u=null!==(s=n.angle)&&void 0!==s?s:0;90!==u&&270!==u||(c=n.height,d=n.width);const p=Math.min((null!==(o=a.width)&&void 0!==o?o:c)/c,(null!==(r=a.height)&&void 0!==r?r:d)/d),g=Math.floor(c*p+.5),f=Math.floor(d*p+.5);await l.resize(g,f,a.mode),null!=n&&n.angle&&await l.rotate({angle:n.angle});const m=[[Math.floor(i[0][0]*p+.5),Math.floor(i[0][1]*p+.5)],[Math.floor(i[1][0]*p+.5),Math.floor(i[1][1]*p+.5)],[Math.floor(i[2][0]*p+.5),Math.floor(i[2][1]*p+.5)],[Math.floor(i[3][0]*p+.5),Math.floor(i[3][1]*p+.5)]];await l.drawQuadrangle({location:m,strokeColor:a.strokeColor,lineWidth:a.lineWidth});const v=await l.getImage({ifDeleteObject:!0,isRGBA:e===tr.RGBA,returnType:ir.RT_BINARY});await l.freeReservedData();const y={data:new Blob([v.imageData],{type:v.blobType}),width:v.imageWidth,height:v.imageHeight,resolutionX:v.imageXResolution,resolutionY:v.imageYResolution};return l.terminate(),y}async resize(t,e,i,n,s){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const r=new lr,a=await r.initImage({source:t,isRGBA:e===tr.RGBA,width:i,height:n,isBGRA:e===tr.BGRA});if(a.srcBuffer&&(t=a.srcBuffer),s>0){let t=1;t=i>n?i/s:n/s;const e=Math.floor(i/t+.5),a=Math.floor(n/t+.5);await r.resize(e,a,o.mode)}const l=await r.getImage({ifDeleteObject:!0,isRGBA:e===tr.RGBA,returnType:ir.RT_BINARY});await r.freeReservedData();const h={data:new Blob([l.imageData],{type:l.blobType}),width:l.imageWidth,height:l.imageHeight,resolutionX:l.imageXResolution,resolutionY:l.imageYResolution};return r.terminate(),h}}class _f extends jr{static create(t,e,i){return new _f(t,e,i)}constructor(t,e,i){super("renameDocument"),Yi(this,"docUid",void 0),Yi(this,"oldName",void 0),Yi(this,"newName",void 0),this.docUid=t,this.oldName=e,this.newName=i}}class Pf extends jr{static create(t,e){return new Pf(t,e)}constructor(t,e){super("paginationChanged"),Yi(this,"current",void 0),Yi(this,"total",void 0),this.current=t,this.total=e}}class Af extends jr{static create(t,e){return new Af(t,e)}constructor(t,e){super("visibleChanged"),Yi(this,"newVisibility",void 0),Yi(this,"oldVisibility",void 0),this.newVisibility=t,this.oldVisibility=e}}class If extends jr{static create(t,e,i){return new If(t,e,i)}constructor(t,e,i){super("openDocument"),Yi(this,"doc",void 0),Yi(this,"viewerUid",void 0),Yi(this,"groupUid",void 0),this.doc=t,this.viewerUid=e,this.groupUid=i}}class Df extends jr{static create(t,e,i){return new Df(t,e,i)}constructor(t,e,i){super("closeDocument"),Yi(this,"doc",void 0),Yi(this,"viewerUid",void 0),Yi(this,"groupUid",void 0),this.doc=t,this.viewerUid=e,this.groupUid=i}}class Rf extends jr{static create(t,e,i,n){return new Rf(t,e,i,n)}constructor(t,e,i,n){super("gotoPage"),Yi(this,"docUid",void 0),Yi(this,"groupUid",void 0),Yi(this,"viewerUid",void 0),Yi(this,"index",void 0),this.docUid=t,this.groupUid=e,this.viewerUid=i,this.index=n}}class kf extends jr{static create(t,e,i){return new kf(t,e,i)}constructor(t,e,i){super("filterChanged"),Yi(this,"docUid",void 0),Yi(this,"pageUids",void 0),Yi(this,"filterType",void 0),this.docUid=t,this.pageUids=e,this.filterType=i}}class Mf extends jr{static create(t,e,i,n){return new Mf(t,e,i,n)}constructor(t,e,i,n){super("currentChangedByScroll"),Yi(this,"docUid",void 0),Yi(this,"groupUid",void 0),Yi(this,"viewerUid",void 0),Yi(this,"current",void 0),this.docUid=t,this.groupUid=e,this.viewerUid=i,this.current=n}}class Lf extends jr{static create(t,e,i){return new Lf(t,e,i)}constructor(t,e,i){super("perspectiveQuadChanged"),Yi(this,"newQuad",void 0),Yi(this,"oldQuad",void 0),Yi(this,"isFull",void 0),this.newQuad=t,this.oldQuad=e,this.isFull=i}}class Of extends jr{static create(t,e,i){return new Of(t,e,i)}constructor(t,e,i){super("operationsChanged"),Yi(this,"docUid",void 0),Yi(this,"undo",void 0),Yi(this,"redo",void 0),this.docUid=t,this.undo=e,this.redo=i}}class Bf extends jr{static create(t,e,i,n,s){return new Bf(t,e,i,n,s)}constructor(t,e,i,n,s){super("perspective"),Yi(this,"docUid",void 0),Yi(this,"pageUid",void 0),Yi(this,"quad",void 0),Yi(this,"width",void 0),Yi(this,"height",void 0),this.docUid=t,this.pageUid=e,this.quad=i,this.width=n,this.height=s}}class Nf extends jr{static create(t){return new Nf(t)}constructor(t){super("deleteDocs"),Yi(this,"docUids",void 0),this.docUids=t}}class Uf extends jr{static create(t){return new Uf(t)}constructor(t){super("viewerCreated"),Yi(this,"viewer",void 0),this.viewer=t}}class Ff extends jr{static create(t,e){return new Ff(t,e)}constructor(t,e){super("textSelected"),Yi(this,"text",void 0),Yi(this,"detail",void 0),this.text=t,this.detail=e}}class Vf extends jr{static create(t,e,i,n,s,o,r,a){return new Vf(t,e,i,n,s,o,r,a)}constructor(t,e,i,n,s,o){let r=arguments.length>6&&void 0!==arguments[6]&&arguments[6],a=arguments.length>7&&void 0!==arguments[7]&&arguments[7];super("textSearchChanged"),Yi(this,"text",void 0),Yi(this,"searchConfig",void 0),Yi(this,"searchResults",void 0),Yi(this,"searchUid",void 0),Yi(this,"searchType",void 0),Yi(this,"addedResults",void 0),Yi(this,"isLastPage",void 0),Yi(this,"isEditPages",void 0),this.text=t,this.searchConfig=e,this.searchResults=i,this.searchUid=n,this.searchType=s,this.addedResults=o,this.isLastPage=r,this.isEditPages=a}}class Wf extends jr{static create(t){return new Wf(t)}constructor(t){super("cropRectDeleted"),Yi(this,"rect",void 0),this.rect=t}}class Hf extends jr{static create(t){return new Hf(t)}constructor(t){super("cropRectDrawn"),Yi(this,"rect",void 0),this.rect=t}}class jf extends jr{static create(t,e){return new jf(t,e)}constructor(t,e){super("cropRectModified"),Yi(this,"oldRect",void 0),Yi(this,"newRect",void 0),this.oldRect=t,this.newRect=e}}class zf extends jr{static create(t,e){return new zf(t,e)}constructor(t,e){super("currentIndexChanged"),Yi(this,"oldIndex",void 0),Yi(this,"newIndex",void 0),this.oldIndex=t,this.newIndex=e}}class Gf extends jr{static create(t,e){return new Gf(t,e)}constructor(t,e){super("displayModeChanged"),Yi(this,"oldDisplayMode",void 0),Yi(this,"newDisplayMode",void 0),this.oldDisplayMode=t,this.newDisplayMode=e}}class Yf extends jr{static create(t,e){return new Yf(t,e)}constructor(t,e){super("fitModeChanged"),Yi(this,"oldFitMode",void 0),Yi(this,"newFitMode",void 0),this.oldFitMode=t,this.newFitMode=e}}class $f extends jr{static create(t,e){return new $f(t,e)}constructor(t,e){super("toolModeChanged"),Yi(this,"oldToolMode",void 0),Yi(this,"newToolMode",void 0),this.oldToolMode=t,this.newToolMode=e}}class Xf extends jr{static create(t,e){return new Xf(t,e)}constructor(t,e){super("zoomChanged"),Yi(this,"oldZoomRatio",void 0),Yi(this,"newZoomRatio",void 0),this.oldZoomRatio=t,this.newZoomRatio=e}}class qf extends jr{static create(t,e,i,n){return new qf(t,e,i,n)}constructor(t,e,i,n){super("resized"),Yi(this,"oldWidth",void 0),Yi(this,"oldHeight",void 0),Yi(this,"newWidth",void 0),Yi(this,"newHeight",void 0),this.oldWidth=t,this.oldHeight=e,this.newWidth=i,this.newHeight=n}}class Zf extends jr{static create(t,e){return new Zf(t,e)}constructor(t,e){super("document"),Yi(this,"docUid",void 0),Yi(this,"docName",void 0),this.docUid=t,this.docName=e}}class Jf extends jr{static create(t,e){return new Jf(t,e)}constructor(t,e){super("CropModeChanged"),Yi(this,"oldCropMode",void 0),Yi(this,"newCropMode",void 0),this.oldCropMode=t,this.newCropMode=e}}class Kf extends jr{static create(t){return new Kf(t)}constructor(t){super("captured"),Yi(this,"pageUid",void 0),this.pageUid=t}}class Qf extends jr{static create(t,e){return new Qf(t,e)}constructor(t,e){super("cameraChanged"),Yi(this,"oldDeviceId",void 0),Yi(this,"newDeviceId",void 0),this.oldDeviceId=t,this.newDeviceId=e}}class tm extends jr{static create(t){return new tm(t)}constructor(t){super("autoDetectChanged"),Yi(this,"enableAutoDetect",void 0),this.enableAutoDetect=t}}class em extends jr{static create(t){return new em(t)}constructor(t){super("autoCaptureChanged"),Yi(this,"enableAutoCapture",void 0),this.enableAutoCapture=t}}class im extends jr{static create(t){return new im(t)}constructor(t){super("cameraPlayed"),Yi(this,"resolution",void 0),this.resolution=t}}class nm extends jr{static create(t){return new nm(t)}constructor(t){super("cameraInit"),Yi(this,"enableConvert",void 0),this.enableConvert=t}}class sm extends jr{static create(t){return new sm(t)}constructor(t){super("torchChanged"),Yi(this,"torchState",void 0),this.torchState=t}}class om extends jr{static create(t,e){return new om(t,e)}constructor(t,e){super("annotationModeChanged"),Yi(this,"oldAnnotationMode",void 0),Yi(this,"newAnnotationMode",void 0),this.oldAnnotationMode=t,this.newAnnotationMode=e}}class rm extends jr{static create(t){return new rm(t)}constructor(t){super("annotationLayerStateChanged"),Yi(this,"state",void 0),this.state=t}}class am extends jr{static create(t,e){return new am(t,e)}constructor(t,e){super("annotationsUpdated"),Yi(this,"uids",void 0),Yi(this,"actions",void 0),this.uids=t,this.actions=e}}class lm extends jr{static create(t,e){return new lm(t,e)}constructor(t,e){super("selectedAnnotationsChanged"),Yi(this,"oldAnnotationUids",void 0),Yi(this,"newAnnotationUids",void 0),this.oldAnnotationUids=t,this.newAnnotationUids=e}}class hm extends jr{static create(t,e){return new hm(t,e)}constructor(t,e){super("AnnotationDefaultStyleChangedEvent"),Yi(this,"oldStyle",void 0),Yi(this,"newStyle",void 0),this.oldStyle=t,this.newStyle=e}}class cm extends jr{static create(t,e,i){return new cm(t,e,i)}constructor(t,e,i){super("cropPages"),Yi(this,"docUid",void 0),Yi(this,"rect",void 0),Yi(this,"pageUids",void 0),this.docUid=t,this.rect=e,this.pageUids=i}}class dm extends jr{static create(t,e,i,n){return new dm(t,e,i,n)}constructor(t,e,i,n){super("copyPage"),Yi(this,"pageUid",void 0),Yi(this,"fileUid",void 0),Yi(this,"fileIndex",void 0),Yi(this,"annotations",void 0),this.pageUid=t,this.fileUid=e,this.fileIndex=i,this.annotations=n}}class um extends jr{static create(t,e,i,n){return new um(t,e,i,n)}constructor(t,e,i,n){super("pagePreloadChanged"),Yi(this,"docUid",void 0),Yi(this,"viewerUid",void 0),Yi(this,"viewerMode",void 0),Yi(this,"changes",void 0),this.docUid=t,this.viewerUid=e,this.viewerMode=i,this.changes=n}}class pm extends jr{static create(t){return new pm(t)}constructor(t){super("pageExistenceChanged"),Yi(this,"pageCount",void 0),this.pageCount=t}}class gm extends jr{static create(t,e){return new gm(t,e)}constructor(t,e){super("deletePages"),Yi(this,"pageUids",void 0),Yi(this,"docUid",void 0),this.pageUids=t,this.docUid=e}}class fm extends jr{static create(t,e,i){return new fm(t,e,i)}constructor(t,e,i){super("rotatePages"),Yi(this,"docUid",void 0),Yi(this,"angle",void 0),Yi(this,"pageUids",void 0),this.docUid=t,this.angle=e,this.pageUids=i}}class mm extends jr{static create(t,e,i,n,s){return new mm(t,e,i,n,s)}constructor(t,e,i,n,s){super("selectPages"),Yi(this,"docUid",void 0),Yi(this,"groupUid",void 0),Yi(this,"viewerUid",void 0),Yi(this,"indices",void 0),Yi(this,"pageUids",void 0),this.docUid=t,this.groupUid=e,this.viewerUid=i,this.indices=n,this.pageUids=s}}class vm extends jr{static create(t,e){return new vm(t,e)}constructor(t,e){super("reorderPages"),Yi(this,"docUid",void 0),Yi(this,"indices",void 0),this.docUid=t,this.indices=e}}class ym extends jr{static create(t,e,i){return new ym(t,e,i)}constructor(t,e,i){super("switchPage"),Yi(this,"docUid",void 0),Yi(this,"one",void 0),Yi(this,"another",void 0),this.docUid=t,this.one=e,this.another=i}}class xm extends jr{static create(t,e,i){return new xm(t,e,i)}constructor(t,e,i){super("createPage"),Yi(this,"pageUid",void 0),Yi(this,"fileUid",void 0),Yi(this,"fileIndex",void 0),this.pageUid=t,this.fileUid=e,this.fileIndex=i}}class wm extends jr{static create(t,e){return new wm(t,e)}constructor(t,e){super("pageRendered"),Yi(this,"index",void 0),Yi(this,"pageUid",void 0),this.index=t,this.pageUid=e}}class Cm extends jr{static create(t,e){return new Cm(t,e)}constructor(t,e){super("pagesDragged"),Yi(this,"indices",void 0),Yi(this,"pageUids",void 0),this.indices=t,this.pageUids=e}}class bm extends jr{static create(t,e,i){return new bm(t,e,i)}constructor(t,e,i){super("pagesDropped"),Yi(this,"indicesBefore",void 0),Yi(this,"indicesAfter",void 0),Yi(this,"pageUids",void 0),this.indicesBefore=t,this.indicesAfter=e,this.pageUids=i}}class Sm extends jr{static create(t,e,i,n){return new Sm(t,e,i,n)}constructor(t,e,i,n){super("selectedPagesChanged"),Yi(this,"oldIndices",void 0),Yi(this,"newIndices",void 0),Yi(this,"oldPageUids",void 0),Yi(this,"newPageUids",void 0),this.oldIndices=t,this.newIndices=e,this.oldPageUids=i,this.newPageUids=n}}class Tm extends jr{static create(t,e,i){return new Tm(t,e,i)}constructor(t,e,i){super("pagesAdded"),Yi(this,"docUid",void 0),Yi(this,"indices",void 0),Yi(this,"pageUids",void 0),this.docUid=t,this.indices=e,this.pageUids=i}}class Em extends jr{static create(t,e,i){return new Em(t,e,i)}constructor(t,e,i){super("pagesDeleted"),Yi(this,"docUid",void 0),Yi(this,"pageUids",void 0),Yi(this,"indices",void 0),this.docUid=t,this.pageUids=e,this.indices=i}}class _m extends jr{static create(t,e,i,n){return new _m(t,e,i,n)}constructor(t,e,i,n){super("addPagesToDoc"),Yi(this,"docUid",void 0),Yi(this,"pageUids",void 0),Yi(this,"indices",void 0),Yi(this,"index",void 0),this.docUid=t,this.pageUids=e,this.indices=i,this.index=n}}class Pm extends jr{static create(t,e,i){return new Pm(t,e,i)}constructor(t,e,i){super("updatePage"),Yi(this,"docUid",void 0),Yi(this,"pageUid",void 0),Yi(this,"data",void 0),this.docUid=t,this.pageUid=e,this.data=i}}class Am extends jr{static create(t,e,i){return new Am(t,e,i)}constructor(t,e,i){super("movePages"),Yi(this,"docUid",void 0),Yi(this,"indices",void 0),Yi(this,"insertBeforeIndex",void 0),this.docUid=t,this.indices=e,this.insertBeforeIndex=i}}let Im=0;const Dm=()=>{const t=`doc-${Date.now().toString()}-${Im.toString()}`;return Im+=1,t};function Rm(t){if(t||(t=`D:${As("yyyyMMddhhmmss")}`),/[+-]\d{2}'\d{2}'$/.test(t))return t;const e=-(new Date).getTimezoneOffset();return`${t}${e>=0?"+":"-"}${String(Math.floor(Math.abs(e)/60)).padStart(2,"0")}'${String(Math.abs(e)%60).padStart(2,"0")}'`}class km{constructor(){var t,e;let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Yi(this,"type",void 0),Yi(this,"uid",void 0),Yi(this,"name",void 0),Yi(this,"pages",void 0),Yi(this,"tags",void 0),Yi(this,"creationDate",void 0),Yi(this,"author",void 0),Yi(this,"isDestroyed",void 0),Yi(this,"pageSize",void 0),this.uid=Us(),this.name=null!==(t=i.name)&&void 0!==t?t:Dm(),this.type=i.type||"document",this.pages=[],this.tags=i.tags||[],this.creationDate=Rm(i.creationDate),this.author=null!==(e=i.author)&&void 0!==e?e:"",this.pageSize="none"}dispose(){this.isDestroyed=!0}}class Mm{constructor(){Yi(this,"users",void 0),this.users=[]}addUser(t){this.users.push(t)}deleteUser(t){const e=this.users.indexOf(t);e>-1&&this.users.splice(e,1)}}var Lm;!function(t){t.IMAGE_PNG="image/png",t.IMAGE_JPEG="image/jpeg",t.IMAGE_BMP="image/bmp",t.IMAGE_TIFF="image/tiff",t.IMAGE_JP2="image/jp2",t.APPLICATION_PDF="application/pdf"}(Lm||(Lm={}));class Om{constructor(t){let{uid:e,mime:i,pageCount:n}=t;Yi(this,"uid",void 0),Yi(this,"mime",void 0),Yi(this,"pageCount",void 0),Yi(this,"name",void 0),Yi(this,"count",void 0),Yi(this,"pages",void 0),this.uid=e,this.mime=i,this.count=0,this.pages=[],this.pageCount=n;for(let t=0;t<n;t++){const t=new Mm;this.pages.push(t)}}getPageByIndex(t){return this.pages[t]}addUser(t,e){const i=this.pages[t];return!!i&&(i.addUser(e),this.count+=1,!0)}deleteUser(t,e){const i=this.pages[t];return!!i&&(i.deleteUser(e),this.count-=1,!0)}}function Bm(t,e,i,n){if(0==(e=(e%360+360)%360))return t;const s=e/90;for(let e=0;e<4;e++){const o=t[2*e],r=t[2*e+1];1===s?(t[2*e]=r,t[2*e+1]=n-o):2===s?(t[2*e]=i-o,t[2*e+1]=n-r):3===s&&(t[2*e]=i-r,t[2*e+1]=o)}return Fm(t,8-2*s),t}function Nm(t,e,i,n){if(0==(e=(e%360+360)%360))return t;const s=e/90;for(let e=0;e<4;e++){const o=t[2*e],r=t[2*e+1];1===s?(t[2*e]=n-r,t[2*e+1]=o):2===s?(t[2*e]=i-o,t[2*e+1]=n-r):3===s&&(t[2*e]=r,t[2*e+1]=i-o)}return Fm(t,2*s),t}function Um(t,e,i){for(;e<i;){const n=t[e];t[e]=t[i],t[i]=n,e+=1,i-=1}}function Fm(t,e){const i=e%t.length;0!==i&&(Um(t,0,t.length-1),Um(t,0,i-1),Um(t,i,t.length-1))}const Vm=t=>Array(4).fill(0).map((e,i)=>[t[2*i],t[2*i+1]]),Wm=(t,e,i)=>0===t[0][0]&&0===t[0][1]&&t[1][0]===e&&0===t[1][1]&&t[2][0]===e&&t[2][1]===i&&0===t[3][0]&&t[3][1]===i;class Hm{constructor(t){Yi(this,"data",void 0),Yi(this,"width",void 0),Yi(this,"height",void 0),Yi(this,"url",void 0),Yi(this,"img",void 0),Yi(this,"users",void 0),Yi(this,"isDestroyed",void 0),Yi(this,"isAvailable",void 0),Yi(this,"pageWidth",void 0),Yi(this,"pageHeight",void 0),Yi(this,"docPage",void 0),this.isDestroyed=!1,this.users=[],this.isAvailable=!1,this.docPage=t}getImageDetail(){const{docPage:t}=this;return{data:this.data,width:this.width,height:this.height,pageWidth:this.pageWidth,pageHeight:this.pageHeight,resolutionX:t.resolutionX,resolutionY:t.resolutionY,url:this.url,img:this.img}}getPageSize(){return{width:this.pageWidth,height:this.pageHeight}}updateImageDetail(t){if(!t)return;t.data&&(this.isAvailable=!0,this.data=t.data);const{docPage:e}=this;this.width=t.width,this.height=t.height,this.pageWidth=t.width/e.resolutionX*Cr.displayResolution,this.pageHeight=t.height/e.resolutionY*Cr.displayResolution}addUser(t){this.getUserIndex(t)<0&&this.users.push(t)}deleteUser(t){const e=this.getUserIndex(t);e>-1&&this.users.splice(e,1)}hasUser(){return!!this.users.length}reset(){this.resetBlob(),this.resetImg()}resetBlob(){this.isAvailable=!1,this.data=null,this.url&&URL.revokeObjectURL(this.url),this.url=null}resetImg(){this.img&&(this.img.src&&URL.revokeObjectURL(this.img.src),this.img.src=""),this.img=null}getUserIndex(t){return this.users.findIndex(e=>{let{viewerUid:i,docUid:n,pageUid:s}=e;return i===t.viewerUid&&n===t.docUid&&s===t.pageUid})}dispose(){this.isDestroyed=!0,this.isAvailable=!1,this.reset()}}function jm(t){const e=function(t){[...t].sort((t,e)=>e[1]-t[1]);let e=Number.MAX_SAFE_INTEGER,i=0;t.forEach((t,n)=>{t[1]<e&&([,e]=t,i=n)});const n=(i+3)%4,s=(i+1)%4,o=zm(t[n],t[i]);return zm(t[s],t[i])>o?n:i}(t),i=t.map((e,i)=>{let n=t[i+1];return 3===i&&([n]=t),Gm(n,e)});let n=Math.max(i[e],i[(e+2)%4]),s=Math.max(i[(e+1)%4],i[(e+3)%4]);return n=Math.round(n),s=Math.round(s),{width:n,height:s}}function zm(t,e){const i=Math.abs(t[0]-e[0]),n=Gm(t,e);return Math.acos(i/n)}function Gm(t,e){return((t[0]-e[0])**2+(t[1]-e[1])**2)**.5}const Ym=t=>{t&&t.forEach(t=>{const e=Math.ceil(t[0]);e-t[0]<=1e-7?t[0]=e:t[0]=Math.floor(t[0]);const i=Math.ceil(t[1]);i-t[1]<=1e-7?t[1]=i:t[1]=Math.floor(t[1])})};function $m(t,e,i,n){e=(e%360+360)%360;const s={...t},{left:o,top:r,width:a,height:l}=t,h=Math.floor(e/90);return 1===h?(s.left=n-r-l,s.top=o):2===h?(s.left=i-o-a,s.top=n-r-l):3===h&&(s.left=r,s.top=i-o-a),h%2>0&&(s.width=l,s.height=a),s}function Xm(t,e){return t.left<e.left+e.width&&t.left+t.width>e.left&&t.top<e.top+e.height&&t.top+t.height>e.top}function qm(t,e){return t.x>=e.left&&t.x<=e.left+e.width&&t.y>=e.top&&t.y<=e.top+e.height}var Zm;!function(t){t.NONE="none",t.LTR="ltr",t.RTL="rtl",t.TTB="ttb",t.BTT="btt"}(Zm||(Zm={}));class Jm{constructor(t,e){let{fileIndex:i,pageUid:n,fileUid:s,rotation:o,filter:r,perspectiveQuad:a,annotations:l,pdfOptions:h,resource:c,cropBox:d,mediaBox:u,pageSize:p}=t;Yi(this,"uid",void 0),Yi(this,"doc",void 0),Yi(this,"metadata",void 0),Yi(this,"customData",void 0),Yi(this,"fileUid",void 0),Yi(this,"fileIndex",void 0),Yi(this,"resolutionX",void 0),Yi(this,"resolutionY",void 0),Yi(this,"filter",void 0),Yi(this,"rotation",void 0),Yi(this,"quad",void 0),Yi(this,"activeQuad",void 0),Yi(this,"isFull",void 0),Yi(this,"raw",void 0),Yi(this,"original",void 0),Yi(this,"display",void 0),Yi(this,"thumbnail",void 0),Yi(this,"editedDisplay",void 0),Yi(this,"initRotation",void 0),Yi(this,"editRotation",void 0),Yi(this,"actionRotation",void 0),Yi(this,"actions",void 0),Yi(this,"pActions",void 0),Yi(this,"actionResult",void 0),Yi(this,"pActionResult",void 0),Yi(this,"isDestroyed",void 0),Yi(this,"annotations",void 0),Yi(this,"pageSize",void 0),Yi(this,"cropBox",void 0),Yi(this,"mediaBox",void 0),Yi(this,"resource",void 0),Yi(this,"editCaches",void 0),Yi(this,"pdfOptions",void 0),Yi(this,"initState",void 0),Yi(this,"oriTexts",void 0),Yi(this,"parsedTexts",void 0),Yi(this,"oriTextSegments",void 0),Yi(this,"visibleLines",void 0),Yi(this,"lines",[]),Yi(this,"lineMap",new Map),Yi(this,"charMap",new Map),Yi(this,"textBlocks",void 0),Yi(this,"textRect",void 0),Yi(this,"curTextRect",void 0),Yi(this,"textStr",void 0),Yi(this,"textStrWithoutWrap",void 0),Yi(this,"textStrInSearch",void 0),Yi(this,"isTextPage",!0),Yi(this,"isUpdated",!1),Yi(this,"defaultRenderPage",void 0),Yi(this,"isLoadingDefaultRenderPage",!1),Yi(this,"redaction",[]),Yi(this,"redactionType",void 0),this.uid=n,this.doc=e,this.annotations=l||[],this.resolutionX=c.resolutionX,this.resolutionY=c.resolutionY,this.fileIndex=i,this.fileUid=s,this.pageSize=null!=p?p:"none",this.resource=c,"none"===this.pageSize?(this.mediaBox={...u},this.cropBox={...d}):this.pageSize,this.filter=r,this.rotation=o||0,this.initRotation=o||0,this.editRotation=o||0,this.actionRotation=0,this.isFull=!0,this.pdfOptions=h,this.raw=new Hm(this),this.original=new Hm(this),this.display=new Hm(this),this.thumbnail=new Hm(this),this.editedDisplay=new Hm(this);let g={width:c.width,height:c.height};if(this.raw.updateImageDetail(g),this.initState={mediaBox:this.mediaBox,cropBox:this.cropBox,rotation:o},a){g=jm(a),this.mediaBox={left:0,top:0,width:Bo(g.width,c.resolutionX,Cr.displayResolution),height:Bo(g.height,c.resolutionY,Cr.displayResolution)},this.cropBox={...this.mediaBox};const t=this.quadToDisplayPPI(a);this.setQuad(t)}this.original.updateImageDetail(g),this.display.updateImageDetail(g),this.actions=[],this.pActions=[],this.actionResult=new Map,this.pActionResult=new Map}textStyleEqual(t,e){return!(!t||!e)&&(Math.abs(Math.abs(t.fontSize)-Math.abs(e.fontSize))<1e-4&&t.fontName===e.fontName&&t.fontWeight===e.fontWeight&&t.renderMode===e.renderMode&&t.fillColor[0]===e.fillColor[0]&&t.fillColor[1]===e.fillColor[1]&&t.fillColor[2]===e.fillColor[2]&&t.fillColor[3]===e.fillColor[3]&&t.strokeColor[0]===e.strokeColor[0]&&t.strokeColor[1]===e.strokeColor[1]&&t.strokeColor[2]===e.strokeColor[2]&&t.strokeColor[3]===e.strokeColor[3]&&t.isItalic===e.isItalic&&t.isBold===e.isBold)}isUnicodeWhiteSpace(t){return-1!==[9,11,12,32,10,13,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,0].indexOf(t)}getDirectionFromAngle(t){const e=Math.PI/4,i=Math.PI/2,n=Math.PI,s=Math.PI/2*3,o=(t+e)%(2*Math.PI);return o>=0&&o<=i?Zm.LTR:o>i&&o<=n?Zm.TTB:o>n&&o<=s?Zm.RTL:Zm.BTT}getAngleFromCharBox(t,e){const i=t.left+t.width/2,n=t.top+t.height/2,s=e.left+e.width/2,o=e.top+e.height/2;let r=Math.atan2(o-n,s-i);return r<0&&(r+=2*Math.PI),r}setParsedTexts(t){if(null===t)return void(this.isTextPage=!1);if(this.visibleLines)return;const e=t.charInfos,{top:i,height:n}=this.mediaBox,s=[];let o=0,r=null,a=-1;const l=[],h=[];e.forEach((e,c)=>{const d=Bo(e.looseCharBox,72,Cr.displayResolution),u=d[0],p=d[2],g=2*i+n-d[3],f=2*i+n-d[1],m={uid:Us(),oriLineUid:"",visibleIndex:c,indexInMergeLine:c,indexWithoutWrap:o,indexWithWrap:c,oriIndex:c,unicode:e.unicode,charBox:{left:u,top:g,width:p-u,height:f-g},objId:e.objId};if(s.push(m),this.charMap.set(m.uid,m),this.isUnicodeWhiteSpace(m.unicode))l.length>0&&(13!==e.unicode&&10!==e.unicode&&(l[l.length-1].isWrap?h.push(m):(o+=1,l[l.length-1].chars.push(m))),10===e.unicode&&(l[l.length-1].isWrap=!0));else{let i=!1;if(r===e.objId||this.textStyleEqual(t.textStyleInfos[r],t.textStyleInfos[e.objId]))if(l[l.length-1].charDirection!==this.getDirectionFromAngle(e.angle))i=!0;else{const t=this.getAngleFromCharBox(l[l.length-1].chars[a].charBox,m.charBox);if(a>0){const e=this.getAngleFromCharBox(l[l.length-1].chars[0].charBox,l[l.length-1].chars[a].charBox);l[l.length-1].direction===Zm.NONE&&(l[l.length-1].direction=this.getDirectionFromAngle(e));const n=Math.PI,s=2*Math.PI;let o=Math.abs(t-e)%s;o=o>n?s-o:o,o>Math.PI/2&&(i=!0)}i||Math.sqrt((m.charBox.left-l[l.length-1].chars[a].charBox.left)**2+(m.charBox.top-l[l.length-1].chars[a].charBox.top)**2)>2.5*(Math.abs(Math.cos(t))*l[l.length-1].avgCharSize.width+Math.abs(Math.sin(t))*l[l.length-1].avgCharSize.height)&&(i=!0)}else i=!0;if(i)if(2===m.unicode);else{o+=1;let i=0;t.textStyleInfos[e.objId]&&(i=Bo(t.textStyleInfos[e.objId].fontSize,72,Cr.displayResolution)/3);let n={width:i,height:i},s=1;m.charBox.width>0&&m.charBox.height>0&&(n={width:(n.width*s+m.charBox.width)/(s+1),height:(n.height*s+m.charBox.height)/(s+1)},s+=1),l.push({chars:[m],isWrap:!1,charDirection:this.getDirectionFromAngle(e.angle),direction:Zm.NONE,avgCharSize:n,nonWhitespaceCharsCount:s,textStyle:t.textStyleInfos[e.objId]}),h.splice(0,h.length),a=0}else l[l.length-1].isWrap&&(l[l.length-1].isWrap=!1,h.forEach(t=>{o+=1,l[l.length-1].chars.push(t)}),h.splice(0,h.length)),o+=1,l[l.length-1].avgCharSize={width:(l[l.length-1].avgCharSize.width*l[l.length-1].nonWhitespaceCharsCount+m.charBox.width)/(l[l.length-1].nonWhitespaceCharsCount+1),height:(l[l.length-1].avgCharSize.height*l[l.length-1].nonWhitespaceCharsCount+m.charBox.height)/(l[l.length-1].nonWhitespaceCharsCount+1)},l[l.length-1].nonWhitespaceCharsCount+=1,l[l.length-1].chars.push(m),a=l[l.length-1].chars.length-1;r=e.objId}}),this.parsedTexts=s,this.oriTextSegments=l,this.lines=l.map((t,e)=>{const i=Km(t.chars.map(t=>t.charBox)),n={...i,uid:Us(),index:e,visibleIndex:e,isRow:i.width>i.height,chars:t.chars,right:i.left+i.width,bottom:i.top+i.height,startIndex:0,endIndex:t.chars.length-1,visibleRect:i,isWrap:t.isWrap};return this.lineMap.set(n.uid,n),n.chars.forEach((t,e)=>{t.visibleIndex=e,t.indexInMergeLine=e,t.oriLineUid=n.uid}),n}),this.lines.length&&this.handleCropBoxForText()}handleCropBoxForText(){const{cropBox:t}=this;this.visibleLines=this.lines.filter(e=>Xm(e,t));let e="",i=-1,n=-1,s=-1;this.visibleLines.forEach((o,r)=>{o.visibleIndex=r,o.startIndex=o.chars.findIndex(e=>Xm(e.charBox,t)),o.endIndex=-1;for(let e=o.chars.length-1;e>=0;e--)if(Xm(o.chars[e].charBox,t)){o.endIndex=e;break}const a=o.chars.slice(o.startIndex,o.endIndex+1).map(t=>t.charBox);o.visibleRect=Km(a),o.chars.slice(o.startIndex,o.endIndex+1).forEach((t,o)=>{t.visibleIndex=o;const r=String.fromCharCode(t.unicode);2!==t.unicode&&(e+=r,s+=1),i+=1,n+=1,t.indexWithWrap=i,t.indexWithoutWrap=n,t.indexInSearch=s}),o.isWrap&&(i+=2,e+=" ",s+=1)}),this.textStrInSearch=e;const o=[];let r=this.visibleLines[0],a={lines:[{index:0,line:r}],...r};o.push(a);for(let t=1;t<this.visibleLines.length;t++){const e=this.visibleLines[t],{visibleRect:i}=e;let n=!1;if(e.isRow!==r.isRow?n=!0:r.isRow?(i.left>a.right||i.left+i.width<a.left)&&(n=!0):(i.top>a.bottom||i.top+i.height<a.top)&&(n=!0),n)a={lines:[{index:t,line:e}],...e,...i,right:i.left+i.width,bottom:i.top+i.height},o.push(a);else{a.lines.push({index:t,line:e});const i=Km([e,a]);Object.assign(a,i),a.right=a.left+a.width,a.bottom=a.top+a.height}r=e}this.textBlocks=o,this.textRect=Km(o)}getHoveredTextLineIndex(t){return this.visibleLines?this.visibleLines.findIndex(e=>qm(t,e.visibleRect)):-1}getHoveredTextLineUid(t){const e=this.visibleLines.find(e=>qm(t,e.visibleRect));return null==e?void 0:e.uid}getSelectedTextLineIndex(t,e){const{x:i,y:n}=e;{let t=-1,s=Number.MAX_VALUE;for(let o=0;o<this.visibleLines.length;o++){const r=this.visibleLines[o];for(let a=r.startIndex;a<=r.endIndex;a++){const{charBox:l}=r.chars[a];if(qm(e,l))return o;const h=Math.min(Math.abs(l.top-n),Math.abs(l.top+l.height-n))+Math.min(Math.abs(l.left-i),Math.abs(l.left+l.width-i));h<s&&(s=h,t=o)}}return t}}getSelectedTextCharIndex(t,e){if(!this.visibleLines)return-1;let i=-1;const n=this.visibleLines[t];let s=1/0,o=-1;for(let t=n.startIndex;t<=n.endIndex;t++){const{charBox:r}=n.chars[t];if(qm(e,r)){i=t;break}{let i=0;i=n.isRow?Math.min(Math.abs(r.left-e.x),Math.abs(r.left+r.width-e.x)):Math.min(Math.abs(r.top+r.height-e.y),Math.abs(r.top-e.y)),i<s&&(s=i,o=t)}}return-1===i&&(i=o),i}getSelectedTextWord(t,e){const i=this.visibleLines[t],n=this.getSelectedTextCharIndex(t,e),{startIndex:s,endIndex:o}=i;let r=n,a=n;if(32===i.chars[n].unicode)return null;if(this.isMultipleClickBoundarySelf(i.chars[n].unicode))return{start:{lineUid:i.uid,charUid:i.chars[n].uid},end:{lineUid:i.uid,charUid:i.chars[n].uid}};for(let t=n;t>=s;t--){if(this.isMultipleClickBoundary(i.chars[t].unicode)){r=t+1,t===a&&(r=t);break}r=t}for(let t=n;t<=o;t++){if(this.isMultipleClickBoundary(i.chars[t].unicode)){a=t-1,t===r&&(a=t);break}a=t}return{start:{lineUid:i.uid,charUid:i.chars[r].uid},end:{lineUid:i.uid,charUid:i.chars[a].uid}}}isMultipleClickBoundary(t){return!(t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95===t||!(t<128))}isMultipleClickBoundarySelf(t){return!(t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95===t||32===t||!(t<128))}getSelectedTextSegment(t,e){let i=0,n=this.visibleLines.length-1;const s=this.lines.indexOf(this.visibleLines[t]);if(0!==this.visibleLines[t].startIndex)i=t;else for(let e=t-1;e>=0;e--){const n=this.lines.indexOf(this.visibleLines[e]);if(this.visibleLines[e].isWrap||n+t-e!==s||this.visibleLines[e].endIndex!==this.visibleLines[e].chars.length-1){i=e+1;break}if(0!==this.visibleLines[e].startIndex){i=e;break}}if(this.visibleLines[t].endIndex!==this.visibleLines[t].chars.length-1||this.visibleLines[t].isWrap)n=t;else for(let e=t+1;e<this.visibleLines.length;e++){if(this.lines.indexOf(this.visibleLines[e])!==s+e-t||0!==this.visibleLines[e].startIndex){n=e-1;break}if(this.visibleLines[e].isWrap||this.visibleLines[e].endIndex!==this.visibleLines[e].chars.length-1){n=e;break}}const o=this.visibleLines[i],r=this.visibleLines[n];return{start:{lineUid:o.uid,charUid:o.chars[o.startIndex].uid},end:{lineUid:r.uid,charUid:r.chars[r.endIndex].uid}}}getSelectedTextLine(t,e,i){const n=this.visibleLines[t];let s,o=[],r=!0;void 0===e&&void 0===i?(s={...n.visibleRect},o=n.chars.slice(n.startIndex,n.endIndex+1)):(s=Km(n.chars.slice(e,i+1).map(t=>t.charBox)),o=n.chars.slice(e,i+1),i!==n.endIndex&&(r=!1));let a=o.map(t=>2===t.unicode?"":String.fromCharCode(t.unicode)).join("");return n.isWrap&&r&&(a+="\r\n"),{...n,selectedRect:s,text:a}}rectUnion(t,e){const i=Math.min(t.left,e.left),n=Math.min(t.top,e.top);return{left:i,top:n,width:Math.max(t.left+t.width,e.left+e.width)-i,height:Math.max(t.top+t.height,e.top+e.height)-n}}rectIntersection(t,e){const i=Math.max(t.left,e.left),n=Math.max(t.top,e.top),s=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height);return{left:i,top:n,width:s>i?s-i:0,height:o>n?o-n:0}}getVerticalOverlap(t,e){const i=this.rectUnion(t,e),n=1e-6;return Math.abs(i.height-t.height)<n||Math.abs(i.height-e.height)<n?1:this.rectIntersection(t,e).height/i.height}shouldMergeHorizonLines(t,e){if(0!==e.startIndex)return!1;const i=t.selectedRect,n=e.selectedRect;if(this.getVerticalOverlap(i,n)<.7)return!1;const s=i.width/(t.endIndex-t.startIndex+1)*1,o=n.width/(e.endIndex-e.startIndex+1)*1,r=i.left-s,a=i.left+i.width+s,l=n.left-o;return r<n.left+n.width+o&&a>l}mergeAdjacentLines(t){const e=[];let i=null;for(let n=0;n<t.length;n++){const s=t[n];i?this.shouldMergeHorizonLines(i,s)?(i.chars=[...i.chars,...s.chars],i.text+=s.text,i.endIndex+=s.endIndex+1,i.selectedRect=this.rectUnion(i.selectedRect,s.selectedRect),i.visibleRect=this.rectUnion(i.visibleRect,s.visibleRect),i.left=i.visibleRect.left,i.top=i.visibleRect.top,i.width=i.visibleRect.width,i.height=i.visibleRect.height,i.right=i.visibleRect.left+i.visibleRect.width,i.bottom=i.visibleRect.top+i.visibleRect.height):(e.push(i),i={...s}):i={...s}}return i&&e.push(i),e}doMergeAdjacentLines(t){let e=this.mergeAdjacentLines(t);for(;;){const t=this.mergeAdjacentLines(e);if(t.length===e.length)break;e=t}return e}getSelectedTextLines(t,e){const i=[];for(let n=t.lineIndex;n<=e.lineIndex;n++){const s=this.visibleLines[n];let o=s.startIndex,r=s.endIndex;n===t.lineIndex&&void 0!==t.charIndex&&(o=t.charIndex),n===e.lineIndex&&void 0!==e.charIndex&&(r=e.charIndex);const a=this.getSelectedTextLine(n,o,r);i.push(a)}return this.doMergeAdjacentLines(i)}getSelectedTextsStr(t,e,i){let n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];const s=this.visibleLines[t];let o=[];void 0===e&&void 0===i?o=s.chars.slice(s.startIndex,s.endIndex+1):(o=s.chars.slice(e,i+1),i!==s.endIndex&&(n=!1));let r=o.map(t=>2===t.unicode?"":String.fromCharCode(t.unicode)).join("");return s.isWrap&&n&&(r+="\r\n"),r}getEndCharRect(t,e){const i=this.visibleLines[t].chars[e].charBox;return{...i,top:i.top,height:i.height}}getSearchedText(t){var e;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:50,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:50;if(this.isDestroyed||null===(e=this.visibleLines)||void 0===e||!e.length)return[];const o=[];let r,a=0;for(;null!==r;)if(r=t.exec(this.textStrInSearch),null!==r){let t=r[0],e=r.index;if(i){const[,i,n]=r;t=n,e=r.index+i.length}let l=-1,h=this.visibleLines.findIndex(t=>(l=t.chars.slice(t.startIndex,t.endIndex+1).findIndex(t=>t.indexInSearch===e),l>-1));-1===h&&(h=this.visibleLines.findIndex(t=>(l=t.chars.slice(t.startIndex,t.endIndex+1).findIndex(t=>t.indexInSearch===e+1),l>-1)));let c=-1,d=this.visibleLines.findIndex(i=>(c=i.chars.slice(i.startIndex,i.endIndex+1).findIndex(i=>i.indexInSearch===e+t.length-1),c>-1));if(-1===d&&t.length>1&&(d=this.visibleLines.findIndex(i=>(c=i.chars.slice(i.startIndex,i.endIndex+1).findIndex(i=>i.indexInSearch===e+t.length-2),c>-1))),-1===l||-1===c)continue;const u=this.getSelectedTextLines({lineIndex:h,charIndex:l+this.visibleLines[h].startIndex},{lineIndex:d,charIndex:c+this.visibleLines[d].startIndex}),p=[];for(let t=0;t<u.length;t++){const e=u[t];p.push({lineIndex:h,text:e.text,box:{...e.selectedRect}})}let g=n;if(0===h)l<n&&(g=l);else for(let t=h;t>0;t--){const i=this.visibleLines[t],n=e-i.chars[i.startIndex].indexInSearch;if(n>g)break;if(this.visibleLines[t-1].isWrap){g=n;break}}const f=this.textStrInSearch.substring(Math.max(e-g,0),Math.min(e+t.length+s,this.textStrInSearch.length)),{context:m,startIndex:v}=Qm(f,t,e-g>0?g:e,1,5);o.push({textUid:`${this.uid}_${a}`,pageUid:this.uid,text:t,context:m,startIndex:v,lines:p}),a+=1}return o}isMediaBoxEqualCropBox(){const{mediaBox:t,cropBox:e}=this;return t.left===e.left&&t.top===e.top&&t.width===e.width&&t.height===e.height}getPageSize(){return"inherit"===this.pageSize?this.doc.pageSize:this.pageSize}copy(t,e){const i=new Jm({pageSize:this.getPageSize(),fileIndex:this.fileIndex,pageUid:t,fileUid:this.fileUid,rotation:this.rotation,filter:this.filter,pdfOptions:this.pdfOptions&&_s(this.pdfOptions),mediaBox:_s(this.mediaBox),cropBox:_s(this.cropBox),resource:_s(this.resource),annotations:[]},e),n=_s(this.actions);n.forEach(t=>{t.docUid=e.uid});const s=_s(this.pActions);s.forEach(t=>{t.docUid=e.uid}),i.actions=n,i.pActions=s,i.initRotation=this.initRotation,i.actionRotation=this.actionRotation,i.editRotation=this.editRotation,i.quad=_s(this.quad),i.activeQuad=_s(this.activeQuad),i.isFull=this.isFull,i.actionResult=new Map(this.actionResult),i.pActionResult=new Map(this.pActionResult);const o={width:this.mediaBox.width||this.display.width||i.raw.width,height:this.mediaBox.height||this.display.height||i.raw.height};return i.original.updateImageDetail(o),i.display.updateImageDetail(o),i}setQuad(t){const e=this.isQuadFull(t);let i=!1;if(this.isFull=e,e)this.quad&&(i=!0,this.editRotation=this.rotation),this.quad=null,this.activeQuad=null;else{const{width:e,height:n}=this.raw.getPageSize(),s=Bm(t.flat(),this.rotation,e,n),o=Vm(s);let r,a;this.quad&&(a=this.quadToPixelPPI(o),r=this.quadToPixelPPI(this.quad),Ym(r),Ym(a)),this.quad&&No(r,a)||(this.quad=o,this.activeQuad=o,i=!0),this.editRotation=this.actionRotation}return i&&this.clearActions(),i}isQuadChanged(t){let e=!1;if(this.isQuadFull(t))this.quad&&(e=!0);else{const{width:i,height:n}=this.raw.getPageSize(),s=Bm(t.flat(),this.rotation,i,n),o=Vm(s);let r,a;this.quad&&(a=this.quadToPixelPPI(o),r=this.quadToPixelPPI(this.quad),Ym(r),Ym(a)),this.quad&&No(r,a)||(e=!0)}return e}setActiveQuad(t){const{width:e,height:i}=this.raw.getPageSize();if(!this.isFull){const n=Bm(t.flat(),this.rotation,e,i),s=Vm(n);this.activeQuad=s}}getQuadVertices(){let t;const{width:e,height:i}=this.raw.getPageSize();return t=this.isFull?[0,0,e,0,e,i,0,i]:this.activeQuad.flat(),t=Nm(t,this.rotation,e,i),t}getProcessedQuad(){if(this.quad){let{width:t,height:e}=this.raw.getPageSize(),{quad:i}=this;i=this.quad.map(t=>[this.toPixelPPI(t[0],!1),this.toPixelPPI(t[1],!0)]),t=this.toPixelPPI(t,!1),e=this.toPixelPPI(e,!0);const n=Nm(i.flat(),this.initRotation,t,e);return Vm(n)}return null}toggleFull(){let t=!1;return this.isFull&&this.activeQuad?(this.isFull=!1,t=!0):this.isFull||(this.isFull=!0,t=!0),t}isQuadFull(t){let{width:e,height:i}=this.raw.getPageSize();const n=Math.abs((this.rotation%360+360)%360);if(90===n||270===n){const t=e;e=i,i=t}return Wm(t,e,i)}getEditResultForPixel(){const t=this.getEditResult();return{rWidth:this.toPixelPPI(t.rWidth,!1),rHeight:this.toPixelPPI(t.rHeight,!0),cropLeft:this.toPixelPPI(t.cropLeft,!1),cropTop:this.toPixelPPI(t.cropTop,!0),cropWidth:this.toPixelPPI(t.cropWidth,!1),cropHeight:this.toPixelPPI(t.cropHeight,!0),rotation:t.rotation}}getEditResult(){if(!this.actions.length){const t=$m(this.cropBox,this.rotation,this.mediaBox.width,this.mediaBox.height);return{rWidth:t.width,rHeight:t.height,cropLeft:this.cropBox.left,cropTop:this.cropBox.top,cropWidth:this.cropBox.width,cropHeight:this.cropBox.height,rotation:this.rotation,mediaBox:{...this.mediaBox},cropBox:{...this.cropBox}}}const t=this.actions[this.actions.length-1],{rotatedCropBox:e,cropBox:i,rotation:n}=this.actionResult.get(t.actionUid).to;return{rWidth:e.width,rHeight:e.height,cropLeft:i.left,cropTop:i.top,cropWidth:i.width,cropHeight:i.height,rotation:n,mediaBox:{...this.mediaBox},cropBox:{...i}}}getEditResultForPerspective(){const t=this.raw.getPageSize(),e={left:0,top:0,width:t.width,height:t.height};if(!this.pActions.length){const i=$m(e,this.rotation,e.width,e.height);return{rWidth:i.width,rHeight:i.height,cropLeft:0,cropTop:0,cropWidth:t.width,cropHeight:t.height,rotation:this.rotation,cropBox:{...e},mediaBox:e}}const i=this.pActions[this.pActions.length-1],{rotatedCropBox:n,cropBox:s,rotation:o}=this.pActionResult.get(i.actionUid).to;return{rWidth:n.width,rHeight:n.height,cropLeft:s.left,cropTop:s.top,cropWidth:s.width,cropHeight:s.height,rotation:o,mediaBox:e,cropBox:{...s}}}getActions(){return[...this.actions]}getPerspectiveActions(){return this.pActions}addAction(t){let e=null;if(this.actions.length){const t=this.actionResult.get(this.actions[this.actions.length-1].actionUid);e={mediaBox:{...t.to.mediaBox},cropBox:{...t.to.cropBox},rotation:t.to.rotation,rotatedCropBox:{...t.to.rotatedCropBox}}}else e={mediaBox:{...this.mediaBox},cropBox:{...this.cropBox},rotation:this.rotation,rotatedCropBox:{...this.cropBox}};if(this.actions.push(t),!this.actionResult.has(t.actionUid)){const i=function(t,e,i,n){let s={...t};const o=e.left+e.width,r=e.top+e.height;let a=i,l=$m(t,a,o,r);if("rotate"===n.type)a+=n.angle,l=$m(t,a,o,r);else if("crop"===n.type){const t=n.rect;l={left:t.left+l.left,top:t.top+l.top,width:t.width,height:t.height},s=function(t,e,i,n){e=(e%360+360)%360;const s={...t},{left:o,top:r,width:a,height:l}=t,h=Math.floor(e/90);return 1===h?(s.left=r,s.top=n-a-o):2===h?(s.left=i-a-o,s.top=n-l-r):3===h&&(s.left=i-l-r,s.top=o),h%2>0&&(s.width=l,s.height=a),s}(l,a,o,r)}return{rotatedCropBox:l,cropBox:s,mediaBox:e,rotation:a}}(e.cropBox,this.mediaBox,this.rotation,t);this.actionResult.set(t.actionUid,{from:e,to:i}),this.cropBox={...i.cropBox},this.mediaBox={...i.mediaBox}}if("rotate"===t.type){let e=null;const{width:i,height:n}=this.raw.getPageSize(),s={left:0,top:0,width:i,height:n};if(this.pActions.length){const t=this.pActionResult.get(this.pActions[this.pActions.length-1].actionUid);e={mediaBox:{...t.to.mediaBox},cropBox:{...t.to.cropBox},rotation:t.to.rotation,rotatedCropBox:{...t.to.rotatedCropBox}}}else e={mediaBox:{...s},cropBox:{...s},rotation:this.rotation,rotatedCropBox:{...s}};if(this.pActions.push(t),!this.pActionResult.has(t.actionUid)){const s=function(t,e,i,n){const s=i+n.angle;return{rotatedCropBox:$m(t,s,e.left+e.width,e.top+e.height),cropBox:t,mediaBox:e,rotation:s}}({left:0,top:0,width:i,height:n},{left:0,top:0,width:i,height:n},this.rotation,t);this.pActionResult.set(t.actionUid,{from:e,to:s})}this.rotation+=t.angle}}deleteAction(t){var e,i;if((null===(e=this.actions[this.actions.length-1])||void 0===e?void 0:e.actionUid)===t){this.actions.pop();const e=this.actionResult.get(t);this.cropBox={...e.from.cropBox},this.mediaBox={...e.from.mediaBox},this.rotation=e.from.rotation,this.actionResult.delete(t)}(null===(i=this.pActions[this.pActions.length-1])||void 0===i?void 0:i.actionUid)===t&&(this.pActions.pop(),this.pActionResult.delete(t))}clearActions(){this.actions=[]}toDisplayPPI(t,e){const{resolutionX:i,resolutionY:n}=this;return e?t/n*Cr.displayResolution:t/i*Cr.displayResolution}toPixelPPI(t,e){const{resolutionX:i,resolutionY:n}=this;return e?t*n/Cr.displayResolution:t*i/Cr.displayResolution}quadToDisplayPPI(t){const e=_s(t);for(let t=0;t<4;t++)e[t][0]=this.toDisplayPPI(e[t][0],!1),e[t][1]=this.toDisplayPPI(e[t][1],!0);return e}quadToPixelPPI(t){const e=_s(t);for(let t=0;t<4;t++)e[t][0]=this.toPixelPPI(e[t][0],!1),e[t][1]=this.toPixelPPI(e[t][1],!0);return e}rectToDisplayPPI(t){const e={...t};return e.left=this.toDisplayPPI(t.left,!1),e.top=this.toDisplayPPI(t.top,!0),e.width=this.toDisplayPPI(t.width,!1),e.height=this.toDisplayPPI(t.height,!0),e}rectToPixelPPI(t){const e={...t};return e.left=this.toPixelPPI(t.left,!1),e.top=this.toPixelPPI(t.top,!0),e.width=this.toPixelPPI(t.width,!1),e.height=this.toPixelPPI(t.height,!0),e}dispose(){this.raw.reset(),this.original.reset(),this.display.reset(),this.thumbnail.reset(),this.isDestroyed=!0}getAnnotationUids(){return[...this.annotations]}}function Km(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;return t.forEach(t=>{t.width>0&&t.height>0&&(e=Math.min(e,t.left),i=Math.min(i,t.top),n=Math.max(n,t.left+t.width),s=Math.max(s,t.top+t.height))}),{left:e,top:i,width:n-e,height:s-i}}function Qm(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:5,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:10;const o=[];let r="",a=0;for(let e=0;e<=t.length;e++){const i=t[e];i&&!/\s/.test(i)?(""===r&&(a=e),r+=i):""!==r&&""!==r&&(o.push({text:r,startPos:a,endPos:e-1}),r="")}let l=-1;for(let t=0;t<o.length;t++){const e=o[t];if(i>=e.startPos&&i<=e.endPos){l=t;break}}const h=i+e.length-1;let c=-1;for(let t=0;t<o.length;t++){const e=o[t];if(h>=e.startPos&&h<=e.endPos){c=t;break}}if(-1===l||-1===c)return{context:t,startIndex:i};const d=Math.max(0,l-n),u=Math.min(o.length-1,c+s),p=o[d].startPos,g=o[u].endPos+1;let f=t.substring(p,g),m=i-p;const v=[".","!","?","\n","\r","。","！","？","；",";"],y=f.substring(0,m);let x=-1;for(const t of v){const e=y.lastIndexOf(t);e>x&&(x=e)}if(-1!==x){let t=x+1;for(;t<f.length&&/\s/.test(f[t]);)t+=1;f=f.substring(t),m-=t}return{context:f,startIndex:m}}class tv extends Wo{constructor(){super(),Yi(this,"uid",void 0),Yi(this,"emitter",void 0),Yi(this,"repo",void 0),Yi(this,"onDocumentCreated",jo(this)),Yi(this,"onDocumentDeleted",jo(this)),Yi(this,"onDocumentRenamed",jo(this)),Yi(this,"onPagesAddedOut",jo(this)),Yi(this,"onAddPagesToDoc",jo(this)),Yi(this,"onBeforeDeletePagesFromDoc",jo(this)),Yi(this,"onDeletePagesFromDoc",jo(this)),Yi(this,"onBeforeDeleteAllPagesFromDoc",jo(this)),Yi(this,"onDeleteAllPagesFromDoc",jo(this)),Yi(this,"onMovePages",jo(this)),Yi(this,"onSwitchPage",jo(this)),Yi(this,"onReorderPages",jo(this)),Yi(this,"onAfterReorderPages",jo(this)),Yi(this,"onBeforeDeleteDocs",jo(this)),Yi(this,"onAfterDeleteDocs",jo(this)),Yi(this,"onOpenDocument",jo(this)),Yi(this,"onCloseDocument",jo(this)),this.emitter=new Ws,this.uid=Us(),this.repo=new Map}dispose(){this.repo.forEach(t=>t.dispose()),this.repo.clear(),super.dispose()}reset(){this.repo.clear()}createDocument(){const t=new km(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});this.repo.set(t.uid,t);const e=Zf.create(t.uid,t.name);return this.onDocumentCreated.emit(e),t}getDocument(t){return this.repo.get(t)}getAllDocuments(){return Array.from(this.repo.values())}renameDocument(t,e){const i=this.repo.get(t);if(!i)return!1;const n=_f.create(t,i.name,e);return i.name=e,this.onDocumentRenamed.emit(n),!0}deleteDocuments(t){return t.forEach(t=>{const e=this.getDocument(t);e.dispose(),this.repo.delete(t);const i=Zf.create(t,e.name);this.onDocumentDeleted.emit(i)}),!0}addPagesToDocument(t,e,i){const n=this.repo.get(t);if(!n)return!1;const{length:s}=e,o=[];let r=n.pages.length;Ls(i)?(n.pages.splice(i,0,...e),r=i):n.pages.push(...e);for(let t=0;t<s;t++)o.push(r+t);const a=_m.create(t,e,o,i);return this.onAddPagesToDoc.emit(a),!0}removePagesFromDocument(t,e){const i=this.getDocument(t);if(!i)return!1;const n=e.map(t=>i.pages.indexOf(t));e.forEach(t=>{xo(i.pages,t)});const s=Em.create(t,e,n);return this.onBeforeDeletePagesFromDoc.emit(s),this.onDeletePagesFromDoc.emit(s),!0}removeAllPagesFromDocument(t){const e=this.getDocument(t);if(!e)return!1;const i=[...e.pages.keys()],n=[...e.pages];e.pages.length=0;const s=Em.create(t,n,i);return this.onBeforeDeleteAllPagesFromDoc.emit(s),this.onDeleteAllPagesFromDoc.emit(s),!0}movePages(t,e,i){const n=this.repo.get(t);if(!n)return!1;wo(n.pages,e,i);const s=Am.create(t,e,i);return this.onMovePages.emit(s),!0}swapPages(t,e,i){const n=this.repo.get(t);if(!n)return!1;Co(n.pages,e,i);const s=ym.create(t,e,i);return this.onSwitchPage.emit(s),!0}reorderPages(t,e){const i=this.repo.get(t);if(!i)return!1;bo(i.pages,e);const n=vm.create(t,e);return this.onReorderPages.emit(n),this.onAfterReorderPages.emit(n),!0}}class ev{on(t,e){}emit(t){}}(new ev).on("debug",function(){});var iv=new WeakMap,nv=new WeakMap,sv=new WeakMap,ov=new WeakMap,rv=new WeakMap,av=new WeakSet,lv=new WeakSet,hv=new WeakSet;class cv{constructor(t,e){an(this,hv),an(this,lv),an(this,av),rn(this,iv,{writable:!0,value:void 0}),rn(this,nv,{writable:!0,value:void 0}),rn(this,sv,{writable:!0,value:!1}),rn(this,ov,{writable:!0,value:void 0}),rn(this,rv,{writable:!0,value:void 0}),Xi(this,nv,t),Xi(this,ov,t.core),Xi(this,rv,e),Xi(this,iv,Us()),t.taskResponses.set($i(this,iv),this)}get uid(){return $i(this,rv)}get fileIndex(){return $i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),sn(this,hv,pv).call(this).fileIndex}get filter(){return $i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),sn(this,hv,pv).call(this).filter}get perspectiveQuad(){$i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED);const t=sn(this,hv,pv).call(this);let{quad:e}=t;return e&&(e=t.quadToPixelPPI(e),Ym(e)),e}get rotation(){return $i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),sn(this,hv,pv).call(this).rotation%360}get mediaBox(){return $i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),gv(Bo(sn(this,hv,pv).call(this).mediaBox,Cr.displayResolution,Cr.dataResolution),2)}get cropBox(){return $i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),gv(Bo(sn(this,hv,pv).call(this).cropBox,Cr.displayResolution,Cr.dataResolution),2)}async fileData(){$i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED);const t=sn(this,hv,pv).call(this);if(!t)return null;const e=await $i(this,nv).core.sourceStore.get(t.fileUid);return"application/ddv-blank-image"!==e.fileData.type?e.fileData:null}async raw(){$i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),sn(this,hv,pv).call(this);const t=Us();sn(this,av,dv).call(this,t);const e=await $i(this,ov).imageDataService.getRaw($i(this,rv));return sn(this,lv,uv).call(this,t),{data:e.data,width:e.width,height:e.height}}async display(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};$i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),sn(this,hv,pv).call(this),t={getPng:!1,isGetPrintPageData:!1,renderAnnotation:!1,...t};const e=Us();sn(this,av,dv).call(this,e);const i=await $i(this,ov).imageDataService.getEditedDisplay($i(this,rv),t.renderAnnotation,t.isGetPrintPageData,t.getPng);return sn(this,lv,uv).call(this,e),{data:null==i?void 0:i.data,width:null==i?void 0:i.width,height:null==i?void 0:i.height}}async thumbnail(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};$i(this,sv)&&pp.throw(pp.PAGEDATA_DESTROYED),sn(this,hv,pv).call(this),t={getPng:!1,isGetPrintPageData:!1,renderAnnotation:!1,...t};const e=Us();sn(this,av,dv).call(this,e);const i=await $i(this,ov).imageDataService.getEditedDisplay($i(this,rv),t.renderAnnotation,t.isGetPrintPageData,t.getPng);return sn(this,lv,uv).call(this,e),{data:i.data,width:i.width,height:i.height}}destroy(){$i(this,nv).deleteResponse($i(this,iv)),Xi(this,nv,null),Xi(this,sv,!0)}}function dv(t){const e=$i(this,ov).pageService.getPage($i(this,rv));if(e){const i={viewerUid:t,docUid:e.doc.uid,pageUid:e.uid};e.raw.addUser(i),e.original.addUser(i),e.thumbnail.addUser(i),e.display.addUser(i)}}function uv(t){const e=$i(this,ov).pageService.getPage($i(this,rv));if(e){const i={viewerUid:t,docUid:e.doc.uid,pageUid:e.uid};e.raw.deleteUser(i),e.original.deleteUser(i),e.thumbnail.deleteUser(i),e.display.deleteUser(i)}}function pv(){const t=$i(this,ov).pageService.getPage($i(this,rv));return t||pp.throw(pp.PAGE_DESTROYED),t}function gv(t,e){let i=!0;const n=Uo(t.left,e),s=Uo(t.top,e),o=Uo(t.width,e),r=Uo(t.height,e),a=1e-7;return(Math.abs(n-t.left)>a||Math.abs(s-t.top)>a||Math.abs(o-t.width)>a||Math.abs(r-t.height)>a)&&(i=!1),i?{left:n,top:s,width:o,height:r}:t}class fv extends Wo{constructor(t){super(),Yi(this,"core",void 0),Yi(this,"taskResponses",new Map),this.core=t,this.listenEvents()}listenEvents(){}requestPageData(t){return this.core.pageService.getPage(t),new cv(this,t)}deleteResponse(t){this.taskResponses.delete(t)}dispose(){this.taskResponses.forEach(t=>{t.destroy()}),this.taskResponses=null,super.dispose()}}class mv{constructor(t){Yi(this,"undoStack",void 0),Yi(this,"redoStack",void 0),Yi(this,"maxTimes",void 0),this.maxTimes=t||100,this.undoStack=[],this.redoStack=[]}getOperation(){return{undo:this.undoStack.length,redo:this.redoStack.length}}execute(t){return!!t.execute()&&(this.undoStack.push(t),this.checkMaxSize(this.undoStack),this.redoStack.length>0&&(this.redoStack.forEach(t=>{t.dispose()}),this.redoStack.length=0),!0)}undo(){const t=this.undoStack.pop();return t&&(t.undo(),this.redoStack.push(t),this.checkMaxSize(this.undoStack)),!!t}redo(){const t=this.redoStack.pop();return t&&(t.execute(),this.undoStack.push(t),this.checkMaxSize(this.undoStack)),!!t}checkMaxSize(t){var e;t.length>this.maxTimes&&(null===(e=t.splice(0,1)[0])||void 0===e||e.dispose())}removeUidsFromCommand(t){this.removeFromStack(this.undoStack,t),this.removeFromStack(this.redoStack,t)}removeFromStack(t,e){t.slice().forEach(e=>{if(!e.isValid){const i=t.indexOf(e);t.splice(i,1),e.dispose()}})}reset(){this.undoStack.forEach(t=>{t.dispose()}),this.redoStack.forEach(t=>{t.dispose()}),this.undoStack=[],this.redoStack=[]}}class vv extends Wo{constructor(){super(),Yi(this,"invokers",void 0),Yi(this,"onOperationsChanged",jo(this)),Yi(this,"onBeforeRefreshCommands",jo(this)),Yi(this,"onRefreshCommands",jo(this)),Yi(this,"maxUndoRedoTimes",void 0),this.invokers=new Map,this.maxUndoRedoTimes=100}setMaxUndoRedoTimes(t){this.maxUndoRedoTimes=t,this.invokers.forEach(e=>{e.maxTimes=t})}createInvoker(t){if(!this.invokers.has(t)){const e=new mv(this.maxUndoRedoTimes);this.invokers.set(t,e)}}deleteInvokers(t){t.forEach(t=>{if(this.invokers.has(t)){const e=this.invokers.get(t);null==e||e.reset(),this.invokers.delete(t)}})}execute(t,e){const i=this.invokers.get(e);null!=i&&i.execute(t)&&this.emitOperationsChanged(e)}undo(t){const e=this.invokers.get(t),i=!(null==e||!e.undo());return i&&this.emitOperationsChanged(t),i}redo(t){const e=this.invokers.get(t),i=!(null==e||!e.redo());return i&&this.emitOperationsChanged(t),i}saveOperations(t){const e=this.invokers.get(t);return!!e&&(e.reset(),this.emitOperationsChanged(t),!0)}getOperationState(t){return this.invokers.get(t).getOperation()}removePageFromCommand(t,e){this.onBeforeRefreshCommands.emit({docUid:t,pageUids:e}),this.invokers.get(t).removeUidsFromCommand(e),this.emitOperationsChanged(t)}emitOperationsChanged(t){const e=this.invokers.get(t);let i=0,n=0;if(e){const t=e.getOperation();i=t.undo,n=t.redo}const s=Of.create(t,i,n);this.onOperationsChanged.emit(s)}dispose(){this.invokers.clear(),super.dispose()}reset(){this.invokers.forEach(t=>{t.reset()}),this.invokers.clear()}}class yv extends Wo{constructor(){super(),Yi(this,"files",void 0),Yi(this,"onDeleteFileData",void 0),this.files=new Map,this.onDeleteFileData=jo(this)}dispose(){this.files.clear(),super.dispose()}reset(){this.files.clear()}addFile(t,e,i){const n=new Om({uid:t,mime:e,pageCount:i});this.files.set(t,n)}getByUid(t){return this.files.get(t)}addUser(t,e,i){const n=this.getByUid(t);return null==n?void 0:n.addUser(e,i)}addUsersByParsedPages(t,e){e.forEach(e=>{this.addUser(t,e.fileIndex,e.pageUid)})}deleteUser(t,e,i){const n=this.getByUid(t);return n&&(n.deleteUser(e,i),n.count||(this.onDeleteFileData.emit(t),this.files.delete(t))),!1}}class xv extends Wo{constructor(t){super(),Yi(this,"pages",void 0),Yi(this,"core",void 0),Yi(this,"onUpdatePage",jo(this)),Yi(this,"onCreatePage",jo(this)),Yi(this,"onCopyPage",jo(this)),Yi(this,"onDeletePages",jo(this)),Yi(this,"onBeforeDeletePages",jo(this)),Yi(this,"onAfterDeletePages",jo(this)),Yi(this,"onBeforeCopyPages",jo(this)),Yi(this,"onCopyPages",jo(this)),this.core=t,this.pages=new Map}handlePagePreloadChange(t){let{viewerUid:e,viewerMode:i,docUid:n,changes:s}=t;s.forEach(t=>{let{pageUid:s,from:o,to:r}=t;const a=this.getPage(s),l={viewerUid:e,docUid:n,pageUid:s},{autoReleaseImg:h}=Cr;o&&!r?(a.raw.deleteUser(l),a.raw.hasUser()||(this.core.imageLoadService.cancelLoadRawImage(s),this.core.parserService.cancelGetPage(a.fileUid,a.fileIndex),a.raw.resetBlob(),h&&a.raw.resetImg()),i!==jg.DEFAULT&&i!==jg.THUMBNAIL||(a.original.deleteUser(l),a.original.hasUser()||(this.core.imageLoadService.cancelLoadOriginalImage(s),a.original.resetBlob(),h&&a.original.resetImg()),a.display.deleteUser(l),a.display.hasUser()||(this.core.imageLoadService.cancelLoadDisplayImage(s),a.display.resetBlob(),h&&a.display.resetImg())),i===jg.THUMBNAIL&&(a.thumbnail.deleteUser(l),a.thumbnail.hasUser()||(this.core.imageLoadService.cancelLoadThumbnailImage(s),a.thumbnail.resetBlob(),h&&a.thumbnail.resetImg())),a.raw.hasUser()||this.core.parserService.cancelGetPage(a.fileUid,a.fileIndex)):(a.raw.addUser(l),i!==jg.DEFAULT&&i!==jg.THUMBNAIL||(a.original.addUser(l),a.display.addUser(l)),i===jg.THUMBNAIL&&a.thumbnail.addUser(l))})}dispose(){this.pages.forEach(t=>{t.dispose()}),this.pages.clear(),super.dispose()}reset(){this.pages.forEach(t=>{t.dispose()}),this.pages.clear()}getPage(t){return this.pages.get(t)}startCreatePagesByParsedPages(t,e,i){t.forEach((t,n)=>{var s;this.createPage({...t,fileUid:e,annotations:(null===(s=t.annotations)||void 0===s?void 0:s.map(t=>t.uid))||[]},i)})}endCreatePagesByParsedPages(t,e){t.forEach(t=>{let{pageUid:i,fileIndex:n}=t;const s=xm.create(i,e,n);this.onCreatePage.emit(s)})}createPage(t,e){const i=new Jm(t,e);return this.pages.set(i.uid,i),i}copyPage(t,e,i){const n=i.copy(t,e);return this.pages.set(n.uid,n),dm.create(t,n.fileUid,n.fileIndex,i.annotations.slice()),n}deletePages(t){const e=gm.create(t);this.onBeforeDeletePages.emit(e),t.forEach(t=>{const e=this.pages.get(t);e&&e.dispose(),this.pages.delete(t)}),this.onDeletePages.emit(e),this.onAfterDeletePages.emit(e)}updatePage(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=this.pages.get(t);if(n){const{doc:s,customData:o}=n;n.dispose();const r=new Jm({...i,pageUid:t},s);r.customData=o,this.pages.set(t,r);const a=Pm.create(s.uid,t,e);this.onUpdatePage.emit(a)}}getPageCount(){return this.pages.size}}var wv=new WeakSet,Cv=new WeakSet;class bv{constructor(t){an(this,Cv),an(this,wv),Yi(this,"core",void 0),Yi(this,"annotationMapper",void 0),this.core=t,this.annotationMapper=new lu}reset(){}async saveToPng(t,e,i){var n;const s=this.core.pageService.getPage(t);if(!s)return Promise.resolve(null);const o=await this.core.sourceStore.get(s.fileUid);if("image/png"===(null===(n=o.fileData)||void 0===n?void 0:n.type)&&!((null==e?void 0:e.saveAnnotation)&&s.annotations.length>0||sn(this,wv,Sv).call(this,s)))return i&&(i.details.current=i.details.total,i.status="InProgress",pp.info(i),i.status="Completed",pp.info(i)),o.fileData;const r=this.core.getPageData(t),a=await r.display({renderAnnotation:!(null==e||!e.saveAnnotation),getPng:!0});r.destroy();const l=$o.isApple&&!(null!=e&&e.saveAnnotation&&s.annotations.length>0)&&sn(this,Cv,Tv).call(this,s);if(!l&&"image/png"===await Io(a.data))return i&&(i.details.current=i.details.total,i.status="InProgress",pp.info(i),i.status="Completed",pp.info(i)),a.data;const h=this.core.saverService.getSaver("image/png");try{const t=await h.save(a.data,{outputType:3,is1Bit:l});return i&&(i.details.current=i.details.total,i.status="InProgress",pp.info(i),i.status="Completed",pp.info(i)),t}finally{h.destroy()}}async saveToJpeg(t,e,i){var n;const s=this.core.pageService.getPage(t);if(!s)return Promise.resolve(null);const o=await this.core.sourceStore.get(s.fileUid);if("image/jpeg"===(null===(n=o.fileData)||void 0===n?void 0:n.type)&&void 0===(null==e?void 0:e.quality)&&!((null==e?void 0:e.saveAnnotation)&&s.annotations.length>0||sn(this,wv,Sv).call(this,s)))return i&&(i.details.current=i.details.total,i.status="InProgress",pp.info(i),i.status="Completed",pp.info(i)),o.fileData;const r=this.core.saverService.getSaver("image/jpeg");try{const n=this.core.getPageData(t),s=await n.display({renderAnnotation:!(null==e||!e.saveAnnotation)});n.destroy();const o=await r.save(s.data,{outputType:1,jpegQuality:null==e?void 0:e.quality});return i&&(i.details.current=i.details.total,i.status="InProgress",pp.info(i),i.status="Completed",pp.info(i)),o}finally{r.destroy()}}async saveToTiff(t,e,i){const n=this.core.saverService.getSaver("image/tiff"),s=!(null==e||!e.saveAnnotation);try{await n.init(e);for(let o=0;o<t.length;o++){const r=t[o],a=this.core.pageService.getPage(r);if(!a)break;const l=this.core.getPageData(r),h=await l.display({renderAnnotation:s});l.destroy();const c=$o.isApple&&!(null!=e&&e.saveAnnotation&&a.annotations.length>0)&&sn(this,Cv,Tv).call(this,a);await n.appendPage(h.data,{is1Bit:c}),i&&(i.details.current=o+1,i.status="InProgress",pp.info(i))}const o=await n.getTiff();return i&&(i.details.current=i.details.total,i.status="Completed",pp.info(i)),o}finally{n.destroy()}}isPdfInfoChanged(t){return!!t.pdfOptions&&(t.rotation%360!==t.pdfOptions.rotation||t.mediaBox.left!==t.pdfOptions.mediaBox.left||t.mediaBox.width!==t.pdfOptions.mediaBox.width||t.mediaBox.height!==t.pdfOptions.mediaBox.height||t.mediaBox.top!==t.pdfOptions.mediaBox.top||t.cropBox.left!==t.pdfOptions.cropBox.left||t.cropBox.width!==t.pdfOptions.cropBox.width||t.cropBox.height!==t.pdfOptions.cropBox.height||t.cropBox.top!==t.pdfOptions.cropBox.top)}async saveToPdf(t,e,i){var n;null!=e&&e.creationDate&&(e.creationDate=Rm(e.creationDate)),null!=e&&e.modifiedDate&&(e.modifiedDate=Rm(e.modifiedDate));const s=(null==e?void 0:e.mimeType)||"application/pdf";!e||"annotation"!==e.saveAnnotation&&"flatten"!==e.saveAnnotation||lg.makeSureAnnotationLicenseExist();const o=null!==(n=null==e?void 0:e.quality)&&void 0!==n?n:80,r=this.core.saverService.getSaver("application/pdf");try{await r.init(e);const n=new Map,f=e&&e.pageType&&e.pageType!==Dr.PAGE_DEFAULT;await r.appendBlankPages(595,842,t.length);const m=[];for(let s=0;s<t.length;s++){var a,l;if(m.includes(s))continue;const u=t[s],p=this.core.pageService.getPage(u);if(!p)break;const g=await this.core.sourceStore.get(p.fileUid),v=f||(null===(a=p.pdfOptions)||void 0===a?void 0:a.convertMode)===hu.CM_IMAGEONLY||(null===(l=p.pdfOptions)||void 0===l?void 0:l.renderOptions.renderGrayscale),y=[],x=[],w=[];if(g.fileData&&"application/pdf"===g.fileData.type&&!v)for(let i=s;i<t.length;i++){var h,c;if(s!==i&&!x.includes(s))break;const o=t[i],r=this.core.pageService.getPage(o);if(!r)continue;if(r.fileUid!==p.fileUid)continue;if(!r.isFull)continue;if("image"===(null==e?void 0:e.saveAnnotation)&&r.annotations.length>0)continue;if((null===(h=r.pdfOptions)||void 0===h?void 0:h.convertMode)===hu.CM_IMAGEONLY||null!==(c=r.pdfOptions)&&void 0!==c&&c.renderOptions.renderGrayscale)continue;let a=!1;r.filter&&"none"!==r.filter&&(a=!0);const l=r.getActions(),d=r.getPerspectiveActions();l.every(t=>"rotate"===t.type||"crop"===t.type)&&d.every(t=>"rotate"===t.type||"crop"===t.type)||(a=!0);let u=!1;a&&this.core.getAnnotationsByPageUid(t[s]).forEach(t=>{t.oriIndex>=0&&!t.modified&&(u=!0)}),a&&!u||(this.isPdfInfoChanged(r)&&n.set(i,{mediaBox:r.mediaBox,cropBox:r.cropBox,rotation:r.rotation}),y.push(r.fileIndex),x.push(i),u&&w.push({pageUid:o,pageIndex:i,fileIndex:r.fileIndex}))}if(y.length>0){var d;const t=null===(d=g.loadOptions)||void 0===d?void 0:d.password,n=[];if(w.forEach(t=>{n.push(t.pageIndex)}),await r.replaceRawPdfPages(g.fileData,t,y,x),i){i.status="InProgress";for(let t=0;t<x.length;t++)n.includes(x[t])||(m.push(x[t]),i.details.current=m.length,pp.info(i))}for(let t=0;t<w.length;t++){const n=await this.core.imageDataService.getNotRotatedDisplay(w[t].pageUid,"image"===(null==e?void 0:e.saveAnnotation),!1,o);await r.changePageImage(w[t].pageIndex,n.data,{cropBox:p.cropBox,mediaBox:p.mediaBox,rotation:p.rotation,width:n.width,height:n.height}),i&&(i.status="InProgress",m.push(w[t].pageIndex),i.details.current=m.length,pp.info(i))}}else{let t;const n=1e-6;let a=!0;Math.abs(p.cropBox.left-p.mediaBox.left)<n&&Math.abs(p.cropBox.top-p.mediaBox.top)<n&&Math.abs(p.cropBox.width-p.mediaBox.width)<n&&Math.abs(p.cropBox.height-p.mediaBox.height)<n&&(a=!1),t=f&&a?await this.core.imageDataService.getNotRotatedCroppedDisplay(u,"image"===(null==e?void 0:e.saveAnnotation),!1,o):await this.core.imageDataService.getNotRotatedDisplay(u,"image"===(null==e?void 0:e.saveAnnotation),!1,o);const l=$o.isApple&&!("image"===(null==e?void 0:e.saveAnnotation)&&p.annotations.length>0)&&sn(this,Cv,Tv).call(this,p);await r.applyImageToPage(s,t.data,{cropBox:p.cropBox,mediaBox:p.mediaBox,rotation:p.rotation,width:t.width,height:t.height,bitDepth:l?1:void 0}),i&&(m.push(s),i.details.current=m.length,i.status="InProgress",pp.info(i))}}n.size>0&&await r.setPageInfo(n);const v=[];for(let i=0;i<t.length;i++){var u;const n=this.core.pageService.getPage(t[i]);if(n)if(e&&"image"===e.saveAnnotation)(null===(u=n.pdfOptions)||void 0===u?void 0:u.annotCount)>0&&await r.removePageAnnotations(i);else{const s=n.pdfOptions&&n.pdfOptions.convertMode===hu.CM_RENDERALL&&n.pdfOptions.renderOptions.renderAnnotations===cu.RENDER_ANNOTATIONS,o=this.core.getAnnotationsByPageUid(t[i]);if(!o.length){!s&&n.pdfOptions&&n.pdfOptions.annotCount>0&&await r.removePageAnnotations(i);continue}e&&"none"===e.saveAnnotation&&o.forEach(t=>{!["textBox","textTypewriter"].includes(t.type)||!t.modified&&Ls(null==t?void 0:t.oriIndex)||t.style.textContents.forEach(t=>{v.push({family:t.fontFamily,isBold:"bold"===t.fontWeight,isItalic:"italic"===t.fontStyle})})});const a=[];for(let t=0;t<o.length;t++)!0===o[t].flattened&&(a.push(o[t]),o.splice(t,1),t-=1);if(a.length>0){const t=await this.annotationMapper.getOriginalAnnotations(a,{width:n.mediaBox.left+n.mediaBox.width,height:2*n.mediaBox.top+n.mediaBox.height});await r.flattenPageAnnotations(i,t)}if(e&&"none"!==e.saveAnnotation){const t=await this.annotationMapper.getOriginalAnnotations(o,{width:n.mediaBox.left+n.mediaBox.width,height:2*n.mediaBox.top+n.mediaBox.height});var p;await r.setPageAnnotations(i,t,s),"flatten"===e.saveAnnotation&&(t.length>0||s&&null!==(p=n.pdfOptions)&&void 0!==p&&p.annotCount)&&await r.flattenPage(i)}else{var g;(null===(g=n.pdfOptions)||void 0===g?void 0:g.annotCount)>0&&await r.removePageAnnotations(i)}}}v.length&&(await r.ifFontsExist(v)||pp.warning(pp.WASM_FONT_LOSS));const y=await r.getPdf(s);return i&&(i.details.current=i.details.total,i.status="Completed",pp.info(i)),y}catch(t){throw pp.EXTERNAL_ERR}finally{r.destroy()}}}function Sv(t){if(!t.isFull)return!0;if(t.filter&&"none"!==t.filter)return!0;if(t.getActions().some(t=>"rotate"!==t.type))return!0;if(t.getPerspectiveActions().some(t=>"rotate"!==t.type))return!0;const e=this.core.getAnnotationsByPageUid(t.uid);let i=!1;return e.forEach(t=>{t.flattened&&(i=!0)}),!!i||0!==t.rotation}function Tv(t){if(1!==t.resource.bitDepth)return!1;if(t.filter&&t.filter!==Vu.NONE&&t.filter!==Vu.BLACK_AND_WHITE&&t.filter!==Vu.SAVE_INK)return!1;const e=this.core.getAnnotationsByPageUid(t.uid);let i=!1;return e.forEach(t=>{t.flattened&&(i=!0)}),!i}const Ev=t=>{const e=new Set(t);return Array.from(e.values())};class _v extends Wo{constructor(){super(),Yi(this,"observer",void 0),Yi(this,"onResizeObserver",jo(this)),this.observer=new ResizeObserver(t=>{t.forEach(t=>{this.onResizeObserver.emit(t)})})}observe(t){this.observer.observe(t)}unobserve(t){this.observer.unobserve(t)}reset(){this.observer.disconnect()}dispose(){this.observer.disconnect(),this.observer=null,super.dispose()}}class Pv{constructor(){Yi(this,"canvas",void 0),Yi(this,"renderer",void 0),Yi(this,"root",void 0),this.renderer=new kh,this.canvas=new ph({renderer:this.renderer,width:10,height:10,canvas:document.createElement("canvas"),dpr:1,willReadFrequently:!0}),this.root=this.canvas.document.documentElement,(new rd).init(this.canvas)}render(t,e,i){this.root.children.slice().forEach(t=>{this.root.removeChild(t)}),this.root.appendChild(t),this.canvas.resize(e||t.width,i||t.height),this.canvas.render()}reset(){this.root.children.slice().forEach(t=>{this.root.removeChild(t)}),this.root.sortable.sorted=[]}getCanvas(){return this.canvas.contextService.getDomElement()}}let Av;const Iv="p".charCodeAt(0),Dv="H".charCodeAt(0),Rv="Y".charCodeAt(0),kv="s".charCodeAt(0);function Mv(t,e){const i=t.slice(0,33);return new Promise((n,s)=>{const o=new FileReader;o.onload=()=>{const i=new Uint8Array(o.result),s=t.slice(33),r=function(t,e,i){if("image/jpeg"===i)return t[13]=1,t[14]=e>>8,t[15]=255&e,t[16]=e>>8,t[17]=255&e,t;if("image/png"===i){const i=new Uint8Array(13);e*=39.3701,i[0]=Iv,i[1]=Dv,i[2]=Rv,i[3]=kv,i[4]=e>>>24,i[5]=e>>>16,i[6]=e>>>8,i[7]=255&e,[i[8],i[9],i[10],i[11]]=[i[4],i[5],i[6],i[7]],i[12]=1;const n=function(t){let e=-1;Av||(Av=function(){const t=new Int32Array(256);for(let e=0;e<256;e++){let i=e;for(let t=0;t<8;t++)i=1&i?3988292384^i>>>1:i>>>1;t[e]=i}return t}());for(let i=0;i<t.length;i++)e=Av[255&(e^t[i])]^e>>>8;return-1^e}(i),s=new Uint8Array(4);s[0]=n>>>24,s[1]=n>>>16,s[2]=n>>>8,s[3]=255&n;const o=new Uint8Array(4);o[0]=0,o[1]=0,o[2]=0,o[3]=9;const r=new Uint8Array(54);return r.set(t,0),r.set(o,33),r.set(i,37),r.set(s,50),r}throw new Error(`The format ${i} is not supported.`)}(i,e,t.type),a=new Blob([r,s],{type:t.type});n(a)},o.onerror=t=>{s(t)},o.readAsArrayBuffer(i)})}class Lv{constructor(t){Yi(this,"core",void 0),Yi(this,"taskMap",void 0),Yi(this,"viewerMap",void 0),Yi(this,"defaultPageMap",void 0),this.core=t,this.taskMap=new Map,this.viewerMap=new Map,this.defaultPageMap=new Map,this.core.pageService.onBeforeDeletePages.on(t=>{t.pageUids.forEach(t=>{const e=this.core.pageService.getPage(t);if(!e||e.isDestroyed)return;this.viewerMap.forEach(i=>{if(i.has(t)){const n=i.get(t);n&&n.tasks.slice().forEach(t=>{this.taskMap.delete(t.taskUid),this.core.parserService.cancelRenderPage(e.fileUid,t)}),i.delete(t)}});const i=this.defaultPageMap.get(t);i&&i.viewerUids.forEach(e=>{this.cancelGetDefaultRenderPage(e,t)})})})}reset(){this.taskMap.clear(),this.viewerMap.clear(),this.defaultPageMap.clear()}async getRenderPage(t,e,i,n,s){const o=this.core.pageService.getPage(e);if(!o||o.isDestroyed)return null;const{fileUid:r,fileIndex:a}=o;let l=this.viewerMap.get(t);l||(l=new Map,this.viewerMap.set(t,l));let h=l.get(e);h||(h={curTask:null,tasks:[]},l.set(e,h));const c=h.tasks;c.slice().forEach(t=>{t.canceled=!0;const e=c.indexOf(t);c.splice(e,1),this.taskMap.delete(t.taskUid),this.core.parserService.cancelRenderPage(r,t)});const d=Us(),u={taskUid:d,canceled:!1,pageUid:e};h.curTask=u,h.tasks||(h.tasks=[]),h.tasks.push(u),this.taskMap.set(d,{taskUid:d,viewerUid:t,pageUid:e});const p=await this.core.sourceStore.get(r);let g;if(g=this.core.parserService.getCustomParserClasses(p.fileData.type)?p.fileData.type:await Io(p.fileData),!g){const i=this.viewerMap.get(t);if(i){const t=i.get(e);t&&t.tasks.slice().forEach(e=>{if(e.taskUid!==t.curTask.taskUid){this.taskMap.delete(e.taskUid);const i=t.tasks.indexOf(e);t.tasks.splice(i,1)}})}pp.throw(pp.FILE_NOT_SUPPORT)}let f=null;u.canceled||(i=Math.max(Math.round(i),1),n=Math.max(Math.round(n),1),f=await this.core.parserService.renderPage(p.fileData,g,r,a,{index:a,width:i,height:n,rect:s,outputType:er.IT_RGBA},u));const m=this.viewerMap.get(t);if(m){const t=m.get(e);t&&t.tasks.slice().forEach(e=>{if(e.taskUid!==t.curTask.taskUid){this.taskMap.delete(e.taskUid);const i=t.tasks.indexOf(e);t.tasks.splice(i,1)}})}return this.taskMap.delete(d),u.canceled?null:f}async cancelGetRenderPage(t,e){const i=this.core.pageService.getPage(e);if(!i||i.isDestroyed)return;const n=this.viewerMap.get(t);if(!n)return;const s=n.get(e);if(!s)return;const{fileUid:o}=i;s.tasks.forEach(t=>{t.canceled=!0,this.taskMap.delete(t.taskUid),this.core.parserService.cancelRenderPage(o,t)}),s.tasks=[]}async getDefaultRenderPage(t,e){const i=this.core.pageService.getPage(e);if(!i)return;const n=this.defaultPageMap.get(e);if(n)return void n.viewerUids.push(t);i.isLoadingDefaultRenderPage=!0;const{fileUid:s,fileIndex:o}=i,r=await this.core.sourceStore.get(s);let a;a=this.core.parserService.getCustomParserClasses(r.fileData.type)?r.fileData.type:await Io(r.fileData),a||(i.isLoadingDefaultRenderPage=!1,pp.throw(pp.FILE_NOT_SUPPORT));const l={taskUid:`${Us()}_defaultRenderPage`,canceled:!1},h={task:l,viewerUids:[t]};this.defaultPageMap.set(e,h);const{mediaBox:c}=i,d=Bo(i.mediaBox,Cr.displayResolution,Cr.dataResolution),{left:u}=d,p=d.top,g=d.left+d.width,f=d.top+d.height,{defaultRenderPageWidth:m,defaultRenderPageHeight:v}=Cr,y=c.width/c.height,x=m/v;let w=0,C=0;c.width<=m&&c.height<=v?(w=c.width,C=c.height):y>x?(w=m,C=m/y):(w=v*y,C=v);const b=await this.core.parserService.renderPage(r.fileData,a,s,o,{index:o,width:w,height:C,rect:[u,p,g,f],outputType:er.IT_RGBA},l);if(this.defaultPageMap.delete(e),!b)return void(i.isLoadingDefaultRenderPage=!1);const S=document.createElement("canvas");S.width=w,S.height=C;const T=S.getContext("2d").createImageData(b.imageInfo.imageWidth,b.imageInfo.imageHeight);T.data.set(b.imageData),S.getContext("2d").putImageData(T,0,0),i.defaultRenderPage=S}cancelGetDefaultRenderPage(t,e){const i=this.core.pageService.getPage(e);if(!i)return;const n=this.defaultPageMap.get(e);if(!n)return;const s=n.viewerUids.indexOf(t);s>=0&&n.viewerUids.splice(s,1),0===n.viewerUids.length&&(this.defaultPageMap.delete(e),i.isLoadingDefaultRenderPage=!1,this.core.parserService.cancelRenderPage(i.fileUid,n.task))}async getRaw(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];try{const i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;if(i.raw.isAvailable)return i.raw.getImageDetail();const{fileUid:n,fileIndex:s}=i,o=await this.core.sourceStore.get(n);let r;return r=this.core.parserService.getCustomParserClasses(o.fileData.type)?o.fileData.type:await Io(o.fileData),r||pp.throw(pp.FILE_NOT_SUPPORT),new Promise((t,a)=>{let l=!1;const h=setTimeout(()=>{l=!0,t(null)},Cr.loadRawPageTimeout);this.core.parserService.getPage(o.fileData,r,n,s).then(n=>{if(l)return;if(clearTimeout(h),!n)return void t(null);let{raw:s}=i;e||(s=new Hm(i)),s.updateImageDetail(n.resource),t(s.getImageDetail())}).catch(e=>{l||(clearTimeout(h),pp.error(e),t(null))})})}catch(t){return pp.error(t),null}}async getOriginal(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;const{original:n}=i;if(n.isAvailable)return n.getImageDetail();const s=await this.getRaw(t);if(!s)return null;const o=await this.handlePerspectiveQuad(t,s);return e&&o&&i.original.updateImageDetail(o),o}async handlePerspectiveQuad(t,e){const i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;let n=e;const s=i.getProcessedQuad();if(s){const o=pp.buildInfo("perspective",{pageUid:t,perspectiveQuad:s});if(pp.info(o),n=await this.core.perspectiveService.perspective({data:e.data,type:tr.JPEG},s,{angle:i.initRotation}),!n)return o.status="Failed",pp.info(o),null;o.status="Completed",pp.info(o)}const o=new Hm(i);return o.updateImageDetail(n),o.getImageDetail()}async getDisplay(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;if(i.display.isAvailable)return i.display.getImageDetail();const n=await this.getOriginal(t);if(!n)return null;const{filter:s}=i,o=await this.handleFilter(t,n);return i.filter!==s?this.getDisplay(t):(e&&o&&i.display.updateImageDetail(o),o)}async handleFilter(t,e){const i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;const n=e,{filter:s}=i;if(s&&"none"!==s){const i=pp.buildInfo("filter",{pageUid:t,filterType:s});pp.info(i);const o=await this.core.filterService.applyFilter({data:e.data,type:tr.JPEG,width:e.width,height:e.height},s);if(!Ds(o))return i.status="Failed",pp.info(i),null;i.status="Completed",pp.info(i),n.data=o}const o=new Hm(i);return o.updateImageDetail(n),o.getImageDetail()}async getEditedDisplay(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=this.core.pageService.getPage(t);if(!s||s.isDestroyed)return null;const o=await this.getDisplay(t,!1),r=this.core.getAnnotationsByPageUid(t).some(t=>!0===t.flattened);if(s.getActions().length||0!==s.rotation||!s.isMediaBoxEqualCropBox()||e&&s.annotations.length||r){const o=await this.applyEditToDisplay(t,e,i,!0,n),r=new Hm(s);return r.updateImageDetail(o),r.getImageDetail()}return o}async getNotRotatedDisplay(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;const s=this.core.pageService.getPage(t);if(!s||s.isDestroyed)return null;const o=await this.getOriginal(t);if(!o)return null;const r=await this.handleFilter(t,o);if(e&&s.annotations.length){const o=await this.applyEditToDisplay(t,e,!1,!1,i,n),r=new Hm(s);return r.updateImageDetail(o),r.getImageDetail()}return r}async getNotRotatedCroppedDisplay(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;const s=this.core.pageService.getPage(t);if(!s||s.isDestroyed)return null;const o=await this.getOriginal(t);if(!o)return null;await this.handleFilter(t,o);const r=await this.applyCropToDisplay(t,e,!1,i,n),a=new Hm(s);return a.updateImageDetail(r),a.getImageDetail()}async getThumbnail(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=this.core.pageService.getPage(t);if(!i||i.isDestroyed)return null;if(i.thumbnail.isAvailable)return i.thumbnail.getImageDetail();const n=await this.getDisplay(t,!0);if(!n)return null;const s=await this.displayToThumbnail(n.data);return s?(e&&i.thumbnail.updateImageDetail(s),s):null}async displayToThumbnail(t){return t}async applyEditToDisplay(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],s=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:100;const r=await this.core.imageLoadService.loadDisplayImage(t),a=this.core.pageService.getPage(t),l=await this.getDisplay(t,!1);let h;if(n)h=a.getEditResultForPixel();else{const[t,e]=Bo([a.mediaBox.width,a.mediaBox.height],Cr.displayResolution,a.resource.resolutionX);h={rWidth:t,rHeight:e,cropLeft:0,cropTop:0,cropWidth:t,cropHeight:e,rotation:0}}const c={width:Math.round(h.rWidth)||1,height:Math.round(h.rHeight)||1,data:null},d=new _l({style:{x:-h.cropLeft,y:-h.cropTop,img:r,width:l.width,height:l.height}}),u=new Ll({style:{x:-(h.cropWidth-h.rWidth)/2,y:-(h.cropHeight-h.rHeight)/2,width:h.cropWidth,height:h.cropHeight}});u.appendChild(d),u.setLocalAngle(h.rotation);let p=null;if(this.core.annotationService&&a.annotations.length){const n=this.core.getAnnotationsByPageUid(t).some(t=>!0===t.flattened);(e||!e&&n)&&(p=new Ll({style:{x:-h.cropLeft,y:-h.cropTop,width:a.original.pageWidth,height:a.original.pageHeight}}),await this.applyAnnotationToPage(p,t,i,!e&&n),u.appendChild(p))}this.core.commonCanvas.render(u,Math.max(1/devicePixelRatio,h.rWidth),Math.max(1/devicePixelRatio,h.rHeight)),this.core.commonCanvas.reset();const g=this.core.commonCanvas.getCanvas();return new Promise((t,e)=>{g.toBlob(async e=>{p&&p.children.forEach(t=>{t instanceof Ac&&t.destroy()}),null!=r&&r.src&&URL.revokeObjectURL(r.src),e=await Mv(e,a.resolutionX||Cr.displayResolution),c.data=e,t(c)},s?"image/png":"image/jpeg",o/100)})}async applyCropToDisplay(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:100;const o=await this.core.imageLoadService.loadDisplayImage(t),r=this.core.pageService.getPage(t),a=await this.getDisplay(t,!1),l=r.toPixelPPI(r.cropBox.width,!1),h=r.toPixelPPI(r.cropBox.height,!0),c={rWidth:Math.round(l),rHeight:Math.round(h),cropLeft:r.toPixelPPI(r.cropBox.left,!1),cropTop:r.toPixelPPI(r.cropBox.top,!0),cropWidth:l,cropHeight:h,rotation:0},d={width:Math.round(c.rWidth)||1,height:Math.round(c.rHeight)||1,data:null},u=new _l({style:{x:-c.cropLeft,y:-c.cropTop,img:o,width:a.width,height:a.height}}),p=new Ll({style:{x:-(c.cropWidth-c.rWidth)/2,y:-(c.cropHeight-c.rHeight)/2,width:c.cropWidth,height:c.cropHeight}});p.appendChild(u),p.setLocalAngle(c.rotation);let g=null;if(this.core.annotationService&&r.annotations.length){const n=this.core.getAnnotationsByPageUid(t).some(t=>!0===t.flattened);(e||!e&&n)&&(g=new Ll({style:{x:-c.cropLeft,y:-c.cropTop,width:r.original.pageWidth,height:r.original.pageHeight}}),await this.applyAnnotationToPage(g,t,i,!e&&n),p.appendChild(g))}this.core.commonCanvas.render(p,Math.max(1/devicePixelRatio,c.rWidth),Math.max(1/devicePixelRatio,c.rHeight)),this.core.commonCanvas.reset();const f=this.core.commonCanvas.getCanvas();return new Promise((t,e)=>{f.toBlob(async e=>{g&&g.children.forEach(t=>{t instanceof Ac&&t.destroy()}),null!=o&&o.src&&URL.revokeObjectURL(o.src),e=await Mv(e,r.resolutionX||Cr.displayResolution),d.data=e,t(d)},n?"image/png":"image/jpeg",s/100)})}async applyAnnotationToPage(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=this.core.pageService.getPage(e),o=[];s.annotations.forEach(t=>{const e=this.core.annotationService.getAnnotationByUid(t);o.push(e)}),o.sort((t,e)=>t.layer-e.layer);for(let e=0;e<o.length;e++){if(i&&!o[e].flags.includes("print"))continue;if(n&&!o[e].flattened)return;if("stamp"===o[e].type&&o[e].style.imageData&&(!Ls(o[e].style.width)||!Ls(o[e].style.height))){const t=new hr,i=await t.readImageInfo({fileSource:o[e].style.imageData});let n=i.imageWidth,s=i.imageHeight;if(n>400||s>400){const t=Math.max(n/400,s/400);n/=t,s/=t}o[e].style.width=n,o[e].style.height=s}const r=this.core.annotationService.createAnnotationShape(o[e],s);r instanceof Ac&&r.style.imageData&&r.style.img instanceof HTMLImageElement&&await new Promise(t=>{r.style.img.onload=()=>{t()}}),r&&t.appendChild(r)}}}class Ov{constructor(t){Yi(this,"name",void 0),this.name=t||"Guest"}getUser(){return this.name}setUser(t){this.name=t}}class Bv extends jr{static create(t){return new Bv(t)}constructor(t){super("setExternalHandler"),Yi(this,"handlerType",void 0),this.handlerType=t}}class Nv{static makeSureSourcesTypeSupported(t,e,i,n,s){const o=[];if(Ts(e))e.forEach((t,e)=>{if(!t||0===t.length){const t=gp("Source[]",i,`[${e}].fileData`,!0);o.push(`${t}: ${pp.FILE_NOT_SUPPORT.message}`)}});else if(!e||0===e.length){const t=gp("Source",i,"fileData");o.push(`${t}: ${pp.FILE_NOT_SUPPORT.message}`)}if(o.length>0){if(!t)throw pp.buildError({...pp.FILE_NOT_SUPPORT,details:o},n,s);pp.throw({...pp.FILE_NOT_SUPPORT,details:o},n,s)}}}class Uv{constructor(t){Yi(this,"core",void 0),this.core=t}async loadText(t){for(const n of t){var e,i;const t=this.core.pageService.getPage(n);if(!t||!t.isTextPage||t.parsedTexts)continue;if((null===(e=t.pdfOptions)||void 0===e?void 0:e.convertMode)!==hu.CM_RENDERALL){t.setParsedTexts(null);continue}const{fileUid:s,fileIndex:o}=t,r=await this.core.sourceStore.get(s);let a;a=this.core.parserService.getCustomParserClasses(r.fileData.type)?r.fileData.type:await Io(r.fileData),a||pp.throw(pp.FILE_NOT_SUPPORT);const l=await this.core.parserService.getPageTexts(r.fileData,a,s,[o]);null!=l&&null!==(i=l[0].charInfos)&&void 0!==i&&i.length?t.setParsedTexts(l[0]):t.setParsedTexts(null)}}}var Fv=new WeakMap,Vv=new WeakMap,Wv=new WeakMap,Hv=new WeakMap,jv=new WeakMap,zv=new WeakMap,Gv=new WeakMap;class Yv{constructor(t,e,i,n){rn(this,Fv,{writable:!0,value:void 0}),rn(this,Vv,{writable:!0,value:Us()}),rn(this,Wv,{writable:!0,value:!1}),rn(this,Hv,{writable:!0,value:void 0}),rn(this,jv,{writable:!0,value:void 0}),rn(this,zv,{writable:!0,value:void 0}),rn(this,Gv,{writable:!0,value:new Map}),Xi(this,Fv,t),Xi(this,Hv,e),Xi(this,jv,i),Xi(this,zv,n),t.searchers.set($i(this,Vv),this)}get docUid(){return $i(this,Hv)}async getResults(t){const e="DocTextSearcher.getResults";$i(this,Wv)&&pp.error(pp.SEARCHER_DESTROYED),Ps(t)&&pp.error(pp.PARAM_MISS,e,"pageIndex"),(!Ls(t)||Ls(t)&&t<0)&&pp.error(pp.PARAM_INVALID,e,"pageIndex");const i=$i(this,Fv).core.getDocument($i(this,Hv));i||pp.error(pp.DOC_NOT_EXIST,e);const n=i.pages[t];if(n||pp.error(pp.PAGE_NOT_EXIST,e),$i(this,Gv).has(n))return $i(this,Gv).get(n);const s=await $i(this,Fv).core.getSearchedTextsByPageUid(n,$i(this,jv),$i(this,zv)),o=Cr.displayResolution,r=Cr.dataResolution,a=s.map(t=>{let{text:e,lines:i,context:s}=t;return{pageUid:n,text:$i(this,jv),rects:i.map(t=>({x:Lo(Bo(t.box.left,o,r),2),y:Lo(Bo(t.box.top,o,r),2),width:Lo(Bo(t.box.width,o,r),2),height:Lo(Bo(t.box.height,o,r),2)})),context:s}});return $i(this,Gv).set(n,a),a}clearCache(t){$i(this,Wv)||t.forEach(t=>{$i(this,Gv).has(t)&&$i(this,Gv).delete(t)})}clearAllCache(){$i(this,Wv)||$i(this,Gv).clear()}destroy(){$i(this,Fv).searchers.delete($i(this,Vv)),Xi(this,Fv,null),$i(this,Gv).clear(),Xi(this,Wv,!0)}}class $v extends Wo{constructor(t){super(),Yi(this,"searchers",new Map),Yi(this,"core",void 0),this.core=t,this.listenEvents()}getSearchersByDocUid(t){const e=[];return this.searchers.forEach(i=>{i.docUid===t&&e.push(i)}),e}listenEvents(){const{documentService:t}=this.core;t.onBeforeDeleteDocs.on(t=>{t.docUids.forEach(t=>{const e=this.getSearchersByDocUid(t);null!=e&&e.length&&e.forEach(t=>{t.destroy()})})},this),t.onDeletePagesFromDoc.on(t=>{const e=this.getSearchersByDocUid(t.docUid);null!=e&&e.length&&e.forEach(e=>{e.clearCache(t.pageUids)})},this),t.onDeleteAllPagesFromDoc.on(t=>{const e=this.getSearchersByDocUid(t.docUid);null!=e&&e.length&&e.forEach(t=>{t.clearAllCache()})},this),this.core.pageService.onUpdatePage.on(t=>{const e=this.getSearchersByDocUid(t.docUid);null!=e&&e.length&&e.forEach(e=>{e.clearCache([t.pageUid])})},this),this.core.editService.onAfterCropPages.on(t=>{const e=this.getSearchersByDocUid(t.docUid);null!=e&&e.length&&e.forEach(e=>{e.clearCache(t.pageUids)})},this),this.core.onFilterChanged.on(t=>{const e=this.getSearchersByDocUid(t.docUid);null!=e&&e.length&&e.forEach(e=>{e.clearCache(t.pageUids)})},this),this.core.onAfterPerspective.on(t=>{const e=this.getSearchersByDocUid(t.docUid);null!=e&&e.length&&e.forEach(e=>{e.clearCache([t.pageUid])})},this)}createDocTextSearcher(t,e,i){return new Yv(this,t,e,i)}dispose(){this.searchers.forEach(t=>{t.destroy()}),this.searchers.clear(),super.dispose()}}function Xv(t,e,i,n,s){const o={isOver:!1,pointerX:-1,pointerY:-1,page:t};if(t&&n){const n=(s%360+360)%360/90,{x:r,y:a}=t.getPosition(),l=t.getScale(),{width:h,height:c}=t;let d=-1,u=-1;0===n?(d=(e-r)/l.x,u=(i-a)/l.y,o.isOver=e>=r&&i>=a&&e<=r+h&&i<=a+c):1===n?(d=(i-a)/l.x,u=(r-e)/l.y,o.isOver=e>=r-c&&i>=a&&e<=r&&i<=a+h):2===n?(d=(r-e)/l.x,u=(a-i)/l.y,o.isOver=e>=r-h&&i>=a-c&&e<=r&&i<=a):3===n&&(d=(a-i)/l.y,u=(e-r)/l.x,o.isOver=e>=r&&i>=a-c&&e<=r+h&&i<=a),o.pointerX=d,o.pointerY=u}return o}class qv extends Wo{constructor(t){super(),Yi(this,"core",void 0),this.core=t}pageVisualToOriginal(t,e,i){const n=this.core.pageService.getPage(t);if(!n)return null;const{rotation:s,cropBox:o}=n,{left:r,top:a,width:l,height:h}=o;let c=0,d=0;switch(Math.abs(s%360)){case 90:c=i,d=h-e;break;case 180:c=l-e,d=h-i;break;case 270:c=l-i,d=e;break;default:c=e,d=i}return{x:c+r,y:d+a}}pageOriginalToVisual(t,e,i){const n=this.core.pageService.getPage(t);if(!n)return null;const{rotation:s,cropBox:o}=n,{left:r,top:a,width:l,height:h}=o,c=e-r,d=i-a;switch(Math.abs(s%360)){case 90:return{x:h-d,y:c};case 180:return{x:l-c,y:h-d};case 270:return{x:d,y:l-c};default:return{x:c,y:d}}}viewerToPageVisual(t,e,i,n){if(!this.core.pageService.getPage(e))return null;if(!this.core.viewerService.getViewer(t))return null;const s=this.viewerToPageOriginal(t,e,i,n);return{...this.pageOriginalToVisual(e,s.x,s.y)}}viewerToPageOriginal(t,e,i,n){const s=this.core.pageService.getPage(e);if(!s)return null;const o=this.core.viewerService.getViewer(t);if(!o)return null;const r=o.getActiveTab(),a=null==r?void 0:r.getPageByUid(e);if(!a)return null;if(Xv(a,i,n,a.isVisible,0).isOver){const t=Xv(a.image,i,n,!0,s.rotation);return{x:t.pointerX,y:t.pointerY}}return null}}const Zv=new Map,Jv=[];let Kv=class t extends Wo{constructor(t,e,i,n,s){super(),Yi(this,"parserService",void 0),Yi(this,"saverService",void 0),Yi(this,"perspectiveService",void 0),Yi(this,"filterService",void 0),Yi(this,"detectorService",void 0),Yi(this,"viewerService",void 0),Yi(this,"editService",void 0),Yi(this,"annotationService",void 0),Yi(this,"documentService",void 0),Yi(this,"trackerService",void 0),Yi(this,"imageLoadService",void 0),Yi(this,"optimizationService",void 0),Yi(this,"processService",void 0),Yi(this,"commandService",void 0),Yi(this,"fileSaveService",void 0),Yi(this,"fileService",void 0),Yi(this,"pageService",void 0),Yi(this,"resizeService",void 0),Yi(this,"imageDataService",void 0),Yi(this,"userService",void 0),Yi(this,"textLoadService",void 0),Yi(this,"pageDataService",void 0),Yi(this,"docTextSearchService",void 0),Yi(this,"coordinateService",void 0),Yi(this,"sourceStore",void 0),Yi(this,"commonCanvas",void 0),Yi(this,"onBeforeGetPageData",void 0),Yi(this,"onBeforeLoadSource",void 0),Yi(this,"onAfterLoadSource",void 0),Yi(this,"onSetExternalHandler",void 0),Yi(this,"onAfterPerspective",void 0),Yi(this,"onFilterChanged",void 0),Yi(this,"onBeforeUnload",void 0),Yi(this,"onAfterUnload",void 0),Yi(this,"removeAllDocUid",void 0),this.parserService=t,this.saverService=e,this.perspectiveService=i,this.filterService=n,this.detectorService=s,this.onBeforeGetPageData=jo(this),this.onBeforeLoadSource=jo(this),this.onAfterLoadSource=jo(this),this.onSetExternalHandler=jo(this),this.onBeforeUnload=jo(this),this.onAfterUnload=jo(this),this.onAfterPerspective=jo(this),this.onFilterChanged=jo(this),this.commonCanvas=new Pv,this.sourceStore=new zg,this.trackerService=new ev,this.documentService=new tv,this.fileService=new yv,this.pageService=new xv(this),this.imageLoadService=new wf(this),this.optimizationService=new Tf,this.processService=new Ef,this.commandService=new vv,this.fileSaveService=new bv(this),this.resizeService=new _v,this.imageDataService=new Lv(this),this.userService=new Ov("Guest"),this.textLoadService=new Uv(this),this.pageDataService=new fv(this),this.coordinateService=new qv(this),Jv.forEach(t=>{var e;null===(e=t.apply)||void 0===e||e.call(t,this)}),this.docTextSearchService=new $v(this),this.initServiceEvent(),wl.bindHandler(["opacity"],void 0,ld),wl.bindHandler(["width","height","borderWidth"],void 0,dd),wl.bindHandler(["startPoint","endPoint","lineEnding"],void 0,ud),wl.bindHandler(["r","rx","ry","borderWidth"],void 0,ad),wl.bindHandler(["points","segments"],void 0,hd),wl.bindHandler(["borderWidth"],void 0,cd),wl.bindHandler(["textContents","borderWidth","textAlign"],void 0,pd),wl.bindHandler(["textAlign"],void 0,gd)}initServiceEvent(){const{documentService:t,commandService:e,pageService:i,viewerService:n,fileService:s,parserService:o}=this;t.onDocumentCreated.on(t=>{e.createInvoker(t.docUid)},e),t.onDocumentDeleted.on(t=>{e.deleteInvokers([t.docUid])},e),n.onPagePreloadChanged.on(t=>{i.handlePagePreloadChange(t)},i),s.onDeleteFileData.on(t=>{this.sourceStore.remove(t)}),s.onDeleteFileData.on(t=>{o.freeParserByFileUid(t)},o),this.editService.onAfterCropPages.on(t=>{t.pageUids.forEach(t=>{const e=i.getPage(t);e&&e.isTextPage&&!e.parsedTexts?this.textLoadService.loadText([e.uid]).then(()=>{e.handleCropBoxForText()}):e&&e.handleCropBoxForText()})})}static getClass(t){return Zv.get(t)}static setClass(t,e){Zv.set(t,e)}static registerPlugin(e){Jv.includes(e)||Jv.push(e),e.install&&e.install(t)}getClass(t){return Zv.get(t)}createAsyncRepository(){return new zg}createViewer(e){const i=t.getClass("Viewer"),n={...e,core:this,groupUid:e.groupUid||Us()},s=this.viewerService.createViewer(i,n);return s.context.isInitialized=!0,s}removeViewer(t){this.viewerService.removeViewer(t.uid)}getViewer(t){return this.viewerService.getViewer(t)}getViewers(){return this.viewerService.getAllViewers()}getFileParserDefaultOptions(t){return this.parserService.getDefaultParserOptions(t)}setFileParserDefaultOptions(t,e){return this.parserService.setDefaultParserOptions(t,e)}setFileParser(t,e){this.parserService.registerCustomParser(t,e)}getSourceParseOptions(t,e){if("application/pdf"===e){var i;const e=t;return e.convertMode=null!==(i=e.convertMode)&&void 0!==i?i:hu.CM_AUTO,_s(e)}if("width"in t)return _s(t)}async loadSource(t,e,i,n){Ts(t)||(t=[t]),this.removeAllDocUid===e&&(this.removeAllDocUid=null);const s=this.documentService.getDocument(e);if(!s)return n&&(n.status="Failed",pp.info(n)),[];const o=Ls(i)?{insertBeforeIndex:i}:{...i},r="ignore"===o.exception,a=await this.getSourcesMimeTypes(t);if(this.removeAllDocUid===e)return this.removeAllDocUid=null,[];r||Nv.makeSureSourcesTypeSupported(!1,a,"sources");const l=[],h=async(t,i)=>{const n=a[i];r&&Nv.makeSureSourcesTypeSupported(!1,n,`sources[${i}]`);const h=[],c=Us(),d=this.getSourceParseOptions(t,n),{fileData:u}=t,{pageCount:p,batchSize:g}=await this.parserService.getParseInfo(u,n,c,d);if(this.removeAllDocUid===e)return[];this.sourceStore.set(c,{fileData:n===u.type?u:u.slice(0,u.size,n),loadOptions:d,pageCount:p}),this.fileService.addFile(c,n,p);const f=this.getBatchIndices(g,p);for(const i of f){var m;const r=await this.parserService.parse(u,n,c,i,d).catch(t=>{throw t});if(this.removeAllDocUid===e)return[];null===(m=t.extraPageData)||void 0===m||m.forEach(t=>{const e=r.find(e=>e.fileIndex===t.index);if(e){const i={...t};delete i.index,Ls(e.rotation)&&Ls(i.rotation)&&(i.rotation+=e.rotation),Ps(i.filter)||(e.filter=i.filter),Ps(i.rotation)||(e.rotation=i.rotation),Ps(i.perspectiveQuad)||(e.perspectiveQuad=i.perspectiveQuad),Ps(i.index)||(e.index=i.index)}});const a=r.map(t=>{var e;const i=Us();return t.pageUid=i,null!==(e=t.filter)&&void 0!==e||(t.filter=this.filterService.getDefaultFilterType()||"none"),i});l.push({fileData:u,mimeType:n,fileUid:c,parsedPages:r,indices:i,parseOptions:d}),this.fileService.addUsersByParsedPages(c,r),r.forEach(t=>{this.annotationService.annotationApp.createAnnotationPage(t.pageUid)}),this.pageService.startCreatePagesByParsedPages(r,c,s),this.documentService.addPagesToDocument(e,a,o.insertBeforeIndex),Ps(o.insertBeforeIndex)||(o.insertBeforeIndex+=r.length),h.push(...a)}return h};this.onBeforeLoadSource.emit({docUid:e});const c=[];for(const[i,s]of t.entries())try{const t=await h(s,i);if(this.removeAllDocUid===e)return this.removeAllDocUid=null,[];c.push(...t),n&&(n.status="InProgress",n.details.current=i+1,pp.info(n))}catch(t){if(!r)throw t;pp.warning(t)}for(let t=0;t<l.length;t++){const i=l[t];if(await this.parserService.parseAnnotation(i.fileData,i.mimeType,i.fileUid,i.parsedPages,i.indices,i.parseOptions),this.removeAllDocUid===e)return this.removeAllDocUid=null,[];this.annotationService.createAnnotationsByParsedPages(e,i.parsedPages),i.parsedPages.forEach(t=>{const e=this.pageService.getPage(t.pageUid);e&&t.annotations&&(e.annotations=t.annotations.map(t=>t.uid))})}const d=c.map(t=>s.pages.indexOf(t));return this.onAfterLoadSource.emit(Tm.create(e,d,c)),this.documentService.onPagesAddedOut.emit(Tm.create(e,[...d],[...c])),n&&(n.details.current=n.details.total,n.status="Completed",pp.info(n)),c}async getSourcesMimeTypes(t){const e=[];for(const i of t){const t=this.parserService.getCustomParserClasses(i.fileData.type)?i.fileData.type:await Io(i.fileData);e.push(t)}return e}getAnnotationsByPageUid(t){const e=this.pageService.getPage(t);return e?e.annotations.map(t=>this.annotationService.getAnnotationByUid(t)):[]}getBatchIndices(t,e){const i=[];for(let n=0;n<e;){const s=t>0?Math.min(t,e-n):e;i.push(Array.from({length:s},(t,e)=>n+e)),n+=s}return i}getPageData(t){return this.pageDataService.requestPageData(t)}async setCustomData(t,e){const i=this.pageService.getPage(t);return i?(i.customData=_s(e),!0):Promise.reject()}async getCustomData(t){const e=this.pageService.getPage(t);return e?_s(e.customData):Promise.reject()}async updatePage(t,e){var i,n;const s=this.pageService.getPage(t);if(!s)return!1;const{fileData:o}=e,r=Us(),a=this.parserService.getCustomParserClasses(o.type)?o.type:await Io(o);Nv.makeSureSourcesTypeSupported(!1,[a],"data");const l=this.getSourceParseOptions(e,a),{pageCount:h}=await this.parserService.getParseInfo(o,a,r,l).catch(t=>{throw t});if(Ls(e.fileIndex)&&(e.fileIndex>=h||e.fileIndex<0)){const t=["UpdateSource.fileIndex is out of range"];throw{...pp.PARAM_INVALID,details:t}}this.sourceStore.set(r,{fileData:o,loadOptions:l,pageCount:h}),this.fileService.addFile(r,a,h);const[c]=await this.parserService.parse(o,a,r,[e.fileIndex||0],l).catch(t=>{throw t});return c.pageUid=t,null!==(i=c.filter)&&void 0!==i||(c.filter=this.filterService.getDefaultFilterType()||"none"),await this.parserService.parseAnnotation(o,a,r,[c],[e.fileIndex||0],l),this.commandService.removePageFromCommand(s.doc.uid,[t]),this.fileService.addUser(r,e.fileIndex||0,t),this.fileService.deleteUser(s.fileUid,s.fileIndex,t),null===(n=this.annotationService)||void 0===n||n.deleteAnnotations(s.annotations,!1),this.pageService.updatePage(t,o,{...c,...e,fileUid:r,annotations:[]}),this.annotationService.createAnnotationsByParsedPages(s.doc.uid,[c]),this.pageService.getPage(t).isUpdated=!0,!0}async getPerspectivePreviewData(t,e,i){const n=this.pageService.getPage(t);if(!n)return null;const s=await this.imageDataService.getRaw(t);if(!s)return null;let{quad:o}=n;o=o?o.map(t=>Bo(t,Cr.displayResolution,n.resource.resolutionX)):[[0,0],[s.width,0],[s.width,s.height],[0,s.height]];const r=await this.processService.perspectivePreview(s.data,4,o,{width:s.width,height:s.height},{...e,...i});return Promise.resolve(r)}createDocument(t){return this.documentService.createDocument(t)}getDocument(t){return this.documentService.getDocument(t)}deleteDocuments(t){const{documentService:e,pageService:i}=this;if(t.map(t=>e.getDocument(t)).includes(void 0))return!1;const n=Nf.create(t);e.onBeforeDeleteDocs.emit(n),t.forEach(t=>{const n=e.getDocument(t);var s;n&&(n.pages.forEach(t=>{const e=i.getPage(t);this.fileService.deleteUser(e.fileUid,e.fileIndex,t)}),null===(s=this.annotationService)||void 0===s||s.deleteAnnotationPages([...n.pages]),i.deletePages(n.pages))});const s=e.deleteDocuments(t);return e.onAfterDeleteDocs.emit(n),s}renameDocument(t,e){this.documentService.renameDocument(t,e)}transferDocument(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{documentService:n}=this,s=n.getDocument(t),o=n.getDocument(e);if(!s||!o)return!1;if(t===e&&!i.copy)return!i.sourceIndices||this.movePages(t,i.sourceIndices,i.insertBeforeIndex);let r=[];if(r=null!=i&&i.sourceIndices?Ev(i.sourceIndices).map(t=>s.pages[t]):[...s.pages],!r.length)return!0;i.copy?r.forEach((t,e,n)=>{const s=this.pageService.getPage(t),r=Us();if(this.fileService.addUser(s.fileUid,s.fileIndex,r),this.pageService.copyPage(r,o,s),!1!==(null==i?void 0:i.includeAnnotations)&&this.annotationService){this.annotationService.annotationApp.createAnnotationPage(r);const t=s.annotations.map(t=>({...this.annotationService.getAnnotationByUid(t).getConfig(),docUid:o.uid,pageUid:r,uid:Us()}));t.length&&this.annotationService.annotationApp.createAnnotations(t)}n[e]=r}):(n.removePagesFromDocument(s.uid,r),r.forEach(t=>{const e=this.pageService.getPage(t);var n;e.doc=o,!1===(null==i?void 0:i.includeAnnotations)&&(null===(n=this.annotationService)||void 0===n||n.deleteAnnotations(e.annotations),e.annotations=[])})),n.addPagesToDocument(o.uid,r,i.insertBeforeIndex);const a=r.map(t=>o.pages.indexOf(t));return n.onPagesAddedOut.emit(Tm.create(o.uid,a,r)),!0}mergeDocuments(t,e){const{documentService:i}=this,n=i.createDocument(e);if(!t.length)return n;t=Ev(t);const s=[];if(t.forEach(t=>{const e=i.getDocument(t);s.push(...e.pages)}),null!=e&&e.deleteOriginal?(i.deleteDocuments(t),s.forEach(t=>{const i=this.pageService.getPage(t);var s;i.doc=n,!1===(null==e?void 0:e.includeAnnotations)&&(null===(s=this.annotationService)||void 0===s||s.deleteAnnotations(i.annotations),i.annotations=[])})):s.forEach((t,i,s)=>{const o=this.pageService.getPage(t),r=Us();if(this.fileService.addUser(o.fileUid,o.fileIndex,r),this.pageService.copyPage(r,n,o),!1!==(null==e?void 0:e.includeAnnotations)&&this.annotationService){this.annotationService.annotationApp.createAnnotationPage(r);const t=o.annotations.map(t=>({...this.annotationService.getAnnotationByUid(t).getConfig(),docUid:n.uid,pageUid:r,uid:Us()}));t.length&&this.annotationService.annotationApp.createAnnotations(t)}s[i]=r}),s.length){i.addPagesToDocument(n.uid,s);const t=s.map(t=>n.pages.indexOf(t));i.onPagesAddedOut.emit(Tm.create(n.uid,t,s))}return n}openDocument(t,e){return this.openOrCloseDocument(t,e)}closeDocument(t,e){return this.openOrCloseDocument(t,e,!0)}openOrCloseDocument(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=this.documentService.getDocument(t);if(!n||!this.viewerService.hasViewer(e))return!1;const s=this.viewerService.getViewer(e);return i?this.documentService.onCloseDocument.emit(Df.create(n,e,s.groupUid)):this.documentService.onOpenDocument.emit(If.create(n,e,s.groupUid)),this.commandService.emitOperationsChanged(t),!0}deletePages(t,e){var i;return e=Ev(e),this.commandService.removePageFromCommand(t,[...e]),e.forEach(t=>{const e=this.pageService.getPage(t);this.fileService.deleteUser(e.fileUid,e.fileIndex,t)}),null===(i=this.annotationService)||void 0===i||i.deleteAnnotationPages(e),this.documentService.removePagesFromDocument(t,[...e]),this.pageService.deletePages(e),!0}deleteAllPages(t){var e;this.removeAllDocUid=t;const i=this.documentService.getDocument(t),n=[...i.pages];return this.commandService.removePageFromCommand(t,n),i.pages.forEach(t=>{const e=this.pageService.getPage(t);this.fileService.deleteUser(e.fileUid,e.fileIndex,t)}),null===(e=this.annotationService)||void 0===e||e.deleteAnnotationPages(i.pages),this.documentService.removeAllPagesFromDocument(t),this.pageService.deletePages(n),!0}movePages(t,e,i){return e=Ev(e),this.documentService.movePages(t,e,i)}swapPages(t,e,i){return this.documentService.swapPages(t,e,i)}reorderPages(t,e){return e=Ev(e),this.documentService.reorderPages(t,e)}async printPages(t,e,i){const n=this.documentService.getDocument(t);if(!n)return Promise.reject(pp.DOC_NOT_EXIST);const s=e||Array.from(Array(n.pages.length).keys()),o=[];for(let t=0;t<s.length;t++){var r;const e=this.getPageData(n.pages[s[t]]),a=await e.display({renderAnnotation:null===(r=null==i?void 0:i.printAnnotation)||void 0===r||r,isGetPrintPageData:!0});e.destroy(),o.push(a)}if(0===o.length)return Promise.reject();const a=[];return o.forEach(t=>{a.push({data:t.data,width:t.width,height:t.height})}),function(t){let e="",i=0,n=0;const s=[];t.forEach((t,o)=>{let r=1120,a=850;const l=a/t.width,h=r/t.height;l<h?r=Math.floor(t.height*l):l>h&&(a=Math.floor(t.width*h));const c=Fs(t.data).data;s.push(c),e+=`<div class="imageContainer"><img id="DDV_Image${o}" src='${c}' referrerpolicy='strict-origin-when-cross-origin'"/></div>`,i+=a,n+=r});const o=`alwaysRaised=yes, z-look=yes, top=0, left=0, toolbar=no, menubar=no, location=no, status=no,width=${i}, height=${n}`,r=window.open("about:blank","_blank",o),a=`<html><head>\n                    <style>\n                        @media print {\n                            body, html {\n                                margin: 0;\n                                padding: 0;\n                                width: 100%;\n                                height: 100%;\n                            }\n\n                            .imageContainer {\n                                break-after: page;\n                                position: relative;\n                                width: 100%;\n                                height: 100%;\n                                display: flex;\n                                align-items: center;\n                                justify-content: center\n                            }\n\n                            img {\n                                object-fit: contain;\n                                max-width: 100%;\n                                max-height: 100%;\n                            }\n                        }\n                    </style>\n                </head><body id='DDV_body'>${e}</body></html>`;r&&(r.document.write(a),r.document.close(),r.addEventListener("load",()=>{const t=r.document.querySelectorAll("img"),e=[];t.forEach(t=>{t.complete&&t.naturalWidth>0?e.push(Promise.resolve()):e.push(new Promise(e=>{t.onload=()=>e(),t.onerror=()=>e()}))}),Promise.all(e).then(()=>{setTimeout(()=>{r.print(),s.forEach(t=>{URL.revokeObjectURL(t)})},100)})}))}(a),!0}setDetectHandler(t,e){this.onSetExternalHandler.emit(Bv.create("detect")),this.detectorService.setDetector(e)}setImageFilterHandler(t){this.onSetExternalHandler.emit(Bv.create("filter")),this.filterService.setImageFilter(t)}clearExternalHandler(t){if(Os(t))switch(t){case"documentBoundariesDetect":this.setDetectHandler(t,null);break;case"imageFilter":this.setImageFilterHandler(null)}}unload(){var t;this.onBeforeUnload.emit(),this.viewerService.reset(),this.commonCanvas.reset(),this.sourceStore.reset(),this.documentService.reset(),this.fileService.reset(),this.pageService.reset(),this.commandService.reset(),this.resizeService.reset(),this.processService.reset(),this.detectorService.reset(),this.parserService.reset(),this.fileSaveService.reset(),null===(t=this.annotationService)||void 0===t||t.reset(),lg.reset(),$o.unload(),this.onAfterUnload.emit()}preloadModule(t){$o.preloadModule(t)}async perspectivePage(t,e,i){let n,s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=this.pageService.getPage(e);if(o.setQuad(i)){if(o.isTextPage=!1,this.annotationService.deleteAnnotations(o.annotations,!1),this.commandService.removePageFromCommand(t,[e]),o.quad){const{width:t,height:e}=jm(o.quad);o.original.updateImageDetail({width:t,height:e}),o.display.updateImageDetail({width:t,height:e})}this.imageLoadService.cancelLoadOriginalImage(e),o.original.reset(),s||(n=await this.imageDataService.getOriginal(e)),this.imageLoadService.cancelLoadDisplayImage(e),this.imageLoadService.cancelLoadThumbnailImage(e),o.display.reset(),o.thumbnail.reset();let{width:r,height:a}=o.original.getPageSize();o.isFull?(o.mediaBox={...o.initState.mediaBox},o.cropBox={...o.initState.cropBox}):(s&&({width:r,height:a}=jm(o.quad)),o.mediaBox={left:0,top:0,width:r,height:a},o.cropBox={...o.mediaBox}),this.onAfterPerspective.emit(Bf.create(o.doc.uid,e,i,r,a))}return s?null:n||this.imageDataService.getOriginal(e)}async filterPages(t,e,i){e.forEach(t=>{const e=this.pageService.getPage(t);e.filter!==i&&(e.filter=i,e.display.reset(),e.thumbnail.reset())});const n=kf.create(t,e,i);return this.onFilterChanged.emit(n),!0}insertBlankPage(t,e,i,n,s,o){const r=this.documentService.getDocument(t);if(!r)return"";this.onBeforeLoadSource.emit({docUid:t});const a=Us(),l={fileData:new Blob([""],{type:"application/ddv-blank-image"}),width:null!=e?e:816,height:null!=i?i:1056,resolutionX:null!=n?n:96,resolutionY:null!=s?s:96},h=this.getSourceParseOptions(l,"application/ddv-blank-image");this.sourceStore.set(a,{fileData:l.fileData,loadOptions:h,pageCount:1}),this.fileService.addFile(a,"application/ddv-blank-image",1),this.parserService.parse(l.fileData,"application/ddv-blank-image",a,[0],h);const{displayResolution:c}=Cr,d=Us();this.fileService.addUser(a,0,d);const u={resource:{data:l.fileData,width:l.width,height:l.height,resolutionX:l.resolutionX,resolutionY:l.resolutionY},mediaBox:{left:0,top:0,width:l.width/l.resolutionX*c,height:l.height/l.resolutionY*c},cropBox:{left:0,top:0,width:l.width/l.resolutionX*c,height:l.height/l.resolutionY*c},annotations:[],fileIndex:0,pageUid:d,fileUid:a};return this.pageService.createPage(u,r),this.annotationService.createAnnotationsByParsedPages(t,[u]),this.documentService.addPagesToDocument(t,[d],o),this.onAfterLoadSource.emit(Tm.create(t,[r.pages.indexOf(d)],[d])),this.documentService.onPagesAddedOut.emit(Tm.create(t,[r.pages.indexOf(d)],[d])),d}async getPageSourceInfo(t){const e=this.pageService.getPage(t),i={};i.bitDepth=e.resource.bitDepth,i.resolutionX=e.resource.resolutionX,i.resolutionY=e.resource.resolutionY;const n=await this.sourceStore.get(e.fileUid);if("application/pdf"!==n.fileData.type)return i.pageContentType=n.fileData.type,i;if(e.pdfOptions&&e.pdfOptions.pageContentType)return i.pageContentType=e.pdfOptions.pageContentType,i;const s=new dr;try{const t=await s.getPdfPageContentType({fileSource:n.fileData,password:n.loadOptions.password},e.fileIndex);return e.pdfOptions&&(e.pdfOptions.pageContentType=t),i.pageContentType=t,i}finally{s.destroy()}}isPageModified(t){var e;const i=this.pageService.getPage(t);if(!i)return!1;if(!i.isFull)return!0;if(i.filter&&"none"!==i.filter)return!0;if(i.isUpdated)return!0;const{cropBox:n,initState:s}=i;if(n.left!==s.cropBox.left||n.top!==s.cropBox.top||n.width!==s.cropBox.width||n.height!==s.cropBox.height)return!0;const o=i.getActions(),r=i.getPerspectiveActions();let a=0;if(o.forEach(t=>{"rotate"===t.type&&(a+=t.angle)}),r.forEach(t=>{"rotate"===t.type&&(a+=t.angle)}),a%360!=0)return!0;if(this.fileSaveService.isPdfInfoChanged(i))return!0;const l=this.getAnnotationsByPageUid(t);if(l.length!==((null==i||null===(e=i.pdfOptions)||void 0===e?void 0:e.parsedAnnotCount)||0))return!0;const h=[...l];h.sort((t,e)=>t.layer-e.layer);for(let t=0;t<h.length;t++)if(Ps(h[t].oriIndex)||h[t].modified||t!==h[t].parsedOriIndex)return!0;return!1}async isPdfEncrypted(t){const e=await this.getSourcesMimeTypes([{fileData:t}]);if(!e.length||"application/pdf"!==e[0])return!1;const i=Us();let n=!1;return await this.parserService.getParseInfo(t,e[0],i).catch(t=>{-80202===t.code&&(n=!0)}),this.parserService.freeParserByFileUid(i),n}async getSearchedTextsByPageUid(t,e,i){if(0===e.length)return[];const n=this.pageService.getPage(t);if(null==n||!n.isTextPage)return[];if(await new Promise(t=>{setTimeout(()=>{t(1)},0)}),await this.textLoadService.loadText([t]),null==n||!n.isTextPage)return[];let s=e;return e.trim().length>0&&(s=e.trim()),s=s.replace(/\s+/g,"<<WHITESPACE>>"),s=Qv(s),s=s.replace(/<<WHITESPACE>>/g,"\\s+"),null!=i&&i.wholeWord&&(s=`(^|\\W)(${s})($|\\W)`),n.getSearchedText(new RegExp(s,"gm"+(null!=i&&i.caseSensitive?"":"i")),null==i?void 0:i.wholeWord)}async getSearchedTexts(t,e,i){if(0===e.length)return null;const n=this.documentService.getDocument(t);if(!n)return null;await this.textLoadService.loadText(n.pages);const s=[];let o=e;e.trim().length>0&&(o=e.trim()),o=o.replace(/\s+/g,"<<WHITESPACE>>"),o=Qv(o),o=o.replace(/<<WHITESPACE>>/g,"\\s+"),null!=i&&i.wholeWord&&(o=`(^|\\W)(${o})($|\\W)`);const r=new RegExp(o,"gm"+(null!=i&&i.caseSensitive?"":"i"));return n.pages.forEach((t,e)=>{const n=this.pageService.getPage(t);if(n.isTextPage){const t=n.getSearchedText(r,null==i?void 0:i.wholeWord);s.push(...t)}}),s}async getSearchedTextPage(t,e,i){if(0===e.length)return null;const n=this.documentService.getDocument(t);if(!n)return null;await this.textLoadService.loadText(n.pages);let s=e;e.trim().length>0&&(s=e.trim()),s=s.replace(/\s+/g,"<<WHITESPACE>>"),s=Qv(s),s=s.replace(/<<WHITESPACE>>/g,"\\s+"),null!=i&&i.wholeWord&&(s=`(^|\\W)(${s})($|\\W)`);const o=[],r=new RegExp(s,"gm"+(null!=i&&i.caseSensitive?"":"i"));return n.pages.forEach((t,e)=>{const n=this.pageService.getPage(t);if(n.isTextPage){const e=n.getSearchedText(r,null==i?void 0:i.wholeWord);e.length&&o.push({pageUid:t,texts:e})}}),o}createTextSearcher(t,e,i){return this.docTextSearchService.createDocTextSearcher(t,e,i)}};function Qv(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ty(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const{tag:i,style:n,id:s,className:o,children:r}=t,a=document.createElement(i);return s&&(a.id=s+e),o&&(a.className=o),n&&function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(Os(e))t.style.cssText=e;else if(i){let i="";Object.keys(e).forEach(t=>{i+=`${t}:${e[t]};`}),t.style.cssText=i}else Object.keys(e).forEach(i=>{t.style[i]=e[i]})}(a,n),r&&r.forEach(t=>{const i=ty(t,e);a.appendChild(i)}),a}function ey(t){t&&(t.style.display="none")}function iy(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";t&&(t.style.display=e)}const ny=t=>parseFloat(Number(t).toFixed(4));function sy(t){let e=1;return t.forEach(t=>{if(t.height>18){const i=t.height/18;e=Math.max(e,i)}}),Math.min(e,8)}function oy(t){return!!t&&("mouse"===t.pointerType||!Ms()&&"pen"===t.pointerType)}class ry extends Wo{constructor(){super(),Yi(this,"uid",void 0),Yi(this,"type",void 0),Yi(this,"action",void 0),Yi(this,"isValid",void 0),this.isValid=!0,this.uid=Us()}execute(){return null}undo(){return null}}new class extends Wo{constructor(){super(...arguments),Yi(this,"docCreated",jo(this)),Yi(this,"docDeleted",jo(this)),Yi(this,"pageAdded",jo(this)),Yi(this,"pageDeleted",jo(this)),Yi(this,"annotationCreated",jo(this)),Yi(this,"annotationDeleted",jo(this)),Yi(this,"annotationUpdated",jo(this)),Yi(this,"addReply",jo(this)),Yi(this,"commentDeleted",jo(this)),Yi(this,"commentUpdated",jo(this))}};class ay extends Hr{static create(t){return new ay(t,t.uid)}constructor(t,e){super(e),Yi(this,"type",void 0),Yi(this,"docUid",void 0),Yi(this,"pageUid",void 0),Yi(this,"style",void 0),Yi(this,"transform",void 0),Yi(this,"flags",void 0),Yi(this,"comment",void 0),Yi(this,"layer",void 0),Yi(this,"modified",!1),Yi(this,"flattened",!1),Yi(this,"oriIndex",void 0),Yi(this,"customData",{}),Yi(this,"startTextPosition",void 0),Yi(this,"endTextPosition",void 0),Yi(this,"startCharRect",void 0),Yi(this,"endCharRect",void 0),Yi(this,"lines",void 0),Yi(this,"isBlankTextAssist",!1),Yi(this,"isMatchText",!1),Yi(this,"isPageTextLoaded",!1),Yi(this,"source",void 0),Yi(this,"parsedOriIndex",void 0),this.type=t.type,this.docUid=t.docUid,this.pageUid=t.pageUid,this.style=t.style,this.flags=t.flags||["print"],this.transform=t.transform,this.oriIndex=t.oriIndex,Ps(null==t?void 0:t.modified)||(this.modified=t.modified),Ps(null==t?void 0:t.flattened)||(this.flattened=t.flattened),this.customData=t.customData||{},this.source=t.source||"file",this.parsedOriIndex=t.parsedOriIndex,this.initTextAssistCtrl(t)}initTextAssistCtrl(t){var e;if(["highlight","underline","strikeout"].includes(this.type))if(null!=t&&t.startCharRect&&null!=t&&t.endCharRect)this.startCharRect=t.startCharRect,this.endCharRect=t.endCharRect;else if(null!==(e=this.style.lines)&&void 0!==e&&e.length)if("api"===this.source||"file"===this.source){const t=16,e=this.style.lines[0],i=this.style.lines[this.style.lines.length-1];this.startCharRect={left:e.left,top:e.top,width:t,height:t},this.endCharRect={left:i.left+i.width-t,top:i.top,width:t,height:i.height}}else"user"===this.source&&(this.isMatchText=!0,this.isBlankTextAssist=!1,this.isPageTextLoaded=!0)}getConfig(){return{uid:this.uid,docUid:this.docUid,pageUid:this.pageUid,type:this.type,style:_s(this.style),transform:_s(this.transform),flags:_s(this.flags),comment:_s(this.comment),layer:this.layer,creationDate:this.comment.creationDate,modificationDate:this.comment.modificationDate,oriIndex:this.oriIndex,modified:this.modified,flattened:this.flattened,customData:_s(this.customData),source:this.source,parsedOriIndex:this.parsedOriIndex,startCharRect:_s(this.startCharRect),endCharRect:_s(this.endCharRect),startTextPosition:_s(this.startTextPosition),endTextPosition:_s(this.endTextPosition)}}clone(t,e){const i=ay.create({docUid:this.docUid,pageUid:t,type:this.type,style:_s(this.style),transform:_s(this.transform),flags:this.flags.slice(),comment:this.comment,oriIndex:this.oriIndex,modified:this.modified,customData:_s(this.customData),source:this.source,parsedOriIndex:this.parsedOriIndex}),n=this.comment.clone(i.uid,e);return i.comment=n,i.layer=this.layer,i}updateStyle(t){Object.assign(this.style,t)}updateComment(t){this.comment.updateComment(t)}addReplies(t){this.comment.replies.push(...t)}deleteReplies(t){const e=this.comment.replies;t.forEach(t=>{if(e.includes(t)){const i=e.findIndex(e=>e.uid===t.uid);e.splice(i,1)}})}updateReply(t){const e=this.comment.replies.findIndex(e=>e.uid===t.uid);this.comment.replies[e]=t}getAllReplies(){return[...this.comment.replies]}deleteReplyReviewSate(t){const e=this.comment.getReply(t);e&&e.deleteReviewState()}addReplyReviewState(t,e){const i=this.comment.getReply(t);i&&i.setReviewState(e)}getReplyReviewState(t){const e=this.comment.getReply(t);return null!=e&&e.reviewStates.length?e.reviewStates[e.reviewStates.length-1]:null}deleteReplyMarkedSate(t){const e=this.comment.getReply(t);e&&e.deleteMarkedState()}addReplyMarkedState(t,e){const i=this.comment.getReply(t);i&&i.setMarkedState(e)}getReplyMarkedState(t){const e=this.comment.getReply(t);return null!=e&&e.markedStates.length?e.markedStates[e.markedStates.length-1]:null}}class ly{static create(t){return new ly(t)}constructor(t){Yi(this,"uid",void 0),Yi(this,"author",void 0),Yi(this,"contents",void 0),Yi(this,"creationDate",void 0),Yi(this,"state",void 0),this.uid=t.uid,this.author=t.author,this.contents=t.contents,this.creationDate=t.creationDate,this.state=t.state}}class hy{static create(t){return new hy(t)}constructor(t){Yi(this,"uid",void 0),Yi(this,"author",void 0),Yi(this,"contents",void 0),Yi(this,"creationDate",void 0),Yi(this,"state",void 0),this.uid=t.uid,this.author=t.author,this.contents=t.contents,this.creationDate=t.creationDate,this.state=t.state}}class cy extends Wr{static create(t){return new cy(t,t.uid)}constructor(t,e){var i,n;super(e),Yi(this,"annotationUid",void 0),Yi(this,"author",void 0),Yi(this,"subject",void 0),Yi(this,"contents",void 0),Yi(this,"creationDate",void 0),Yi(this,"modificationDate",void 0),Yi(this,"markedStates",void 0),Yi(this,"reviewStates",void 0),this.annotationUid=t.annotationUid,this.author=t.author,this.subject=t.subject,this.contents=t.contents,this.creationDate=t.creationDate,this.modificationDate=t.modificationDate,this.markedStates=[],this.reviewStates=[],null!==(i=t.markedStates)&&void 0!==i&&i.length&&t.markedStates.forEach(t=>{const e=hy.create(t);this.markedStates.push(e)}),null!==(n=t.reviewStates)&&void 0!==n&&n.length&&t.reviewStates.forEach(t=>{const e=ly.create(t);this.reviewStates.push(e)})}updateReply(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,t)}setMarkedState(t){const e=this.markedStates.length,i=this.markedStates[e-1];if((null==i?void 0:i.state)!==t.state||!i&&"marked"===t.state){const e=hy.create(t);return this.markedStates.push(e),!0}return!1}deleteMarkedState(){this.markedStates.pop()}setReviewState(t){const e=ly.create(t);this.reviewStates.push(e)}deleteReviewState(){this.reviewStates.pop()}clone(t,e){const i=cy.create({annotationUid:t,author:this.author,subject:this.subject,contents:this.contents,creationDate:e,modificationDate:e});return this.cloneStates(i),i}cloneStates(t){this.markedStates.forEach(e=>{const i=hy.create({...e,uid:Us()});t.markedStates.push(i)}),this.reviewStates.forEach(e=>{const i=ly.create({...e,uid:Us()});t.reviewStates.push(i)})}}class dy extends cy{static create(t,e){return new dy(t,e)}constructor(t,e){super(t,e),Yi(this,"replies",void 0),this.replies=[]}updateComment(t){Object.assign(this,t)}getReply(t){return this.replies.find(e=>e.uid===t.uid)}clone(t,e){const i=dy.create({annotationUid:t,author:this.author,subject:this.subject,contents:this.contents,creationDate:e,modificationDate:e});return this.cloneStates(i),this.replies.forEach(n=>{i.replies.push(n.clone(t,e))}),i}}class uy extends Wr{static create(t){return new uy(t)}constructor(t){super(t),Yi(this,"bottom",void 0),Yi(this,"top",void 0),Yi(this,"annotations",void 0),Yi(this,"layers",void 0),this.annotations=[],this.bottom=-1,this.top=0,this.layers=[]}clone(t){const e=uy.create(t);return e.top=this.top,e.bottom=this.bottom,e.annotations=this.annotations.slice(),e.layers=_s(this.layers),e}createTop(){const{top:t}=this;return this.top+=1,t}addAnnotation(t,e){if(!this.annotations.includes(t)){this.annotations.push(t);const i={annotationUid:t,layer:e};return this.layers.push(i),Ps(e)?(i.layer=this.top,this.top+=1):(this.sortLayers(),this.top=Math.max(this.top,e+1)),i}return null}sortLayers(){this.layers.sort((t,e)=>t.layer-e.layer)}deleteAnnotations(t){t.forEach(t=>{const e=this.annotations.indexOf(t);e>-1&&this.annotations.splice(e,1);const i=this.layers.findIndex(e=>e.annotationUid===t);i>-1&&this.layers.splice(i,1)})}moveAnnotation(t){const e=this.annotations.indexOf(t);if(e<0)return null;const i=this.layers.findIndex(e=>e.annotationUid===t);if(i<0)return null;const n={annotationUid:t,index:e,layerIndex:i,layer:this.layers[i].layer};return this.deleteAnnotations([t]),n}undoMoveAnnotation(t){const{annotationUid:e}=t;this.annotations.includes(e)||this.layers.find(t=>t.annotationUid===e)||(this.annotations.splice(t.index,0,e),this.layers.splice(t.layerIndex,0,{annotationUid:e,layer:t.layer}))}bringForward(t){const e=this.layers.findIndex(e=>e.annotationUid===t);if(e<0)return null;const i=this.layers[e],n=this.layers[e+1];return n&&(this.switchLayer(i,n),this.sortLayers()),{curLayer:i,forward:n}}switchLayer(t,e){const i=t.layer;t.layer=e.layer,e.layer=i}sendBackward(t){const e=this.layers.findIndex(e=>e.annotationUid===t);if(e<0)return null;const i=this.layers[e],n=this.layers[e-1];return n&&(this.switchLayer(i,n),this.sortLayers()),{curLayer:i,backward:n}}bringToFront(t){const e=this.layers.findIndex(e=>e.annotationUid===t);if(e<0)return null;const i=this.layers[e];return e<this.layers.length-1&&(i.layer=this.top,this.top+=1,this.sortLayers()),i}sendToBack(t){const e=this.layers.findIndex(e=>e.annotationUid===t);if(e<0)return null;const i=this.layers[e];return e>0&&(i.layer=this.bottom,this.bottom-=1,this.sortLayers()),i}restoreLayer(t,e){const i=this.layers.findIndex(e=>e.annotationUid===t);return i<0?null:(this.layers[i].layer=e,this.sortLayers(),!0)}getLayerState(t){const e=this.layers.findIndex(e=>e.annotationUid===t);if(e<0)return{back:!1,front:!1,forward:!1,backward:!1};const i={back:!0,front:!0,forward:!0,backward:!0};return 0===e&&(i.back=!1,i.backward=!1),e===this.layers.length-1&&(i.front=!1,i.forward=!1),1===this.layers.length&&(i.front=!1,i.forward=!1,i.back=!1,i.backward=!1),i}getAnnotationUidListByLayer(){return this.layers.slice().sort((t,e)=>t.layer-e.layer).map(t=>t.annotationUid)}}const py=new class{constructor(){Yi(this,"db",void 0),this.db=new Map}findAnnotationByUid(t){return this.db.get(t)}deleteAnnotation(t){return!!this.db.has(t.uid)&&(this.db.delete(t.uid),!0)}has(t){return this.db.has(t.uid)}save(t){this.db.set(t.uid,t)}clear(){this.db.clear()}},gy=new class{constructor(){Yi(this,"db",void 0),this.db=new Map}findCommentByUid(t){return this.db.get(t)}deleteComment(t){this.db.has(t.uid)&&this.db.delete(t.uid)}has(t){return this.db.has(t.uid)}save(t){this.db.set(t.uid,t)}clear(){this.db.clear()}},fy=new class{constructor(){Yi(this,"db",void 0),this.db=new Map}findPageByUid(t){return this.db.get(t)}deletePagesByUids(t){t.forEach(t=>{this.db.delete(t)})}has(t){return this.db.has(t.uid)}save(t){this.db.set(t.uid,t)}clear(){this.db.clear()}},my=new class extends Wo{constructor(){super(...arguments),Yi(this,"annotationCreated",jo(this)),Yi(this,"annotationDeleted",jo(this)),Yi(this,"annotationUpdated",jo(this)),Yi(this,"commentDeleted",jo(this)),Yi(this,"commentUpdated",jo(this)),Yi(this,"addReply",jo(this)),Yi(this,"replyDeleted",jo(this)),Yi(this,"replyUpdated",jo(this)),Yi(this,"addReplyReviewState",jo(this)),Yi(this,"deleteReplyReviewState",jo(this)),Yi(this,"addReplyMarkedState",jo(this)),Yi(this,"deleteReplyMarkedState",jo(this)),Yi(this,"bringFroward",jo(this)),Yi(this,"sendBackward",jo(this)),Yi(this,"bringToFront",jo(this)),Yi(this,"sendToBack",jo(this)),Yi(this,"restoreLayer",jo(this)),Yi(this,"annotationPageSwitched",jo(this))}};class vy extends jr{static create(t){return new vy(t)}constructor(t){super("annotationCreatedDomainEvent"),Yi(this,"annotations",void 0),this.annotations=t}}const yy=new class{constructor(t,e,i,n){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"annotationPageRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.annotationPageRepo=i,this.eventHooks=n}execute(t){const e=t.map(t=>{const e=ay.create({...t}),i=this.annotationPageRepo.findPageByUid(e.pageUid).addAnnotation(e.uid,t.layer);if(i&&(e.layer=i.layer),this.annotationRepo.save(e),t.comment){var n;const i=dy.create(t.comment);e.comment=i,null!==(n=t.comment.replies)&&void 0!==n&&n.length&&t.comment.replies.forEach(t=>{const e=cy.create(t);i.replies.push(e),this.replyRepo.save(e)})}return e}),i=vy.create(e);return this.eventHooks.annotationCreated.emit(i),e}}(py,gy,fy,my);class xy extends jr{static create(t,e){return new xy(t,e)}constructor(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];super("annotationDeletedDomainEvent"),Yi(this,"annotations",void 0),Yi(this,"emitEvent",void 0),this.annotations=t,this.emitEvent=e}}const wy=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"annotationPageRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.annotationPageRepo=e,this.eventHooks=i}execute(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];for(const e of t)if(!this.annotationRepo.has(e))return!1;t.forEach(t=>{this.annotationRepo.deleteAnnotation(t),this.annotationPageRepo.findPageByUid(t.pageUid).deleteAnnotations([t.uid])});const i=xy.create(t,e);return this.eventHooks.annotationDeleted.emit(i),!0}}(py,fy,my),Cy=new class{constructor(t){Yi(this,"annotationRepo",void 0),this.annotationRepo=t}execute(t){return this.annotationRepo.findAnnotationByUid(t)}}(py);class by extends jr{static create(t){return new by(t)}constructor(t){super("addReplyDomainEvent"),Yi(this,"reply",void 0),this.reply=t}}const Sy=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.eventHooks=i}execute(t){const e=this.annotationRepo.findAnnotationByUid(t.annotationUid),i=cy.create({annotationUid:t.annotationUid,author:t.author,contents:t.contents,creationDate:t.creationDate,modificationDate:t.modificationDate,subject:""});e.addReplies([i]),this.replyRepo.save(i);const n=by.create(i);return this.eventHooks.addReply.emit(n),!0}}(py,gy,my);class Ty extends jr{static create(t,e,i){return new Ty(t,e,i)}constructor(t,e,i){super("annotationUpdatedDomainEvent"),Yi(this,"updateDetails",void 0),Yi(this,"updatedBy",void 0),Yi(this,"updateActions",void 0),this.updateDetails=t,this.updatedBy=e,this.updateActions=i}}const Ey=new class{constructor(t,e){Yi(this,"annotationRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.eventHooks=e}execute(t){const e=t.updateDetails.map(t=>{const e=t.to.changed,i=this.annotationRepo.findAnnotationByUid(t.annotationUid);return i?(e.style&&i.updateStyle(e.style),e.transform&&_o(e.transform,i.transform),e.flags&&(i.flags=[...e.flags]),Ps(e.flattened)||(i.flattened=e.flattened),Ps(e.layer)||(i.layer=e.layer),Ps(e.startCharRect)||(i.startCharRect=e.startCharRect),Ps(e.endCharRect)||(i.endCharRect=e.endCharRect),Ps(e.startTextPosition)||(i.startTextPosition=e.startTextPosition),Ps(e.endTextPosition)||(i.endTextPosition=e.endTextPosition),i.modified=e.modified,e.comment&&Object.assign(i.comment,e.comment),this.annotationRepo.save(i),i):null}),i=Ty.create(t.updateDetails,t.updatedBy,t.updateActions);return this.eventHooks.annotationUpdated.emit(i),e}}(py,my);class _y extends jr{static create(t){return new _y(t)}constructor(t){super("replyUpdatedDomainEvent"),Yi(this,"reply",void 0),this.reply=t}}const Py=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.eventHooks=i}execute(t){const e=this.annotationRepo.findAnnotationByUid(t.annotationUid);if(!e)return!1;const i=this.replyRepo.findCommentByUid(t.uid);if(!i)return!1;i.updateReply({author:t.author,contents:t.contents,modifiedDate:t.modificationDate}),e.updateReply(i),this.annotationRepo.save(e),this.replyRepo.save(i);const n=_y.create(i);return this.eventHooks.replyUpdated.emit(n),!0}}(py,gy,my);class Ay extends jr{static create(t){return new Ay(t)}constructor(t){super("replyDeletedDomainEvent"),Yi(this,"reply",void 0),this.reply=t}}const Iy=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.eventHooks=i}execute(t){if(!this.replyRepo.has(t))return!1;const e=this.annotationRepo.findAnnotationByUid(t.annotationUid);if(!e)return!1;e.deleteReplies([t]),this.replyRepo.deleteComment(t);const i=Ay.create(t);return this.eventHooks.replyDeleted.emit(i),!0}}(py,gy,my);class Dy extends jr{static create(t,e,i){return new Dy(t,e,i)}constructor(t,e,i){super("bringToFrontDomainEvent"),Yi(this,"annotationUid",void 0),Yi(this,"from",void 0),Yi(this,"to",void 0),this.annotationUid=t,this.from=e,this.to=i}}const Ry=new class{constructor(t,e,i){Yi(this,"annotRepo",void 0),Yi(this,"annotPageRepo",void 0),Yi(this,"eventHooks",void 0),this.annotRepo=t,this.annotPageRepo=e,this.eventHooks=i}execute(t){const e=this.annotRepo.findAnnotationByUid(t);if(!e)return!1;const i=this.annotPageRepo.findPageByUid(e.pageUid),n=i.getAnnotationUidListByLayer(),s=i.bringToFront(t);if(!s)return!1;e.layer=s.layer;const o=i.getAnnotationUidListByLayer(),r=Dy.create(t,n,o);return this.eventHooks.bringToFront.emit(r),!0}}(py,fy,my);class ky extends jr{static create(t,e,i){return new ky(t,e,i)}constructor(t,e,i){super("sendToBackDomainEvent"),Yi(this,"annotationUid",void 0),Yi(this,"from",void 0),Yi(this,"to",void 0),this.annotationUid=t,this.from=e,this.to=i}}const My=new class{constructor(t,e,i){Yi(this,"annotRepo",void 0),Yi(this,"annotPageRepo",void 0),Yi(this,"eventHooks",void 0),this.annotRepo=t,this.annotPageRepo=e,this.eventHooks=i}execute(t){const e=this.annotRepo.findAnnotationByUid(t);if(!e)return!1;const i=this.annotPageRepo.findPageByUid(e.pageUid),n=i.getAnnotationUidListByLayer(),s=i.sendToBack(t);if(!s)return!1;e.layer=s.layer;const o=i.getAnnotationUidListByLayer(),r=ky.create(t,n,o);return this.eventHooks.sendToBack.emit(r),!0}}(py,fy,my);class Ly extends jr{static create(t,e,i,n){return new Ly(t,e,i,n)}constructor(t,e,i,n){super("bringForwardDomainEvent"),Yi(this,"annotationUid",void 0),Yi(this,"forwardUid",void 0),Yi(this,"from",void 0),Yi(this,"to",void 0),this.annotationUid=t,this.forwardUid=e,this.from=i,this.to=n}}const Oy=new class{constructor(t,e,i){Yi(this,"annotRepo",void 0),Yi(this,"annotPageRepo",void 0),Yi(this,"eventHooks",void 0),this.annotRepo=t,this.annotPageRepo=e,this.eventHooks=i}execute(t){const e=this.annotRepo.findAnnotationByUid(t);if(!e)return!1;const i=this.annotPageRepo.findPageByUid(e.pageUid),n=i.getAnnotationUidListByLayer(),s=i.bringForward(t);if(!s)return!1;const{curLayer:o,forward:r}=s;e.layer=o.layer,r&&(this.annotRepo.findAnnotationByUid(r.annotationUid).layer=r.layer);const a=i.getAnnotationUidListByLayer(),l=Ly.create(t,null==r?void 0:r.annotationUid,n,a);return this.eventHooks.bringFroward.emit(l),!0}}(py,fy,my);class By extends jr{static create(t,e,i,n){return new By(t,e,i,n)}constructor(t,e,i,n){super("sendBackwardDomainEvent"),Yi(this,"annotationUid",void 0),Yi(this,"backwardUid",void 0),Yi(this,"from",void 0),Yi(this,"to",void 0),this.annotationUid=t,this.backwardUid=e,this.from=i,this.to=n}}const Ny=new class{constructor(t,e,i){Yi(this,"annotRepo",void 0),Yi(this,"annotPageRepo",void 0),Yi(this,"eventHooks",void 0),this.annotRepo=t,this.annotPageRepo=e,this.eventHooks=i}execute(t){const e=this.annotRepo.findAnnotationByUid(t);if(!e)return!1;const i=this.annotPageRepo.findPageByUid(e.pageUid),n=i.getAnnotationUidListByLayer(),s=i.sendBackward(t);if(!s)return!1;const{curLayer:o,backward:r}=s;e.layer=o.layer,r&&(this.annotRepo.findAnnotationByUid(r.annotationUid).layer=r.layer);const a=i.getAnnotationUidListByLayer(),l=By.create(t,null==r?void 0:r.annotationUid,n,a);return this.eventHooks.sendBackward.emit(l),!0}}(py,fy,my);class Uy extends jr{static create(t){return new Uy(t)}constructor(t){super("commentUpdatedDomainEvent"),Yi(this,"comment",void 0),this.comment=t}}const Fy=new class{constructor(t,e){Yi(this,"annotationRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.eventHooks=e}execute(t){const e=this.annotationRepo.findAnnotationByUid(t.annotationUid);if(!e)return!1;e.updateComment(t);const i=Uy.create(e.comment);return this.eventHooks.commentUpdated.emit(i),!0}}(py,my);class Vy extends jr{static create(t){return new Vy(t)}constructor(t){super("deleteReplyReviewStateDomainEvent"),Yi(this,"replyUid",void 0),this.replyUid=t}}const Wy=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.eventHooks=i}execute(t){const e=this.replyRepo.findCommentByUid(t);if(!e)return!1;const i=this.annotationRepo.findAnnotationByUid(e.annotationUid);if(!i)return!1;i.deleteReplyReviewSate(e),this.annotationRepo.save(i);const n=Vy.create(t);return this.eventHooks.deleteReplyReviewState.emit(n),!0}}(py,gy,my);class Hy extends jr{static create(t){return new Hy(t)}constructor(t){super("addReplyReviewStateDomainEvent"),Yi(this,"author",void 0),Yi(this,"creationDate",void 0),Yi(this,"contents",void 0),Yi(this,"state",void 0),Yi(this,"replyUid",void 0),this.author=t.author,this.creationDate=t.creationDate,this.contents=t.contents,this.state=t.state,this.replyUid=t.replyUid}}const jy=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.eventHooks=i}execute(t){const e=this.replyRepo.findCommentByUid(t.replyUid);if(!e)return!1;const i=this.annotationRepo.findAnnotationByUid(e.annotationUid);if(!i)return!1;i.addReplyReviewState(e,t),this.annotationRepo.save(i);const n=Hy.create(t);return this.eventHooks.addReplyReviewState.emit(n),!0}}(py,gy,my),zy=new class{constructor(t){Yi(this,"annotationPageRepo",void 0),this.annotationPageRepo=t}execute(t){let e=this.annotationPageRepo.findPageByUid(t);return e||(e=uy.create(t),this.annotationPageRepo.save(e)),e}}(fy),Gy=new class{constructor(t,e,i){Yi(this,"annotationPageRepo",void 0),Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),this.annotationPageRepo=t,this.annotationRepo=e,this.replyRepo=i}execute(t){const e=this.annotationPageRepo.findPageByUid(t.pageUid);if(!e)return null;const i=e.clone(t.newPageUid),n=new Map;return e.annotations.forEach((e,s)=>{const o=this.annotationRepo.findAnnotationByUid(e).clone(t.newPageUid,"");o.comment.replies.forEach(t=>{this.replyRepo.save(t)}),this.annotationRepo.save(o),i.annotations[s]=o.uid,n.set(e,o.uid)}),i.layers.forEach(t=>{t.annotationUid=n.get(t.annotationUid)}),this.annotationPageRepo.save(i),i}}(fy,py,gy),Yy=new class{constructor(t){Yi(this,"annotationPageRepo",void 0),this.annotationPageRepo=t}execute(t){this.annotationPageRepo.deletePagesByUids(t)}}(fy),$y=new class{constructor(t,e,i){Yi(this,"annotationPageRepo",void 0),Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),this.annotationPageRepo=t,this.annotationRepo=e,this.replyRepo=i}execute(t){const e=this.annotationPageRepo.findPageByUid(t.pageUid);if(!e)return null;const i=this.annotationRepo.findAnnotationByUid(t.annotationUid);if(!i)return null;const n=i.clone(t.pageUid," ");return n.comment.replies.forEach(t=>{this.replyRepo.save(t)}),e.addAnnotation(n.uid),this.annotationRepo.save(n),n}}(fy,py,gy);class Xy extends jr{static create(t,e,i){return new Xy(t,_s(e),_s(i))}constructor(t,e,i){super("annotationPageSwitchedDomainEvent"),Yi(this,"annotationUid",void 0),Yi(this,"from",void 0),Yi(this,"to",void 0),this.annotationUid=t,this.from=e,this.to=i}}const qy=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"annotationPageRepo",void 0),Yi(this,"eventHook",void 0),this.annotationRepo=t,this.annotationPageRepo=e,this.eventHook=i}execute(t){const{annotationUid:e,pageUid:i,x:n,y:s,layer:o}=t,r=this.annotationRepo.findAnnotationByUid(e);if(!r)return!1;const a=this.annotationPageRepo.findPageByUid(r.pageUid);if(!a)return!1;const l=this.annotationPageRepo.findPageByUid(i);if(!l)return!1;const h={pageUid:r.pageUid,x:r.style.x,y:r.style.y,layer:r.layer};a.deleteAnnotations([e]),l.addAnnotation(e,o),r.updateStyle({x:n,y:s}),r.layer=o,r.pageUid=i;const c=Xy.create(r.uid,h,{pageUid:i,x:n,y:s,layer:o});return this.eventHook.annotationPageSwitched.emit(c),!0}}(py,fy,my);class Zy extends jr{static create(t,e){return new Zy(t,e)}constructor(t,e){super("restoreLayerDomainEvent"),Yi(this,"annotationUid",void 0),Yi(this,"layer",void 0),this.annotationUid=t,this.layer=e}}const Jy=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"annotationPageRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.annotationPageRepo=e,this.eventHooks=i}execute(t){let{annotationUid:e,layer:i}=t;const n=this.annotationRepo.findAnnotationByUid(e);if(!n)return!1;this.annotationPageRepo.findPageByUid(n.pageUid).restoreLayer(e,i),n.layer=i;const s=Zy.create(e,i);return this.eventHooks.restoreLayer.emit(s),!0}}(py,fy,my),Ky=new class{constructor(t,e){Yi(this,"annotationPageRepo",void 0),Yi(this,"annotationRepo",void 0),this.annotationPageRepo=t,this.annotationRepo=e}execute(t){let e={back:!1,front:!1,forward:!1,backward:!1};const i=this.annotationRepo.findAnnotationByUid(t);if(!i)return e;const n=this.annotationPageRepo.findPageByUid(i.pageUid);return n?(e=n.getLayerState(t),e):e}}(fy,py);class Qy extends jr{static create(t){return new Qy(t)}constructor(t){super("AddReplyMarkedStateDomainEvent"),Yi(this,"author",void 0),Yi(this,"creationDate",void 0),Yi(this,"contents",void 0),Yi(this,"state",void 0),Yi(this,"replyUid",void 0),this.author=t.author,this.creationDate=t.creationDate,this.contents=t.contents,this.state=t.state,this.replyUid=t.replyUid}}const tx=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.eventHooks=i}execute(t){const e=this.replyRepo.findCommentByUid(t.replyUid);if(!e)return!1;const i=this.annotationRepo.findAnnotationByUid(e.annotationUid);if(!i)return!1;i.addReplyMarkedState(e,t),this.annotationRepo.save(i);const n=Qy.create(t);return this.eventHooks.addReplyMarkedState.emit(n),!0}}(py,gy,my),ex=new class{constructor(t,e,i){Yi(this,"annotationRepo",void 0),Yi(this,"replyRepo",void 0),Yi(this,"eventHooks",void 0),this.annotationRepo=t,this.replyRepo=e,this.eventHooks=i}execute(t){const e=this.replyRepo.findCommentByUid(t);if(!e)return!1;const i=this.annotationRepo.findAnnotationByUid(e.annotationUid);if(!i)return!1;i.deleteReplyReviewSate(e),this.annotationRepo.save(i);const n=Vy.create(t);return this.eventHooks.deleteReplyReviewState.emit(n),!0}}(py,gy,my),ix=new class{constructor(t){Yi(this,"annotationReplyRepo",void 0),this.annotationReplyRepo=t}execute(t){return this.annotationReplyRepo.findCommentByUid(t)}}(gy);class nx extends Wo{constructor(){super(),Yi(this,"annotationRepo",py),Yi(this,"annotationReplyRepo",gy),Yi(this,"annotationPageRepo",fy),Yi(this,"hooks",my),this.register(my)}dispose(){this.reset(),this.hooks.dispose(),super.dispose()}reset(){this.annotationPageRepo.clear(),this.annotationReplyRepo.clear(),this.annotationRepo.clear()}createAnnotationPage(t){return zy.execute(t)}copyAnnotationPage(t,e){return Gy.execute({pageUid:t,newPageUid:e})}deleteAnnotationPage(t){return Yy.execute(t)}createAnnotations(t){return yy.execute(t)}copyAnnotation(t,e){return $y.execute({annotationUid:t,pageUid:e})}deleteAnnotations(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=t.map(t=>(Os(t)&&(t=py.findAnnotationByUid(t)),t));return wy.execute(i,e)}updateAnnotation(t){return Ey.execute(t)}switchAnnotationPage(t,e){return qy.execute({annotationUid:Es(t)?t.uid:t,...e})}getAnnotationByUid(t){return Cy.execute(t)}getAnnotationLayerState(t){return Ky.execute(t)}addReply(t){return Sy.execute(t)}deleteReply(t){return Os(t)&&(t=gy.findCommentByUid(t)),Iy.execute(t)}updateReply(t){return Py.execute(t)}getReply(t){return ix.execute(t)}updateComment(t){return Fy.execute(t)}deleteReplyReviewState(t){return Wy.execute(t)}addReplyReviewState(t){return jy.execute(t)}getReplyReviewState(t){return Os(t)&&(t=gy.findCommentByUid(t)),ix.execute(t.uid)}deleteReplyMarkedState(t){return ex.execute(t)}addReplyMarkedState(t){return tx.execute(t)}bringToFront(t){return Ry.execute(t)}sendToBack(t){return My.execute(t)}bringForward(t){return Oy.execute(t)}sendBackward(t){return Ny.execute(t)}restoreLayer(t,e){return Jy.execute({annotationUid:t,layer:e})}}const sx=["enableContinuousDrawing","controlsStyle","inkCreateDelay","showOnTopWhenSelected","defaultStyleConfig","eraserStyle","selectionStyle","enableMoveWithKeyboard","enableDeleteWithKeyboard","enableMultipleSelectWidthCtrl"];class ox extends Wo{constructor(t){super(),Yi(this,"context",void 0),this.context=t}updateConfig(t){for(const[e,i]of Object.entries(t))sx.includes(e)&&this[e](i)}defaultStyleConfig(t){if(!Es(t))return;const{annotationController:e}=this.context,{viewer:i}=this.context,n=i.getAnnotationConfig().defaultStyleConfig,s={...t,stamp:{imageData:null,stampConfig:null,...t.stamp}},{hasChanges:o,changes:r,oldValues:a}=function(t,e){if(t===e)return{hasChanges:!1,changes:{},oldValues:{}};const i={},n={};let s=!1;const o=Object.keys(e);for(let r=0;r<o.length;r++){const a=o[r],l=null==t?void 0:t[a],h=e[a],c=rx(l,h);c.changed&&(i[a]=void 0!==c.newData?c.newData:h,n[a]=void 0!==c.oldData?c.oldData:l,s=!0)}return{hasChanges:s,changes:i,oldValues:n}}(n,s);var l,h,c;Ps(null==r?void 0:r.stamp)||(Ps(null===(l=r.stamp)||void 0===l?void 0:l.imageData)&&Ps(null===(h=r.stamp)||void 0===h?void 0:h.stampConfig)&&Ps(null===(c=r.stamp)||void 0===c?void 0:c.stampIcon)?a.stamp={opacity:n.stamp.opacity}:(a.stamp={...n.stamp},r.stamp={...n.stamp,...r.stamp},r.stamp.opacity===a.stamp.opacity&&(delete r.stamp.opacity,delete a.stamp.opacity)));o&&(e.setAnnotationInteractiveConfig({defaultStyleConfig:r}),e.updateFreeTextDefaultConfig(),i.hooks.annotationDefaultStyleChanged.emit(new hm(a,r)))}enableContinuousDrawing(t){const{annotationController:e}=this.context;e.interactiveConfig.enableContinuousDrawing=t}enableMoveWithKeyboard(t){const{annotationController:e}=this.context;e.interactiveConfig.enableMoveWithKeyboard=t}enableDeleteWithKeyboard(t){const{annotationController:e}=this.context;e.interactiveConfig.enableDeleteWithKeyboard=t}enableMultipleSelectWidthCtrl(t){const{annotationController:e}=this.context;e.interactiveConfig.enableMultipleSelectWidthCtrl=t}controlsStyle(t){if(!Es(t))return;const{annotationController:e}=this.context;e.setAnnotationInteractiveConfig({controlsStyle:t})}inkCreateDelay(t){const{annotationController:e}=this.context;e.interactiveConfig.inkCreateDelay=t}showOnTopWhenSelected(t){const{annotationController:e}=this.context;e.interactiveConfig.showOnTopWhenSelected=t}}function rx(t,e){if(t===e)return{changed:!1};if(Array.isArray(e)){if(!Array.isArray(t)||t.length!==e.length)return{changed:!0,newData:e,oldData:t};for(let i=0;i<e.length;i++)if(t[i]!==e[i])return{changed:!0,newData:e,oldData:t};return{changed:!1}}if(e&&"object"==typeof e&&!(e instanceof Blob)){const i={},n={};let s=!1;const o=Object.keys(e),r=t&&"object"==typeof t&&!Array.isArray(t);for(let a=0;a<o.length;a++){const l=o[a],h=r?t[l]:void 0,c=e[l],d=rx(h,c);d.changed&&(i[l]=void 0!==d.newData?d.newData:c,n[l]=void 0!==d.oldData?d.oldData:h,s=!0)}return s?{changed:!0,newData:i,oldData:n}:{changed:!1}}return{changed:!0,newData:e,oldData:t}}class ax{constructor(t,e){Yi(this,"shape",void 0),Yi(this,"ctx",void 0),Yi(this,"page",void 0),Yi(this,"isHitStartCtrl",!1),Yi(this,"isHitEndCtrl",!1),Yi(this,"startTextPosition",void 0),Yi(this,"endTextPosition",void 0),Yi(this,"oldStartTextPosition",void 0),Yi(this,"oldEndTextPosition",void 0),Yi(this,"oldStartCharRect",void 0),Yi(this,"oldEndCharRect",void 0),Yi(this,"startCharRect",void 0),Yi(this,"endCharRect",void 0),Yi(this,"lines",void 0),Yi(this,"startPoint",void 0),Yi(this,"isPointerdown",void 0),Yi(this,"isEdited",!1),Yi(this,"isMatchText",!1),this.ctx=t,this.page=e}setShape(t){this.shape=t}isHitPoint(t){const e=this.canvasToMediaBox(t);return this.isHitStartCtrl=this.shape.isPointOnStartCtrl(e),this.isHitEndCtrl=this.shape.isPointOnEndCtrl(e),!this.isHitStartCtrl&&!this.isHitEndCtrl||this.isCtrlPointOoutOfCropBox()?this.shape.isPointOnBody(e)?(this.isCtrlPointOoutOfCropBox(),9):-1:10}isCtrlPointOoutOfCropBox(){return!1}isCtrlPointOoutOfCropBox1(){const t=this.ctx.context.core.pageService.getPage(this.page.uid);if(null==t||!t.isTextPage)return!0;let e=!1;const{bounds:i}=this.shape,{cropBox:n}=t;return!(i.left>=n.left&&i.top>=n.top&&i.left+i.width>n.left+n.width&&i.top+i.height>n.top+n.height)&&(this.shape.startCharRect&&(qm({x:this.shape.startCharRect.left,y:this.shape.startCharRect.top},t.cropBox)||Xm(this.shape.startCharRect,t.cropBox))||(e=!0),this.shape.endCharRect&&(qm({x:this.shape.endCharRect.left,y:this.shape.endCharRect.top},t.cropBox)||Xm(this.shape.startCharRect,t.cropBox))||(e=!0),this.shape.isOutOfCropBox=e,e)}startHandler(t){const e=this.ctx.context.core.annotationService.getAnnotationByUid(this.shape.id);if(e.isBlankTextAssist)return;const i=this.ctx.context.core.pageService.getPage(this.page.uid);if(null==i||!i.isTextPage)return;if(this.isCtrlPointOoutOfCropBox())return;const n=this.canvasToMediaBox(t);if(this.isHitStartCtrl=this.shape.isPointOnStartCtrl(n),this.isHitEndCtrl=this.shape.isPointOnEndCtrl(n),!this.isHitStartCtrl&&!this.isHitEndCtrl)return;const{annotationEditService:s}=this.ctx.context;if(s.isPointerType&&(s.needRenderMagnifier=!0,s.renderMagnifier(t)),this.shape.startTextPosition)this.oldStartCharRect={...this.shape.startCharRect},this.oldEndCharRect={...this.shape.endCharRect},this.oldStartTextPosition={...this.shape.startTextPosition},this.oldEndTextPosition={...this.shape.endTextPosition},this.startTextPosition={...this.shape.startTextPosition},this.endTextPosition={...this.shape.endTextPosition};else if(e.isMatchText){const t=this.ctx.context.calcTextStartPosition({x:this.shape.startCharRect.left+8,y:this.shape.startCharRect.top+8},this.page,!0),e=this.ctx.context.calcTextStartPosition({x:this.shape.endCharRect.left+8,y:this.shape.endCharRect.top+8},this.page,!0);this.oldStartCharRect={...this.startCharRect},this.oldEndCharRect={...this.endCharRect},this.oldStartTextPosition={...t},this.oldEndTextPosition={...e},this.startTextPosition={...t},this.endTextPosition={...e},this.shape.startTextPosition={...t},this.shape.endTextPosition={...e}}else{const t=this.ctx.matchText(e);if(!t)return;this.isMatchText=!0;const{startTextPosition:i,endTextPosition:n,startCharRect:s,endCharRect:o}=t;this.oldStartCharRect=s,this.oldEndCharRect=o,this.oldStartTextPosition={...i},this.oldEndTextPosition={...n},this.startTextPosition={...i},this.endTextPosition={...n},this.shape.startTextPosition={...i},this.shape.endTextPosition={...n};const r=this.ctx.context.core.annotationService.getAnnotationByUid(e.uid);r.startTextPosition||(r.startTextPosition={...i}),r.endTextPosition||(r.endTextPosition={...n})}this.startPoint=t,this.isPointerdown=!0}moveHandler(t){if(!this.isPointerdown)return;const e=this.ctx.context.getActiveTab();if(null==e||!e.total)return;const{page:i}=this,n=this.ctx.context.core.pageService.getPage(i.uid);if(null!=n&&n.isTextPage&&(this.isHitStartCtrl||this.isHitEndCtrl)){if(null==n||!n.visibleLines)return;let s=null;if(this.isHitStartCtrl?(s=this.ctx.context.calcTextEndPosition(t,i,e,this.endTextPosition.mediaBoxPoint),this.startTextPosition=s):this.isHitEndCtrl&&(s=this.ctx.context.calcTextEndPosition(t,i,e,this.startTextPosition.mediaBoxPoint),this.endTextPosition=s),s){const{textPages:t,startCharRect:e,endCharRect:i,startTextPosition:n,endTextPosition:s}=this.ctx.context.textSelectionService.calcSelectedText(this.startTextPosition,this.endTextPosition);this.isEdited=!0,this.startCharRect=e,this.endCharRect=i,this.shape.startCharRect=e,this.shape.endCharRect=i,this.shape.startTextPosition=n,this.shape.endTextPosition=s;const o=t[0].lines.map(t=>t.selectedRect);this.lines=o,this.shape.updateStyle({lines:o})}const{annotationEditService:o}=this.ctx.context;o.isPointerType&&(o.isRenderMagnifier=!0,o.magnifierPoint=t)}}endHandler(){if(this.isEdited){const t=this.shape.getAnnotationConfig(),e=this.isSameTextSelectedPosition(this.startTextPosition,this.oldStartTextPosition),i=this.isSameTextSelectedPosition(this.endTextPosition,this.oldEndTextPosition),n=this.isSameTextCharRect(t.startCharRect,this.oldStartCharRect),s=this.isSameTextCharRect(t.endCharRect,this.oldEndCharRect);if(!n||!s||!e||!i||this.isMatchText){const e=sy(this.lines);this.shape.style.borderWidth=e;const i={startCharRect:t.startCharRect,endCharRect:t.endCharRect,startTextPosition:t.startTextPosition,endTextPosition:t.endTextPosition,style:{lines:t.style.lines}};this.ctx.annotationController.hooks.emitModifyAnnotation(["resized"],[{shape:this.shape,changedOptions:i}])}}this.isEdited=!1,this.isPointerdown=!1,this.isHitStartCtrl=!1,this.isHitEndCtrl=!1,this.isMatchText=!1,this.ctx.context.render(73)}canvasToMediaBox(t){const{page:e}=this,i=this.ctx.context.getPointerOverMediaBoxInfo(e.mediaBox,t.x,t.y,e.rotation);return{x:i.pointerX,y:i.pointerY}}isSameTextSelectedPosition(t,e){return t.pageUid===e.pageUid&&t.lineUid===e.lineUid&&t.charUid===e.charUid}isSameTextCharRect(t,e){return t.left===e.left&&t.top===e.top}}const lx={arc:"annotationArc",circle:"annotationCircle",ellipse:"annotationEllipse",image:"annotationImage",ink:"annotationInk",rectangle:"annotationRect",line:"annotationLine",polyline:"annotationPolyline",polygon:"annotationPolygon",textTypewriter:"annotationFreeText",textBox:"annotationTextBox",stamp:"annotationStamp",textAssist:"annotationTextAssist",highlight:"annotationHighlight",underline:"annotationUnderline",strikeout:"annotationStrikeout",incomplete:"annotationIncomplete"},hx={annotationArc:"arc",annotationCircle:"circle",annotationEllipse:"ellipse",annotationImage:"image",annotationInk:"ink",annotationRect:"rectangle",annotationLine:"line",annotationPolyline:"polyline",annotationPolygon:"polygon",annotationFreeText:"textTypewriter",annotationTextBox:"textBox",annotationStamp:"stamp",annotationTextAssist:"textAssist",annotationHighlight:"highlight",annotationUnderline:"underline",annotationStrikeout:"strikeout"};class cx extends Wo{constructor(t){super(),Yi(this,"viewer",void 0),Yi(this,"annotationConfigService",void 0),Yi(this,"annotationController",void 0),Yi(this,"context",void 0),this.viewer=t,this.context=t.context,this.annotationConfigService=new ox(this),this.initAnnotationController(),this.listenViewerEventsForAnnotation()}isTextAssistType(t){return["highlight","underline","strikeout"].includes(t)}initAnnotationController(){(this.context.isDefaultViewer||this.context.isThumbnailViewer)&&((new rd).init(this.context.rendererService.docRenderer.canvas),this.annotationController=new Hc(this.context.rendererService.getCanvasDom()),this.listenViewerNativeEventsForAnnotation(),this.annotationController.hooks.deleteAnnotation.on(t=>{const e=new Set(t.shapes.map(t=>t.uid));this.context.core.annotationService.deleteAnnotations([...e])},this),this.annotationController.hooks.selectAnnotation.on(t=>{const e=lm.create(t.oldAnnotationsUids,t.newAnnotationUids);this.syncAnnotationLayerState(),this.viewer.hooks.selectedAnnotationsChanged.emit(e),t.emitSelected&&this.viewer.emit("selectedAnnotationsChanged",{newAnnotationUids:[...t.newAnnotationUids],oldAnnotationUids:[...t.oldAnnotationsUids]})},this),this.annotationController.hooks.modifyAnnotation.on(t=>{const e=t.shapes.map(t=>{let e;if("annotationFreeText"===t.shape.config.type){const i=t.shape.getAnnotationConfig(),n=this.context.core.annotationService.getAnnotationByUid(t.shape.id);if(!n)return;const s=0===n.style.textContents.length?{x:i.style.x,y:i.style.y,width:i.style.width,...t.changedOptions.style}:{...t.changedOptions.style};e={annotationUid:t.shape.id,options:{transform:_s(i.transform),style:s}}}else e={annotationUid:t.shape.id,options:t.changedOptions};return e});this.context.core.annotationService.updateAnnotations(e,this.context.uid,t.actions)},this),this.annotationController.hooks.addAnnotation.on(t=>{const e=this.context.getActiveTab();if(!e)return;const{annotationService:i}=this.context.core;t.shapes.forEach(t=>{const n=t.shape.getAnnotationConfig(),s=Rm(),o=["print"];t.shape instanceof hc&&"freeTextWriter"===t.shape.textType&&o.push("noRotate","noResize"),(t.shape instanceof fc||t.shape instanceof pc||t.shape instanceof gc)&&o.push("noRotate");const r=i.createAnnotation(e.uid,{uid:t.uid,docUid:e.uid,pageUid:t.shape.pageUid,type:hx[n.type],transform:_s(n.transform),style:_s(n.style),flags:o,comment:{annotationUid:t.uid,author:"",subject:"",contents:"",creationDate:s,modificationDate:s,markedStates:[],reviewStates:[],replies:[]},source:"user"});this.annotationController.updateLayer(t.uid,r.layer)})},this),this.annotationController.hooks.annotationModeChanged.on(t=>{"none"===t&&this.exitAnnotationMode()},this),this.annotationController.hooks.beforeAnnotationEdit.on(t=>{this.viewer.hooks.beforeAnnotationEdit.emit(t)},this),this.annotationController.hooks.afterAnnotationEdit.on(t=>{this.viewer.hooks.afterAnnotationEdit.emit(t)},this),this.annotationController.hooks.beforeAnnotationDraw.on(t=>{this.viewer.hooks.beforeAnnotationDraw.emit(t)},this),this.annotationController.hooks.afterAnnotationDraw.on(t=>{this.viewer.hooks.afterAnnotationDraw.emit(t)},this),this.annotationController.hooks.renderAnnotation.on(()=>{var t;null===(t=this.context)||void 0===t||t.render(71)},this),this.annotationController.hooks.selectAnnotationTextChars.on(t=>{this.viewer.hooks.annotationTextCharsSelected.emit(t)},this),this.annotationController.hooks.annotationTextContentUpdated.on(t=>{this.viewer.hooks.annotationTextContentUpdated.emit(t)},this),this.annotationController.hooks.annotationTextPositionUpdated.on(t=>{const e=t.id,i=this.context.core.annotationService.getAnnotationByUid(e),{position:n}=t.context.getTransform();i.style.x=n.x,i.style.y=n.y,i.transform.position={...n}}))}exitAnnotationMode(){"annotation"===this.viewer.getViewerConfig().toolMode&&this.viewer.updateViewerConfig({toolMode:"pan"})}listenViewerNativeEventsForAnnotation(){const{eventDom:t}=this.context;zo(t,Ms()?"click":"pointerup",this).on(t=>{t.preventDefault(),this.annotationController.clickHandler(t)}),zo(t,"dblclick",this).on(t=>{this.annotationController.dblClickHandler(t)})}listenViewerEventsForAnnotation(){const{context:t,context:{hooks:e,tabService:i}}=this;(t.isDefaultViewer||t.isThumbnailViewer)&&(e.pageExistenceChanged.on(t=>{0===t.pageCount&&(this.annotationController.container=null,this.annotationController.containerId=null,this.context.annotationEditService.containerPage=null,this.annotationController.clearShapeArrMap())},this),e.toolModeChanged.on(e=>{const{annotationMode:i}=t.viewerConfig;if("annotation"!==e.newToolMode)this.annotationController.setAnnotationMode("none"),"crop"!==e.newToolMode&&"textSelection"!==e.newToolMode||this.selectAnnotations([]);else{let t="draw";"select"===i?t="select":"erase"===i&&(t="erase"),this.annotationController.setAnnotationMode(t)}},this),e.annotationModeChanged.on(e=>{const{toolMode:i}=t.viewerConfig;if("select"===e.newAnnotationMode||"erase"===e.newAnnotationMode){const t=e.newAnnotationMode;"annotation"===i&&this.annotationController.setAnnotationMode(t)}else{const t=lx[e.newAnnotationMode];this.annotationController.drawType=t,"annotation"===i&&this.annotationController.setAnnotationMode("draw")}},this),e.addPagesToDoc.on(t=>{i.getTab(t.docUid)&&this.addAnnotationByPageUids(t.pageUids)},this),e.openDocument.on(t=>{i.getTab(t.uid)&&(this.selectAnnotations([]),this.addAnnotationByPageUids(t.pages))},this),e.closeDocument.on(t=>{t.pages.forEach(t=>{const e=this.context.core.pageService.getPage(t);this.annotationController.deleteShape(e.annotations,!1,!1)}),this.annotationController.clearShapeArrMap()},this),e.deletePages.on(t=>{t.pageUids.forEach(t=>{const e=this.context.core.pageService.getPage(t);this.annotationController.deleteShape(e.annotations,!1,!1),this.annotationController.deleteShapeArrMap(t)})},this),e.syncDocument.on(t=>{i.getTab(t.uid)&&(this.selectAnnotations([]),this.addAnnotationByPageUids(t.pages))},this),e.afterRender.on(e=>{if(null==e||!e.total)return;const i=t.annotationEditService.containerPage;if(!i)return;if(!e.getPageByUid(i.uid))return;let{x:n,y:s}=i.cropBox.getPosition(),{width:o,height:r}=i.cropBox;const a=(i.rotation%360+360)%360/90;if(1===a?n-=r:2===a?(n-=o,s-=r):3===a&&(s-=o),1===a||3===a){const t=o;o=r,r=t}this.annotationController.eventService.setEventArea({left:n,top:s,width:o,height:r})},this))}disableTextEditMode(){const{eventService:t}=this.annotationController;null!=t&&t.activatedShape&&(null==t?void 0:t.activatedShape)instanceof hc&&null!=t&&t.activatedShape.isEditMode&&(null==t||t.activatedShape.textEditEventHandler.disableEditMode(),this.context.render(72))}addAnnotationByPageUids(t){t.forEach(t=>{const e=this.context.core.pageService.getPage(t);if(e.annotations.forEach(t=>{const e=this.context.core.annotationService.annotationApp.getAnnotationByUid(t);this.addAnnotationByAnnotationData(e)}),0===e.annotations.length){const t=this.context.tabService.getTab(e.doc.uid);if(!t)return;const i=t.getPageByUid(e.uid);if(!i)return;this.annotationController.setAnnotationContainer(e.uid,i.mediaBox)}})}addAnnotationByAnnotationData(t){if("unknown"===t.type)return!0;const e=this.context.core.pageService.getPage(t.pageUid);if(!e)return!1;const i=this.context.tabService.getTab(e.doc.uid);if(!i)return!1;const n=i.getPageByUid(t.pageUid);if(!n)return!1;let s=t.getConfig();this.annotationController.setAnnotationContainer(t.pageUid,n.mediaBox);const o=this.isTextAssistType(t.type),r=this.annotationController.addShape(lx[t.type],{id:t.uid,style:{...s.style,zIndex:t.layer},transform:s.transform},!1,o?new ax(this,n):void 0);o&&(r.startCharRect=t.startCharRect,r.endCharRect=t.endCharRect),s=t.getConfig();const a={enableControl:!s.flags.includes("readOnly")&&!s.flags.includes("flattened"),isVisible:!s.flags.includes("noView"),enableEdit:!s.flags.includes("noResize"),enableRotate:!s.flags.includes("noRotate"),enableMove:!s.flags.includes("noMove")};if(r instanceof hc&&"freeTextWriter"===r.textType){a.enableEdit=!1,a.enableRotate=!1;const e=r.getAnnotationConfig();t.style.width=e.style.width}if(r.context.isInGroup&&(a.enableRotate=!1),this.annotationController.setAnnotationFlags(t.uid,a,!1),r instanceof Ac&&"base"===r.stampType||r instanceof oc){const e=r.getAnnotationConfig();t.transform.position=e.transform.position,t.transform.scale=e.transform.scale,t.style=e.style}return this.syncAnnotationLayerState(),!0}updateAnnotations(t,e,i,n){if(e===this.context.uid)return!0;const s=t.reduce((t,e)=>{const i=this.context.core.annotationService.annotationApp.getAnnotationByUid(e);if(i){const n=this.context.core.pageService.getPage(i.pageUid);if(n&&this.context.tabService.getTab(n.doc.uid)){const n=i.getConfig();t.push({annotationUid:e,config:n}),this.viewer.context.core.annotationService.annotationApp.restoreLayer(e,i.layer)}}return t},[]);return s.length===t.length&&(s.forEach((t,e)=>{var s,o;let{annotationUid:r,config:a}=t;const l=this.annotationController.getShape(r),h={enableControl:!a.flags.includes("readOnly")&&!a.flags.includes("flattened"),isVisible:!a.flags.includes("noView"),enableEdit:!a.flags.includes("noResize"),enableRotate:!a.flags.includes("noRotate"),enableMove:!a.flags.includes("noMove")};if(l&&l.context.isGrouped&&(l.context.tempData.enableRotate=h.enableRotate,h.enableRotate=!1),this.annotationController.setAnnotationFlags(r,h,!1),i||this.annotationController.updateShape(r,{id:r,style:n[e].to.changed.style||{},transform:a.transform}),!l)return;const c=this.context.core.annotationService.annotationApp.getAnnotationByUid(r),d=l.getAnnotationConfig();if(this.isTextAssistType(c.type)){const t=n[e].to.changed;t.startCharRect&&(l.startCharRect=t.startCharRect),t.endCharRect&&(l.endCharRect=t.endCharRect),t.startTextPosition&&(l.startTextPosition=t.startTextPosition),t.endTextPosition&&(l.endTextPosition=t.endTextPosition)}null!=d&&null!==(s=d.transform)&&void 0!==s&&s.position&&(c.transform.position=d.transform.position),null!=d&&null!==(o=d.transform)&&void 0!==o&&o.scale&&(c.transform.scale=d.transform.scale),l instanceof Ac&&"stamp"===l.renderType&&(c.style.stampConfig=d.style.stampConfig)}),!0)}updateAnnotationPage(t,e){const i=this.context.core.annotationService.getAnnotationByUid(t);if(!i)return;const n=this.context.core.pageService.getPage(i.pageUid);if(!n)return;const s=this.context.tabService.getTab(n.doc.uid);if(!s)return;const o=s.getPageByUid(e);o&&(this.annotationController.moveShape([t],e,o.mediaBox),this.syncAnnotationLayerState())}updateLayer(t){const e=t.reduce((t,e)=>{const i=this.context.core.annotationService.annotationApp.getAnnotationByUid(e);if(i){const e=this.context.core.pageService.getPage(i.pageUid);e&&this.context.tabService.getTab(e.doc.uid)&&t.push(i)}return t},[]);return e.length===t.length&&(e.forEach(t=>{this.annotationController.updateLayer(t.uid,t.layer)}),this.syncAnnotationLayerState(),!0)}syncAnnotationLayerState(){let t={back:!1,front:!1,forward:!1,backward:!1};const e=this.annotationController.getSelectedShapeUids();return 1===e.length&&(t=this.context.core.annotationService.getAnnotationLayerState(e[0])),this.viewer.hooks.annotationLayerStateChanged.emit(rm.create(t)),t}deleteAnnotations(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];this.annotationController.deleteShape(t,!1,e),this.syncAnnotationLayerState()}selectAnnotations(t){return this.annotationController.selectShape(t)}getSelectedAnnotations(){const t=this.annotationController.getSelectedShapeUids();if(!t.length)return[];const e=[];return t.forEach(t=>{const i=this.context.core.annotationService.annotationApp.getAnnotationByUid(t);i&&e.push(i)}),e}matchText(t){var e;const i=this.context.core.pageService.getPage(t.pageUid);if(!i)return null;const{lines:n}=t.style;if(!i.isTextPage||null===(e=i.visibleLines)||void 0===e||!e.length||null==n||!n.length)return t.isMatchText=!0,t.isBlankTextAssist=!0,null;let s,o,r=Number.MAX_SAFE_INTEGER,a=Number.MIN_SAFE_INTEGER,l=Number.MAX_SAFE_INTEGER,h=Number.MIN_SAFE_INTEGER;return n.forEach(t=>{i.visibleLines.forEach((e,i)=>{if(dx(e,t)){if(l>i){l=i,r=Number.MAX_SAFE_INTEGER;const n=e.chars.findIndex(e=>dx(e.charBox,t));r>n&&(r=n,s=e.chars[n].charBox)}if(h<i){h=i,a=Number.MIN_SAFE_INTEGER;let n=-1;for(let i=e.chars.length-1;i>=0;i--)if(dx(e.chars[i].charBox,t)){n=i;break}n>a&&(a=n,o=e.chars[n].charBox)}}})}),s?{startTextPosition:{lineUid:i.visibleLines[l].uid,charUid:i.visibleLines[l].chars[r].uid,pageUid:i.uid,mediaBoxPoint:{x:s.left+s.width/2,y:s.top+s.height/2}},endTextPosition:{lineUid:i.visibleLines[h].uid,charUid:i.visibleLines[h].chars[a].uid,pageUid:i.uid,mediaBoxPoint:{x:o.left+o.width/2,y:o.top+o.height/2}},startCharRect:s,endCharRect:o}:(t.isMatchText=!0,t.isBlankTextAssist=!0,null)}}function dx(t,e){return t.left<e.left+e.width-.1&&t.left+t.width-.1>e.left&&t.top<e.top+e.height-.1&&t.top+t.height-.1>e.top}const ux={highlight:"highlight",underline:"underline",strikeout:"strikeout"};class px extends Wo{constructor(t){super(),Yi(this,"containerPage",void 0),Yi(this,"context",void 0),Yi(this,"isEditTextAssist",!1),Yi(this,"isStartDrawTextAssist",!1),Yi(this,"textAssistTimer",void 0),Yi(this,"startTextPosition",void 0),Yi(this,"endTextPosition",void 0),Yi(this,"textSelectionThreshold",1),Yi(this,"startPoint",void 0),Yi(this,"isMovedForTextSelection",void 0),Yi(this,"isPointerdown",!1),Yi(this,"opPageUid",null),Yi(this,"startCharRect",void 0),Yi(this,"endCharRect",void 0),Yi(this,"isEditTextAssistStart",!1),Yi(this,"isEditTextAssistEnd",!1),Yi(this,"canvas",void 0),Yi(this,"isPointerType",!1),Yi(this,"isRenderMagnifier",!1),Yi(this,"magnifierPoint",null),Yi(this,"needRenderMagnifier",!1),Yi(this,"isMouseOverText",!1),this.context=t,this.canvas=this.context.context.rendererService.getCanvasDom(),this.context.context.hooks.afterRender.on(()=>{this.needRenderMagnifier&&this.renderMagnifier(this.magnifierPoint)},this),(this.context.context.isDefaultViewer||this.context.context.isThumbnailViewer)&&this.context.context.core.editService.onAfterCropPages.on(t=>{this.deactivateAnnotation()},this)}renderMagnifier(t){this.magnifierPoint=t,this.context.context.viewerConfig.enableTextMagnifier&&this.context.context.magnifierService.render("text",this.canvas,this.magnifierPoint)}isHitAnnotation(t){return this.context.annotationController.isHitShape(t)}isTextAssistMode(){return["highlight","underline","strikeout"].includes(this.context.context.viewerConfig.annotationMode)}startHandler(t,e){if(this.isPointerdown)return;const{context:i}=this.context,[n]=i.toCanvas(t),{page:s}=i.getPointerOverPageInfo(n.pageX,n.pageY).pageInfo;if(!s)return;const o=!oy(t);this.isPointerType=o,this.isPointerdown=!0,this.startPoint={x:n.pageX,y:n.pageY};const r=this.context.context.getActiveTab(),{isHit:a,shape:l,isHitSelected:h}=this.isHitAnnotation(t);if("annotation"===this.context.context.viewerConfig.toolMode&&this.isTextAssistMode()){if(!this.context.context.core.pageService.getPage(s.uid).isTextPage)return;const e=this.context.context.getPointerOverMediaBoxInfo(s.mediaBox,n.pageX,n.pageY,s.rotation),{start:i,end:a}=this.isHitTextAssistCtrlPoint(s,{x:e.pointerX,y:e.pointerY});if(i||a)this.isEditTextAssistStart=i,this.isEditTextAssistEnd=a,o&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:n.pageX,y:n.pageY},this.context.context.render(58));else if(oy(t)){if(!this.isStartDrawTextAssist){const t=this.context.context.calcTextStartPosition({x:n.pageX,y:n.pageY},this.containerPage);t&&(this.startTextPosition=t,this.isStartDrawTextAssist=!0,this.context.context.hooks.beforeTextSelected.emit())}}else o&&(this.textAssistTimer=setTimeout(()=>{clearTimeout(this.textAssistTimer),this.textAssistTimer=null;const[e]=this.context.context.toCanvas(t),{page:i}=this.context.context.getPointerOverPageInfo(e.pageX,e.pageY).pageInfo,s=this.context.context.calcTextStartPosition({x:e.pageX,y:e.pageY},i);if(s){this.isStartDrawTextAssist=!0,this.startTextPosition=s;const{textPages:t,startCharRect:e,endCharRect:i,startTextPosition:o,endTextPosition:a}=this.context.context.textSelectionService.calcSelectedText(this.startTextPosition,s);r.setTextSelection(t,e,i,o,a),this.needRenderMagnifier=!0,this.magnifierPoint={x:n.pageX,y:n.pageY},this.context.context.render(58),this.context.context.hooks.beforeTextSelected.emit()}},this.context.context.viewerConfig.enterTextModeTimeMobile))}else{if(a&&this.context.isTextAssistType(l.textAssistType))return this.context.annotationController.startHandler(t,e),void this.loadTextForAnnotation(l);this.context.annotationController.startHandler(t,e)}}cursorHandler(t){const e=this.context.annotationController.eventService,{cursorService:i}=this.context.context;if(e.isStartDraw)return void i.lockCursor();if(e.isStartEdit)return void i.lockCursor();const n=this.context.annotationController.cursorHandler(t);this.context.context.applyCursorState(n)}moveHandler(t,e){const{context:i}=this.context,[n]=i.toCanvas(t),{page:s}=i.getPointerOverPageInfo(n.pageX,n.pageY).pageInfo;if("annotation"===this.context.context.viewerConfig.toolMode&&this.isTextAssistMode()){if(this.opPageUid=null==s?void 0:s.uid,this.isPointerdown&&qs(this.startPoint,{x:n.pageX,y:n.pageY})>this.textSelectionThreshold&&(this.isMovedForTextSelection=!0),s){const e=i.getActiveTab(),o=this.context.context.core.pageService.getPage(s.uid);if(this.isStartDrawTextAssist){if(null==o||!o.isTextPage)return;i.cursorService.lockCursor();const r=this.context.context.calcTextEndPosition({x:n.pageX,y:n.pageY},s,e,this.startTextPosition.mediaBoxPoint);if(r){this.endTextPosition=r;const{textPages:s,startCharRect:o,endCharRect:a,startTextPosition:l,endTextPosition:h}=i.textSelectionService.calcSelectedText(this.startTextPosition,this.endTextPosition);this.startCharRect=o,this.endCharRect=a,e.setTextSelection(s,o,a,l,h),!oy(t)&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:n.pageX,y:n.pageY}),i.render(59)}}else if(o.visibleLines&&null!=o&&o.isTextPage){const t=this.context.context.getPointerOverMediaBoxInfo(s.mediaBox,n.pageX,n.pageY,s.rotation),e={x:t.pointerX,y:t.pointerY},i=o.getHoveredTextLineIndex(e);this.isMouseOverText=-1!==i}}}else this.isRenderMagnifier&&i.viewerConfig.enableTextMagnifier&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:n.pageX,y:n.pageY}),this.context.annotationController.moveHandler(t,!s)}endHandler(t){const{context:e}=this.context;if(this.textAssistTimer&&(clearTimeout(this.textAssistTimer),this.textAssistTimer=null),this.needRenderMagnifier&&(this.context.context.magnifierService.hide(),this.needRenderMagnifier=!1),this.isStartDrawTextAssist){const t=this.applyTextSelectionToAnnotation(ux[e.viewerConfig.annotationMode]);if(t&&t.length){const i=t[t.length-1];e.clearSelectedTexts(),this.context.context.hooks.afterTextSelected.emit(),this.context.annotationController.interactiveConfig.enableContinuousDrawing||(this.context.annotationController.setAnnotationMode("none",!0),this.activateAnnotation(i,!1),i.textAssistEventHandler.enableEditMode()),this.context.context.render(60)}}else this.isMovedForTextSelection||e.clearSelectedTexts();this.context.context.cursorService.unlockCursor(),this.context.annotationController.endHandler(t),this.isStartDrawTextAssist=!1,this.isPointerdown=!1,this.isMovedForTextSelection=!1,this.opPageUid=null,this.isPointerType=!1,this.isRenderMagnifier=!1,this.magnifierPoint=null,this.magnifierPoint=null,this.isMouseOverText=!1}applyTextSelectionToAnnotation(t){const e=this.context.context.textSelectionService.getTextSelectionLines();return e?e.map((i,n)=>{const s=this.context.context.getActiveTab();let{startCharRect:o,startTextPosition:r,endCharRect:a,endTextPosition:l}=s;if(n>0){const t=i.lines[0].chars[0];o=t.charBox,r={lineUid:t.oriLineUid,charUid:t.uid,pageUid:i.pageUid,mediaBoxPoint:{x:o.left,y:o.top}}}if(n<e.length-1){const t=i.lines[i.lines.length-1],e=t.chars[t.chars.length-1];a={...e.charBox},l={lineUid:e.oriLineUid,charUid:e.uid,pageUid:i.pageUid,mediaBoxPoint:{x:a.left,y:a.top}}}const h=this.createTextAssist(i,t,{startCharRect:o,endCharRect:a,startTextPosition:r,endTextPosition:l});h.startCharRect=o,h.endCharRect=a,h.startTextPosition=r,h.endTextPosition=l;const c=this.context.annotationController.getShape(h.uid);return c&&(c.startCharRect=o,c.endCharRect=a,c.startTextPosition=r,c.endTextPosition=l),c}):null}activateAnnotation(t,e){this.context.annotationController.eventService.activateShape(t,e),this.loadTextForAnnotation(t)}loadTextForAnnotation(t){if(t.context.isActive&&this.context.isTextAssistType(t.textAssistType)){const{core:e}=this.context.context,i=e.annotationService.getAnnotationByUid(t.id);i&&!i.isPageTextLoaded&&e.textLoadService.loadText([i.pageUid]).then(()=>{i.isPageTextLoaded=!0})}}deactivateAnnotation(){this.context.annotationController.eventService.inactivateShape(!0),this.context.annotationController.eventService.defaultGroup.clear()}hasActiveAnnotation(){return this.context.annotationController.getSelectedShapeUids().length>0}keydownHandler(t){const e=this.context.context.getActiveTab();this.context.annotationController.keyDownHandler(t,e.context.zoom)}keyupHandler(t){this.context.annotationController.keyUpHandler(t)}setAnnotationContainer(t){this.containerPage=t,this.context.annotationController.setAnnotationContainer(t.uid,t.mediaBox)}setAnnotationInteractionArea(t){this.context.annotationController.eventService.setEventArea({left:t.left,top:t.top,width:t.width,height:t.height})}copyAnnotations(){const t=this.context.annotationController.getSelectedShapeUids();0===t.length||this.context.annotationController.isInTextEditMode()?this.context.viewer.clearAnnotationClipboard():this.context.viewer.copyAnnotations(t)}cutAnnotations(){const t=this.context.annotationController.getSelectedShapeUids();0===t.length||this.context.annotationController.isInTextEditMode()?this.context.viewer.clearAnnotationClipboard():this.context.viewer.cutAnnotations(t)}pasteAnnotations(){this.context.annotationController.isInTextEditMode()||this.context.viewer.pasteAnnotations()}initTextAssist(){}createTextAssist(t,e,i){const{context:n}=this.context,s=n.getActiveTab(),o=Us(),r=Rm(),{defaultStyleConfig:a}=this.context.viewer.getAnnotationConfig(),{opacity:l}=a[e];let h=a.highlight.background,c=1;"underline"===e?h=a.underline.borderColor:"strikeout"===e&&(h=a.strikeout.borderColor);const d=t.lines.map(t=>{let{selectedRect:e}=t;return{...e}});c=sy(d);const u=n.core.annotationService.createAnnotation(s.uid,{uid:o,docUid:s.uid,pageUid:t.pageUid,type:e,style:{opacity:l,borderColor:h,background:h,borderWidth:c,lines:d},flags:["print","noMove","noRotate"],comment:{annotationUid:o,author:"",subject:"",contents:"",creationDate:r,modificationDate:r,markedStates:[],reviewStates:[],replies:[]},transform:{},source:"user",...i});return Object.assign(u.customData,{isDDVTextAssist:!0}),this.context.annotationController.updateLayer(o,u.layer),u}updateTextAssist(t,e){}isHitTextAssistCtrlPoint(t,e){const{core:i}=this.context.context,n={start:!1,end:!1,annotationUid:""};return t.mediaBox.childNodes.some(t=>{if(this.context.isTextAssistType(t.textAssistType)){if(!t.context.isActive)return!1;const s=i.annotationService.getAnnotationByUid(t.id),o=t.getScale().x,r=this.context.context.viewerConfig.textSelectionStyle.ctrlBorderRadius/o,{startCharRect:a,endCharRect:l}=s;if(a&&qs({x:a.left+a.width/2,y:a.top-r},e)<=r)return n.start=!0,n.annotationUid=t.id,!0;if(l&&qs({x:l.left+l.width/2,y:l.top+l.height+r},e)<=r)return n.end=!0,n.annotationUid=t.id,!0}return!1}),n}dispose(){super.dispose(),this.containerPage=null}}class gx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="createAnnotation",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){const{action:t}=this,{annotationApp:e}=this.core.annotationService,{annotationConfig:i}=this.action;return!!e.createAnnotations([{docUid:t.docUid,uid:i.uid,pageUid:t.pageUid,type:i.type,style:i.style,transform:i.transform,flags:i.flags,comment:i.comment,layer:i.layer,flattened:i.flattened,source:i.source,oriIndex:i.oriIndex,parsedOriIndex:i.parsedOriIndex,startCharRect:i.startCharRect,endCharRect:i.endCharRect}])}undo(){this.core.annotationService.annotationApp.deleteAnnotations([this.action.annotationConfig.uid])}}class fx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="deleteAnnotation",e.commandService.onBeforeRefreshCommands.on(e=>{t.docUid===e.docUid&&(t.deleteConfigs.slice().forEach(i=>{if(e.pageUids.includes(i.pageUid)){const e=t.deleteConfigs.findIndex(t=>t.pageUid===i.pageUid);t.deleteConfigs.splice(e,1)}}),this.isValid=t.deleteConfigs.length>0)},this)}execute(){const{action:t}=this,e=t.deleteConfigs.map(t=>t.uid);return this.core.annotationService.annotationApp.deleteAnnotations(e),!0}undo(){const{annotationApp:t}=this.core.annotationService,e=this.action.deleteConfigs.map(t=>({docUid:this.action.docUid,uid:t.uid,type:t.type,pageUid:t.pageUid,style:t.style,transform:t.transform,flags:t.flags,comment:t.comment,layer:t.layer,oriIndex:t.oriIndex,modified:t.modified,flattened:t.flattened,parsedOriIndex:t.parsedOriIndex,source:t.source,startCharRect:t.startCharRect,endCharRect:t.endCharRect}));t.createAnnotations(e)}}class mx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),Yi(this,"oldLayer",void 0),Yi(this,"newLayer",void 0),this.action=t,this.core=e,this.type="bringAnnotationToFront",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){const{annotationApp:t}=this.core.annotationService,{annotationUid:e}=this.action,i=t.getAnnotationByUid(e);return this.oldLayer||(this.oldLayer=i.layer),this.newLayer?t.restoreLayer(e,this.newLayer):(t.bringToFront(e),this.newLayer=i.layer),!0}undo(){this.core.annotationService.annotationApp.restoreLayer(this.action.annotationUid,this.oldLayer)}}class vx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),Yi(this,"oldLayer",void 0),Yi(this,"newLayer",void 0),this.action=t,this.core=e,this.type="bringAnnotationForward",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){const{annotationApp:t}=this.core.annotationService,{annotationUid:e}=this.action,i=t.getAnnotationByUid(e);return this.oldLayer||(this.oldLayer=i.layer),this.newLayer?t.restoreLayer(e,this.newLayer):(t.bringForward(e),this.newLayer=i.layer),!0}undo(){this.core.annotationService.annotationApp.restoreLayer(this.action.annotationUid,this.oldLayer)}}class yx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="sendAnnotationBackward",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){return this.core.annotationService.annotationApp.sendBackward(this.action.annotationUid)}undo(){this.core.annotationService.annotationApp.bringForward(this.action.annotationUid)}}class xx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),Yi(this,"oldLayer",void 0),Yi(this,"newLayer",void 0),this.action=t,this.core=e,this.type="sendAnnotationToBack",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){const{annotationApp:t}=this.core.annotationService,{annotationUid:e}=this.action,i=t.getAnnotationByUid(e);return this.oldLayer||(this.oldLayer=i.layer),this.newLayer?t.restoreLayer(e,this.newLayer):(t.sendToBack(e),this.newLayer=i.layer),!0}undo(){this.core.annotationService.annotationApp.restoreLayer(this.action.annotationUid,this.oldLayer)}}class wx extends ry{constructor(t,e,i){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),Yi(this,"updatedBy",void 0),this.action=t,this.core=e,this.updatedBy=i,this.type="updateAnnotation",e.commandService.onBeforeRefreshCommands.on(e=>{if(t.docUid!==e.docUid)return;const{pageUid:i}=t;e.pageUids.includes(i)&&(this.isValid=!1)},this)}execute(){return this.update(!0),this.updatedBy=null,!0}undo(){this.update(!1)}update(t){const{annotationApp:e}=this.core.annotationService,i=this.action.updateDetails.map(e=>({annotationUid:e.annotationUid,from:_s(t?e.from:e.to),to:_s(t?e.to:e.from)}));e.updateAnnotation({updateDetails:i,updatedBy:this.updatedBy,updateActions:[...this.action.updateActions]})}}class Cx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="switchAnnotationPage",e.commandService.onBeforeRefreshCommands.on(e=>{t.docUid===e.docUid&&t.moveConfigs.slice().every(t=>((e.pageUids.includes(t.from.pageUid)||e.pageUids.includes(t.to.pageUid))&&(this.isValid=!1),this.isValid))},this)}execute(){const{annotationApp:t}=this.core.annotationService;return this.action.moveConfigs.forEach(e=>{if(Ps(e.to.layer)){const i=t.annotationPageRepo.findPageByUid(e.to.pageUid).createTop();e.to.layer=i}t.switchAnnotationPage(e.annotationUid,{...e.to})}),!0}undo(){const{annotationApp:t}=this.core.annotationService;this.action.moveConfigs.forEach(e=>{t.switchAnnotationPage(e.annotationUid,{...e.from})})}}class bx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="deleteReplyMarkedState",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){return this.core.annotationService.annotationApp.deleteReplyMarkedState(this.action.replyUid)}undo(){this.core.annotationService.annotationApp.addReplyMarkedState({replyUid:this.action.replyUid,...this.action.config,state:this.action.config.state.state})}}class Sx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="addReplyMarkedState",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){return this.core.annotationService.annotationApp.addReplyMarkedState({replyUid:this.action.replyUid,...this.action.config})}undo(){this.core.annotationService.annotationApp.deleteReplyMarkedState(this.action.replyUid)}}class Tx extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="deleteReplyReviewState",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){return this.core.annotationService.annotationApp.deleteReplyReviewState(this.action.replyUid)}undo(){this.core.annotationService.annotationApp.addReplyReviewState({replyUid:this.action.replyUid,...this.action.config,state:this.action.config.state.state})}}class Ex extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="addReplyReviewState",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){return this.core.annotationService.annotationApp.addReplyReviewState({replyUid:this.action.replyUid,...this.action.config})}undo(){this.core.annotationService.annotationApp.deleteReplyReviewState(this.action.replyUid)}}class _x extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="addReply",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){const{replyConfig:t}=this.action,{annotationApp:e}=this.core.annotationService;return!!e.addReply({annotationUid:t.annotationUid,author:t.author,subject:t.subject,contents:t.contents,creationDate:t.creationDate,modificationDate:t.modificationDate})}undo(){this.core.annotationService.annotationApp.deleteReply(this.action.replyConfig.uid)}}class Px extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="deleteReply",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){return this.core.annotationService.annotationApp.deleteReply(this.action.replyConfig.uid)}undo(){const{replyConfig:t}=this.action,{annotationApp:e}=this.core.annotationService;e.addReply({annotationUid:t.annotationUid,author:t.author,subject:t.subject,contents:t.contents,creationDate:t.creationDate,modificationDate:t.modificationDate})}}class Ax extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="updateReply",this.core.commandService.onBeforeRefreshCommands.on(t=>{t.pageUids.includes(this.action.pageUid)&&(this.isValid=!1)},this)}execute(){return this.update("do")}undo(){this.update("undo")}update(t){const e="do"===t?this.action.updateDetail.to:this.action.updateDetail.from;return this.core.annotationService.annotationApp.updateReply({uid:e.uid,annotationUid:e.annotationUid,author:e.author,contents:e.contents,creationDate:e.creationDate,modificationDate:e.modificationDate})}}class Ix extends Wo{constructor(t){super(),Yi(this,"core",void 0),Yi(this,"annotationApp",void 0),Yi(this,"hooks",void 0),Yi(this,"enableEmitLayerChanged",!0),Yi(this,"pasteConfig",{pasteComment:!1,pasteReply:!0,updateDate:!0}),Yi(this,"clipboard",[]),Yi(this,"currentClipboard",[]),Yi(this,"currentPastePageUid",null),Yi(this,"flattenedAnnotationUidsMap",new Map),this.core=t,this.annotationApp=new nx,this.hooks=this.annotationApp.hooks,this.bindAnnotationFlattenEvent()}bindAnnotationFlattenEvent(){this.hooks.annotationCreated.on(t=>{const{flattenedAnnotationUidsMap:e}=this;t.annotations.forEach(t=>{if(t.flattened){const{pageUid:i}=t;e.has(i)?e.get(i).push(t.uid):e.set(i,[t.uid])}})},this),this.hooks.annotationDeleted.on(t=>{t.annotations.forEach(t=>{if(t.flattened){const e=this.flattenedAnnotationUidsMap.get(t.pageUid),i=e.indexOf(t.uid);-1!==i&&e.splice(i,1)}})},this),this.hooks.annotationUpdated.on(t=>{t.updateActions.includes("flattenedChanged")&&t.updateDetails.forEach(t=>{let{annotationUid:e}=t;const i=this.getAnnotationByUid(e),n=this.flattenedAnnotationUidsMap.get(i.pageUid);i.flattened?n?n.includes(e)||n.push(e):this.flattenedAnnotationUidsMap.set(i.pageUid,[e]):n&&n.includes(e)&&n.splice(n.indexOf(e),1)})},this)}reset(){this.annotationApp.reset()}getAnnotationByUid(t){return this.annotationApp.getAnnotationByUid(t)}deleteAnnotationPages(t){const e=t.reduce((t,e)=>{const i=this.core.pageService.getPage(e);return i&&t.push(...i.annotations),t},[]);this.deleteAnnotations(e,!1),this.annotationApp.annotationPageRepo.deletePagesByUids(t)}createAnnotationsByParsedPages(t,e){const i=Rm();return e.reduce((e,n)=>{var s;this.annotationApp.createAnnotationPage(n.pageUid);const o=null===(s=n.annotations)||void 0===s?void 0:s.reduce((e,s)=>{var o,r,a,l,h;kx(s);const c={uid:s.uid,docUid:t,pageUid:n.pageUid,type:s.type,style:s.style,transform:s.transform,flags:s.flags,comment:Dx(s.comment),creationDate:null!==(o=null===(r=s.comment)||void 0===r?void 0:r.creationDate)&&void 0!==o?o:i,modificationDate:null!==(a=null===(l=s.comment)||void 0===l?void 0:l.modifiedDate)&&void 0!==a?a:i,oriIndex:null===(h=s.raw)||void 0===h?void 0:h.oriIndex,parsedOriIndex:s.parsedOriIndex,customData:{...s.customData||{}},source:"file"};return e.push(c),e},[]);return null!=o&&o.length?(this.annotationApp.createAnnotations(o),e.push(o.map(t=>t.uid))):e.push([]),e},[])}createAnnotation(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(kx(e),i){const i=new gx({actionUid:Us(),type:"createAnnotation",docUid:t,pageUid:e.pageUid,annotationConfig:{uid:e.uid,type:e.type,style:e.style,transform:e.transform,flags:e.flags,comment:e.comment,layer:e.layer,modified:e.modified,oriIndex:e.oriIndex,flattened:e.flattened,source:e.source,parsedOriIndex:e.parsedOriIndex,startCharRect:e.startCharRect,endCharRect:e.endCharRect}},this.core);this.core.commandService.execute(i,t)}else this.annotationApp.createAnnotations([e]);return this.annotationApp.getAnnotationByUid(e.uid)}deleteAnnotations(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{pageService:i,commandService:n}=this.core,s=t.reduce((t,e)=>{const n=this.annotationApp.getAnnotationByUid(e);if(n){const e=i.getPage(n.pageUid),s=t.get(e.doc.uid)||{uid:e.doc.uid,annotationConfigs:[]};t.set(s.uid,s);const o=n.getConfig();o.layer=n.layer,o.flattened=n.flattened,null!=o&&o.flattened&&!o.flags.includes("flattened")&&o.flags.push("flattened"),s.annotationConfigs.push(o)}return t},new Map);if(e)for(const[t,e]of s){const i=e.annotationConfigs.map(t=>({uid:t.uid,type:t.type,pageUid:t.pageUid,style:t.style,transform:t.transform,flags:t.flags,comment:t.comment,layer:t.layer,oriIndex:t.oriIndex,parsedOriIndex:t.parsedOriIndex,modified:t.modified,flattened:t.flattened,source:t.source,startCharRect:t.startCharRect,endCharRect:t.endCharRect})),s=new fx({actionUid:Us(),type:"deleteAnnotation",docUid:t,deleteConfigs:i},this.core);n.execute(s,e.uid)}else this.annotationApp.deleteAnnotations(t,!1)}updateAnnotations(t,e,i,n){let s,o;const r=t.reduce((t,e)=>{const{annotationUid:i}=e,n=this.annotationApp.getAnnotationByUid(i);var r,a,l;return n&&(s=n.pageUid,o=n.docUid,null==n||!n.flattened||null==e||null===(r=e.options)||void 0===r||!r.flags||null!=e&&null!==(a=e.options)&&void 0!==a&&null!==(a=a.flags)&&void 0!==a&&a.includes("flattened")||!1===(null==e||null===(l=e.options)||void 0===l?void 0:l.flattened)||e.options.flags.push("flattened"),t.push({annotation:n,options:e.options})),t},[]);if(null==r||!r.length||r.length!==t.length)return;const a=Rm(),l=r.map(t=>{let{annotation:e,options:i}=t;i.comment||(i.comment={}),i.comment.modificationDate=a,i.modified=!n||e.modified;const s=e.getConfig(),o=_o(i,e.getConfig()),{newChanged:r,oldChanged:l}=Mx(i,s);return{annotationUid:e.uid,from:{all:s,changed:l},to:{all:o,changed:r}}}),h=new wx({actionUid:Us(),type:"updateAnnotation",docUid:o,pageUid:s,updateDetails:l,updateActions:i||[]},this.core,e);this.core.commandService.execute(h,o)}switchAnnotationPage(t){const e=t.map(t=>({annotation:this.annotationApp.getAnnotationByUid(t.annotationUid),...t})),i=this.core.pageService.getPage(e[0].annotation.pageUid);if(!i)return;const n=e.map(t=>{let{annotationUid:e,annotation:i,pageUid:n,x:s,y:o}=t;return{annotationUid:e,from:{pageUid:i.pageUid,x:i.style.x,y:i.style.y,layer:i.layer},to:{pageUid:n,x:Ps(s)?i.style.x:s,y:Ps(o)?i.style.y:o,layer:void 0}}}),s=new Cx({actionUid:Us(),type:"switchAnnotationPage",docUid:i.doc.uid,moveConfigs:n},this.core);this.core.commandService.execute(s,i.doc.uid)}duplicateAnnotation(t,e){const i=this.annotationApp.getAnnotationByUid(t);if(!i)return null;const n=i.getConfig();return n.uid=Us(),e&&(n.pageUid=e),n.comment.creationDate=Rm(),n.comment.modificationDate=n.comment.creationDate,this.createAnnotation(n.docUid,n)}copyAnnotations(t){t.length&&(this.clipboard=[],this.currentClipboard=[],this.currentPastePageUid=null),t.forEach(t=>{const e=this.annotationApp.getAnnotationByUid(t);if(e&&!["highlight","strikeout","underline"].includes(e.type)){const t=e.getConfig();this.clipboard.push(t),this.currentClipboard.push(_s(t))}})}cutAnnotations(t){const e=[];t.forEach(t=>{const i=this.annotationApp.getAnnotationByUid(t);i&&!["highlight","strikeout","underline"].includes(i.type)&&e.push(t)}),this.copyAnnotations(t),this.deleteAnnotations(e)}pasteAnnotations(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10;if(!this.clipboard.length)return;const n=this.core.pageService.getPage(e);this.currentPastePageUid&&this.currentPastePageUid!==e&&(this.currentClipboard=_s(this.clipboard)),this.currentPastePageUid=e,this.currentClipboard.forEach(s=>{var o,r,a,l;const h=Rm();let{x:c,y:d}=s.style;const u=!Ps(null==s||null===(o=s.style)||void 0===o?void 0:o.x)&&!Ps(null==s||null===(r=s.style)||void 0===r?void 0:r.y);!u&&null!=s&&null!==(a=s.transform)&&void 0!==a&&a.position&&(c=s.transform.position.x,d=s.transform.position.y),c+=i,d+=i,(c>n.cropBox.left+n.cropBox.width-i||d>n.cropBox.top+n.cropBox.height-i||c<n.cropBox.left||d<n.cropBox.top)&&(c=n.cropBox.left,d=n.cropBox.top),u?(s.style.x=c,s.style.y=d,delete s.transform.position):!u&&null!=s&&null!==(l=s.transform)&&void 0!==l&&l.position&&(s.transform.position={x:c,y:d});const p=_s(s);p.layer=void 0;const g=Us();Object.assign(p,{uid:g,docUid:t,pageUid:e,creationDate:h,modificationDate:h});const f={annotationUid:g,creationDate:h,modificationDate:h,markedStates:[],reviewStates:[],replies:[]};this.pasteConfig.pasteComment?this.pasteConfig.pasteReply||Object.assign(p.comment,f):Object.assign(p.comment,f,{contents:""}),this.createAnnotation(s.docUid,p)})}clearAnnotationClipboard(){this.clipboard=[],this.currentClipboard=[],this.currentPastePageUid=null}bringToFront(t){return this.handleLayer(t,"f")}bringForward(t){return this.handleLayer(t,"fw")}sendToBack(t){const e=this.getAnnotationByUid(t),i=this.flattenedAnnotationUidsMap.get(e.pageUid);if(null==i||!i.length)return this.handleLayer(t,"b");if(!this.getAnnotationLayerState(t).back)return!0;this.enableEmitLayerChanged=!1;const n=i.length,s=e.layer;this.annotationApp.sendToBack(t);for(let i=0;i<n;i++)i===n-1?(e.layer=s,this.enableEmitLayerChanged=!0,this.bringForward(t)):this.annotationApp.bringForward(t);return!0}sendBackward(t){return this.handleLayer(t,"bw")}handleLayer(t,e){const i=this.annotationApp.getAnnotationByUid(t);if(!i)return!1;const n=this.core.pageService.getPage(i.pageUid);if(!n)return!1;const s={actionUid:Us(),type:e,annotationUid:t,docUid:n.doc.uid,pageUid:n.uid},o=this.annotationApp.getAnnotationLayerState(t);let r;return"f"===e&&o.front?r=new mx(s,this.core):"fw"===e&&o.forward?r=new vx(s,this.core):"bw"===e&&o.backward?r=new yx(s,this.core):"b"===e&&o.back&&(r=new xx(s,this.core)),r&&this.core.commandService.execute(r,n.doc.uid),!0}getAnnotationLayerState(t){const e=this.annotationApp.getAnnotationLayerState(t),i=this.getAnnotationByUid(t);if(!i)return e;const n=this.flattenedAnnotationUidsMap.get(i.pageUid);if(null==n||!n.length)return e;const s=[...this.core.getAnnotationsByPageUid(i.pageUid)];return s.sort((t,e)=>t.layer-e.layer),s.indexOf(i)===n.length&&(e.back=!1,e.backward=!1),e}updateComment(){}addReply(t,e,i){const n=this.annotationApp.getAnnotationByUid(e);if(!n)return;const s=new _x({actionUid:Us(),type:"addReply",docUid:t,pageUid:n.pageUid,annotationUid:e,replyConfig:i},this.core);this.core.commandService.execute(s,t)}deleteReply(t,e){const i=this.annotationApp.getReply(e);if(!i)return;const n=this.annotationApp.getAnnotationByUid(i.annotationUid);if(!n)return;const s=new Px({actionUid:Us(),type:"deleteReply",docUid:t,pageUid:n.pageUid,annotationUid:i.annotationUid,replyConfig:{uid:i.uid,author:i.author,contents:i.contents,creationDate:i.creationDate,modificationDate:i.modificationDate,markedStates:i.markedStates.slice(),reviewStates:i.reviewStates.slice()}},this.core);this.core.commandService.execute(s,t)}updateReply(t,e,i){const n=this.annotationApp.getReply(e);if(!n)return;const s=this.annotationApp.getAnnotationByUid(n.annotationUid);if(!s)return;const o=new Ax({actionUid:Us(),type:"updateReply",docUid:t,pageUid:s.pageUid,annotationUid:s.uid,updateDetail:{from:null,to:null}},this.core);this.core.commandService.execute(o,t)}addReviewState(t,e){const i=this.annotationApp.getReply(e);if(!i)return;if(!i.markedStates.length)return;const n=this.annotationApp.getAnnotationByUid(i.annotationUid);if(!n)return;const s=Rm(),o=new Ex({actionUid:Us(),type:"addReplyMarkedState",replyUid:Us(),pageUid:n.pageUid,config:{uid:Us(),author:"",contents:"",creationDate:s,state:"none"}},this.core);this.core.commandService.execute(o,t)}deleteReviewState(t,e){const i=this.annotationApp.getReply(e);if(!i)return;if(!i.markedStates.length)return;const n=this.annotationApp.getAnnotationByUid(i.annotationUid);if(!n)return;const s=new Tx({actionUid:Us(),type:"deleteReplyMarkedState",pageUid:n.pageUid,replyUid:e,config:{uid:i.uid,author:i.author,contents:i.contents,creationDate:i.creationDate,state:i.reviewStates[i.reviewStates.length-1]}},this.core);this.core.commandService.execute(s,t)}addCheckMarkState(t,e){const i=this.annotationApp.getReply(e);if(!i)return;if(!i.markedStates.length)return;const n=this.annotationApp.getAnnotationByUid(i.annotationUid);if(!n)return;const s=Rm(),o=new Sx({actionUid:Us(),type:"addReplyMarkedState",replyUid:Us(),pageUid:n.pageUid,config:{uid:Us(),author:"",contents:"",creationDate:s,state:"marked"}},this.core);this.core.commandService.execute(o,t)}deleteCheckMarkState(t,e){const i=this.annotationApp.getReply(e);if(!i)return;if(!i.markedStates.length)return;const n=this.annotationApp.getAnnotationByUid(i.annotationUid);if(!n)return;const s=new bx({actionUid:Us(),type:"deleteReplyMarkedState",pageUid:n.pageUid,replyUid:e,config:{uid:i.uid,author:i.author,contents:i.contents,creationDate:i.creationDate,state:i.markedStates[i.markedStates.length-1]}},this.core);this.core.commandService.execute(s,t)}createAnnotationShape(t,e){const{type:i,transform:n,style:s}=t.getConfig(),o=s,r=n;e&&!["highlight","underline","strikeout","incomplete"].includes(t.type)&&function(t,e){const i=["rx","x","width","borderWidth","fontSize"],n=["ry","y","height"],s=["startPoint","endPoint"];Object.keys(t).forEach(o=>{const r=t[o];if(i.includes(o)||n.includes(o)){const i=da(r);t[o]=e.toPixelPPI(i.value,n.includes(o))}else s.includes(o)?t[o]={x:e.toPixelPPI(r.x,!1),y:e.toPixelPPI(r.y,!0)}:"lineDash"===o?t[o]=r.map(t=>e.toPixelPPI(t,!1)):"points"===o?t[o]=r.map(t=>({x:e.toPixelPPI(t.x,!1),y:e.toPixelPPI(t.y,!0)})):"segments"===o?t[o]=r.map(t=>t.map(t=>({x:e.toPixelPPI(t.x,!1),y:e.toPixelPPI(t.y,!0)}))):"textContents"===o&&(t[o]=r.map(t=>({...t,fontSize:e.toPixelPPI(da(t.fontSize).value,!1)})))})}(o,e),"ellipse"===i&&(o.x+=o.width/2||0,o.y+=o.height/2||0,o.rx=o.width/2||o.rx,o.ry=o.height/2||o.ry),r&&null!=r&&r.position&&(r.position={x:e.toPixelPPI(r.position.x,!1),y:e.toPixelPPI(r.position.y,!0)});const a={id:t.uid,style:o,transform:r};let l;switch(i){case"rectangle":l=new rc(a);break;case"ellipse":l=new nc(a);break;case"line":l=new fc(a);break;case"ink":l=new oc(a);break;case"polygon":l=new pc(a);break;case"polyline":l=new gc(a);break;case"textTypewriter":l=new hc(a,"freeTextWriter",{});break;case"textBox":l=new hc(a,"textBox");break;case"stamp":l=new Ac(a);break;case"highlight":l=new Lc(a);break;case"underline":l=new Bc(a);break;case"strikeout":l=new Oc(a);break;case"incomplete":l=new Dc(a)}if(l instanceof Ac&&!l.style.imageData&&l.updateStampStyle({x:o.x,y:o.y,width:o.width,height:o.height}),["highlight","underline","strikeout","incomplete"].includes(i)){const{resolutionX:t,resolutionY:i}=e,{displayResolution:n}=Cr,s=t/n,o=i/n;l.setOrigin(0,0),l.scaleLocal(s,o)}return l}getAnnotationUidsByLayer(t){const e=this.annotationApp.annotationPageRepo.findPageByUid(t);return null==e?void 0:e.getAnnotationUidListByLayer()}flattenAnnotations(t){const e=t.map(t=>this.getAnnotationByUid(t)),i=[],n=[];this.enableEmitLayerChanged=!1,e.forEach(t=>{const e=t.layer;this.core.annotationService.annotationApp.sendToBack(t.uid);const s=this.flattenedAnnotationUidsMap.get(t.pageUid);s?(s.forEach(e=>{this.core.annotationService.annotationApp.bringForward(t.uid)}),s.push(t.uid)):this.flattenedAnnotationUidsMap.set(t.pageUid,[t.uid]),n.push(e),i.push({annotationUid:t.uid,options:{flags:[...t.flags,"flattened"],flattened:!0}})}),this.enableEmitLayerChanged=!0,e.forEach((t,e)=>{i[e].options.layer=t.layer,t.layer=n[e]}),this.updateAnnotations(i,void 0,["flattenedChanged"],!0)}unFlattenAnnotation(t){const e=this.getAnnotationByUid(t),i=this.flattenedAnnotationUidsMap.get(e.pageUid);if(!i||0===i.length)return!1;const n=i.indexOf(e.uid);if(-1===n)return!1;this.enableEmitLayerChanged=!1;const s=i.length-(n+1),o=e.layer;for(let t=0;t<s;t++)this.core.annotationService.annotationApp.bringForward(e.uid);const r=e.layer,a=e.flags.filter(t=>"flattened"!==t);return e.layer=o,this.updateAnnotations([{annotationUid:e.uid,options:{flags:a,flattened:!1,layer:r}}],void 0,["flattenedChanged"],!0),i.includes(e.uid)&&i.splice(n,1),this.enableEmitLayerChanged=!0,!0}}function Dx(t){var e;return{annotationUid:t.uid,author:t.author,subject:t.subject,contents:t.contents,creationDate:t.creationDate,modificationDate:t.modifiedDate,markedStates:Rx(t.markedStates||[]),reviewStates:Rx(t.reviewStates||[]),replies:(null===(e=t.replies)||void 0===e?void 0:e.map(t=>Dx(t)))||[]}}function Rx(t){return t.map(t=>({uid:t.uid,author:t.author,contents:t.contents,creationDate:t.creationDate,state:t.state}))}function kx(t){if("stamp"===t.type){const e=new Ac({style:t.style,transform:t.transform}),i=e.getAnnotationConfig();t.style=i.style,t.transform={...t.transform,position:i.transform.position,scale:i.transform.scale},e.destroy()}}function Mx(t,e){const i=Object.keys(t),n={},s={};return i.forEach(i=>{if(Es(t[i])&&Es(e[i])){const o=Mx(t[i],e[i]);n[i]=o.newChanged,s[i]=o.oldChanged}else n[i]=t[i],s[i]=e[i]}),{newChanged:n,oldChanged:s}}var Lx=new WeakMap,Ox=new WeakMap,Bx=new WeakMap,Nx=new WeakMap,Ux=new WeakSet,Fx=new WeakSet;class Vx{constructor(t,e){an(this,Fx),an(this,Ux),rn(this,Lx,{writable:!0,value:void 0}),rn(this,Ox,{writable:!0,value:void 0}),rn(this,Bx,{writable:!0,value:void 0}),rn(this,Nx,{writable:!0,value:void 0}),sn(this,Ux,Wx).call(this,t,e)}getCanvas(){return $i(this,Lx).contextService.getDomElement()}getInkOptions(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(!$i(this,Nx))return null;const{x:e,y:i}=$i(this,Nx).getLocalPosition();$i(this,Nx).setLocalPosition(0,0);const n=$i(this,Nx).getAnnotationConfig(),s={borderWidth:n.style.borderWidth,borderColor:n.style.borderColor,opacity:n.style.opacity};if(t){const{displayResolution:t,dataResolution:o}=Cr,r=n.style.segments.map(e=>e.map(e=>({x:Bo(e.x,t,o),y:Bo(e.y,t,o)})));return s.borderWidth=Bo(s.borderWidth,t,o),$i(this,Nx).setLocalPosition(e,i),$i(this,Nx).getAnnotationConfig(),{points:r,...s}}return{segments:n.style.segments,...s}}getSignatureImage(){if(!$i(this,Nx))return Promise.resolve(null);const t=$i(this,Nx).getBoundingRect(),e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(this.getCanvas(),t.left*devicePixelRatio,t.top*devicePixelRatio,t.width*devicePixelRatio,t.height*devicePixelRatio,0,0,t.width,t.height),new Promise(t=>{e.toBlob(t,"image/png")})}updateSignatureStyle(t){Xi(this,Bx,{...$i(this,Bx),...t}),$i(this,Nx)&&($i(this,Nx).updateStyle({...t}),$i(this,Lx).render())}clearSignature(){$i(this,Ox).children.slice().forEach(t=>{$i(this,Ox).removeChild(t)}),Xi(this,Nx,null),$i(this,Lx).render()}resizeCanvas(t,e){$i(this,Lx).resize(t,e)}}function Wx(t,e){const i=document.createElement("canvas");i.style.touchAction="none",Xi(this,Lx,new ph({renderer:new kh,width:t,height:e,canvas:i,dpr:window.devicePixelRatio,willReadFrequently:!0})),Xi(this,Ox,$i(this,Lx).document.documentElement),(new rd).init($i(this,Lx)),sn(this,Fx,Hx).call(this)}function Hx(){let t=!1;const e=this.getCanvas();e.addEventListener("pointerdown",e=>{const i={x:e.offsetX,y:e.offsetY};t=!0,$i(this,Nx)?($i(this,Nx).addSegment(),$i(this,Nx).addPoint(i)):(Xi(this,Nx,new oc({style:{segments:[[i]],...$i(this,Bx),lineCap:"round",lineJoin:"round"}})),$i(this,Ox).appendChild($i(this,Nx))),$i(this,Lx).render()}),e.addEventListener("pointermove",e=>{if(!t)return;const i={x:e.offsetX,y:e.offsetY};$i(this,Nx).addPoint(i),$i(this,Lx).render()}),document.addEventListener("pointerup",()=>{t&&(t=!1,$i(this,Nx).pathDirty=!0,$i(this,Nx).boundsDirty=!0,$i(this,Lx).render())})}const jx={stampText:"Draft",fontSize:32,fontFamily:"Arial",fontWeight:"bold",fontStyle:"normal",underline:!1,strikeout:!1,color:"#182564",borderColor:"#182564",background:"#c7d2e4",timeStampFontSize:16,userName:"Guest",hasUserName:!0,hasDate:!0,hasTime:!0};var zx=new WeakMap,Gx=new WeakMap,Yx=new WeakMap,$x=new WeakMap,Xx=new WeakMap,qx=new WeakMap,Zx=new WeakSet,Jx=new WeakSet;class Kx{constructor(t,e){an(this,Jx),an(this,Zx),rn(this,zx,{writable:!0,value:void 0}),rn(this,Gx,{writable:!0,value:void 0}),rn(this,Yx,{writable:!0,value:void 0}),rn(this,$x,{writable:!0,value:void 0}),rn(this,Xx,{writable:!0,value:void 0}),rn(this,qx,{writable:!0,value:{...jx}}),Xi(this,Yx,t),Xi(this,$x,e),sn(this,Zx,Qx).call(this,t,e)}get signatureStyle(){return{...$i(this,qx)}}getStampConfig(){const{background:t,borderColor:e,stampText:i}=$i(this,qx),n=[],s=function(t,e){const i=t-1,n=e-1;return[{x:i,y:n-10.6,step:2},{x:i,y:n-4.8,step:1},{x:i-6,y:n,step:1},{x:i-13.4,y:n,step:1},{x:14.4,y:n,step:0},{x:7,y:n,step:1},{x:1,y:n-4.8,step:1},{x:1,y:n-10.6,step:1},{x:1,y:11.6,step:0},{x:1,y:5.8,step:1},{x:7,y:1,step:1},{x:14.4,y:1,step:1},{x:i-13.4,y:1,step:0},{x:i-6,y:1,step:1},{x:i,y:5.8,step:1},{x:i,y:11.6,step:1},{x:i,y:n-10.6,step:0}]}($i(this,Yx),$i(this,$x));n.push({type:"path",stampPoints:s,borderWidth:1.3333333333333333,lineDash:[0,0],lineCap:"butt",lineJoin:"miter",miterLimit:4,background:t,borderColor:e});const{color:o,fontFamily:r,fontSize:a,fontStyle:l,fontWeight:h}=$i(this,qx),c=null!=r&&r.includes(" ")?`'${r}'`:r,d=document.createElement("canvas").getContext("2d"),{hasUserName:u,hasDate:p,hasTime:g,timeStampFontSize:f,userName:m}=$i(this,qx),v=u||p||g;if(v){let t="";t+=u?`${m} `:"",t+=p?`${function(){const t=new Date,e=t.getFullYear(),i=(t.getMonth()+1).toString().padStart(2,"0");return`${t.getDate().toString().padStart(2,"0")}/${i}/${e}`}()} `:"",t+=g?`${function(){const t=new Date;let e=t.getHours();const i=e>=12?"PM":"AM";return e%=12,e=e||12,`${e}:${t.getMinutes().toString().padStart(2,"0")} ${i}`}()}`:"";const e=`${l} ${h} ${f}px ${c}`;d.font=e;const{width:i,actualBoundingBoxAscent:s,actualBoundingBoxDescent:a}=d.measureText(t.trim()),v=s+a;n.push({type:"text",text:t,x:($i(this,Yx)-i)/2,y:$i(this,$x)/2+$i(this,$x)/4+v/2,color:o,fontFamily:r,fontSize:f,fontStyle:l,fontWeight:h})}if(i){const t=`${l} ${h} ${a}px ${c}`;d.font=t;const{underline:e,strikeout:s}=this.signatureStyle,{width:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g}=d.measureText(i),f=p+g;if(n.push({type:"text",text:i,x:($i(this,Yx)-u)/2,y:v?$i(this,$x)/2:$i(this,$x)/2+f/2,color:o,fontFamily:r,fontSize:a,fontStyle:l,fontWeight:h}),s){const t=v?$i(this,$x)/2-f/3:$i(this,$x)/2+f/2-f/3,e=($i(this,Yx)-u)/2;n.push({type:"path",stampPoints:[{x:e,y:t,step:2},{x:e+u,y:t,step:0}],borderWidth:2,borderColor:o,clipped:!0})}if(e){const t=v?$i(this,$x)/2+f/10:$i(this,$x)/2+f/2+f/10,e=($i(this,Yx)-u)/2;n.push({type:"path",stampPoints:[{x:e,y:t,step:2},{x:e+u,y:t,step:0}],borderWidth:2,borderColor:o,clipped:!0})}}return n}getCanvas(){return $i(this,Gx).contextService.getDomElement()}updateSignatureStyle(t){Xi(this,qx,{...$i(this,qx),...t});const e=this.getStampConfig();$i(this,Xx).stampConfig=e,$i(this,Xx).initStamp(),$i(this,Gx).render()}getSignatureImage(){if(!$i(this,Xx))return Promise.resolve(null);const t=document.createElement("canvas");return t.width=$i(this,Yx),t.height=$i(this,$x),t.getContext("2d").drawImage(this.getCanvas(),-.65*devicePixelRatio,-.65*devicePixelRatio,($i(this,Yx)+1.3)*devicePixelRatio,($i(this,$x)+1.3)*devicePixelRatio,0,0,$i(this,Yx),$i(this,$x)),new Promise(e=>{t.toBlob(e,"image/png")})}}function Qx(t,e){const i=document.createElement("canvas");Xi(this,Gx,new ph({renderer:new kh,width:t,height:e,canvas:i,dpr:window.devicePixelRatio,willReadFrequently:!0})),i.style.width=`${t}px`,i.style.height=`${e}px`,Xi(this,zx,$i(this,Gx).document.documentElement),Xi(this,Xx,new Ac({style:{stampConfig:this.getStampConfig()}})),$i(this,zx).appendChild($i(this,Xx)),(new rd).init($i(this,Gx)),$i(this,Gx).render()}const tw={install(t){const e=t.getClass("Viewer"),i=(n=e,class extends n{constructor(t){super(t),Yi(this,"annotationViewerContext",void 0),this.annotationViewerContext=this.register(new cx(this)),this.listenGlobalEventForAnnotation(),this.listenHooksForAnnotation(),this.listenNativeEventsForAnnotation(),this.context.hasAnnotationModule=!0,this.context.annotationEditService=this.register(new px(this.annotationViewerContext));const e=this.getViewerConfig();this.context.isDefaultViewer&&this.updateAnnotationConfig({enableDeleteWithKeyboard:e.enableDeleteWithKeyboard,enableMoveWithKeyboard:e.enableMoveAnnotationWithKeyboard,enableMultipleSelectWidthCtrl:e.enableMultipleSelectAnnotationWithKeyboard})}listenHooksForAnnotation(){const t=()=>{const t=this.getSelectedAnnotations();if(1!==t.length)return;if(!t[0])return;const e=this.getAnnotationObject(t[0].uid);e instanceof hc&&e.isEditMode&&e.updateCursor()};this.hooks.scroll.on(e=>{this.context.isDefaultViewer&&t()},this),this.hooks.resize.on(e=>{this.context.isDefaultViewer&&t()},this),this.hooks.zoomChanged.on(e=>{this.context.isDefaultViewer&&t()},this),this.hooks.pageChanged.on(t=>{if(this.context.isDefaultViewer||this.context.isThumbnailViewer){const t=this.getActiveTab();if(null!=t&&t.total){const e=t.getCurrentPage();this.context.annotationEditService.setAnnotationContainer(e)}t&&"single"===t.context.displayMode&&this.annotationViewerContext.disableTextEditMode()}},this),this.hooks.currentPageChanged.on(t=>{if(this.context.isDefaultViewer||this.context.isThumbnailViewer){const t=this.getActiveTab();if(null!=t&&t.total){const e=t.getCurrentPage();this.context.annotationEditService.setAnnotationContainer(e)}}},this)}listenGlobalEventForAnnotation(){if(!this.context.isDefaultViewer&&!this.context.isThumbnailViewer)return;const{core:t}=this.context,e=t.annotationService.annotationApp.hooks;t.onBeforeGetPageData.on(t=>{const{activatedShape:e}=this.annotationViewerContext.annotationController.eventService;(null==e?void 0:e.pageUid)===t.pageUid&&e instanceof hc&&e.isEditMode&&e.textEditEventHandler.emitTextContentUpdated()},this),e.annotationCreated.on(t=>{let e=!1;var i;t.annotations.forEach(t=>{this.annotationViewerContext.addAnnotationByAnnotationData(t),e||this.annotationIsVisible(t.uid)&&(e=!0)}),e&&(null===(i=this.context)||void 0===i||i.render(61))},this),e.annotationDeleted.on(t=>{var e;this.annotationViewerContext.deleteAnnotations(t.annotations.map(t=>t.uid),t.emitEvent),null===(e=this.context)||void 0===e||e.render(62)},this),e.annotationUpdated.on(t=>{var e;const i=t.updateDetails.map(t=>t.annotationUid),n=function(t){if(!t.length)return!1;for(const e of t)if("flagsChanged"!==e&&"flattenedChanged"!==e)return!1;return!0}(t.updateActions);this.annotationViewerContext.updateAnnotations(i,t.updatedBy,n,t.updateDetails),this.hooks.annotationsUpdated.emit(new am(i,t.updateActions)),null===(e=this.context)||void 0===e||e.render(63)},this),e.bringFroward.on(t=>{var e;this.annotationViewerContext.updateLayer([t.annotationUid,t.forwardUid]),this.annotationIsVisible(t.annotationUid)&&(null===(e=this.context)||void 0===e||e.render(64))},this),e.bringToFront.on(t=>{var e;this.annotationViewerContext.updateLayer([t.annotationUid]),this.annotationIsVisible(t.annotationUid)&&(null===(e=this.context)||void 0===e||e.render(64))},this),e.sendBackward.on(t=>{var e;this.annotationViewerContext.updateLayer([t.annotationUid,t.backwardUid]),this.annotationIsVisible(t.annotationUid)&&(null===(e=this.context)||void 0===e||e.render(66))},this),e.sendToBack.on(t=>{var e;this.annotationViewerContext.updateLayer([t.annotationUid]),this.annotationIsVisible(t.annotationUid)&&(null===(e=this.context)||void 0===e||e.render(67))},this),e.restoreLayer.on(t=>{var e;this.annotationViewerContext.updateLayer([t.annotationUid]),this.annotationIsVisible(t.annotationUid)&&(null===(e=this.context)||void 0===e||e.render(68))},this),e.annotationPageSwitched.on(t=>{var e;this.annotationViewerContext.updateAnnotationPage(t.annotationUid,t.to.pageUid),this.annotationIsVisible(t.annotationUid)&&(null===(e=this.context)||void 0===e||e.render(69))},this)}listenNativeEventsForAnnotation(){(this.context.isDefaultViewer||this.context.isThumbnailViewer)&&zo(document,"click",this).on(t=>{const e=this.getActiveTab(),i="visible"===this.context.viewerConfig.visibility;e&&i&&(this.context.viewService.mainContainer.contains(null==t?void 0:t.target)||this.annotationViewerContext.disableTextEditMode())})}getAnnotationConfig(){return _s(this.annotationViewerContext.annotationController.interactiveConfig)}updateAnnotationConfig(t){this.annotationViewerContext.annotationConfigService.updateConfig(t)}selectAnnotations(t){return this.annotationViewerContext.selectAnnotations(t)}deleteAnnotations(t){this.context.core.annotationService.deleteAnnotations(t),this.context.render(70)}updateAnnotation(t,e,i){const n=this.getAnnotationObject(t);n instanceof hc&&n.isEditMode&&n.textEditEventHandler.emitTextContentUpdated(),this.context.core.annotationService.updateAnnotations([{annotationUid:t,options:e}],void 0,i)}getSelectedAnnotations(){return this.annotationViewerContext.getSelectedAnnotations()}bringForward(t){return this.context.core.annotationService.bringForward(t)}bringToFront(t){return this.context.core.annotationService.bringToFront(t)}sendBackward(t){return this.context.core.annotationService.sendBackward(t)}sendToBack(t){return this.context.core.annotationService.sendToBack(t)}getAnnotationObject(t){return this.annotationViewerContext.annotationController.getShape(t)}copyAnnotations(t){t||(t=this.getSelectedAnnotations().map(t=>t.uid)),t.length&&this.context.core.annotationService.copyAnnotations(t)}cutAnnotations(t){t||(t=this.getSelectedAnnotations().map(t=>t.uid)),t.length&&this.context.core.annotationService.cutAnnotations(t)}pasteAnnotations(t,e){const i=this.context.getActiveTab();if(null==i||!i.total)return;const n=i.getCurrentPage();if(!n)return;const s=this.context.viewerConfig.copyAnnotationOffset;this.context.core.annotationService.pasteAnnotations(t||i.uid,e||n.uid,s)}clearAnnotationClipboard(){this.context.core.annotationService.clearAnnotationClipboard()}undo(){const{activatedShape:t}=this.annotationViewerContext.annotationController.eventService;if(!this.context.getActiveTab())return!1;const e=t instanceof hc&&t.isEditMode;e&&t.textEditEventHandler.emitTextContentUpdated();const i=super.undo();return e&&t.textEditEventHandler.resetStartTextContent(),i}redo(){const{activatedShape:t}=this.annotationViewerContext.annotationController.eventService;if(!this.context.getActiveTab())return!1;const e=t instanceof hc&&t.isEditMode;e&&t.textEditEventHandler.emitTextContentUpdated();const i=super.redo();return e&&t.textEditEventHandler.resetStartTextContent(),i}annotationIsVisible(t){const e=this.context.core.annotationService.annotationApp.getAnnotationByUid(t),i=this.context.core.pageService.getPage(e.pageUid);if(i){const t=this.context.tabService.getTab(i.doc.uid);if(null!=t&&t.isActive&&t.getPageByUid(e.pageUid).isVisible)return!0}return!1}});var n;t.setClass("Viewer",i)},apply(t){const e=new Ix(t);t.annotationService=e;const{pageService:i}=t;e.hooks.annotationCreated.on(t=>{t.annotations.forEach(t=>{const e=i.getPage(t.pageUid);e&&e.annotations.push(t.uid)})},i),e.hooks.annotationDeleted.on(t=>{t.annotations.forEach(t=>{const e=i.getPage(t.pageUid);if(e){const i=e.annotations.indexOf(t.uid);e.annotations.splice(i,1)}})},i),e.hooks.annotationPageSwitched.on(t=>{const e=i.getPage(t.from.pageUid),n=i.getPage(t.to.pageUid);if(e){const i=e.annotations.indexOf(t.annotationUid);e.annotations.splice(i,1)}n&&n.annotations.push(t.annotationUid)},i)}},ew={canvasStyle:{cursor:"default"},currentPageStyle:{border:""},pageStyle:{border:"2px solid #707070",background:"#e2e2e2"},selectedPageStyle:{background:"#6f76ff",border:"2px solid #e98b1f"},hoveredPageStyle:{background:"#a5a9fb",border:"2px solid #e98b1f"},placeholderStyle:{background:"#b5b5b5",border:"0px solid #f00"},pageNumberStyle:{width:24,height:24,left:"50%",top:"",right:"",bottom:"0px",translateX:"-50%",translateY:0,border:"0px solid #000",borderRadius:0,background:"#fff",opacity:1,visibility:"visible",onPage:!1,color:"#000",fontSize:12,fontFamily:"sans-serif",textAlign:"center",textBaseline:"middle"},checkboxStyle:{width:24,height:24,left:0,top:0,right:"",bottom:"",translateX:0,translateY:0,border:"1px solid #000",borderRadius:0,background:"#fff",opacity:1,visibility:"visible",visibleByHover:!0,checkMarkColor:"#000",checkMarkLineWidth:2},removeBtnStyle:{visibility:"visible",width:24,height:24,background:"#fff",border:"1px solid #515151",borderRadius:"50%",opacity:1,left:"",top:-8,right:-8,bottom:"",checkMarkColor:"#ea2e2e"},quadSelectionStyle:{border:"1px dashed #fe8e14",ctrlBorderRadius:0,ctrlBorder:"1px dashed #fe8e14",ctrlWidth:10,ctrlHeight:10,invalidCtrlBorderColor:"#fe8e14",invalidBorderColor:"#fe8e14"},textSelectionStyle:{background:"rgba(51,103,209,0.5)",ctrlBackground:"rgba(51,103,209,0.8)",ctrlBorderRadius:8,ctrlBorderWidth:1,ctrlBorderColor:"rgba(51,103,209,0.8)"},textSearchStyle:{background:"rgba(248, 245, 33, 0.8)",currentBackground:"rgba(255, 174, 0, 0.8)"},croppingMagnifierStyle:{type:"circle",size:100,borderColor:"#323232",borderWidth:3,crosshairWidth:1,crosshairColor:"#323232",magnification:3},textMagnifierStyle:{type:"circle",size:100,borderColor:"#323232",borderWidth:3,magnification:3},magnifierStyle:{type:"circle",size:100,borderColor:"#323232",borderWidth:3,crosshairWidth:1,crosshairColor:"#323232",magnification:3},cursorStyle:{default:"default",annotationSelect:"crosshair",annotationDraw:"crosshair",annotationMove:"move",annotationNSResize:"ns-resize",annotationEWResize:"ew-resize",annotationNWResize:"nw-resize",annotationNEResize:"ne-resize",annotationSWResize:"sw-resize",annotationSEResize:"se-resize",annotationRotate:"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAsUlEQVR4nOXSwXHCMBQG4VVHdBC5g5TgVJASonTgVJCUkBJEBVACJUAHrHh4gAFmEFd25rNP/qWDE6cWysCkh5sH3vWrHxU6agOfmtSqhPO2Wmqtq5JG4vTWUpXLFsrASh/acFZSayRGvlW4XSFuO2itQ0lzmTht0r0K8KZBh5J62ypzvMUzAxX416SnBgpRwV5s4EutTFSBXc/ASPxsczvlnoHWyGlkUE0+evvDD4k3ex4wI7FMVvTgAAAAAElFTkSuQmCC) -15 15, auto",annotationErase:"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAATtJREFUOE+Vk8ErRFEUxs93/gXZUUrNhiRFWUkWVpaWSomlpaVkaUlZ2CiWllZKjbJQVqQokaYspPwL5+e9aeb15s17z7i7273nd77v3O/KBliSrs1sycxugMV8if6ql3RpZiPAvaR5M/vJQ2oBki7MbBR47DYqQioB7n4OjAHPRZV5SCnA3U+AceCtyqKkZTP76AO4+yHQAFoDzGerB+DuB8DUgMXpQL8zgLvvA3P/KG4BK13AnqQFMxsC7uqkS5o1s3dgNb0ndz9ON8BwAmnWQSRNS3qNiLXcswogs1IFSTIxIeklIjZ7kij1AtqyCkokNSQ9RcR2Xybc/QyYASYL5LYdM/uS9BARO2WzaUvvdLS+jyI1Jd1GxG5loHLDSDtmEEmfSWSvImKj9lXyh+5+Cqx3VB2VeS7CfgHdAKKUgZXPMQAAAABJRU5ErkJggg==) 10 10,auto",annotationActivable:"pointer",pan:"grab",panning:"grabbing",text:"text",textHover:"default",cropDraw:"crosshair",cropMove:"move",cropNSResize:"ns-resize",cropEWResize:"ew-resize",cropNWResize:"nw-resize",cropNEResize:"ne-resize",cropSWResize:"sw-resize",cropSEResize:"se-resize",zoomIn:"zoom-in",zoomOut:"zoom-out"},enableDragPage:!0,dragThreshold:3,dragStartTimeThreshold:500,enablePanX:!0,enablePanY:!0,panThreshold:3,enableZoom:!0,enableZoomWithCtrl:!0,enableZoomWithTouch:!0,zoom:1,minZoom:.02,maxZoom:8,wheelZoomFactor:1.2,tapZoomFactor:1.2,zoomOrigin:{x:"center",y:"center"},enableZoomInCropMode:!0,enableZoomInPanMode:!0,enableZoomInAnnotationMode:!0,enableZoomInTextSelectionMode:!0,enableSlide:!0,startSlideThreshold:20,slideThreshold:.2,startSlideThresholdForPerspective:30,slideThresholdForPerspective:.2,multiselectMode:!1,enableSelectWithShift:!0,enableSelectWithCtrl:!0,enableTextSelection:!0,enableTextMagnifier:!0,enableEditCropBoxVertices:!0,enableEditCropBoxMidpoints:!0,enableHideEditingCropBoxVertex:!0,enableHideEditingCropBoxMidpoint:!0,enableMagnifier:!0,scrollDirection:"vertical",displayMode:"single",fitMode:"window",margin:10,rows:4,columns:1,maxRows:20,maxColumns:20,renderingMode:"image",hasThb:!1,visibility:"visible",viewerMode:jg.DEFAULT,toolMode:"pan",annotationMode:"select",enableMultiTab:!1,scrollToLatest:!1,autoScroll:!0,autoChangeIndex:!0,enableLoadSourceByDrag:!0,enterTextModeTime:150,enterTextModeTimeMobile:500,multipleClickTimeout:500,textSearchDelay:500,enableCursorService:!0,maxUndoRedoTimes:1e3,autoScrollBoundarySize:20,autoScrollStepSize:10,enableAutoScrollForTextSelection:!0,enableAutoScrollForDragPages:!0,enableFillColor:!0,blankFillColor:"#fff",maxOptimizationSize:7e3,enableOptimizePage:!1,enableAnnotationInteraction:!0,enableSelectAnnotation:!0,enableRotateAnnotation:!0,enableMoveAnnotation:!0,enableResizeAnnotation:!0,copyAnnotationOffset:10,enableKeyboardInteraction:!0,enableZoomInWithKeyboard:!0,enableZoomOutWithKeyboard:!0,enableUndoWithKeyboard:!0,enableRedoWithKeyboard:!0,enableDeleteWithKeyboard:!0,enableSelectAllWithKeyboard:!0,enableMoveAnnotationWithKeyboard:!0,enableSaveWithKeyboard:!0,enableLoadSourceWithKeyboard:!0,enablePrintWithKeyboard:!0,enableSelectPageWithKeyboard:!0,enableCopyCutPasteWithKeyboard:!0,enableMultipleSelectAnnotationWithKeyboard:!0,moveAnnotationStepSize:2,moveAnnotationAcceleration:1};class iw extends Cl{constructor(){super({name:"Checkbox"}),Yi(this,"shapeType","checkbox"),Yi(this,"checkboxStyle",void 0),Yi(this,"parsedCheckboxStyle",void 0),Yi(this,"isChecked",!1)}get checked(){return this.isChecked}set checked(t){this.isChecked=t}updateStyle(t){Object.assign(this.style,t)}}class nw extends Cl{constructor(){super({name:"PageNumber"}),Yi(this,"shapeType","pageNumber"),Yi(this,"text",void 0),Yi(this,"parsedPageNumberStyle",void 0),this.text="0"}updateText(t){this.text=t}updateStyle(t){Object.assign(this.style,t)}}class sw extends Cl{constructor(){super({name:"TextSelection"}),Yi(this,"shapeType","textSelection"),Yi(this,"lines",void 0),Yi(this,"parsedTextSelectionStyle",void 0),Yi(this,"startCharRect",void 0),Yi(this,"endCharRect",void 0)}updateLines(t){this.lines=t}updateStyle(t){Object.assign(this.style,t)}isPointOnTextSelection(t){var e;return!(null===(e=this.lines)||void 0===e||!e.some(e=>e.left<=t.x&&e.left+e.width>=t.x&&e.top<=t.y&&e.top+e.height>=t.y))}hasSelectedText(){var t;return!(null===(t=this.lines)||void 0===t||!t.length)}}class ow extends Cl{constructor(){super({name:"SearchedText"}),Yi(this,"shapeType","textSearch"),Yi(this,"lines",void 0),Yi(this,"selectedTextUid",void 0)}update(t){this.lines=t}updateStyle(t){Object.assign(this.style,t)}setCurrent(t){this.selectedTextUid=t}clear(){this.selectedTextUid=null,this.lines=null,this.style.lines=null}}class rw extends Ll{constructor(t){super({...t,name:"TabPage"}),Yi(this,"uid",void 0),Yi(this,"tab",void 0),Yi(this,"isSelected",!1),Yi(this,"isHovered",!1),Yi(this,"isDragging",!1),Yi(this,"hasCache",void 0),Yi(this,"isLoading",!1),Yi(this,"isPreload",!1),Yi(this,"isLoaded",!1),Yi(this,"rWidth",void 0),Yi(this,"rHeight",void 0),Yi(this,"rotation",0),Yi(this,"cropLeft",void 0),Yi(this,"cropTop",void 0),Yi(this,"cropWidth",void 0),Yi(this,"cropHeight",void 0),Yi(this,"mediaBoxRect",void 0),Yi(this,"cropBoxRect",void 0),Yi(this,"isOptimized",!1),Yi(this,"optimizedUid","1"),Yi(this,"optimizationUid","2"),Yi(this,"editUid",void 0),Yi(this,"editedUid",void 0),Yi(this,"zoom",1),Yi(this,"image",void 0),Yi(this,"borderBox",void 0),Yi(this,"checkbox",void 0),Yi(this,"pageNumber",void 0),Yi(this,"curBox",void 0),Yi(this,"mediaBox",void 0),Yi(this,"cropBox",void 0),Yi(this,"realTimeBox",void 0),Yi(this,"textSelection",void 0),Yi(this,"textSearch",void 0),Yi(this,"visibleSortIndex",void 0),Yi(this,"needLayout",void 0),Yi(this,"pageIndex",void 0),Yi(this,"visiblePart",void 0),Yi(this,"visiblePartData",void 0),this.tab=t.tab,this.uid=t.uid,this.rWidth=t.style.width,this.rHeight=t.style.height,this.initSubShapes(t)}initSubShapes(t){this.updateStyle({visibility:"hidden"});const e=new _l({name:"pageImage",id:this.uid,style:{x:0,y:0,zIndex:-99999}}),i=new Ll({name:"pageOptimizedBox",style:{x:0,y:0}}),n=new Ll({name:"pageCropBox"});n.clippable=!0;const s=new Ll({name:"pageMediaBox"}),o=new Ll({name:"pageBorderBox",style:{...t.style,...t.formattedPageStyle}}),r=new Ll({name:"currentStyleBox",style:{visibility:"hidden"}}),a=new iw,l=new nw,h=new sw,{textSelectionStyle:c,textSearchStyle:d}=this.tab.viewerContext.viewerConfig;h.updateStyle({x:0,y:0,visibility:"visible",zIndex:9999,...c});const u=new ow;u.updateStyle({x:0,y:0,visibility:"visible",zIndex:9999,...d}),s.appendChild(e),s.appendChild(h),s.appendChild(u),n.appendChild(s),o.appendChild(i),o.appendChild(n),o.appendChild(r),o.appendChild(a),this.appendChild(l),this.appendChild(o),this.image=e,this.borderBox=o,this.realTimeBox=i,this.pageNumber=l,this.checkbox=a,this.curBox=r,this.cropBox=n,this.mediaBox=s,this.textSelection=h,this.textSearch=u}getRotation(){let t=this.rotation%360;return t<0&&(t+=360),90*Math.round(t/90)}getRect(){const t=this.realTimeBox.getPosition();return{left:t.x,top:t.y,width:this.rWidth,height:this.rHeight}}setImgDom(t){this.image.style.img=t}getImgDom(){return this.image.style.img}clearOptimization(){this.visiblePartData=null,this.visiblePart=null,this.isOptimized=!1,this.realTimeBox.imageData=null,this.image.updateStyle({visibility:"visible"}),this.optimizationUid=Us()}destroy(){this.image.style.img=null,this.image=null,this.realTimeBox=null}setPage(t,e,i,n){this.updateStyle({x:t,y:e,width:i,height:n})}setBorderBox(t,e,i,n,s){Ps(s)?this.borderBox.updateStyle({x:t,y:e,width:i,height:n}):this.borderBox.updateStyle({x:t,y:e,width:i,height:n,borderWidth:s})}setCropBox(t,e,i,n,s){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;this.cropBox.setLocalScale(1),this.cropBox.updateStyle({x:t,y:e,width:i,height:n}),this.cropBox.setLocalScale(s),this.cropBox.setLocalAngle(o),180===this.cropBox.getAngle()&&this.cropBox.setLocalAngle(179.9)}setRealTimeBox(t,e,i,n,s){this.realTimeBox.setLocalScale(1),this.realTimeBox.updateStyle({x:t,y:e,width:i,height:n}),this.realTimeBox.setLocalScale(s,s)}setMediaBox(t,e,i,n){this.mediaBox.updateStyle({x:t,y:e,width:i,height:n})}setCurBox(t,e,i,n){this.curBox.updateStyle({x:t,y:e,width:i,height:n})}setImage(t,e,i,n){this.image.updateStyle({x:t,y:e,width:i,height:n})}setTextSelection(t){this.textSelection&&this.textSelection.updateLines(t)}setTextSelectionStyle(t){this.textSelection&&this.textSelection.updateStyle(t)}setStartCharRect(t){this.textSelection&&(this.textSelection.startCharRect=t)}setEndCharRect(t){this.textSelection&&(this.textSelection.endCharRect=t)}isPointOnTextSelection(t){var e;return!(null===(e=this.textSelection.lines)||void 0===e||!e.some(e=>e.left<=t.x&&e.left+e.width>=t.x&&e.top<=t.y&&e.top+e.height>=t.y))}isPointOnTextStart(t){var e,i;if(null===(e=this.textSelection)||void 0===e||null===(e=e.lines)||void 0===e||!e.length)return!1;const n=null===(i=this.textSelection)||void 0===i?void 0:i.startCharRect;if(!n)return!1;if(qm(t,this.textSelection.startCharRect))return!0;const s=this.textSelection.getScale().x,o=this.textSelection.style.ctrlBorderRadius/s;return qs({x:n.left+n.width/2,y:n.top-o},t)<=o}isPointOnTextEnd(t){var e,i;if(null===(e=this.textSelection)||void 0===e||null===(e=e.lines)||void 0===e||!e.length)return!1;const n=null===(i=this.textSelection)||void 0===i?void 0:i.endCharRect;if(!n)return!1;if(qm(t,this.textSelection.endCharRect))return!0;const s=this.textSelection.getScale().x,o=this.textSelection.style.ctrlBorderRadius/s;return qs({x:n.left+n.width/2,y:n.top+n.height+o},t)<=o}setSearchedText(t){const e=t.texts.map(t=>({textUid:t.textUid,boxes:t.lines.map(t=>t.box)}));this.textSearch.update(e)}selectSearchedText(t){this.textSearch.setCurrent(t)}clearSearchedText(){this.textSearch.clear()}getTextSelectionBoundingForCanvas(){var t;if(null===(t=this.textSelection)||void 0===t||null===(t=t.lines)||void 0===t||!t.length)return null;const{lines:e}=this.textSelection;let i=e[0].left,n=e[0].top,s=e[0].left+e[0].width,o=e[0].top+e[0].height;e.forEach(t=>{const e=t.left+t.width,r=t.top+t.height;i=Math.min(i,t.left),n=Math.min(n,t.top),s=Math.max(s,e),o=Math.max(o,r)});const{x:r,y:a}=this.textSelection.getScale(),{x:l,y:h}=this.textSelection.getPosition();return{left:i*r+l,top:n*a+h,width:(s-i)*r,height:(o-n)*a}}getTextSelectionControlPointsRect(){const{startCharRect:t,endCharRect:e}=this.textSelection,i=[],{ctrlBorderRadius:n}=this.textSelection.style,{x:s,y:o}=this.textSelection.getScale(),{x:r,y:a}=this.textSelection.getPosition(),{width:l,height:h}=this,c=this.getRotation(),d=90===c||180===c?r-l:r,u=180===c||270===c?a-h:a;if(t){const{left:e,top:r,width:a}=t;let p=e+a/2,g=r,f=p*s+d-n,m=g*o+u-2*n;90===c?(p=l/s-r,g=e+a/2,f=p*s+d,m=g*o+u-n):180===c?(p=l/s-e-a/2,g=h/o-r,f=p*s+d-n,m=g*o+u):270===c&&(p=r,g=h/o-e-a/2,f=p*s+d-2*n,m=g*o+u-n);const v={left:f,top:m,width:2*n,height:2*n};i.push(v)}if(e){const{left:t,top:r,width:a,height:p}=e;let g=t+a/2,f=r+p,m=g*s+d-n,v=f*o+u;90===c?(g=l/s-r-p,f=t+a/2,m=g*s+d-2*n,v=f*o+u-n):180===c?(g=l/s-t-a/2,f=h/o-r-p,m=g*s+d-n,v=f*o+u-2*n):270===c&&(g=r+p,f=h/o-t-a/2,m=g*s+d,v=f*o+u-n/2);const y={left:m,top:v,width:2*n,height:2*n};i.push(y)}return i}}function aw(t){const{borderWidth:e,borderColor:i,borderStyle:n}=lo(t),s=parseInt(e||"0px",10);let o=[0,0];return"dashed"===n&&(o=[2*s,s]),{borderWidth:s,borderStyle:o,borderColor:i||"",lineDash:o}}const lw=t=>{const{border:e}=t;if(!e)return 0;const i=e.match(/[0-9]+/g)[0];return parseInt(i||"0",10)};function hw(t,e){if(Ps(t)||""===t)return null;const i=ua(t);return"%"===i.unit?e*i.value/100:i.value}function cw(t,e,i){t.style.width=`${e}px`,t.style.height=`${i}px`}function dw(t){const e=devicePixelRatio;return Ls(t)&&t>0?(t=Math.floor(t*e)/e)||(t=1/e):t=0,t}function uw(t){const e=devicePixelRatio;return Ls(t)&&t>0?(t=Math.round(t*e)/e)||(t=1/e):t=0,t}function pw(t){return uw(t)}const gw=()=>{const t=document.createElement("div");t.style.width="100px",t.style.height="100px",t.style.overflow="scroll",t.style.position="absolute",t.style.top="-9999px",document.body.appendChild(t);const e=t.offsetWidth-t.clientWidth;return document.body.removeChild(t),e};function fw(t,e,i,n){const s={isOver:!1,pointerX:-1,pointerY:-1,page:t};if(t){const{x:o,y:r}=t.getPosition(),{width:a,height:l}=t,h=(n%360+360)%360/90,c=t.getScale();let d=-1,u=-1;0===h?(d=(e-o)/c.x,u=(i-r)/c.y,s.isOver=e>=o&&i>=r&&e<=o+a&&i<=r+l):1===h?(d=(i-r)/c.x,u=(o-e)/c.y,s.isOver=e>=o-l&&i>=r&&e<=o&&i<=r+a):2===h?(d=(o-e)/c.x,u=(r-i)/c.y,s.isOver=e>=o-a&&i>=r-l&&e<=o&&i<=r):3===h&&(d=(r-i)/c.y,u=(e-o)/c.x,s.isOver=e>=o&&i>=r-l&&e<=o+a&&i<=r),s.pointerX=d,s.pointerY=u}return s}class mw{constructor(t,e){Yi(this,"tab",void 0),Yi(this,"viewerContext",void 0),Yi(this,"viewportWidth",600),Yi(this,"viewportHeight",800),Yi(this,"currentViewportWidth",0),Yi(this,"currentViewportHeight",0),Yi(this,"currentLayoutWidth",0),Yi(this,"currentLayoutHeight",0),Yi(this,"placeholderPages",[]),Yi(this,"scrollLeft",0),Yi(this,"scrollTop",0),Yi(this,"maxScrollLeft",0),Yi(this,"maxScrollTop",0),Yi(this,"startRow",0),Yi(this,"endRow",0),Yi(this,"startColumn",0),Yi(this,"endColumn",0),Yi(this,"preloadCount",1),Yi(this,"pagePreloadChanges",[]),Yi(this,"direction","vertical"),Yi(this,"displayMode",void 0),Yi(this,"fitMode",void 0),Yi(this,"rows",void 0),Yi(this,"columns",void 0),Yi(this,"zoom",void 0),Yi(this,"defaultReference",void 0),Yi(this,"zoomReference",void 0),Yi(this,"resizeReference",void 0),Yi(this,"oldZoom",void 0),Yi(this,"isZoomChanged",void 0),Yi(this,"isOutOfBounds",void 0),Yi(this,"isScrollbarResized",!0),Yi(this,"scrollbarWidthCache",void 0),Yi(this,"defaultWidth",void 0),Yi(this,"defaultHeight",void 0),this.tab=t,this.viewerContext=e;const{viewerConfig:i}=e;this.rows=i.rows,this.columns=i.columns,this.zoom=i.zoom,this.oldZoom=i.zoom,this.displayMode=i.displayMode,this.fitMode=i.fitMode,this.direction=i.scrollDirection,this.isZoomChanged=!1,this.isOutOfBounds=!1}get isVertical(){return"vertical"===this.direction}get isContinuousDisplay(){return"continuous"===this.displayMode}get isSingleDisplay(){return"single"===this.displayMode}get scrollbarWidth(){if(!this.isScrollbarResized&&this.scrollbarWidthCache)return this.scrollbarWidthCache;const t=gw();return this.scrollbarWidthCache=t,this.isScrollbarResized=!1,t}getRealRowAndColumnContinuous(){const{rows:t,columns:e,isVertical:i}=this,{total:n}=this.tab;let s=t,o=e;return i?(s=Math.ceil(n/e),n<=e&&(o=Math.max(1,n),s=1)):(o=Math.ceil(n/t),n<=t&&(s=Math.max(1,n),o=1)),{realRow:s,realColumn:o}}getRealRowAndColumnThumbnail(){const{total:t}=this.tab,{rows:e,columns:i,isVertical:n}=this,s=n?i:Math.ceil(t/e);return{realRow:n?Math.ceil(t/i):e,realColumn:s}}getZoomOriginCord(){const{zoomOrigin:t}=this.viewerContext.viewerConfig,e={start:0,center:.5,end:1};return{originX:this.currentViewportWidth*e[t.x],originY:this.currentViewportHeight*e[t.y]}}getMargin(){return this.formatMarginAndGap(this.viewerContext.viewerConfig.margin)}getPageBorderWidth(){const{styleService:t}=this.viewerContext,{borderWidth:e}=t.getParsedPageStyle();return{borderWidth:e,selectedBorderWidth:t.getParsedSelectedPageStyle().borderWidth,hoveredBorderWidth:t.getParsedHoveredPageStyle().borderWidth}}getPages(){return this.tab.allPages}getParsedPageNumberStyle(t,e){return this.viewerContext.styleService.getParsedPageNumberStyle({width:t,height:e})}getPageNumberStyle(){return this.viewerContext.viewerConfig.pageNumberStyle}getParsedCheckboxStyle(t,e){return this.viewerContext.styleService.getParsedCheckboxStyle({width:t,height:e})}getParsedPageStyle(){return this.viewerContext.styleService.getParsedPageStyle()}getParsedCurrentPageStyle(){return this.viewerContext.styleService.getParsedCurrentPageStyle()}getParsedSelectedPageStyle(){return this.viewerContext.styleService.getParsedSelectedPageStyle()}getParsedHoveredPageStyle(){return this.viewerContext.styleService.getParsedHoveredPageStyle()}getParsedPlaceholderStyle(){return this.viewerContext.styleService.getParsedPlaceholderStyle()}getParsedCanvasStyle(){return this.viewerContext.styleService.getParsedCanvasStyle()}formatMarginAndGap(t){if(Os(t)){if(/px/.test(t)){const[e]=t.match(/(\d+)/);return parseInt(e,10)}const e=this.viewerContext.rendererService.getCanvasDom();if(/%/.test(t)){const i=e.width/ao(),[n]=t.match(/(\d+)/);return i*parseInt(n,10)/100}if(/em/.test(t)){const i=getComputedStyle(e).fontSize,[n]=i.match(/(\d+)/),[s]=t.match(/(\d+)/);return parseInt(n,10)*parseInt(s,10)}}return Ls(t)?t:parseInt(t,10)}setZoom(t){this.oldZoom=this.zoom,this.zoom=t,this.tab.allPages.forEach(e=>{e.zoom=t})}getTabOffset(){const{maxScrollLeft:t,maxScrollTop:e,currentLayoutWidth:i,currentLayoutHeight:n,currentViewportWidth:s,currentViewportHeight:o,scrollLeft:r,scrollTop:a}=this;let l=0,h=0;const c=this.getParsedCanvasStyle().borderWidth||0;return l=t>0?-r:(s-(i-2*c))/2,h=e>0?-a:(o-(n-2*c))/2,{offsetX:l,offsetY:h}}parseReferenceDefault(){const{tab:t,maxScrollLeft:e,maxScrollTop:i}=this,n=t.current,s=this.placeholderPages[n];if(!s)return{scrollLeft:0,scrollTop:0};const o=this.getMargin();let r=s.x-o,a=s.y-o;return this.isContinuousDisplay&&(r=s.pageX-o,a=s.pageY-o),r=Bs(r,0,e),a=Bs(a,0,i),{scrollLeft:r,scrollTop:a}}parseReferenceZoom(t,e,i){if(Ps(t)&&(t=this.zoomReference),Ps(e)||Ps(i)){const{originX:t,originY:n}=this.getZoomOriginCord();e=t,i=n}let{scrollLeft:n,scrollTop:s}=this.parseReference(t,e,i);const{maxScrollLeft:o,maxScrollTop:r}=this;return n=Bs(n,0,o),s=Bs(s,0,r),{scrollLeft:n,scrollTop:s}}parseReferenceResize(){const{resizeReference:t}=this;let{scrollLeft:e,scrollTop:i}=this.parseReference(t,0,0);const{maxScrollLeft:n,maxScrollTop:s}=this;return e=Bs(e,0,n),i=Bs(i,0,s),{scrollLeft:e,scrollTop:i}}updateReference(){const{currentViewportWidth:t,currentViewportHeight:e}=this,i=this.generateReference(0,0),n=this.generateReference(t/2,e/2),{originX:s,originY:o}=this.getZoomOriginCord(),r=this.generateReference(s,o);this.defaultReference=n,this.resizeReference=i,this.zoomReference=r}generateReference(t,e){let i,n,s,o,r=null,a=Number.MAX_VALUE;const{offsetX:l,offsetY:h}=this.getTabOffset(),{zoom:c}=this;return this.placeholderPages.forEach(d=>{if(d&&("single"===this.displayMode&&d.uid===this.tab.currentUid||"continuous"===this.displayMode)){const u=d.x+l,p=d.y+h,g=new $s(u+d.width/2,p+d.height/2).distanceTo({x:t,y:e});g<a&&(a=g,r=d.uid,t<u?(i="start",s=u-t):t>u+d.width?(i="end",s=t-(u+d.width)):(i="center",s=(t-u)/c),e<p?(n="start",o=p-e):e>p+d.height?(n="end",o=e-(p+d.height)):(n="center",o=(e-p)/c))}}),{pageX:s,pageY:o,positionX:i,positionY:n,pageUid:r}}parseReference(t,e,i){const{pageX:n,pageY:s,positionX:o,positionY:r,pageUid:a}=t,l=this.placeholderPages.find(t=>t.uid===a),{zoom:h}=this;let c,d,u=0,p=0;return l&&("start"===o?c=l.x-n:"center"===o?c=l.x+n*h:"end"===o&&(c=l.x+l.width+n),"start"===r?d=l.y-s:"center"===r?d=l.y+s*h:"end"===r&&(d=l.y+l.height+s)),u=c-e,p=d-i,{scrollLeft:u,scrollTop:p}}getScrollValuesByCurrentChanged(){const{placeholderPages:t,currentViewportWidth:e,currentViewportHeight:i,startRow:n,endRow:s,startColumn:o,endColumn:r,isVertical:a}=this,{current:l}=this.tab,h=this.getMargin(),{realRow:c,realColumn:d}=this.getRealRowAndColumnThumbnail();let u=l,p=l;a?(u=n*d+o,p=s*d+r):(u=o*c+n,p=r*c+s);let g=Bs(this.scrollLeft,0,this.maxScrollLeft),f=Bs(this.scrollTop,0,this.maxScrollTop);if(l>=u&&l<=p)return{scrollLeft:g,scrollTop:f};const m=t[l];return m&&(a?(g=0,l<u?f=m.y-h:l>p&&(f=m.y+m.height+h-i)):(f=0,l<u?g=m.x-h:l>p&&(g=m.x+m.width+h-e))),g=Bs(g,0,this.maxScrollLeft),f=Bs(f,0,this.maxScrollTop),{scrollLeft:g,scrollTop:f}}getCurrentByScroll(){let t=this.tab.current;const{placeholderPages:e,currentViewportWidth:i,currentViewportHeight:n,startRow:s,endRow:o,startColumn:r,endColumn:a,isVertical:l}=this,{realRow:h,realColumn:c}=this.getRealRowAndColumnContinuous(),d=i/2,u=n/2,{offsetX:p,offsetY:g}=this.getTabOffset(),{current:f}=this.tab;let m=Number.MAX_VALUE,v=Number.MAX_VALUE,y=l?Math.floor(f/c):f%h,x=l?f%c:Math.floor(f/h);for(let t=s;t<=o;t++){const i=e[t*c];if(!i)continue;const{y:n,height:s}=i,o=n+g,r=o-u,a=u-o-s;if(r<=0&&a<=0){y=t;break}r>0&&r<v?(v=r,y=t):a>0&&a<v&&(v=a,y=t)}for(let t=r;t<=a;t++){const i=e[r];if(!i)continue;const{x:n,width:s}=i,o=n+p,a=o-d,l=d-o-s;if(a<=0&&l<=0){x=t;break}a>0&&a<m?(m=a,x=t):l>0&&l<m&&(m=l,x=t)}return t=y*c+x,t===this.tab.current?null:t}setTabScrollValue(t,e){this.scrollLeft=t,this.scrollTop=e;const{offsetX:i,offsetY:n}=this.getTabOffset();this.tab.setPosition({x:i,y:n})}}class vw extends Cl{constructor(t,e){super({name:"DocTab"}),Yi(this,"uid",void 0),Yi(this,"docType",void 0),Yi(this,"docName",void 0),Yi(this,"doc",void 0),Yi(this,"isActive",!1),Yi(this,"currentUid",void 0),Yi(this,"total",void 0),Yi(this,"selected",void 0),Yi(this,"context",void 0),Yi(this,"viewerContext",void 0),Yi(this,"shiftReference",void 0),Yi(this,"oldCurrentUid",void 0),Yi(this,"oldCurrent",void 0),Yi(this,"oldTotal",void 0),Yi(this,"pageMap",new Map),Yi(this,"textPages",void 0),Yi(this,"startTextPosition",void 0),Yi(this,"endTextPosition",void 0),Yi(this,"startCharRect",void 0),Yi(this,"endCharRect",void 0),Yi(this,"selectedTextsCache",void 0),Yi(this,"visibleChildren",[]),Yi(this,"preloadChildren",[]),Yi(this,"isTab",!0),Yi(this,"allPages",[]),Yi(this,"hoveredPage",void 0),this.doc=t,this.uid=t.uid,this.docName=t.name,this.docType=t.type,this.total=0,this.selected=[],this.viewerContext=e,this.context=new mw(this,e),this.oldCurrent=-1,this.oldCurrentUid=void 0,t.pages.forEach((t,e)=>{const i=this.createPage(t);i.pageIndex=e,this.pageMap.set(t,i),this.allPages.push(i)}),this.total=t.pages.length,this.total>0&&(this.updateOldInfo(),this.currentUid=this.allPages[this.scrollToLatest?this.total-1:0].uid),this.oldTotal=0}get scrollToLatest(){let{scrollToLatest:t}=this.viewerContext.viewer.group.config;return Ps(t)&&(t=this.viewerContext.viewerConfig.scrollToLatest),t}get pages(){return this.childNodes}get current(){return this.currentUid?this.uidToIndex(this.currentUid):-1}get isDocType(){return"document"===this.docType}createPage(t){const{pageStyle:e,pageNumberStyle:i,checkboxStyle:n,removeBtnStyle:s,blankFillColor:o}=this.viewerContext.viewerConfig,r=function(t){const{border:e,background:i}=t;let n={};return e&&(n=aw(e)),{background:i,...n}}(e),{width:a,height:l}=this.viewerContext.getPageRenderSize(t);return new rw({tab:this,uid:t,formattedPageStyle:r,pageNumberStyle:i,checkboxStyle:n,removeBtnStyle:s,blankFillColor:o,style:{pointerEvents:"auto",width:a,height:l}})}updateOldInfo(){this.oldCurrentUid=this.currentUid,this.oldCurrent=this.current,this.oldTotal=this.total}updateViewportSize(t,e){this.context.viewportWidth=t,this.context.viewportHeight=e}rename(t){this.docName=t}getCurrentPage(){return this.getPageByUid(this.currentUid)}getAllPageUids(){return this.allPages.map(t=>t.uid)}freshPageIndex(){this.allPages.forEach((t,e)=>{t.pageIndex=e})}appendPages(t,e,i){const n=t.length;if(!n)return;const s=Ls(i);if(t.forEach((t,e)=>{const n=this.createPage(t);this.pageMap.set(t,n),Ls(i)?this.allPages.splice(i+e,0,n):this.allPages.push(n)}),this.freshPageIndex(),this.total=this.allPages.length,e)this.currentUid=this.indexToUid(s?i+n-1:this.total-1),this.updateDefaultReference();else if(!this.currentUid){var o;this.currentUid=null===(o=this.allPages[0])||void 0===o?void 0:o.uid,this.updateDefaultReference()}}deletePages(t){this.updateOldInfo();const e=[...t],i=t.includes(this.currentUid);if(i){const i=t.indexOf(this.currentUid);e.splice(i,1),e.push(this.currentUid)}e.forEach(t=>{const e=this.getPageByUid(t);if(i&&e.uid===this.currentUid){if(1===this.total)this.currentUid=null;else{const{current:t}=this,e=t===this.total-1?-1:1;this.currentUid=this.indexToUid(t+e)}this.updateDefaultReference()}if(xo(this.selected,t),this.removeChild(e),xo(this.allPages,e),this.pageMap.delete(e.uid),this.total-=1,this.textPages){const t=this.textPages.findIndex(t=>t.pageUid===e.uid);t>-1&&this.textPages.splice(t,1)}}),this.freshPageIndex(),0===this.total&&(this.oldTotal=0,this.currentUid=null,this.selected=[],this.visibleChildren=[],this.preloadChildren=[],this.context.placeholderPages=[])}deleteAllPages(){this.updateOldInfo(),this.childNodes.slice().forEach(t=>{this.removeChild(t)}),this.allPages=[],this.pageMap.clear(),this.visibleChildren=[],this.preloadChildren=[],this.currentUid=null,this.selected=[],this.context.placeholderPages=[],this.total=0,this.oldTotal=0}movePages(t,e){this.updateOldInfo();const i=wo(this.allPages,t,e);return this.freshPageIndex(),i}switchPage(t,e){this.updateOldInfo();const i=Co(this.allPages,t,e);return i&&this.freshPageIndex(),i}reorderPages(t){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&this.updateOldInfo();const e=bo(this.allPages,t);return e&&this.freshPageIndex(),e}gotoPage(t){return 0===this.total?-1:(this.updateOldInfo(),t!==this.current&&(t=Bs(t,0,this.total-1),this.currentUid=this.indexToUid(t),this.updateDefaultReference()),this.updateShiftReference(),t)}selectPages(t){this.allPages.forEach(e=>{e.isSelected=t.includes(e.uid)}),this.selected=t}selectPagesByIndices(t){const e=this.indicesToUids(t);this.selectPages(e)}getSelected(){return this.selected.slice()}getSelectedIndices(){return this.selected.map(t=>this.uidToIndex(t))}getPageByIndex(t){return this.allPages[t]}getPageByUid(t){return this.pageMap.get(t)}getPageIndex(t){return this.pageMap.get(t.uid)?t.pageIndex:-1}uidToIndex(t){return this.pageMap.get(t)?this.pageMap.get(t).pageIndex:-1}uidsToIndices(t){return t.map(t=>this.uidToIndex(t))}indexToUid(t){var e;return null===(e=this.allPages[t])||void 0===e?void 0:e.uid}indicesToUids(t){return t.map(t=>this.indexToUid(t))}updateShiftReference(){this.shiftReference=this.currentUid}updateDefaultReference(){this.context.defaultReference={pageUid:this.currentUid}}setTextSelection(t,e,i,n,s){const o=new Map;if(this.textPages)for(let e=0;e<this.textPages.length;e++){const i=this.textPages[e],n=this.getPageByUid(i.pageUid);n&&(0!==e&&e!==this.textPages.length-1&&t.find(t=>t.pageUid===i.pageUid)&&i.pageUid!==t[t.length-1].pageUid&&i.pageUid!==t[0].pageUid?o.set(i.pageUid,i):n.setTextSelection(null))}this.selectedTextsCache=null,this.textPages=t,this.startTextPosition=n,this.endTextPosition=s,this.startCharRect=e,this.endCharRect=i,t.forEach((n,s)=>{const r=this.getPageByUid(n.pageUid);o.has(n.pageUid)||r.setTextSelection(n.lines.map(t=>t.selectedRect)),r.setStartCharRect(0===s?e:null),r.setEndCharRect(s===t.length-1?i:null)})}clearTextSelection(){var t;return!(null===(t=this.textPages)||void 0===t||!t.length||(this.textPages.forEach(t=>{const e=this.getPageByUid(t.pageUid);e&&(e.setTextSelection([]),e.setStartCharRect(null),e.setEndCharRect(null))}),this.textPages=null,this.startTextPosition=null,this.endTextPosition=null,this.selectedTextsCache=null,0))}hasSelectedTexts(){return!!this.textPages}getTextSelectionLines(){return this.textPages?this.textPages:null}getTextSelectionControlPointsRect(){if(!this.textPages)return[];const t=[];return this.textPages.forEach(e=>{const i=this.getPageByUid(e.pageUid),n=i.getTextSelectionControlPointsRect();i.isVisible&&n.length&&t.push(...n)}),t}destroy(){super.destroy(),this.deleteAllPages(),this.isActive=!1,this.doc=null,this.context=null,this.viewerContext=null,this.isDestroyed=!0}}class yw extends Wo{constructor(t){super(),Yi(this,"tabActivationStack",void 0),Yi(this,"tabs",void 0),Yi(this,"activeTabUid",void 0),Yi(this,"context",void 0),this.tabActivationStack=[],this.tabs=new Map,this.context=t}dispose(){this.clearTabs(),this.tabActivationStack.length=0,super.dispose()}updateViewportSize(t,e){const i=this.getActiveTab();null!=i&&i.isDocType&&i.updateViewportSize(t,e)}createTab(t){if(this.tabs.has(t.uid))return this.tabs.get(t.uid);let e=null;return"document"===t.type&&(e=new vw(t,this.context)),this.context.viewerConfig.enableMultiTab||this.clearTabs(),this.tabs.set(e.uid,e),e}closeTab(t){if(!this.tabs.has(t))return!1;const{tabActivationStack:e}=this;if(e.includes(t)){const i=e.indexOf(t);e.splice(i,1)}return this.getTab(t).isActive=!1,this.tabs.delete(t),this.activeTabUid===t&&(this.activeTabUid=e[e.length-1]),!0}getTab(t){return this.tabs.get(t)}getDocTab(t){const e=this.getTab(t);return null!=e&&e.isDocType?e:null}hasTab(t){return this.tabs.has(t)}getActiveTab(){return this.tabs.get(this.activeTabUid)}getActiveTabUid(){return this.activeTabUid}getAllTabs(){return Array.from(this.tabs.values())}activateTab(t){if(!this.tabs.has(t))return!1;const{tabActivationStack:e}=this;if(this.context.viewerConfig.enableMultiTab){if(e.includes(t)){const i=e.indexOf(t);e.splice(i,1)}}else e.length=0;return e.push(t),this.activeTabUid=t,this.tabs.forEach(e=>{e.isActive=e.uid===t}),!0}clearTabs(){this.getAllTabs().forEach(t=>{t.destroy()}),this.tabs.clear()}resizeScrollbar(){this.tabs.forEach(t=>{t.context.isScrollbarResized=!0})}}class xw{constructor(t){Yi(this,"parsedPageStyleCache",void 0),Yi(this,"parsedCurrentPageStyleCache",void 0),Yi(this,"parsedSelectedPageStyleCache",void 0),Yi(this,"parsedHoveredPageStyleCache",void 0),Yi(this,"parsedPlaceholderStyleCache",void 0),Yi(this,"parsedCheckboxStyleCache",void 0),Yi(this,"parsedPageNumberStyleCache",void 0),Yi(this,"parsedQuadSelectionStyleCache",void 0),Yi(this,"parsedCanvasStyleCache",void 0),Yi(this,"context",void 0),Yi(this,"isPageStyleChanged",void 0),Yi(this,"isCurrentPageStyleChanged",void 0),Yi(this,"isSelectedPageStyleChanged",void 0),Yi(this,"isHoveredPageStyleChanged",void 0),Yi(this,"isPlaceholderStyleChanged",void 0),Yi(this,"isCheckboxStyleChanged",void 0),Yi(this,"isPageNumberStyleChanged",void 0),Yi(this,"isQuadSelectionStyleChanged",void 0),Yi(this,"isCanvasStyleChanged",void 0),this.context=t}getParsedCanvasStyle(){return!this.isCanvasStyleChanged&&this.parsedCanvasStyleCache||(this.parsedCanvasStyleCache=ww(this.context.viewerConfig.canvasStyle),this.isCanvasStyleChanged=!1),this.parsedCanvasStyleCache}getParsedCheckboxStyle(t){return!this.isCheckboxStyleChanged&&this.parsedCheckboxStyleCache||(this.parsedCheckboxStyleCache=ww(this.context.viewerConfig.checkboxStyle,t),this.isCheckboxStyleChanged=!1),this.parsedCheckboxStyleCache}getParsedPageNumberStyle(t){return!this.isPageNumberStyleChanged&&this.parsedPageNumberStyleCache||(this.parsedPageNumberStyleCache=ww(this.context.viewerConfig.pageNumberStyle,t),this.isPageStyleChanged=!1),this.parsedPageNumberStyleCache}getParsedPageStyle(){return!this.isPageStyleChanged&&this.parsedPageStyleCache||(this.parsedPageStyleCache=ww(this.context.viewerConfig.pageStyle),this.isPageStyleChanged=!1),this.parsedPageStyleCache}getParsedCurrentPageStyle(){return!this.isCurrentPageStyleChanged&&this.parsedCurrentPageStyleCache||(this.parsedCurrentPageStyleCache=ww(this.context.viewerConfig.currentPageStyle),this.isCurrentPageStyleChanged=!1),this.parsedCurrentPageStyleCache}getParsedSelectedPageStyle(){return!this.isSelectedPageStyleChanged&&this.parsedSelectedPageStyleCache||(this.parsedSelectedPageStyleCache=ww(this.context.viewerConfig.selectedPageStyle),this.isSelectedPageStyleChanged=!1),this.parsedSelectedPageStyleCache}getParsedHoveredPageStyle(){return!this.isHoveredPageStyleChanged&&this.parsedHoveredPageStyleCache||(this.parsedHoveredPageStyleCache=ww(this.context.viewerConfig.hoveredPageStyle),this.isHoveredPageStyleChanged=!1),this.parsedHoveredPageStyleCache}getParsedPlaceholderStyle(){return!this.isPlaceholderStyleChanged&&this.parsedPlaceholderStyleCache||(this.parsedPlaceholderStyleCache=ww(this.context.viewerConfig.placeholderStyle),this.isPlaceholderStyleChanged=!1),this.parsedPlaceholderStyleCache}getParsedQuadSelectionStyle(){return!this.isQuadSelectionStyleChanged&&this.parsedQuadSelectionStyleCache||(this.parsedQuadSelectionStyleCache=ww(this.context.viewerConfig.quadSelectionStyle),this.isQuadSelectionStyleChanged=!1),this.parsedQuadSelectionStyleCache}isBorderWidthEqualHovered(){const{viewerConfig:t}=this.context;return lw(t.pageStyle)===lw(t.hoveredPageStyle)}isSelectedBorderWidthEqualHovered(){const{viewerConfig:t}=this.context;return lw(t.selectedPageStyle)===lw(t.hoveredPageStyle)}isSelectedBorderWidthEqualNormal(){const{viewerConfig:t}=this.context;return lw(t.pageStyle)===lw(t.selectedPageStyle)}}function ww(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{width:0,height:0};const i={};if(function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{border:i,ctrlBorder:n}=t;if(!Ps(i)){const t=aw(i);Object.assign(e,t)}if(!Ps(n)){const t=aw(n);Object.assign(e,{ctrlBorderWidth:t.borderWidth,ctrlBorderColor:t.borderColor,ctrlBorderStyle:t.borderStyle})}}(t,i),function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Cw.forEach(i=>{Ps(t[i])||(e[i]=da(t[i]).value||0)})}(t,i),function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};bw.forEach(i=>{Ps(t[i])||(e[i]=t[i])})}(t,i),function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!Ps(t.width)&&(i.width=hw(t.width,e.width),Ps(t.translateX)||(i.translateX=hw(t.translateX,i.width)),!Ps(t.borderRadius))){const e=hw(t.borderRadius,i.width);i.borderRadiusX=Math.max(0,Math.min(e,i.width/2))}if(!Ps(t.height)&&(i.height=hw(t.height,e.height),Ps(t.translateY)||(i.translateY=hw(t.translateY,i.height)),!Ps(t.borderRadius))){const e=hw(t.borderRadius,i.height);i.borderRadiusY=Math.max(0,Math.min(e,i.height/2))}if(!Ps(t.borderRadius)){const n=hw(t.borderRadius,e.width);i.borderRadius=Math.max(0,Math.min(n,e.height/2,e.width/2))}if(!Ps(t.ctrlBorderRadius)){const e=hw(t.ctrlBorderRadius,i.ctrlWidth);i.ctrlBorderRadius=Math.max(0,Math.min(e,i.ctrlWidth/2,i.ctrlHeight/2))}Sw.forEach(n=>{const s=["left","right"].includes(n)?e.width:e.height,o=ua(t[n]);let r=o.value;"%"===o.unit&&(r=s*o.value/100),i[n]=r})}(t,e,i),t.left||t.right||t.bottom||t.top){const{left:n,top:s,right:o,bottom:r,width:a,height:l,translateX:h,translateY:c}=i;""!==t.left?i.x=n+h||0:""!==t.right&&Ls(a)?i.x=e.width-a-o+h||0:i.x=0,""!==t.top?i.y=s+c||0:""!==t.bottom&&Ls(l)?i.y=e.height-l-r+c||0:i.y=0}return i}const Cw=["borderWidth","ctrlBorderWidth","checkMarkLineWidth","fontSize","ctrlWidth","ctrlHeight"],bw=["background","maskColor","color","borderColor","borderStyle","invalidBorderColor","ctrlBorderColor","ctrlBackground","ctrlBorderStyle","invalidCtrlBorderColor","checkMarkColor","onPage","opacity","visibility","visibleByHover","fontFamily","textAlign","textBaseline","lineJoin","lineCap"],Sw=["left","top","right","bottom"],Tw="visible",Ew="hidden";class _w{constructor(t){Yi(this,"context",void 0),this.context=t}handleVisibility(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.context.isDestroyed||t.isDestroyed||!t.total||!t.isActive)return;const{context:i}=this;if(i.isDefaultViewer?t.context.isContinuousDisplay?this.continuousVisibility(t,e):t.context.isSingleDisplay&&this.singleVisibility(t):i.isThumbnailViewer?this.thumbnailVisibility(t,e):i.isPerspectiveViewer&&t.context.isSingleDisplay&&this.singleVisibility(t),t.context.pagePreloadChanges.length){t.context.pagePreloadChanges.forEach(e=>{if(e.from&&!e.to){const i=t.getPageByUid(e.pageUid);i&&(i.isLoaded=!1)}});const e=um.create(t.uid,i.uid,i.viewerConfig.viewerMode,t.context.pagePreloadChanges);i.core.viewerService.onPagePreloadChanged.emit(e)}}thumbnailVisibility(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const{total:i}=t;if(!i)return;const n=t.context;if(n.isOutOfBounds)return void t.allPages.forEach(t=>{t.updateStyle({visibility:"hidden"})});const{rows:s,columns:o,placeholderPages:r,preloadCount:a,isVertical:l}=n,{width:h,height:c}=r[0],d=n.getParsedPageStyle(),u=n.getParsedCurrentPageStyle(),p=n.getParsedSelectedPageStyle(),g=n.getParsedHoveredPageStyle(),f=n.getParsedPlaceholderStyle(),m=n.getParsedPageNumberStyle(h,c),v=n.getParsedCheckboxStyle(h,c),{visibility:y,top:x,bottom:w,onPage:C,height:b}=m;let S=0;const T="visible"===y,E=n.getPageNumberStyle();if(T){const t=""!==E.top?x:w||0;C||(S=""!==E.top?b+t:0)}const{realColumn:_,realRow:P}=n.getRealRowAndColumnThumbnail(),{startRow:A,endRow:I}=this.getVisibleRow(t,P,_),{startColumn:D,endColumn:R}=this.getVisibleColumn(t,P,_);t.context.startRow=A,t.context.endRow=I,t.context.startColumn=D,t.context.endColumn=R;const k=dw(u.borderWidth),M=[];t.visibleChildren=[],t.preloadChildren=[],t.allPages.forEach((e,i)=>{e.visibleSortIndex=i;const n=l?Math.floor(i/o):i%s,r=l?i%o:Math.floor(i/s),h=n>=A&&n<=I&&r>=D&&r<=R,c=n>=A-a&&n<=I+a&&r>=D-a&&r<=R+a,y=h?Tw:Ew;e.isPreload!==c&&(M.push({from:e.isPreload,to:c,pageUid:e.uid,index:i}),e.isPreload&&!c&&(this.context.cancelLoadVisiblePartData(e.uid),this.context.cancelGetDefaultRenderPage(e.uid))),e.isPreload=c,c&&t.preloadChildren.push(e);let x=!1;if(e.isVisible&&!h?t.childNodes.includes(e)&&t.removeChild(e):!e.isVisible&&h&&(x=!0),e.needLayout=x,e.isVisible!==h&&e.updateStyle({visibility:y}),h){t.visibleChildren.push(e),t.childNodes.includes(e)||t.appendChild(e);let n={borderWidth:0,background:"#ffffff00"};e.isDragging&&(n=f);let s=d;e.isHovered&&(s=g),e.isSelected&&(s=p);const o=dw(s.borderWidth);if(e.updateStyle({visibility:y,...n}),e.borderBox.updateStyle({...s,visibility:y,borderWidth:o}),T){let t=m.y;C||(t=""!==E.top?-S:m.y+m.bottom),e.pageNumber.parsedPageNumberStyle={...m,y:t},e.pageNumber.updateText((i+1).toString())}e.pageNumber.updateStyle({visibility:m.visibility,zIndex:m.onPage?1:0});let r=v.visibility;v.visibleByHover&&(r=e.isHovered||e.isSelected?v.visibility:"hidden"),e.checkbox.parsedCheckboxStyle={...v},e.checkbox.updateStyle({visibility:r}),e.checkbox.checked=e.isSelected,e.curBox.updateStyle({...u,visibility:e.uid===t.currentUid?Tw:Ew,borderWidth:k})}}),t.context.pagePreloadChanges=M,t.childNodes.sort((t,e)=>t.visibleSortIndex-e.visibleSortIndex),t.visibleChildren.forEach(i=>{if(!e&&!i.needLayout)return;const s=t.getPageIndex(i),o=n.placeholderPages[s];if(!o)return;const{pageWidth:r,pageHeight:a,borderBoxWidth:l,borderBoxHeight:h,x:c,y:u}=o;let f=d.borderWidth;i.isHovered&&(f=g.borderWidth),i.isSelected&&(f=p.borderWidth),f=dw(f);let m=l-2*f,v=h-2*f;m=Math.max(m,0),v=Math.max(v,0);const y=i.rWidth,x=i.rHeight;let w=y,C=x,b=1;(y>m||x>v)&&(y/x>m/v?(b=m/y,w=m,C=x*b):(b=v/x,C=v,w=y*b)),i.zoom=b;const T=uw(c),E=uw(u+S);let _=f+(m-w)/2,P=f+(v-C)/2;_=uw(_),P=uw(P);const A=pw(y),I=pw(x),D=y*(1-b)/2,R=x*(1-b)/2,k=i.cropWidth,M=i.cropHeight,L=_-D-(k-A)/2,O=P-R-(M-I)/2,B=_-D,N=P-R,U=A,F=I,V=_,W=P,H=pw(w),j=pw(C);i.setPage(T,E,r,a),i.setBorderBox(0,0,l,h,f),i.setCropBox(L,O,k,M,b,i.rotation),i.setRealTimeBox(B,N,U,F,b);const{width:z,height:G}=n.viewerContext.getPageRenderSize(i.uid);i.setMediaBox(-i.cropLeft,-i.cropTop,z,G),i.setImage(i.mediaBoxRect.left,i.mediaBoxRect.top,z,G),i.setCurBox(V,W,H,j)})}continuousVisibility(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const{preloadCount:i,isVertical:n}=t.context,s=t.context.getParsedPageStyle(),o=t.context.getParsedCurrentPageStyle(),{realRow:r,realColumn:a}=t.context.getRealRowAndColumnContinuous(),{startRow:l,endRow:h}=this.getVisibleRow(t,r,a),{startColumn:c,endColumn:d}=this.getVisibleColumn(t,r,a);t.context.startRow=l,t.context.endRow=h,t.context.startColumn=c,t.context.endColumn=d;const u=dw(s.borderWidth),p=dw(o.borderWidth),g=[];t.visibleChildren=[],t.preloadChildren=[],t.allPages.forEach((e,f)=>{e.visibleSortIndex=f;const m=n?Math.floor(f/a):f%r,v=n?f%a:Math.floor(f/r),y=m>=l&&m<=h&&v>=c&&v<=d,x=m>=l-i&&m<=h+i&&v>=c-i&&v<=d+i;e.isPreload!==x&&(g.push({from:e.isPreload,to:x,pageUid:e.uid,index:f}),e.isPreload&&!x&&(this.context.cancelLoadVisiblePartData(e.uid),this.context.cancelGetDefaultRenderPage(e.uid))),e.isPreload=x,x&&t.preloadChildren.push(e);let w=!1;e.isVisible&&!y?t.childNodes.includes(e)&&(e.visiblePartData=null,e.visiblePart=null,t.removeChild(e)):!e.isVisible&&y&&(w=!0),e.needLayout=w,e.isVisible!==y&&e.updateStyle({visibility:y?Tw:Ew}),y&&(t.visibleChildren.push(e),t.childNodes.includes(e)||t.appendChild(e),e.checkbox.updateStyle({visibility:Ew}),e.pageNumber.updateStyle({visibility:Ew}),e.curBox.updateStyle({...o,visibility:e.uid===t.currentUid?Tw:Ew,borderWidth:p}),e.borderBox.updateStyle({...s,borderWidth:u}))}),t.context.pagePreloadChanges=g,t.childNodes.sort((t,e)=>t.visibleSortIndex-e.visibleSortIndex);const f=t.context,m=2*s.borderWidth;t.visibleChildren.forEach(i=>{if(!e&&!i.needLayout)return;const n=t.getPageIndex(i),{zoom:s}=i,o=i.rWidth,r=i.rHeight,a=o*s,l=r*s,h=f.placeholderPages[n];if(!h)return;const{pageX:c,pageY:d}=h;let p=a+m,g=l+m;p=pw(p),g=pw(g);const v=uw(u),y=v,x=pw(o),w=pw(r),C=o*(1-s)/2,b=r*(1-s)/2,S=v,T=v,E=pw(a),_=pw(l),P=i.cropWidth,A=i.cropHeight,I=v-C-(P-x)/2,D=y-b-(A-w)/2,R=v-C,k=y-b;i.setPage(c,d,p,g),i.setBorderBox(0,0,p,g),i.setCropBox(I,D,P,A,s,i.rotation),i.setRealTimeBox(R,k,o,r,s);const{width:M,height:L}=f.viewerContext.getPageRenderSize(i.uid);i.setMediaBox(-i.cropLeft,-i.cropTop,M,L),i.setImage(i.mediaBoxRect.left,i.mediaBoxRect.top,M,L),i.setCurBox(S,T,E,_)})}singleVisibility(t){const{preloadCount:e}=t.context,{current:i,total:n}=t,s=t.getCurrentPage();if(!s)return;const o=t.context.getParsedPageStyle(),r=Math.max(i-e,0),a=Math.min(i+e,n-1);s.checkbox.updateStyle({visibility:Ew}),s.pageNumber.updateStyle({visibility:Ew});const l=dw(o.borderWidth),h=[];t.visibleChildren=[],t.preloadChildren=[],t.allPages.forEach((e,i)=>{const n=i>=r&&i<=a,c=e.uid===s.uid;e.isPreload!==n&&(h.push({from:e.isPreload,to:n,pageUid:e.uid,index:i}),e.isPreload&&!n&&(this.context.cancelLoadVisiblePartData(e.uid),this.context.cancelGetDefaultRenderPage(e.uid))),e.isPreload=n,n&&t.preloadChildren.push(e);let d=!1;e.isVisible&&!c?t.childNodes.includes(e)&&t.removeChild(e):!e.isVisible&&c&&(d=!0),e.needLayout=d,e.updateStyle({visibility:c?Tw:Ew}),c&&(t.visibleChildren.push(e),t.childNodes.includes(e)||t.appendChild(e),e.borderBox.updateStyle({...o,borderWidth:l}),e.curBox.updateStyle({visibility:Ew}))}),t.context.pagePreloadChanges=h}getVisibleColumn(t,e,i){const{scrollLeft:n,placeholderPages:s,currentViewportWidth:o,isVertical:r}=t.context;let a=0,l=i-1;if(r&&this.context.isThumbnailViewer)return{startColumn:a,endColumn:l};let h=Number.MAX_VALUE,c=Number.MAX_VALUE,d=!1,u=!1;for(let t=0;t<i;t++){const i=s[r?t:t*e];if(!i)continue;const{x:p,width:g}=i;if(!d){const e=p-n;e<=0&&p+g-n>1?(d=!0,a=t):e>0&&e<h&&(h=e,a=t)}if(!u){const e=n+o,i=e-(p+g);p-e<-1&&i<=0?(u=!0,l=t):i>0&&i<c&&(c=i,l=t)}if(d&&u)break}return{startColumn:a,endColumn:l}}getVisibleRow(t,e,i){const{scrollTop:n,placeholderPages:s,currentViewportHeight:o,isVertical:r}=t.context;let a=0,l=e-1;if(!r&&this.context.isThumbnailViewer)return{startRow:a,endRow:l};let h=Number.MAX_VALUE,c=Number.MAX_VALUE,d=!1,u=!1;for(let t=0;t<e;t++){const e=s[r?t*i:t];if(!e)continue;const{y:p,height:g}=e;if(!d){const e=p-n;e<=0&&p+g-n>1?(d=!0,a=t):e>0&&e<h&&(h=e,a=t)}if(!u){const e=n+o,i=e-(p+g);p-e<-1&&i<=0?(u=!0,l=t):i>0&&i<c&&(c=i,l=t)}if(d&&u)break}return{startRow:a,endRow:l}}}const Pw={tag:"div",id:"ddv-thumbnail-container",className:"ddv-thumbnail-container"},Aw={tag:"div",id:"ddv-main-container",className:"ddv-main-container",children:[{tag:"div",id:"ddv-scroller-and-canvas",className:"ddv-scroller-and-canvas",children:[{tag:"div",id:"ddv-canvas-container",className:"ddv-canvas-container",children:[]},{tag:"div",id:"ddv-scroll-container",className:"ddv-scroll-container",children:[{tag:"div",id:"ddv-scroll-content",className:"ddv-scroll-content"}]}]}]},Iw={tag:"div",id:"ddv-video-container",className:"ddv-video-container"},Dw={tag:"div",id:"ddv-audio-container",className:"ddv-audio-container"},Rw={tag:"div",id:"ddv-main-and-thumbnail",className:"ddv-main-and-thumbnail"},kw={tag:"div",id:"ddv-core",className:"ddv-core"};class Mw extends Wo{constructor(t,e){super(),Yi(this,"container",void 0),Yi(this,"defaultDom",void 0),Yi(this,"mainAndThbContainer",void 0),Yi(this,"thumbnailContainer",void 0),Yi(this,"mainContainer",void 0),Yi(this,"scrollerAndCanvasContainer",void 0),Yi(this,"scrollContainer",void 0),Yi(this,"scrollContent",void 0),Yi(this,"canvasContainer",void 0),Yi(this,"annotationCanvasContainer",void 0),Yi(this,"videoContainer",void 0),Yi(this,"audioContainer",void 0),Yi(this,"rootDom",void 0),Yi(this,"hooks",void 0),Yi(this,"isBindContainer",!1),Yi(this,"viewportWidth",void 0),Yi(this,"viewportHeight",void 0),Yi(this,"context",void 0),Yi(this,"dpr",ao()),Yi(this,"hasScrollbarX",!1),Yi(this,"hasScrollbarY",!1),Yi(this,"winResizeTimer",void 0),this.context=t,this.hooks=e;const i=ty(kw,t.postfix);this.defaultDom=i}dispose(){var t,e;null===(t=this.rootDom)||void 0===t||t.remove(),null===(e=this.thumbnailContainer)||void 0===e||e.remove(),this.defaultDom=null,this.rootDom=null,this.thumbnailContainer=null,this.context=null,this.dpr=null,super.dispose()}createMainAndThbContainer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(!this.mainAndThbContainer){const e=ty(Rw,t);this.mainAndThbContainer=e,this.defaultDom.appendChild(e)}}createMainContainer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(!this.mainContainer){const e=ty(Aw,t);this.mainContainer=e,this.mainAndThbContainer.appendChild(e);const i=e.querySelector(`#ddv-scroller-and-canvas${t}`),n=e.querySelector(`#ddv-canvas-container${t}`),s=e.querySelector(`#ddv-scroll-container${t}`),o=e.querySelector(`#ddv-scroll-content${t}`);this.scrollerAndCanvasContainer=i,this.canvasContainer=n,this.scrollContainer=s,this.scrollContent=o;const r=t=>{t.target===e&&this.isBindContainer&&this.context.isInitialized&&this.context.resize()},{resizeService:a}=this.context.core;a.observe(e),a.onResizeObserver.on(r,this),this.context.hooks.destroy.on(()=>{a.unobserve(e)},this)}}createThumbnailContainer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(!this.thumbnailContainer){const e=ty(Pw,t);this.thumbnailContainer=e,this.mainAndThbContainer.insertBefore(e,this.mainContainer)}}createVideoContainer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(!this.videoContainer){const e=ty(Iw,t);this.mainContainer.appendChild(e)}}createAudioContainer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(!this.audioContainer){const e=ty(Dw,t);this.mainContainer.appendChild(e)}}getViewportSize(){if(!this.mainContainer)return{width:0,height:0};const{offsetWidth:t,offsetHeight:e}=this.getElSize(this.mainContainer),i=this.getCanvasBorderSize();return{width:t-2*i,height:e-2*i}}resetViewport(){const{scrollContent:t,canvasContainer:e,annotationCanvasContainer:i}=this;cw(e,0,0),cw(t,0,0);const{width:n,height:s}=this.getViewportSize();this.viewportWidth=n,this.viewportHeight=s,this.updateCanvasContainerSize()}resizeViewport(){const{canvasContainer:t,scrollContainer:e,annotationCanvasContainer:i}=this;cw(t,0,0);const{offsetWidth:n,offsetHeight:s}=this.getElSize(e);this.viewportWidth=n,this.viewportHeight=s,this.updateCanvasContainerSize()}checkIsRound(t){const e=getComputedStyle(t);return{roundWidth:parseFloat(e.width)%1>=.5,roundHeight:parseFloat(e.height)%1>=.5}}getElSize(t){const{roundWidth:e,roundHeight:i}=this.checkIsRound(t);let{clientWidth:n,clientHeight:s,offsetWidth:o,offsetHeight:r}=t;return e&&(n-=1,o-=1),i&&(s-=1,r-=1),{clientWidth:n,clientHeight:s,offsetWidth:o,offsetHeight:r}}getMaxScrollValue(){const{scrollContainer:t}=this;let e=t.scrollWidth-t.clientWidth,i=t.scrollHeight-t.clientHeight;return this.hasScrollbarX||(e=0),this.hasScrollbarY||(i=0),{scrollLeft:e,scrollTop:i}}isViewerResized(){return this.scrollContainer.offsetWidth!==this.viewportWidth||this.scrollContainer.offsetHeight!==this.viewportHeight}isDPRChanged(){const t=ao();return this.dpr!==t&&(this.dpr=t,!0)}bindContainer(t){let e=t;return t&&Os(t)&&(e=document.querySelector(`#${t}`)),e instanceof HTMLElement&&(e.appendChild(this.defaultDom),this.container=e,this.rootDom=this.defaultDom,this.isBindContainer=!0,this.context.resize(),!0)}unbindContainer(){if(!this.container||0===this.container.children.length)return!1;for(let t=0;t<this.container.children.length;t++)if(this.container.children[t]===this.rootDom){this.container.removeChild(this.rootDom);break}return this.isBindContainer=!1,!0}scrollTo(t,e){const{scrollContainer:i}=this;i.scrollTo?i.scrollTo(t,e):(i.scrollLeft=t,i.scrollTop=e)}scrollBy(t,e){const{scrollContainer:i}=this;i.scrollBy?i.scrollBy(t,e):(i.scrollLeft+=t,i.scrollTop+=e)}updateScrollerContentSize(t){const{currentLayoutWidth:e,currentLayoutHeight:i}=t.context,{scrollContent:n,canvasContainer:s,annotationCanvasContainer:o,scrollContainer:r}=this;cw(s,10,10),cw(n,e,i);let a=r.scrollWidth-r.clientWidth,l=r.scrollHeight-r.clientHeight;const h=getComputedStyle(r),c=getComputedStyle(n),d=parseFloat(h.width),u=parseFloat(h.height);d>=parseFloat(c.width)&&(a=0),u>=parseFloat(c.height)&&(l=0),t.context.maxScrollLeft=a,t.context.maxScrollTop=l;const p=a>0,g=l>0;let f=!1;p!==this.hasScrollbarX&&(this.hasScrollbarX=p,f=!0),p&&g||cw(n,p?e:e-20,g?i:i-20),g!==this.hasScrollbarY&&(this.hasScrollbarY=g,f=!0),f&&this.context.clearCurrentTabOptimization(),this.updateCanvasContainerSize()}updateCanvasContainerSize(){const{scrollContainer:t,canvasContainer:e,annotationCanvasContainer:i}=this,{width:n,height:s}=getComputedStyle(this.scrollContainer);let o,r=parseFloat(n),a=parseFloat(s);t.offsetWidth!==t.clientWidth&&(Ls(o)||(o=gw()),r-=o),t.offsetHeight!==t.clientHeight&&(Ls(o)||(o=gw()),a-=o),cw(e,r,a)}getCanvasBorderSize(){const{canvasContainer:t}=this;return(t.offsetWidth-t.clientWidth)/2}}class Lw{constructor(){Yi(this,"canvasDom",void 0),Yi(this,"canvas",void 0),Yi(this,"renderer",void 0),Yi(this,"isInitialized",!1),Yi(this,"canvasWidth",0),Yi(this,"canvasHeight",0)}clear(){var t;const e=null===(t=this.canvas)||void 0===t?void 0:t.document.documentElement;e&&(e.children.slice().forEach(t=>{e.removeChild(t)}),e.sortable.sorted=[])}appendDocToRoot(t){var e;const i=null===(e=this.canvas)||void 0===e?void 0:e.document.documentElement;if(i)if(t)0===i.children.length?i.appendChild(t):i.children.indexOf(t)<0&&i.replaceChild(t,i.children[0]);else{const t=[...i.children];for(let e=t.length;e>=0;e--)i.removeChild(t[e])}}render(t){var e;(null===(e=this.canvas)||void 0===e?void 0:e.document.documentElement)&&this.canvas.render()}initCanvas(t){let{container:e,width:i,height:n,limit1px:s}=t;const o=new kh({}),r=new ph({renderer:o,container:e,width:i,height:n});r.limit1px=s,this.canvasWidth=i,this.canvasHeight=n,this.renderer=o,this.canvas=r,this.canvasDom=r.contextService.getDomElement(),this.canvasDom.style.width="100%",this.canvasDom.style.height="100%",this.canvasDom.style.touchAction="none",this.isInitialized=!0}registerShapeRenderer(t,e){this.canvas.contextService.registerShapeRenderer(t,e)}getCanvasPosition(){const t=this.canvasDom.getBoundingClientRect(),{scrollX:e,scrollY:i}={scrollX:void 0===window.scrollX?window.pageXOffset:window.scrollX,scrollY:void 0===window.scrollY?window.pageYOffset:window.scrollY};return{x:t.left+e,y:t.top+i}}resize(t,e){const i=ao();this.canvas.setDPR(i),this.canvasWidth=t,this.canvasHeight=e,this.canvas.resize(t,e)}}class Ow{render(t,e){const{opacity:i,visibility:n}=t.parsedCheckboxStyle;0!==i&&"hidden"!==n&&(e.save(),e.globalAlpha=i,this.renderBox(t,e,"out"),e.clip(),this.renderBox(t,e,"in"),this.fill(t,e),this.renderBox(t,e,"center"),this.stroke(t,e),this.renderCheckMark(t,e),e.restore())}renderBox(t,e,i){const{x:n,y:s,width:o,height:r,borderWidth:a,borderRadiusX:l,borderRadiusY:h}=t.parsedCheckboxStyle;let c=0;"center"===i?c=a/2:"in"===i&&(c=a);const d=[{x:n+l,y:s+h,start:Math.PI,end:3*Math.PI/2},{x:n+o-l,y:s+h,start:3*Math.PI/2,end:2*Math.PI},{x:n+o-l,y:s+r-h,start:0,end:Math.PI/2},{x:n+l,y:s+r-h,start:Math.PI/2,end:Math.PI}],u=Math.max(l-c,0),p=Math.max(h-c,0);if(e.beginPath(),e.ellipse&&u&&p)for(let t=0;t<4;t++){const{x:i,y:n,start:s,end:o}=d[t];e.ellipse(i,n,u,p,0,s,o)}else e.rect(n,s,o,r);e.closePath()}fill(t,e){const{background:i}=t.parsedCheckboxStyle;i&&""!==i&&(e.fillStyle=i,e.fill())}stroke(t,e){const{borderColor:i,borderWidth:n,borderStyle:s}=t.parsedCheckboxStyle;e.setLineDash(s),e.strokeStyle=i,e.lineWidth=n,n>0&&i&&""!==i&&e.stroke()}renderCheckMark(t,e){if(!t.checked)return;const{x:i,y:n,width:s,height:o,borderWidth:r,checkMarkLineWidth:a,checkMarkColor:l}=t.parsedCheckboxStyle,h=Math.max(Math.min(s-2*r,o-2*r),0);let c=i,d=n;0!==h&&(s<o?(c+=r,d=d+r+(o-s)/2):(c=c+r+(s-o)/2,d+=r),e.setLineDash([0,0]),e.lineWidth=a,e.strokeStyle=l,e.beginPath(),e.moveTo(c+.15*h,d+.5*h),e.lineTo(c+.4*h,d+.8*h),e.lineTo(c+.85*h,d+.2*h),e.stroke())}}class Bw{render(t,e){const{opacity:i,visibility:n}=t.parsedPageNumberStyle;0!==i&&"hidden"!==n&&(e.save(),e.globalAlpha=i,this.renderBox(t,e,"out"),e.clip(),this.renderBox(t,e,"in"),this.fill(t,e),this.renderBox(t,e,"center"),this.stroke(t,e),this.renderFont(t,e),e.restore())}renderBox(t,e,i){const{x:n,y:s,width:o,height:r,borderWidth:a,borderRadiusX:l,borderRadiusY:h}=t.parsedPageNumberStyle;let c=0;"center"===i?c=a/2:"in"===i&&(c=a);const d=[{x:n+l,y:s+h,start:Math.PI,end:3*Math.PI/2},{x:n+o-l,y:s+h,start:3*Math.PI/2,end:2*Math.PI},{x:n+o-l,y:s+r-h,start:0,end:Math.PI/2},{x:n+l,y:s+r-h,start:Math.PI/2,end:Math.PI}],u=Math.max(l-c,0),p=Math.max(h-c,0);if(e.beginPath(),e.ellipse&&u&&p)for(let t=0;t<4;t++){const{x:i,y:n,start:s,end:o}=d[t];e.ellipse(i,n,u,p,0,s,o)}else e.rect(n,s,o,r);e.closePath()}renderFont(t,e){const{x:i,y:n,width:s,height:o,fontSize:r,color:a,fontFamily:l}=t.parsedPageNumberStyle;e.fillStyle=a,e.textAlign="center",e.textBaseline="middle",l.includes(" ")?e.font=`${r}px '${l}'`:e.font=`${r}px ${l}`,e.fillText(t.text,i+s/2,n+o/2+r/8,s)}fill(t,e){const{background:i}=t.parsedPageNumberStyle;i&&""!==i&&(e.fillStyle=i,e.fill())}stroke(t,e){const{borderColor:i,borderWidth:n,borderStyle:s}=t.parsedPageNumberStyle;e.setLineDash(s),e.strokeStyle=i,e.lineWidth=n,n>0&&i&&""!==i&&e.stroke()}}class Nw{render(t,e){var i;if(null===(i=t.lines)||void 0===i||!i.length)return;const n=t.style;e.save(),e.fillStyle=t.style.background,e.globalCompositeOperation="multiply",e.beginPath(),t.lines.forEach(t=>{e.rect(t.left,t.top,t.width,t.height)}),e.fill(),e.closePath();const s=t.getScale().x,o=n.ctrlBorderRadius/s,r=[];if(t.startCharRect){const{startCharRect:e}=t;r.push({x:e.left+e.width/2,y:e.top-o})}if(t.endCharRect){const{endCharRect:e}=t;r.push({x:e.left+e.width/2,y:e.top+e.height+o})}e.lineWidth=n.ctrlBorderWidth/s,e.strokeStyle=n.ctrlBorderColor,e.fillStyle=n.ctrlBackground,r.forEach(t=>{e.beginPath(),e.ellipse(t.x,t.y,o,o,0,0,2*Math.PI),e.closePath(),n.ctrlBackground&&e.fill(),e.stroke()}),e.restore()}}class Uw{render(t,e){var i;if(null===(i=t.lines)||void 0===i||!i.length)return;const{selectedTextUid:n}=t;e.save(),e.globalCompositeOperation="multiply",t.lines.forEach(i=>{i.textUid===n?e.fillStyle=t.style.currentBackground:e.fillStyle=t.style.background,e.beginPath(),i.boxes.forEach(t=>{e.rect(t.left,t.top,t.width,t.height)}),e.fill(),e.closePath()}),e.restore()}}class Fw extends Wo{constructor(t,e){super(),Yi(this,"context",void 0),Yi(this,"docRenderer",void 0),Yi(this,"aRenderer",void 0),Yi(this,"hooks",void 0),Yi(this,"reasons",[]),Yi(this,"tab",void 0),this.context=t,this.hooks=e,this.docRenderer=new Lw;const i=()=>{null!=this&&this.context&&(this.reasons.length&&this.tab&&this.tab.isActive&&(this.internalRender(this.tab),this.hooks.renderReason.emit(this.reasons),this.tab=null,this.reasons=[]),requestAnimationFrame(i))};i()}getScrollContainer(){throw new Error("Method not implemented.")}dispose(){super.dispose(),this.context=null,this.docRenderer=null,this.hooks=null}initRenderer(t,e,i){if(!this.docRenderer.isInitialized){Object.assign(t.style,this.context.viewerConfig.canvasStyle);const n=this.context.isDefaultViewer;this.docRenderer.initCanvas({container:t,width:e,height:i,limit1px:n}),this.docRenderer.registerShapeRenderer("checkbox",new Ow),this.docRenderer.registerShapeRenderer("pageNumber",new Bw),this.docRenderer.registerShapeRenderer("textSelection",new Nw),this.docRenderer.registerShapeRenderer("textSearch",new Uw)}}getCanvasDom(){return this.docRenderer.canvasDom}clearCanvas(){const t=this.getCanvasDom();t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}resize(t,e){this.docRenderer&&this.docRenderer.resize(t,e)}updateCanvasSize(){if(this.docRenderer){const t=this.getCanvasDom();if(!t)return;const{clientWidth:e,clientHeight:i}=t;this.docRenderer.resize(e,i)}}render(t,e){t.isDestroyed||(this.tab=t,this.docRenderer.appendDocToRoot(t),this.reasons.push(e),3===e&&this.docRenderer.render(t))}internalRender(t){t.isDestroyed||(this.hooks.beforeRender.emit(t),this.docRenderer.render(t),this.hooks.afterRender.emit(t),t.preloadChildren.forEach((t,e)=>{if(t.isVisible&&t.isLoaded){const e=wm.create(t.pageIndex,t.uid);this.hooks.pageRendered.emit(e)}}))}getCanvasPageRect(){const t=this.docRenderer.canvasDom.getBoundingClientRect(),{scrollX:e,scrollY:i}=window;return{left:t.left+e,top:t.top+i,width:t.width,height:t.height}}}function Vw(t){const e=t.getPages(),i=e.length;if(!i)return t.currentLayoutWidth=0,void(t.currentLayoutHeight=0);let{viewportWidth:n,viewportHeight:s}=t;const{rows:o,columns:r,scrollbarWidth:a,tab:l,isVertical:h}=t,c=t.getMargin();r*o<i&&(h?n-=a:s-=a);let d=0,u=0;h?(d=(n-(r+1)*c)/r,u=(s-(o+1)*c)/o):(u=(s-(o+1)*c)/o,d=(n-(r+1)*c)/r);let p=!1;(d<0||u<0)&&(p=!0,d=Math.max(0,d),u=Math.max(0,u));const g=h?Math.max(o,Math.ceil(i/r)):o,f=h?r:Math.max(r,Math.ceil(i/o)),m=d*f+(f+1)*c,v=u*g+(g+1)*c,y=e.map(t=>({uid:t.uid,x:0,y:0,width:d,height:u,borderBoxWidth:0,borderBoxHeight:0,pageWidth:0,pageHeight:0})),x=t.getParsedPageStyle(),w=t.getParsedPageNumberStyle(d,u),{visibility:C,top:b,bottom:S,onPage:T,height:E}=w;let _=d,P=u;const A=d;let I=u;const D="visible"===C,R=t.getPageNumberStyle();if(D){const t=""!==R.top?b:S||0;T||(P=u-E-t,I=u-E-t,R.top)}P<0&&(p=!0,P=Math.max(0,P)),(_-2*x.borderWidth<0||P-2*x.borderWidth<0)&&(p=!0);const k=t.viewerContext.viewService.getCanvasBorderSize();t.currentLayoutWidth=p?0:m+2*k,t.currentLayoutHeight=p?0:v+2*k,t.currentViewportWidth=p?t.viewportWidth:n,t.currentViewportHeight=p?t.viewportHeight:s,t.isOutOfBounds=p,p||(_=pw(_),P=pw(P),e.forEach((t,e)=>{const i=h?e%r:Math.floor(e/o),n=h?Math.floor(e/r):e%o,s=c+i*(c+d),a=c+n*(c+u);y[e].x=s,y[e].y=a,y[e].borderBoxWidth=_,y[e].borderBoxHeight=P,y[e].pageWidth=A,y[e].pageHeight=I}),t.placeholderPages=y,l.context.viewerContext.visibilityService.handleVisibility(l,!0))}function Ww(t){const{tab:e}=t,i=e.getCurrentPage();if(!i)return t.currentLayoutWidth=0,void(t.currentLayoutHeight=0);const{viewportWidth:n,viewportHeight:s,scrollbarWidth:o,fitMode:r}=t,a=t.getMargin(),l=t.getParsedPageStyle(),{borderWidth:h=0}=l,c=2*h,d=i.rWidth,u=i.rHeight,p=2*a,g=c+p,f=c+p,m=n-g,v=s-f;let{zoom:y}=t;const x=jw(r,{zoom:y,validLayoutWidth:d,validLayoutHeight:u,scrollbarWidth:o,fitViewportWidth:m,fitViewportHeight:v,isZoomChanged:t.isZoomChanged},Hw);t.isZoomChanged=!1;const{zoomedLayoutWidth:w,zoomedLayoutHeight:C,zoomedViewportWidth:b,zoomedViewportHeight:S,newFitMode:T}=x;if(y=x.zoom,T&&r!==T){t.fitMode=T,t.viewerContext.viewerConfig.fitMode=T;const e=Yf.create(r,T);t.viewerContext.hooks.fitModeChanged.emit(e)}t.setZoom(y);const E=w+g,_=C+f,P=b+g,A=S+f,I=t.viewerContext.viewService.getCanvasBorderSize();t.currentLayoutWidth=E+2*I,t.currentLayoutHeight=_+2*I,t.currentViewportWidth=P,t.currentViewportHeight=A,i.zoom=y,t.tab.setPosition({x:-0,y:-0});const D=e.allPages.map(t=>{let{uid:e}=t;return{uid:e,x:a,y:a,width:w+c,height:C+c}});t.placeholderPages=D;const R=pw(w+c),k=pw(C+c),M=uw(a),L=M,O=dw(h),B=O,N=pw(d),U=pw(u),F=d*(1-y)/2,V=u*(1-y)/2,W=i.cropWidth,H=i.cropHeight,j=O-F-(W-N)/2,z=B-V-(H-U)/2,G=O-F,Y=B-V;i.setPage(M,L,R,k),i.setBorderBox(0,0,R,k),i.setCropBox(j,z,W,H,y,i.rotation),i.setRealTimeBox(G,Y,d,u,y);const{width:$,height:X}=t.viewerContext.getPageRenderSize(i.uid);i.setMediaBox(-i.cropLeft,-i.cropTop,$,X),i.setImage(0,0,$,X)}function Hw(t,e){let{zoom:i,validLayoutWidth:n,validLayoutHeight:s,scrollbarWidth:o,fitViewportWidth:r,fitViewportHeight:a}=e;return"none"===t||"actualSize"===t?("actualSize"===t&&(i=1),Math.floor(n*i)>r&&(a-=o),Math.floor(s*i)>a&&(r-=o)):"width"===t||"window"===t&&n/r>=s/a?(i=r/n,s*i>a&&(r-=o,i=r/n)):(i=a/s,n*i>r&&(a-=o,i=a/s)),{zoom:i,zoomedLayoutWidth:n*i,zoomedLayoutHeight:s*i,zoomedViewportWidth:r,zoomedViewportHeight:a}}function jw(t,e,i){const{zoom:n,isZoomChanged:s}=e;let o={};if(s){let s;const r=ny(n);1===n?(s="actualSize",o=i("actualSize",e)):(o=i("width",e),ny(o.zoom)===r?(s="width","window"===t&&(s="window")):(o=i("height",e),r===ny(o.zoom)&&(s="height","window"===t&&(s="window")))),s?o.newFitMode=s:(o=i("none",e),o.newFitMode="none")}else o=i(t,e);return o}function zw(t,e){let{zoom:i,fitWidth:n,fitHeight:s,validLayoutWidth:o,validLayoutHeight:r,scrollbarWidth:a,isVertical:l,fitViewportWidth:h,fitViewportHeight:c}=e;return"none"===t||"actualSize"===t?("actualSize"===t&&(i=1),Math.floor(o*i)>h&&(c-=a),Math.floor(r*i)>c&&(h-=a)):"width"===t||"window"===t&&n/h>=s/c?(i=h/n,l?r*i>c&&(h-=a,i=h/n):(o*i>h&&(c-=a),s*i>c&&(h-=a,i=h/n))):(i=c/s,l?(r*i>c&&(h-=a),n*i>h&&(c-=a,i=c/s)):o*i>h&&(c-=a,i=c/s)),{zoom:i,zoomedLayoutWidth:o*i,zoomedLayoutHeight:r*i,zoomedViewportWidth:h,zoomedViewportHeight:c}}const Gw=t=>{const e=t.getPages();if(!e.length)return;const{tab:i}=t,n=i.current,s=e[n-1],o=e[n+1];s&&Yw(t,s,-1),o&&Yw(t,o,1)};function Yw(t,e,i){const{viewportWidth:n,viewportHeight:s}=t,o=t.getParsedPageStyle(),{borderWidth:r=0}=o,a=t.getMargin(),{rWidth:l,rHeight:h}=e,c=n-2*a-2*r,d=s-2*a-2*r;let u=0,p=0,g=1;l/h>c/d?(u=c,g=c/l,p=h*g):(p=d,g=d/h,u=l*g);let f=(c-u)/2+a,m=(d-p)/2+a;f=Math.max(a,f),m=Math.max(a,m);const{x:v,y:y}=t.tab.getPosition();-1===i?(f=-n+f-v,m-=y):1===i&&(f=n+f-v,m-=y);const x=l*(1-g)/2,w=h*(1-g)/2,C=r,b=r,S=l,T=h,E=e.cropWidth,_=e.cropHeight,P=C-x-(E-S)/2,A=b-w-(_-T)/2,I="visible",D="hidden";e.updateStyle({visibility:I,x:f,y:m,width:u+2*r,height:p+2*r}),e.borderBox.updateStyle({x:0,y:0,width:u+2*r,height:p+2*r,...o,background:"#ffffff00",visibility:I}),e.cropBox.setLocalScale(1),e.cropBox.updateStyle({x:P,y:A,width:E,height:_}),e.cropBox.setLocalScale(g,g),e.cropBox.setLocalAngle(e.rotation);const{width:R,height:k}=t.viewerContext.getPageRenderSize(e.uid);e.mediaBox.updateStyle({x:-e.cropLeft,y:-e.cropTop,width:R,height:k}),e.zoom=g,e.checkbox.updateStyle({visibility:D}),e.pageNumber.updateStyle({visibility:D}),e.setImage(0,0,R,k)}function $w(t){const{displayMode:e}=t;"single"===e?Ww(t):"continuous"===e?function(t){const e=t.getPages();if(!e.length)return t.currentLayoutWidth=0,void(t.currentLayoutHeight=0);let{zoom:i}=t;const{viewportWidth:n,viewportHeight:s,tab:o,fitMode:r,scrollbarWidth:a,isVertical:l}=t,h=t.getParsedPageStyle(),{borderWidth:c}=h,d=2*c,u=t.getMargin(),{realRow:p,realColumn:g}=t.getRealRowAndColumnContinuous(),f=new Array(g).fill(0),m=new Array(p).fill(0);let v=0,y=0;e.forEach((t,e)=>{const i=l?Math.floor(e/g):e%p,n=l?e%g:Math.floor(e/p),s=t.rWidth+d,o=t.rHeight+d;f[n]=Math.max(f[n],s),m[i]=Math.max(m[i],o),v=Math.max(f[n],v),y=Math.max(m[i],y)});let x=f.reduce((t,e)=>t+e,0),w=m.reduce((t,e)=>t+e,0);const C=(g+1)*u,b=(p+1)*u,S=g*d+C,T=p*d+b;x+=C,w+=b;const E=x-S,_=w-T;let P=0,A=0,I=0,D=0;l?(P=n-S,A=s-2*u-d,I=f.reduce((t,e)=>t+e-d,0),D=y-d):(P=n-2*u-d,A=s-T,I=v-d,D=m.reduce((t,e)=>t+e-d,0));const R=jw(r,{zoom:i,fitWidth:I,fitHeight:D,validLayoutWidth:E,validLayoutHeight:_,scrollbarWidth:a,isVertical:l,fitViewportWidth:P,fitViewportHeight:A,isZoomChanged:t.isZoomChanged},zw);t.isZoomChanged=!1;const{zoomedLayoutWidth:k,zoomedLayoutHeight:M,zoomedViewportWidth:L,zoomedViewportHeight:O,newFitMode:B}=R;if(i=R.zoom,B&&r!==B){t.fitMode=B,t.viewerContext.viewerConfig.fitMode=B;const e=Yf.create(r,B);t.viewerContext.hooks.fitModeChanged.emit(e)}t.setZoom(i);const N=k+S,U=M+T;let F=0,V=0;l?(F=L+(g+1)*u+g*d,V=O+2*u+d):(F=L+2*u+d,V=O+(p+1)*u+p*d);const W=t.viewerContext.viewService.getCanvasBorderSize();t.currentLayoutWidth=N+2*W,t.currentLayoutHeight=U+2*W,t.currentViewportWidth=F,t.currentViewportHeight=V,t.tab.setPosition({x:-0,y:-0});const H=o.allPages.map(t=>({uid:t.uid,x:0,y:0,width:0,height:0,pageX:0,pageY:0}));e.forEach((t,e)=>{const n=l?Math.floor(e/g):e%p,s=l?e%g:Math.floor(e/p),o=(f[s]-d)*i+d,r=(m[n]-d)*i+d,a=t.rWidth,h=t.rHeight;let v=0,y=0;if(0===s)v=u;else{const t=H[l?e-1:(s-1)*p+n];v=t.x+t.width+u}if(0===n)y=u;else{const t=H[l?(n-1)*g+s:e-1];y=t.y+t.height+u}const x=H[e];x.width=o,x.height=r,x.x=v,x.y=y,t.zoom=i;const w=y+(r-h*i)/2-c,C=uw(v+(o-a*i)/2-c),b=uw(w);x.pageX=C,x.pageY=b}),t.placeholderPages=H,t.viewerContext.visibilityService.handleVisibility(o,!0)}(t):"slide"===e&&Gw(t)}class Xw{constructor(t,e){Yi(this,"context",void 0),Yi(this,"hooks",void 0),this.context=t,this.hooks=e}layout(t,e){if(t.isDestroyed||!t.isActive)return;let i;if(this.context.isDefaultViewer)i=$w;else if(this.context.isThumbnailViewer)i=Vw;else if(this.context.isPerspectiveViewer){const{displayMode:e}=t.context;"single"===e?i=Ww:"slide"===e&&(i=Gw)}i&&(this.hooks.layoutReason.emit(e),this.hooks.beforeLayout.emit(t),i(t.context),this.hooks.afterLayout.emit(t))}}const qw=["viewerMode","displayMode","toolMode","annotationMode","fitMode","visibility","zoom","zoomOrigin","minZoom","maxZoom","multiselectMode","canvasStyle","pageStyle","selectedPageStyle","hoveredPageStyle","placeholderStyle","pageNumberStyle","checkboxStyle","currentPageStyle","quadSelectionStyle","textSelectionStyle","cursorStyle","rows","columns","maxColumns","maxRows","margin"];class Zw extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"handlers",{}),this.context=t}dispose(){this.context=null,this.handlers={},super.dispose()}updateConfig(t){for(const[e,i]of Object.entries(t))qw.includes(e)&&this[e](i)}registerHandler(t,e){return!this[t]&&(this[t]=e,!0)}viewerMode(t){const{context:e}=this;e.viewerConfig.viewerMode=t,jg.CAPTURE}toolMode(t){const{context:e}=this,i=e.viewerConfig.toolMode;t!==i&&(e.viewerConfig.toolMode=t,e.hooks.toolModeChanged.emit($f.create(i,t)))}annotationMode(t){const{context:e}=this,i=e.viewerConfig.annotationMode;t!==i&&(e.viewerConfig.annotationMode=t),e.hooks.annotationModeChanged.emit(om.create(i,t))}fitMode(t){const{context:e}=this,i=e.getActiveTab();if(!i){const i=e.viewerConfig.fitMode;if(i===t)return;return e.viewerConfig.fitMode=t,void e.hooks.fitModeChanged.emit(Yf.create(i,t))}const n=i.context.fitMode;n!==t&&(i.context.fitMode=t,"none"!==t&&(e.showTab(i,{isClearOptimization:!0,renderReason:20}),e.hooks.fitModeChanged.emit(Yf.create(n,t))))}displayMode(t){const{context:e}=this,i=e.getActiveTab();let n;if(i){if(n=i.context.displayMode,t===n)return;i.context.displayMode=t,e.showTab(i,{isClearOptimization:!0,renderReason:21})}else{if(n=e.viewerConfig.displayMode,t===n)return;e.viewerConfig.displayMode=t}if("slide"!==n&&"slide"!==t){const i=Gf.create(n,t);e.viewer.hooks.displayModeChanged.emit(i)}}margin(t){const{context:e}=this;e.viewerConfig.margin!==t&&(e.viewerConfig.margin=t,e.showCurrentTab({isClearOptimization:!0,renderReason:7}))}rows(t){const{context:e}=this,i=e.getActiveTab();i?t!==i.context.rows&&(e.styleService.isCheckboxStyleChanged=!0,e.styleService.isPageNumberStyleChanged=!0,i.context.rows=t,this.context.showTab(i,{isClearOptimization:!0,renderReason:22})):e.viewerConfig.rows=t}columns(t){const{context:e}=this,i=e.getActiveTab();i?t!==i.context.columns&&(e.styleService.isCheckboxStyleChanged=!0,e.styleService.isPageNumberStyleChanged=!0,i.context.columns=t,this.context.showTab(i,{isClearOptimization:!0,renderReason:22})):e.viewerConfig.columns=t}maxColumns(t){t=Math.max(1,t);const{context:e}=this;e.viewerConfig.maxColumns=t;const i=e.getActiveTab();i&&i.context.columns>t&&this.columns(t)}maxRows(t){t=Math.max(1,t);const{context:e}=this;e.viewerConfig.maxRows=t;const i=e.getActiveTab();i&&i.context.rows>t&&this.rows(t)}zoom(t){const{context:e}=this;e.getActiveTab()&&e.zoomTo(t)}visibility(t){const{context:e}=this;if(t===e.viewerConfig.visibility)return;const{rootDom:i,defaultDom:n,thumbnailContainer:s}=e.viewService;if(!i)return;const{ui:o}=e.viewer,r=!s&&o.container.classList.contains("ddv-thumbnail-container"),a=e.viewerConfig.visibility;e.viewerConfig.visibility=t,"visible"===t?(i.style.display="flex",n.style.display="flex",r?(o.container.style.display="flex",e.core.viewerService.onResize.emit()):e.core.viewerService.onResize.emit()):(i.style.display="none",r&&(o.container.style.display="none",e.core.viewerService.onResize.emit()));const l=Af.create(t,a);e.hooks.visibleChanged.emit(l)}zoomOrigin(t){const{context:e}=this;e.viewerConfig.zoomOrigin=t}minZoom(t){const{context:e}=this;e.viewerConfig.minZoom=t}maxZoom(t){const{context:e}=this;e.viewerConfig.maxZoom=t}multiselectMode(t){const{context:e}=this;e.viewerConfig.multiselectMode=t}canvasStyle(t){const{context:e}=this;if(Es(t))if(Object.assign(e.viewerConfig.canvasStyle,t),e.isCaptureViewer){var i;const n=null===(i=e.viewer)||void 0===i||null===(i=i.cameraContext)||void 0===i?void 0:i.cameraContainer;n&&Object.assign(n.style,t)}else{const{canvasContainer:i,annotationCanvasContainer:n}=e.viewService;if(i){const{eventDom:n}=e;Object.assign(i.style,t),t.cursor&&n&&Object.assign(n.style,{cursor:t.cursor}),e.styleService.isCanvasStyleChanged=!0,t.border&&e.resize()}}}pageStyle(t){const{context:e}=this;Es(t)&&(Object.assign(e.viewerConfig.pageStyle,t),e.styleService.isPageStyleChanged=!0,e.showCurrentTab({isClearOptimization:!0,renderReason:8}))}selectedPageStyle(t){const{context:e}=this;Es(t)&&(Object.assign(e.viewerConfig.selectedPageStyle,t),e.styleService.isSelectedPageStyleChanged=!0,e.showCurrentTab({isClearOptimization:!0,renderReason:9}))}hoveredPageStyle(t){const{context:e}=this;Es(t)&&(Object.assign(e.viewerConfig.hoveredPageStyle,t),e.styleService.isHoveredPageStyleChanged=!0,e.showCurrentTab({isClearOptimization:!0,renderReason:10}))}placeholderStyle(t){const{context:e}=this;Es&&(Object.assign(e.viewerConfig.placeholderStyle,t),e.styleService.isPlaceholderStyleChanged=!0,e.showCurrentTab({renderReason:11}))}currentPageStyle(t){const{context:e}=this;Es&&(Object.assign(e.viewerConfig.currentPageStyle,t),e.styleService.isCurrentPageStyleChanged=!0,e.showCurrentTab({renderReason:12}))}pageNumberStyle(t){const{context:e}=this;if(Es(t)){const{pageNumberStyle:i}=e.viewerConfig;let n=!1;void 0!==t.onPage?(t.onPage!==i.onPage||!1===t.onPage)&&(n=!0):!1===i.onPage&&(n=!0),Object.assign(i,t),e.styleService.isPageNumberStyleChanged=!0,e.showCurrentTab({isClearOptimization:n,renderReason:13})}}checkboxStyle(t){const{context:e}=this;Es(t)&&(Object.assign(e.viewerConfig.checkboxStyle,t),e.styleService.isCheckboxStyleChanged=!0,e.showCurrentTab({renderReason:14}))}quadSelectionStyle(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{context:e}=this;Es(t)&&(Object.assign(e.viewerConfig.quadSelectionStyle,t),e.styleService.isQuadSelectionStyleChanged=!0,e.hooks.quadSelectionStyleChanged.emit(),e.showCurrentTab({renderReason:15}))}textSelectionStyle(t){const{context:e}=this;Es(t)&&(Object.assign(e.viewerConfig.textSelectionStyle,t),e.tabService.getAllTabs().forEach(e=>{e.allPages.forEach(e=>{e.setTextSelectionStyle(t)})}),e.render(40))}cursorStyle(t){const{context:e}=this;Es(t)&&Object.assign(e.viewerConfig.cursorStyle,t)}scrollDirection(t){const{context:e}=this;e.viewerConfig.scrollDirection=t;const i=e.getActiveTab();i&&(i.context.direction=t,e.resize())}}class Jw extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"hoveredPageUid",null),Yi(this,"undo",0),Yi(this,"redo",0),this.context=t}dispose(){super.dispose(),this.context=null}handleExternalEvents(){const{context:t}=this,{hooks:e}=this.context;this.bindFileDropEvents(),this.bindNativeEvents(),this.convertInternalHooks();let i=0,n=0;e.pageChanged.on(e=>{const s=e.current+1,{total:o}=e;i===s&&n===o||(i=s,n=o,t.emit("paginationChanged",{currentPageNumber:s,pageCount:o}))},this),e.layoutReason.on(e=>{t.emit("layoutReason",e)},this),e.renderReason.on(e=>{t.emit("renderReason",e)},this),e.operationsChanged.on(e=>{this.undo===e.undo&&this.redo===e.redo||t.emit("undoRedoStateChanged",{undoCount:e.undo,redoCount:e.redo}),this.undo=e.undo,this.redo=e.redo},this),e.scroll.on(e=>{t.emit("scroll",e)}),e.currentIndexChanged.on(e=>{t.emit("currentIndexChanged",{oldIndex:e.oldIndex,newIndex:e.newIndex})},this),e.currentPageChanged.on(()=>{const e=this.context.getActiveTab();if(!e)return;const{currentUid:i,oldCurrentUid:n}=e;t.emit("currentPageChanged",{oldPageUid:n||"",newPageUid:i||""})},this),e.displayModeChanged.on(e=>{t.emit("displayModeChanged",{oldDisplayMode:e.oldDisplayMode,newDisplayMode:e.newDisplayMode})},this),e.fitModeChanged.on(e=>{t.emit("fitModeChanged",{oldFitMode:e.oldFitMode,newFitMode:e.newFitMode})},this),e.toolModeChanged.on(e=>{t.emit("toolModeChanged",{oldToolMode:e.oldToolMode,newToolMode:e.newToolMode})},this),e.annotationModeChanged.on(e=>{t.emit("annotationModeChanged",{oldAnnotationMode:e.oldAnnotationMode,newAnnotationMode:e.newAnnotationMode})}),e.zoomChanged.on(e=>{e.oldZoomRatio!==e.newZoomRatio&&t.viewer.emit("zoomChanged",{oldZoomRatio:e.oldZoomRatio,newZoomRatio:e.newZoomRatio})},this),e.textSelected.on(e=>{if(e.detail.length){if(!this.context.hasCallback("textSelected"))return;const t=[],i=Cr.displayResolution,n=Cr.dataResolution;e.detail.forEach(e=>{const s=[];e.lines.forEach(t=>{s.push({x:Lo(Bo(t.selectedRect.left,i,n),2),y:Lo(Bo(t.selectedRect.top,i,n),2),width:Lo(Bo(t.selectedRect.width,i,n),2),height:Lo(Bo(t.selectedRect.height,i,n),2)})}),t.push({pageUid:e.pageUid,text:e.text,rects:s})}),this.context.viewer.emit("textSelected",t)}else t.viewer.emit("textUnselected",null)},this),this.context.hooks.searchTextChanged.on(t=>{if(!this.context.hasCallback("textSearchTriggered"))return;if(!t.isLastPage)return;const e=[],{text:i}=t,n=Cr.displayResolution,s=Cr.dataResolution;t.searchResults.forEach(t=>{const{pageUid:o}=t;t.texts.forEach(t=>{const r=[];t.lines.forEach(t=>{r.push({x:Lo(Bo(t.box.left,n,s),2),y:Lo(Bo(t.box.top,n,s),2),width:Lo(Bo(t.box.width,n,s),2),height:Lo(Bo(t.box.height,n,s),2)})}),e.push({pageUid:o,text:i,rects:r,context:t.context})})}),this.context.emit("textSearchTriggered",e)},this),e.selectedPageChanged.on(t=>{this.context.viewer.emit("selectedPagesChanged",{oldIndices:t.oldIndices,newIndices:t.newIndices,oldPageUids:t.oldPageUids,newPageUids:t.newPageUids})},this),e.resize.on(t=>{this.context.viewer.emit("resized",{oldWidth:t.oldWidth,oldHeight:t.oldHeight,newWidth:t.newWidth,newHeight:t.newHeight})},this),e.pageRendered.on(t=>{this.context.emit("pageRendered",{index:t.index,pageUid:t.pageUid})},this),e.pagesDragged.on(e=>{t.viewer.emit("pagesDragged",{indices:e.indices,pageUids:e.pageUids})}),e.pagesDropped.on(e=>{t.viewer.emit("pagesDropped",{indicesBefore:e.indicesBefore,indicesAfter:e.indicesAfter,pageUids:e.pageUids})},this),e.visibleChanged.on(e=>{t.viewer.emit("visibilityChanged",{isVisible:"visible"===e.newVisibility})},this)}convertInternalHooks(){const{hooks:t}=this.context;t.pageChanged.on(e=>{const i=this.context.getActiveTab();let n;i&&0!==i.total?0===i.oldTotal&&i.total>0&&(n=e.total):n=0,Ps(n)||t.pageExistenceChanged.emit(pm.create(n))},this),t.pageChangedAfterRender.on(e=>{const i=this.context.getActiveTab();if(!i)return;const{current:n,oldCurrent:s,currentUid:o,oldCurrentUid:r}=i;if(s!==n){const e=zf.create(s,n);t.currentIndexChanged.emit(e)}r!==o&&t.currentPageChanged.emit(e)},this)}bindNativeEvents(){const{context:t}=this,{eventDom:e}=this.context;this.context.isCaptureViewer||(zo(e,"click",this).on(e=>{if(!t.hasCallback("click"))return;const i=this.formatEvent(e);t.emit("click",i)}),zo(e,"contextmenu",this).on(e=>{if(e.preventDefault(),!t.hasCallback("rightclick"))return;const i=this.formatEvent(e);t.emit("rightclick",i)}),zo(e,"pointerdown",this).on(e=>{if(!t.hasCallback("pointerdown"))return;const i=this.formatEvent(e);t.emit("pointerdown",i)}),zo(e,"pointermove",this).on(e=>{const i=this.formatEvent(e),{pageUid:n}=i;let s=-1;if(this.hoveredPageUid){const t=this.context.getActiveTab();t?s=t.uidToIndex(this.hoveredPageUid):this.hoveredPageUid=""}n&&this.hoveredPageUid&&n!==this.hoveredPageUid?(t.emit("pageout",{...i,pageUid:this.hoveredPageUid,index:s}),t.emit("pageover",i)):n&&n!==this.hoveredPageUid?t.emit("pageover",i):!n&&this.hoveredPageUid&&t.emit("pageout",{...i,pageUid:this.hoveredPageUid,index:s}),this.hoveredPageUid=n,t.emit("pointermove",i)}),zo(e,"pointerup",this).on(e=>{if(!t.hasCallback("pointerup"))return;const i=this.formatEvent(e);t.emit("pointerup",i)}),zo(e,"dblclick",this).on(e=>{if(!t.hasCallback("dblclick"))return;const i=this.formatEvent(e);t.emit("dblclick",i)}),zo(document.body,"dblclick",this).on(t=>{}))}bindFileDropEvents(){const{context:t}=this,{eventDom:e}=t;t.viewerConfig.enableLoadSourceByDrag&&!this.context.isCaptureViewer&&(zo(e,"dragenter",this).on(t=>{t.preventDefault()}),zo(e,"dragleave",this).on(t=>{t.preventDefault()}),zo(e,"drop",this).on(async t=>{var e,i;t.preventDefault();const n=null===(e=t.dataTransfer)||void 0===e?void 0:e.files;if(!n)return;let{viewer:s}=this.context;"thumbnail"===s.getViewerConfig().viewerMode&&this.context.mainViewerUid&&(s=this.context.core.viewerService.getViewer(this.context.mainViewerUid));const o=!0===(null===(i=s.popupConfig)||void 0===i||null===(i=i.passwordLoaderConfig)||void 0===i?void 0:i.enabled),r=n.length,a={renderAnnotations:lg.annotationLicenseModuleIsExist()?cu.LOAD_ANNOTATIONS:cu.NO_ANNOTATIONS},l="image"===this.context.viewerConfig.renderingMode?hu.CM_AUTO:hu.CM_RENDERALL;if(o)for(let t=0;t<r;t++){const e=new Blob([n[t]],{type:n[t].type});await s.context.core.isPdfEncrypted(e)?await new Promise(i=>{s.emit("ui_showPasswordLoader",{blob:e,fileName:n[t].name,resolve:i})}):s.context.loadSource({fileData:e,convertMode:l,renderOptions:a})}else{const t=[];for(let e=0;e<r;e++){const i=new Blob([n[e]],{type:n[e].type});"application/pdf"===n[e].type?t.push({fileData:i,convertMode:l,renderOptions:a}):t.push({fileData:i})}this.context.loadSource(t)}}),zo(e,"dragover",this).on(t=>{t.preventDefault()}))}formatEvent(t){var e,i;const[n]=this.context.toCanvas(t),s=this.context.getPointerOverPageInfo(n.pageX,n.pageY),o=Cr.displayResolution,r=Cr.dataResolution,{pointerX:a,pointerY:l}=s.imageInfo;return{index:s.index,pageUid:null!==(e=null===(i=s.pageInfo.page)||void 0===i?void 0:i.uid)&&void 0!==e?e:"",imageX:a<0?-1:Uo(Bo(a,o,r),2),imageY:l<0?-1:Uo(Bo(l,o,r),2),canvasX:Math.floor(n.pageX),canvasY:Math.floor(n.pageY),nativeEvent:t}}}class Kw extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"offsetX",0),Yi(this,"offsetY",0),Yi(this,"startX",0),Yi(this,"startY",0),Yi(this,"isDragging",!1),Yi(this,"startPage",void 0),Yi(this,"newIndexes",void 0),Yi(this,"cacheChildren",void 0),Yi(this,"cacheSelectedIndexes",void 0),Yi(this,"isMousedown",!1),Yi(this,"starDragIndices",[]),Yi(this,"autoScrollTimer",void 0),Yi(this,"isAutoScroll",!1),Yi(this,"lastAutoScrollEvent",void 0),this.context=t}dispose(){super.dispose(),this.context=null}startHandler(t){const{context:e}=this,{viewerConfig:i,styleService:n}=e;if("pan"!==i.toolMode)return;this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null);const s=e.getActiveTab();if(null==s||!s.total)return;this.isAutoScroll=!1,this.isMousedown=!0;const[o]=e.toCanvas(t),{page:r}=e.getPointerOverPageInfo(o.pageX,o.pageY).pageInfo;if(r&&r){this.startX=o.pageX,this.startY=o.pageY;const t=r.getPosition();this.offsetX=o.pageX-t.x,this.offsetY=o.pageY-t.y,this.startPage=r,this.cacheChildren=s.allPages.slice()}}moveHandler(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const{context:i}=this,n=i.getActiveTab();if(!n||!i.isThumbnailViewer)return;const[s]=i.toCanvas(t),o=i.getPointerOverPageInfo(s.pageX,s.pageY),{page:r}=o.pageInfo,a=this.context.rendererService.getCanvasDom().getBoundingClientRect();if(!e&&a.top<t.clientY&&a.bottom>t.clientY&&a.left<t.clientX&&a.right>t.clientX&&(this.lastAutoScrollEvent=t,this.autoScrollTimer&&!e&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null)),this.isDragging){var l,h,c;if(r&&!r.isSelected){const t=n.selected.map(t=>n.uidToIndex(t)).sort((t,e)=>t-e),e=t[0],s=n.getPageIndex(r),o=n.allPages.slice();t.slice().reverse().forEach(t=>{o.splice(t,1)});let a=o.indexOf(r);s>e&&(a+=1),this.cacheSelectedIndexes.forEach((t,e)=>{const i=n.getPageByUid(t.uid);o.splice(a+e,0,i)}),this.newIndexes=o.map(t=>n.getPageIndex(t)),n.reorderPages(this.newIndexes,!1),i.layoutService.layout(n,53),i.visibilityService.handleVisibility(n)}const t=i.styleService.getParsedPlaceholderStyle(),e=devicePixelRatio;let o=s.pageX-this.offsetX,a=s.pageY-this.offsetY;o=Math.round(o*e)/e,a=Math.round(a*e)/e,n.selected.forEach(e=>{const i=n.getPageByUid(e);i.isDragging=!0,i.updateStyle({...t}),i.borderBox.updateStyle({visibility:"hidden"})}),null===(l=this.startPage)||void 0===l||l.updateStyle({zIndex:1}),null===(h=this.startPage)||void 0===h||h.borderBox.updateStyle({visibility:"visible"}),null===(c=this.startPage)||void 0===c||c.borderBox.setPosition({x:o,y:a});const{maxScrollTop:d,maxScrollLeft:u}=n.context;(d||u)&&i.viewerConfig.enableAutoScrollForDragPages&&(this.isAutoScroll=!0),i.loadVisiblePages(n),i.rendererService.render(n,53)}else if(r&&r===this.startPage&&r.isSelected&&((s.pageX-this.startX)**2+(s.pageY-this.startY)**2)**.5>=i.viewerConfig.dragThreshold&&this.startPage&&i.viewerConfig.enableDragPage){this.isDragging=!0,this.cacheSelectedIndexes=n.selected.map(t=>({uid:t,index:n.uidToIndex(t)})).sort((t,e)=>t.index-e.index);const t=n.uidsToIndices(n.selected);this.starDragIndices=[...t],i.viewer.hooks.pagesDragged.emit(Cm.create(t,[...n.selected]))}}pointermoveForAutoScroll(t,e){this.isAutoScroll&&this.autoScroll(e)}autoScroll(t){const{context:e}=this,i=e.getActiveTab(),n=e.viewerConfig.autoScrollStepSize/devicePixelRatio*2,{maxScrollTop:s,scrollTop:o,maxScrollLeft:r,scrollLeft:a}=i.context;let l=!1;s&&t.top&&0!==o&&(l=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollTop:t,scrollTop:s}=i.context;t&&(0!==s?(e.viewService.scrollBy(0,-n),this.moveHandler(this.lastAutoScrollEvent,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),e.viewService.scrollBy(0,-n)),s&&t.bottom&&o!==s&&(l=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollTop:t,scrollTop:s}=i.context;t&&(s!==t?(e.viewService.scrollBy(0,n),this.moveHandler(this.lastAutoScrollEvent,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),e.viewService.scrollBy(0,n)),r&&t.left&&0!==a&&(l=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollLeft:t,scrollLeft:s}=i.context;t&&(0!==s?(e.viewService.scrollBy(-n,0),this.moveHandler(this.lastAutoScrollEvent,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),e.viewService.scrollBy(-n,0)),r&&t.right&&a!==r&&(l=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollLeft:t,scrollLeft:s}=i.context;t&&(s!==t?(e.viewService.scrollBy(n,0),this.moveHandler(this.lastAutoScrollEvent,!0)):(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),e.viewService.scrollBy(n,0)),this.autoScrollTimer&&!l&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null)}endHandler(){var t;if(!this.isMousedown)return;const{context:e}=this,i=e.getActiveTab();if(i){if(this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null),this.isAutoScroll=!1,this.isDragging){if(this.newIndexes){const t=i.allPages.map(t=>this.cacheChildren.indexOf(t));i.allPages=this.cacheChildren,i.freshPageIndex(),e.viewer.reorderPages(t),this.newIndexes=null}i.selected.forEach(t=>{const e=i.getPageByUid(t);e.borderBox.setLocalPosition({x:0,y:0}),e.isDragging=!1,e.borderBox.updateStyle({visibility:"visible"})});const t=i.uidsToIndices(i.selected);e.viewer.hooks.pagesDropped.emit(bm.create(this.starDragIndices,t,[...i.selected]))}null===(t=this.startPage)||void 0===t||t.updateStyle({zIndex:0}),this.isDragging&&(e.scrollByCurrentChanged=!0,e.layoutService.layout(i,54),e.visibilityService.handleVisibility(i),e.rendererService.render(i,54)),this.isMousedown=!1,this.startPage=null,this.isDragging=!1}}}class Qw extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"isStart",!1),Yi(this,"startX",void 0),Yi(this,"startY",void 0),Yi(this,"lastX",void 0),Yi(this,"lastY",void 0),Yi(this,"startTime",void 0),Yi(this,"startScrollLeft",void 0),Yi(this,"startScrollTop",void 0),Yi(this,"isScrolling",void 0),Yi(this,"scrollTimer",void 0),Yi(this,"scrollDirectionX","left"),Yi(this,"scrollDirectionY","top"),Yi(this,"canvasElX",void 0),Yi(this,"canvasElY",void 0),this.context=t,this.isScrolling=!1}startHandler(t){const{context:e}=this;if(e.isPanning||e.isZooming)return;const i=e.getActiveTab();if(null==i||!i.total)return;const n=e.toCanvas(t);if(n.length>1)return;this.canvasElX=t.screenX,this.canvasElY=t.screenY;const{pageX:s,pageY:o}=n[0];this.isStart=!0,this.startX=s,this.startY=o,this.lastX=s,this.lastY=o,this.startTime=(new Date).getTime();const{scrollLeft:r,scrollTop:a}=i.context;this.startScrollLeft=r,this.startScrollTop=a,this.isScrolling=!1,this.scrollTimer&&(Js.clearTimer(this.scrollTimer),this.scrollTimer=null)}moveHandler(t){if(!this.isStart)return;t instanceof PointerEvent&&t.cancelable&&t.preventDefault();const{context:e}=this;if(e.isZooming)return;const i=e.toCanvas(t);if(i.length>1)return;const n=e.getActiveTab(),{maxScrollLeft:s,maxScrollTop:o}=n.context;let{scrollLeft:r,scrollTop:a}=n.context;if(!s&&!o)return;const{viewerConfig:l}=e,{panThreshold:h,enablePanX:c,enablePanY:d}=l,{pageX:u,pageY:p}=i[0],g=u-this.startX,f=p-this.startY,m=u-this.lastX,v=p-this.lastY;if(e.isPanning){if(!r&&!a&&m>=0&&v>=0)return;if(r===s&&a===o&&m<=0&&v<=0)return;c&&(r=this.startScrollLeft-g),d&&(a=this.startScrollTop-f),r=Bs(r,0,s),a=Bs(a,0,o),e.viewService.scrollTo(r,a)}else e.isPanning=c&&Math.abs(g)>=h||d&&Math.abs(f)>=h;this.lastX=u,this.lastY=p}endHandler(t){if(!this.isStart)return;this.isStart=!1,this.context.isPanning=!1;const{context:e}=this,i=e.toCanvas(t,!0);if(i.length>1)return;if(e.isZooming)return;if(oy(t))return;if(this.canvasElX===t.screenX&&this.canvasElY===t.screenY)return;const{scrollLeft:n,scrollTop:s}=this.context.viewService.getMaxScrollValue(),{scrollLeft:o,scrollTop:r}=this.context.viewService.scrollContainer;if(!this.isScrolling&&(n>0||s>0)){const t=(new Date).getTime(),e=i[0].pageX,a=i[0].pageY,l=e-this.startX,h=a-this.startY;let c=!1,d=!1;l>0?(c=0!==o,this.scrollDirectionX="right"):(c=o!==n,this.scrollDirectionX="left"),h>0?(d=0!==r,this.scrollDirectionY="bottom"):(d=r!==s,this.scrollDirectionY="top");const u=t-this.startTime;if((Math.abs(l)>10||Math.abs(h)>10)&&u>0&&u<300&&(c||d)){let t=Math.abs(l)/u,e=Math.abs(h)/u;(t>.4||e>.4)&&(t=Math.min(t,2.8),e=Math.min(e,2.8),this.scroll(t,e,-.05))}}}scroll(t,e,i){this.isScrolling=!0;const{scrollLeft:n,scrollTop:s}=this.context.viewService.scrollContainer;let o=0,r=0;this.scrollTimer=Js.createTimer(()=>{const{scrollLeft:a,scrollTop:l}=this.context.viewService.getMaxScrollValue();if(t<=0&&e<=0||!1===this.isScrolling)return Js.clearTimer(this.scrollTimer),this.scrollTimer=null,void(this.isScrolling=!1);t>=0&&("right"===this.scrollDirectionX?o-=40*t:o+=40*t,t+=i),e>=0&&("bottom"===this.scrollDirectionY?r-=40*e:r+=40*e,e+=i);const h=Bs(n+o,0,a),c=Bs(s+r,0,l);this.context.viewService.scrollTo(h,c)},25)}}class tC extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"scrollTimer",void 0),Yi(this,"wheelPosition",void 0),Yi(this,"isMouseInCanvas",void 0),Yi(this,"scrollLoadTimer",void 0),this.context=t}scrollHandler(t){const{context:e}=this;if(e.scrollByCurrentChanged)return e.scrollByCurrentChanged=!1,void e.hooks.scroll.emit(t);const i=e.getActiveTab();if(null==i||!i.total)return;const{scrollLeft:n,scrollTop:s}=t.target;i.context.setTabScrollValue(n,s),e.visibilityService.handleVisibility(i),this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=setTimeout(()=>{if(!e.isDestroyed&&i.isActive){if(e.isDefaultViewer){if(i.context.updateReference(),i.context.isContinuousDisplay&&e.viewerConfig.autoChangeIndex){const t=i.context.getCurrentByScroll();null!==t&&(i.gotoPage(t),e.visibilityService.handleVisibility(i),e.emitPageChangedEvent(i),e.emitPageChangedAfterRenderEvent(i),e.core.viewerService.onCurrentChangedByScroll.emit(Mf.create(i.uid,e.groupUid,e.uid,t)))}e.loadVisiblePages(i)}else e.isThumbnailViewer&&e.loadVisiblePages(i);this.scrollTimer=null}},25),this.scrollLoadTimer||(this.scrollLoadTimer=setTimeout(()=>{this.scrollLoadTimer=null,e.loadVisiblePages(i)},20)),e.rendererService.render(i,55),e.hooks.scroll.emit(t)}handleHover(){if(!this.context.isThumbnailViewer||!this.wheelPosition)return;const[t]=this.context.toCanvas(this.wheelPosition),e=this.context.getPointerOverPageInfo(t.pageX,t.pageY),{page:i}=e.pageInfo;this.context.getActiveTab().preloadChildren.forEach(t=>{i&&i.uid===t.uid&&this.isMouseInCanvas?t.isHovered=!0:t.isHovered=!1}),this.isMouseInCanvas=!1,this.wheelPosition=null}wheelHandler(t){}wheelHandler1(t){if(!fo(t)&&!mo(t))return;this.wheelPosition=t;const e=this.context.isPointerOverCanvas(t);this.isMouseInCanvas=e;const{context:i}=this,n=i.getActiveTab(),{maxScrollLeft:s,maxScrollTop:o,scrollLeft:r,scrollTop:a}=n.context;let{wheelDelta:l}=t;t.deltaY&&(l=-t.deltaY),1===t.deltaMode?l*=16:2===t.deltaMode&&(l=l<0?-100:100),t.shiftKey&&s?(l>0&&0!==r||l<0&&r!==s)&&(t.cancelable&&t.preventDefault(),i.scrollByCurrentChanged=!1,i.viewService.scrollBy(-l,0)):o&&(l<0&&a!==o||l>0&&0!==a)&&(t.cancelable&&t.preventDefault(),i.scrollByCurrentChanged=!1,i.viewService.scrollBy(0,-l))}}class eC extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"wheelTimer",void 0),Yi(this,"isStart",void 0),Yi(this,"isZooming",void 0),Yi(this,"startDistance",void 0),Yi(this,"touchZoomTimer",void 0),Yi(this,"startZoom",void 0),this.context=t,this.isZooming=!1,this.isStart=!1,this.startZoom=1}zoomTo(t,e,i){var n;t=ny(t);const{context:s}=this;if(!s.isDefaultViewer)return;const o=s.getActiveTab();if(null==o||!o.total)return;const{viewerConfig:r}=s;t=Bs(t,r.minZoom,r.maxZoom),Ls(e)&&Ls(i)||({originX:e,originY:i}=o.context.getZoomOriginCord());const a=null===(n=o.context.placeholderPages)||void 0===n?void 0:n.length;let l;a&&(l=o.context.generateReference(e,i));const h=o.context.zoom;if(o.context.setZoom(t),r.zoom=t,o.context.isZoomChanged=!0,a){s.layoutService.layout(o,57),s.viewService.updateScrollerContentSize(o),s.rendererService.updateCanvasSize();const{scrollLeft:t,scrollTop:n}=o.context.parseReferenceZoom(l,e,i);o.context.setTabScrollValue(t,n),s.viewService.scrollTo(t,n),s.visibilityService.handleVisibility(o),s.loadVisiblePages(o),s.clearCurrentTabOptimization(),s.loadVisiblePartData(),s.rendererService.render(o,57)}o.context.oldZoom=h,s.emitZoomChangedEvent(o)}wheelHandler(t){const{viewerConfig:e}=this.context;if(e.enableZoom&&e.enableZoomWithCtrl&&go(t)){let{wheelDelta:i}=t;t.deltaY&&(i=-t.deltaY),t.cancelable&&t.preventDefault(),this.wheelTimer||(this.wheelTimer=setTimeout(()=>{clearTimeout(this.wheelTimer),this.wheelTimer=null;const n=e.wheelZoomFactor||1,s=i>0?n:1/n,{left:o,top:r}=this.context.rendererService.getCanvasPageRect();this.zoomTo(e.zoom*s,t.pageX-o,t.pageY-r)},40))}}touchstartHandler(t){const{context:e}=this,i=e.getActiveTab(),{displayMode:n}=i.context,s="continuous"===n||"single"===n;if(!e.viewerConfig.enableZoom||!s)return;const o=e.toCanvas(t);o.length<2||(e.isZooming=!0,this.startZoom=i.context.zoom,this.startDistance=iC(o),this.isStart=!0)}touchmoveHandler(t){if(!this.isStart)return;t.cancelable&&t.preventDefault();const{context:e}=this,i=e.toCanvas(t);if(i.length<2)return;const n=(i[0].pageX+i[1].pageX)/2,s=(i[0].pageY+i[1].pageY)/2;let o=iC(i)/this.startDistance;t.scale&&(o=t.scale);const r=e.getActiveTab();let{zoom:a}=r.context;const l=a;a=this.startZoom*o,a!==l&&(this.touchZoomTimer||(this.touchZoomTimer=setTimeout(()=>{this.zoomTo(a,n,s),clearTimeout(this.touchZoomTimer),this.touchZoomTimer=null},25))),e.isZooming=!0}touchendHandler(t){this.isStart&&(this.isStart=!1,this.startZoom=1,this.context.isZooming=!1)}tapZoomHandler(t){const{toolMode:e,enableZoom:i,tapZoomFactor:n}=this.context.viewerConfig;if(!i)return;const s="zoomIn"===e,o="zoomOut"===e;if(!s&&!o)return;const r=this.context.toCanvas(t);if(r.length>1)return;const a=this.context.getActiveTab();let{zoom:l}=a.context;s?l*=n||1:o&&(l/=n||1),this.zoomTo(l,r[0].pageX,r[0].pageY)}}function iC(t){return((t[0].pageX-t[1].pageX)**2+(t[0].pageY-t[1].pageY)**2)**.5}class nC extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"isStart",!1),Yi(this,"startX",void 0),Yi(this,"isSliding",void 0),Yi(this,"slideDistance",void 0),Yi(this,"slideDirection",void 0),Yi(this,"slideRAF",void 0),Yi(this,"tabX",void 0),Yi(this,"tabY",void 0),this.context=t,this.isSliding=!1}startHandler(t){if(!this.context.viewerConfig.enableSlide)return;if(this.isSliding)return;const e=this.context.getActiveTab();if(null==e||!e.total)return;const{scrollLeft:i,scrollTop:n}=this.context.viewService.getMaxScrollValue();if(i>0||n>0)return;const s=this.context.toCanvas(t);if(s.length>1)return;const o=e.getPosition();this.tabX=o.x,this.tabY=o.y,this.startX=s[0].pageX,this.isStart=!0}moveHandler(t){if(!this.isStart)return;const{context:e}=this,i=e.getActiveTab(),n=e.toCanvas(t)[0].pageX-this.startX;if(n>0?this.slideDirection="right":n<0&&(this.slideDirection="left"),this.slideDistance=Math.min(i.context.viewportWidth,Math.abs(n)),this.isSliding)"right"===this.slideDirection?i.setPosition({x:this.slideDistance+this.tabX,y:this.tabY,z:0}):"left"===this.slideDirection&&i.setPosition({x:-this.slideDistance+this.tabX,y:this.tabY,z:0}),e.render(42);else if("single"===i.context.displayMode&&"pan"===e.viewerConfig.toolMode&&e.viewerConfig.enableSlide){const{scrollLeft:t,scrollTop:i}=this.context.viewService.getMaxScrollValue();Math.abs(n)>e.viewerConfig.startSlideThreshold&&t<=0&&i<=0&&(this.isSliding=!0,this.context.isSliding=!0,e.configService.updateConfig({displayMode:"slide"}))}}endHandler(t){if(!this.isStart)return;const{context:e}=this;this.context.toCanvas(t,!0);const i=e.getActiveTab(),{displayMode:n}=i.context;"slide"===n&&this.slide(i),this.isStart=!1}slide(t){let e,i=0,n=0,s=0,o=!1;const{viewerConfig:r}=this.context,a=t.context.viewportWidth*r.slideThresholdForPerspective;this.slideDistance>=Math.max(a,r.startSlideThreshold)?(n=t.context.viewportWidth,e=n-this.slideDistance,"left"===this.slideDirection?t.current!==t.total-1?(s=-this.slideDistance,i=-e/6):(n=0,e=this.slideDistance,o=!0,s=-this.slideDistance,i=e/6):0!==t.current?(s=this.slideDistance,i=e/6):(n=0,e=this.slideDistance,o=!0,s=this.slideDistance,i=-e/6)):(o=!0,n=0,e=this.slideDistance,"left"===this.slideDirection?(s=-this.slideDistance,i=e/6):(s=this.slideDistance,i=-e/6));const l=()=>{s+=i;const e=s>=0;if(Math.abs(s)>=n&&(s=n,e||(s*=-1)),t.setPosition({x:s+this.tabX,y:this.tabY,z:0}),Math.abs(s)===n)return o||("right"===this.slideDirection?this.context.viewer.gotoPage(t.current-1):this.context.viewer.gotoPage(t.current+1),this.context.configService.updateConfig({fitMode:"window"})),this.isSliding=!1,this.context.isSliding=!1,this.context.configService.updateConfig({displayMode:"single"}),void cancelAnimationFrame(this.slideRAF);this.slideRAF=requestAnimationFrame(l),this.context.render(43)};this.slideRAF=requestAnimationFrame(l)}}class sC extends Wo{constructor(t){super(),Yi(this,"context",void 0),this.context=t}handleOptimizationEvents(){let t;this.context.hooks.afterRender.on(e=>{"image"===this.context.viewerConfig.renderingMode&&this.context.viewerConfig.enableOptimizePage&&(Ms()||(t&&(clearTimeout(t),t=null),t=setTimeout(()=>{this.optimizeTab(e),t=null},500)))})}dispose(){super.dispose(),this.context=null}optimizeTab(t){t.visibleChildren.forEach(t=>{!t.isOptimized&&t.isVisible&&t.isLoaded&&setTimeout(()=>{!t.isOptimized&&t.isVisible&&t.isLoaded&&this.optimizePage(t.uid)},500)})}cancelOptimization(t){this.context.core.optimizationService.cancel(t)}optimizePage(t){if(!this.context)return;const{context:e}=this,{viewerConfig:i}=e;if(!i.enableOptimizePage)return;const n=e.getActiveTab();if(null==n||!n.total)return;const s=n.getPageByUid(t);if(!s)return;if(s.isOptimized||!s.isVisible||!s.isLoaded||s.optimizationUid===s.optimizedUid||e.isSliding||e.isDestroyed)return;const o=e.core.pageService.getPage(t);if(null==o||!o.display.img)return;const{img:r}=s.image.style;if(!r)return;const{naturalWidth:a,naturalHeight:l}=r;let h=a,c=l;const{maxOptimizationSize:d}=i;if(h>d||c>d||s.rWidth>d||s.rHeight>d)return;let u=0,p=0,g=0,f=0,m=0;({rWidth:h,rHeight:c,cropLeft:u,cropTop:p,cropWidth:g,cropHeight:f,rotation:m}=o.getEditResultForPixel());const v=devicePixelRatio,y=Math.floor(s.realTimeBox.width*v+.5)||1,x=Math.floor(s.realTimeBox.height*v+.5)||1;y>h||x>c||e.core.optimizationService.optimize(s.optimizationUid,()=>{const t=Bo(o.mediaBox.left,Cr.displayResolution,o.resource.resolutionX),n=Bo(o.mediaBox.top,Cr.displayResolution,o.resource.resolutionX),d=new _l({style:{x:-u+t,y:-p+n,img:r,width:a,height:l}});let v="rgba(0,0,0,0)";if(i.enableFillColor)v=i.blankFillColor;else if(i.viewerMode===jg.THUMBNAIL){let t=i.pageStyle;s.isSelected?t=i.selectedPageStyle:s.isHovered&&(t=i.hoveredPageStyle),v=t.background}const w=new Ll({style:{x:-(g-h)/2,y:-(f-c)/2,width:g,height:f,background:v}});w.appendChild(d),w.setLocalAngle(m);const{commonCanvas:C}=e.core;C.render(w,h,c),C.reset();const b=C.getCanvas();s.isOptimized=!0;const S=b.getContext("2d"),T=Math.floor(h)||1,E=Math.floor(c)||1,_=S.getImageData(0,0,T,E);return{sourceWidth:T,sourceHeight:E,width:Math.ceil(y)||1,height:Math.ceil(x)||1,source:_,taskUid:s.optimizationUid}}).then(t=>{if(!e.isDestroyed&&s.isVisible&&t.taskUid===s.optimizationUid){s.isOptimized=!0,s.optimizedUid=s.optimizationUid;const i=e.core.commonCanvas.getCanvas().getContext("2d",{willReadFrequently:!0}).createImageData(y,x);i.data.set(t.target),s.realTimeBox.imageData=i,s.image.updateStyle({visibility:"hidden"}),s.isVisible&&e.render(41)}}).catch(t=>{s.isOptimized=!1})}}class oC extends Wo{constructor(t,e,i,n,s,o,r){super(),Yi(this,"context",void 0),Yi(this,"panModeInteraction",void 0),Yi(this,"cropModeInteraction",void 0),Yi(this,"annotationModeInteraction",void 0),Yi(this,"zoomInModeInteraction",void 0),Yi(this,"zoomOutModeInteraction",void 0),Yi(this,"textSelectionModeInteraction",void 0),this.context=t,this.panModeInteraction=e,this.cropModeInteraction=i,this.annotationModeInteraction=n,this.zoomInModeInteraction=s,this.zoomOutModeInteraction=o,this.textSelectionModeInteraction=r}handleEvents(){if(this.context.isCaptureViewer)return;const{eventDom:t}=this.context;zo(t,"pointerdown",this).on(t=>{if(this.context.isPointerWorking=!0,0!==t.button)return;const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.pointerdownHandler(t),this.cropModeInteraction.pointerdownHandler(t),this.annotationModeInteraction.pointerdownHandler(t),this.zoomInModeInteraction.startHandler(t),this.zoomOutModeInteraction.startHandler(t),this.textSelectionModeInteraction.pointerdownHandler(t))}),zo(t,"pointermove",this).on(t=>{const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.pointermoveHandler(t,!1),this.cropModeInteraction.pointermoveHandler(t),this.panModeInteraction.cursorHandler(t),this.zoomInModeInteraction.moveHandler(t),this.zoomOutModeInteraction.moveHandler(t),this.textSelectionModeInteraction.pointermoveHandler(t))},{passive:!1}),zo(t,"pointerup",this).on(t=>{if(this.context.isPointerWorking=!1,0!==t.button)return;const e=this.context.getActiveTab();null!=e&&e.total&&this.panModeInteraction.pointerupHandler(t)}),zo(document,"pointerdown",this).on(t=>{this.context.isPointerWorking=!0}),zo(document,"pointermove",this).on(t=>{const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.pointermoveHandler(t,!0),this.panModeInteraction.pointerMoveForAutoScroll(t),this.annotationModeInteraction.pointermoveHandler(t),this.annotationModeInteraction.cursorHandler(t),this.textSelectionModeInteraction.pointerMoveForAutoScroll(t))},{passive:!1}),zo(document,"pointerup",this).on(t=>{if(this.context.isPointerWorking=!1,0!==t.button)return;const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.pointerupHandler(t),this.cropModeInteraction.pointerupHandler(t),this.annotationModeInteraction.pointerupHandler(t),this.zoomInModeInteraction.endHandler(t),this.zoomOutModeInteraction.endHandler(t),this.textSelectionModeInteraction.pointerupHandler(t))}),zo(document,"visibilitychange",this).on(t=>{this.annotationModeInteraction.visibilityChangedHandler(),this.cropModeInteraction.visibilityChangedHandler(),this.panModeInteraction.visibilityChangedHandler(),this.textSelectionModeInteraction.visibilityChangedHandler()}),zo(t,"touchstart",this).on(t=>{const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.touchstartHandler(t),this.cropModeInteraction.touchstartHandler(t),this.textSelectionModeInteraction.touchstartHandler(t))},{passive:!1}),zo(t,"touchmove",this).on(t=>{const e=this.context.getActiveTab();null!=e&&e.total&&(t.cancelable&&t.preventDefault(),this.panModeInteraction.touchmoveHandler(t),this.cropModeInteraction.touchmoveHandler(t),this.textSelectionModeInteraction.touchmoveHandler(t))},{passive:!1}),zo(t,"touchend",this).on(t=>{const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.touchendHandler(t),this.cropModeInteraction.touchendHandler(t),this.textSelectionModeInteraction.touchendHandler(t))}),zo(t,"wheel",this).on(t=>{const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.wheelHandler(t),this.cropModeInteraction.wheelHandler(t),this.annotationModeInteraction.wheelHandler(t),this.textSelectionModeInteraction.wheelHandler(t))},{passive:!1}),zo(this.context.viewService.scrollContainer,"scroll",this).on(t=>{const e=this.context.getActiveTab();null!=e&&e.total&&(this.panModeInteraction.scrollHandler(t),this.cropModeInteraction.scrollHandler(t),this.annotationModeInteraction.scrollHandler(t),this.textSelectionModeInteraction.scrollHandler(t))}),zo(document,"keydown",this).on(t=>{if(!this.context.isFocusCanvas||!this.context.viewerConfig.enableKeyboardInteraction)return;const e=this.context.getActiveTab();null!=e&&e.total&&((t.ctrlKey||t.metaKey)&&"a"===t.key.toLowerCase()&&t.preventDefault(),this.panModeInteraction.keydownHandler(t),this.cropModeInteraction.keydownHandler(t),this.annotationModeInteraction.keydownHandler(t),this.zoomInModeInteraction.keydownHandler(t),this.zoomOutModeInteraction.keydownHandler(t),this.textSelectionModeInteraction.keydownHandler(t))}),zo(document,"keyup",this).on(t=>{this.context.isFocusCanvas&&this.context.viewerConfig.enableKeyboardInteraction&&this.context.getActiveTab()&&(this.panModeInteraction.keyupHandler(t),this.annotationModeInteraction.keyupHandler(t))}),zo(document,"pointerdown",this).on(t=>{var e;if(this.context.isDestroyed)return;if("hidden"===this.context.viewerConfig.visibility)return;if(t.target instanceof HTMLInputElement)return void(this.context.isFocusCanvas=!1);if(this.context.viewerConfig.hasThb&&this.context.viewService.thumbnailContainer.contains(t.target))return void(this.context.isFocusCanvas=!1);let i=!(null===(e=this.context.viewService.rootDom)||void 0===e||!e.contains(t.target));i||document.body.contains(t.target)||!this.context.isDefaultViewer||(i=!0),this.context.isFocusCanvas=i})}}class rC extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"isPointerdown",!1),Yi(this,"startPage",void 0),Yi(this,"mouseOverPage",void 0),Yi(this,"lastMoveEvent",void 0),this.context=t,this.context.hooks.scroll.on(t=>{if(this.context.isThumbnailViewer){const t=this.context.getActiveTab();if(null==t||!t.total)return;this.lastMoveEvent&&this.moveHandler(this.lastMoveEvent)}},this)}startHandler(t){const{context:e}=this,{viewerConfig:i,styleService:n}=e,s=this.context.getActiveTab();if(null==s||!s.total)return;this.isPointerdown=!0;const[o]=e.toCanvas(t),{page:r}=e.getPointerOverPageInfo(o.pageX,o.pageY).pageInfo;if(!r)return;if(this.startPage=r,!mo(t)&&!fo(t))return;const a=s.getPageIndex(r),l=s.getCurrentPage(),h=t.shiftKey&&i.enableSelectWithShift;if(h&&s.selected.length){if(h&&l!==r&&s.shiftReference){const t=s.uidToIndex(s.shiftReference),i=Math.min(a,t),n=Math.max(a,t),o=[];for(let t=i;t<=n;t++)o.push(t);a<t&&o.reverse();const{shiftReference:r}=s;e.viewer.gotoPage(a),s.shiftReference=r,e.viewer.selectPagesByIndices(o)}}else i.multiselectMode||(r.uid!==s.currentUid?e.viewer.gotoPage(a):s.shiftReference=r.uid,r.isSelected||e.viewer.selectPagesByIndices([a]))}moveHandler(t){var e;const{context:i}=this,{styleService:n}=i;if(!oy(t))return;const s=i.getActiveTab();if(null==s||!s.total)return;if(this.context.isPointerOverCanvas(t)?this.lastMoveEvent=t:this.lastMoveEvent=null,t.target!==this.context.eventDom&&!s.hoveredPage)return;const[o]=i.toCanvas(t),r=i.getPointerOverPageInfo(o.pageX,o.pageY),{page:a}=r.pageInfo,{mouseOverPage:l}=this;i.viewerConfig.enableOptimizePage&&!n.isBorderWidthEqualHovered()&&(l&&!l.isSelected&&(a&&l===a||i.clearOptimization([l.uid])),a&&!a.isSelected&&(l&&l===a||i.clearOptimization([a.uid]))),this.mouseOverPage=a;let h=!1;oy(t)?s.hoveredPage?a?s.hoveredPage.uid!==a.uid&&(s.hoveredPage.isHovered=!1,s.hoveredPage=a,a.isHovered=!0,h=!0):(s.hoveredPage.isHovered=!1,s.hoveredPage=null,h=!0):a&&(s.hoveredPage=a,s.hoveredPage.isHovered=!0,h=!0):null!==(e=s.hoveredPage)&&void 0!==e&&e.isHovered&&(s.hoveredPage.isHovered=!1),h&&(i.layoutService.layout(s,56),i.visibilityService.handleVisibility(s),i.loadVisiblePartData(),i.rendererService.render(s,56))}endHandler(t){if(!this.isPointerdown)return;const{context:e}=this,[i]=e.toCanvas(t,!0),n=e.getActiveTab();if(null==n||!n.total)return;const s=e.getPointerOverPageInfo(i.pageX,i.pageY).pageInfo.page;if(s&&s===this.startPage)if(po(t)&&e.viewerConfig.enableSelectWithCtrl||e.viewerConfig.multiselectMode){const t=n.selected.slice(),i=t.indexOf(s.uid);s.isSelected?t.splice(i,1):t.push(s.uid);const o=n.uidsToIndices(t);if(s.uid!==n.currentUid){const t=n.uidToIndex(s.uid);e.viewer.gotoPage(t)}e.viewer.selectPagesByIndices(o)}else if(!vo(t)){const t=n.getPageIndex(s);s.uid!==n.currentUid&&e.viewer.gotoPage(t),e.viewer.selectPagesByIndices([t])}this.isPointerdown=!1,this.startPage=null}keydownHandler(t){}}class aC extends Wo{constructor(t){super(),Yi(this,"context",void 0),this.context=t}selectAllHandler(t){this.context.viewerConfig.enableSelectAllWithKeyboard&&po(t)&&this.context.isThumbnailViewer&&(t.preventDefault(),this.context.viewer.selectAllPages())}undoHandler(t){this.context.viewerConfig.enableUndoWithKeyboard&&po(t)&&(t.preventDefault(),this.context.viewer.undo())}redoHandler(t){this.context.viewerConfig.enableRedoWithKeyboard&&po(t)&&(t.preventDefault(),this.context.viewer.redo())}zoomInHandler(t){this.context.viewerConfig.enableZoomInWithKeyboard&&po(t)&&(t.preventDefault(),this.context.viewer.zoomIn())}zoomOutHandler(t){this.context.viewerConfig.enableZoomOutWithKeyboard&&po(t)&&(t.preventDefault(),this.context.viewer.zoomOut())}arrowLeftHandler(t){const{context:e}=this;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const i=e.getActiveTab(),{maxScrollLeft:n,currentViewportWidth:s,scrollLeft:o}=i.context;t.preventDefault();const r=s/30;if(e.isDefaultViewer)mo(t)?0!==i.current&&e.viewer.gotoPage(i.current-1):fo(t)&&(n?0===o?0!==i.current&&e.viewer.gotoPage(i.current-1):(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(-r,0)):0!==i.current&&e.viewer.gotoPage(i.current-1));else if(e.isThumbnailViewer){if(vo(t))return;0!==i.current&&e.viewer.gotoPage(i.current-1)}}arrowRightHandler(t){const{context:e}=this;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const i=e.getActiveTab(),{maxScrollLeft:n,currentViewportWidth:s,scrollLeft:o}=i.context;t.preventDefault();const r=s/30;if(e.isDefaultViewer)mo(t)?i.current!==i.total-1&&e.viewer.gotoPage(i.current+1):fo(t)&&(n?o===n?i.current!==i.total-1&&e.viewer.gotoPage(i.current+1):(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(r,0)):i.current!==i.total-1&&e.viewer.gotoPage(i.current+1));else if(e.isThumbnailViewer){if(vo(t))return;i.current!==i.total-1&&e.viewer.gotoPage(i.current+1)}}arrowUpHandler(t){const{context:e}=this;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const i=e.getActiveTab(),{maxScrollTop:n,currentViewportHeight:s,scrollTop:o}=i.context;t.preventDefault();const r=s/30;if(e.isDefaultViewer)mo(t)&&(n?0===o?0!==i.current&&e.viewer.gotoPage(i.current-1):(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(0,-r)):0!==i.current&&e.viewer.gotoPage(i.current-1));else if(e.isThumbnailViewer){if(vo(t))return;const{rows:n,columns:s}=i.context,{current:o}=i,r=Math.floor(o/s),a=o%s;0===r?0!==i.current&&e.viewer.gotoPage(i.current-1):e.viewer.gotoPage(s*(r-1)+a)}}arrowDownHandler(t){const{context:e}=this;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const i=e.getActiveTab(),{maxScrollTop:n,currentViewportHeight:s,scrollTop:o}=i.context;t.preventDefault();const r=s/30;if(e.isDefaultViewer)mo(t)&&(n?o===n?i.current!==i.total-1&&e.viewer.gotoPage(i.current+1):(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(0,r)):i.current!==i.total-1&&e.viewer.gotoPage(i.current+1));else if(e.isThumbnailViewer){if(vo(t))return;const{rows:n,columns:s}=i.context,{current:o}=i,r=Math.floor(o/s),a=o%s;if(r===Math.floor((i.total-1)/s))0!==i.current&&e.viewer.gotoPage(i.current+1);else{const t=Math.min(i.total-1,s*(r+1)+a);e.viewer.gotoPage(t)}}}escapeHandler(t){vo(t)||(t.preventDefault(),this.context.viewer.updateViewerConfig({toolMode:"pan"}))}enterHandler(t){vo(t)||t.preventDefault()}pageUpHandler(t){if(vo(t))return;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const{context:e}=this,i=e.getActiveTab(),{maxScrollTop:n,currentViewportHeight:s,scrollTop:o,scrollLeft:r}=i.context;t.preventDefault(),e.isDefaultViewer&&("single"===i.context.displayMode?n&&0!==o?(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(0,-s)):0!==i.current&&(e.viewer.gotoPage(i.current-1),e.scrollByCurrentChanged=!1,e.viewService.scrollBy(r-i.context.scrollLeft,n)):"continuous"===i.context.displayMode&&n&&0!==o&&(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(0,-s)))}pageDownHandler(t){if(vo(t))return;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const{context:e}=this,i=e.getActiveTab(),{maxScrollTop:n,currentViewportHeight:s,scrollTop:o,scrollLeft:r}=i.context;t.preventDefault(),e.isDefaultViewer&&("single"===i.context.displayMode?n&&o!==n?(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(0,s)):i.current!==i.total-1&&(e.viewer.gotoPage(i.current+1),e.scrollByCurrentChanged=!1,e.viewService.scrollBy(r-i.context.scrollLeft,0)):"continuous"===i.context.displayMode&&n&&o!==n&&(e.scrollByCurrentChanged=!1,e.viewService.scrollBy(0,s)))}homeHandler(t){if(vo(t))return;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const{context:e}=this,i=e.getActiveTab();i.context,t.preventDefault(),e.isDefaultViewer?0!==i.current&&e.viewer.gotoPage(0):e.isThumbnailViewer&&0!==i.current&&e.viewer.gotoPage(0)}endHandler(t){if(vo(t))return;if(t.preventDefault(),!this.context.viewerConfig.enableSelectPageWithKeyboard)return;const{context:e}=this,i=e.getActiveTab();i.context,t.preventDefault(),e.isDefaultViewer?i.current!==i.total-1&&e.viewer.gotoPage(i.total-1):e.isThumbnailViewer&&i.current!==i.total-1&&e.viewer.gotoPage(i.total-1)}}class lC{constructor(t){Yi(this,"context",void 0),Yi(this,"isEditAnnotation",!1),Yi(this,"isMove",!1),Yi(this,"isSlide",!1),Yi(this,"isActivateAnnotation",!1),Yi(this,"isTouchstart",!1),Yi(this,"isPointerdown",!1),Yi(this,"isFirstMove",!0),Yi(this,"isPointerOnAnnotation",!1),Yi(this,"isAnnotationActive",!1),Yi(this,"activeShape",void 0),Yi(this,"pointerNum",0),Yi(this,"startPoint",void 0),Yi(this,"dragTimer",void 0),Yi(this,"isDragPages",!1),Yi(this,"isMoveForThumbnail",!1),Yi(this,"isMoved",!1),Yi(this,"canScroll",!0),Yi(this,"startX",void 0),Yi(this,"startY",void 0),Yi(this,"isTextSelectionMode",!1),Yi(this,"isStartTextSelection",!1),Yi(this,"startTextPosition",void 0),Yi(this,"endTextPosition",void 0),Yi(this,"textSelectionTimer",void 0),Yi(this,"textSelectionTimerMobile",void 0),Yi(this,"isEditTextStart",!1),Yi(this,"isEditTextEnd",!1),Yi(this,"isMovedForTextSelection",!1),Yi(this,"isZoomedForTextSelection",!1),Yi(this,"textSelectionThreshold",1),Yi(this,"activeAnnotationThreshold",1),Yi(this,"moveThreshold",2),Yi(this,"slideThreshold",10),Yi(this,"clearSelectionTimerThreshold",3),Yi(this,"hasSelectedText",!1),Yi(this,"textPages",[]),Yi(this,"canPan",!1),Yi(this,"canvas",void 0),Yi(this,"clickTimer",void 0),Yi(this,"clickCount",0),Yi(this,"lastClickPoint",void 0),Yi(this,"isOverTextCtrlPoint",!1),Yi(this,"needRenderMagnifier",!1),Yi(this,"magnifierPoint",void 0),Yi(this,"isMovedForMultiClick",!1),Yi(this,"isHitTextCtrlPoint",!1),Yi(this,"autoScrollTimer",void 0),Yi(this,"hitPage",void 0),Yi(this,"isAutoScroll",!1),Yi(this,"lastAutoScrollEvent",void 0),Yi(this,"lastMoveEvent",void 0),this.context=t,this.canvas=this.context.rendererService.getCanvasDom(),this.context.hooks.afterRender.on(()=>{this.needRenderMagnifier&&this.context.magnifierService.render("text",this.canvas,this.magnifierPoint)},this.context)}get isPanMode(){return"pan"===this.context.viewerConfig.toolMode}pointerdownHandler(t){if(this.isPointerdown||!this.isPanMode)return;const e=this.context.getActiveTab();if(null==e||!e.total)return;if("slide"===e.context.displayMode)return;if(!this.context.isPointerOverCanvas(t))return;this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null);const{isDefaultViewer:i,isThumbnailViewer:n,viewService:s,hasAnnotationModule:o,annotationEditService:r,selectPagesService:a,moveService:l,dragService:h,slideService:c,viewerConfig:{dragStartTimeThreshold:d,enableSlide:u,enableDragPage:p}}=this.context,{displayMode:g}=e.context;if(this.isPointerdown=!0,this.isFirstMove=!0,i){this.isAutoScroll=!1,this.isMovedForMultiClick=!1;const[i]=this.context.toCanvas(t);this.startPoint={x:i.pageX,y:i.pageY};const{page:n}=this.context.getPointerOverPageInfo(i.pageX,i.pageY).pageInfo;if(n){const s=this.context.core.pageService.getPage(n.uid),a=fw(n.mediaBox,i.pageX,i.pageY,n.rotation),l={x:a.pointerX,y:a.pointerY};if(this.context.viewerConfig.enableTextSelection&&null!=s&&s.isTextPage&&s.visibleLines&&e.hasSelectedTexts()){const e=n.isPointOnTextStart(l),s=n.isPointOnTextEnd(l),o=!oy(t);if((e||s)&&this.clickCount<1)return this.isHitTextCtrlPoint=!0,this.isEditTextStart=e,this.isEditTextEnd=s,this.context.hooks.beforeTextSelected.emit(),void(o&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:i.pageX,y:i.pageY},this.context.render(29)))}else if(o){if(n){let{x:t,y:e}=n.cropBox.getPosition(),{width:i,height:s}=n.cropBox;const o=(n.rotation%360+360)%360/90;if(1===o?t-=s:2===o?(t-=i,e-=s):3===o&&(e-=i),1===o||3===o){const t=i;i=s,s=t}r.setAnnotationContainer(n),r.setAnnotationInteractionArea({left:t,top:e,width:i,height:s})}const{isHit:e,shape:i,isHitSelected:s}=this.context.annotationEditService.isHitAnnotation(t);e&&n?(this.activeShape=i,this.isPointerOnAnnotation=!0,oy(t)?oy(t)&&(this.isAnnotationActive=!0,this.isEditAnnotation=!0,r.startHandler(t,!0)):s?(this.isAnnotationActive=!0,this.isEditAnnotation=!0,r.startHandler(t,!1)):(this.isActivateAnnotation=!0,r.deactivateAnnotation()),r.hasActiveAnnotation()&&(this.canScroll=!1)):r.deactivateAnnotation()}if(!this.isPointerOnAnnotation&&this.context.viewerConfig.enableTextSelection&&null!=s&&s.isTextPage&&s.visibleLines&&!this.isHitTextCtrlPoint)if(oy(t)){if(oy(t)&&this.isTextSelectionMode){const t=this.context.calcTextStartPosition({x:i.pageX,y:i.pageY},n);if(t&&(this.isStartTextSelection=!0,this.startTextPosition=t,this.context.textSelectionService.clearSelectedTexts(),this.context.hooks.beforeTextSelected.emit()),this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null),this.clickTimer=setTimeout(()=>{this.clickCount=0,this.clickTimer=null},this.context.viewerConfig.multipleClickTimeout),this.clickCount>0)if(this.lastClickPoint.x===i.pageX&&this.lastClickPoint.y===i.pageY){const i=e.uidToIndex(n.uid);1===this.clickCount?t&&this.selectClickedText(t.lineUid,l,n.uid,i,!0):this.clickCount>1&&t&&this.selectClickedText(t.lineUid,l,n.uid,i,!1),this.clickCount+=1}else this.clickCount=1,this.lastClickPoint={x:i.pageX,y:i.pageY};else this.clickCount=1,this.lastClickPoint={x:i.pageX,y:i.pageY}}}else!this.isStartTextSelection&&this.pointerNum<2&&(this.textSelectionTimerMobile&&clearTimeout(this.textSelectionTimerMobile),this.textSelectionTimerMobile=setTimeout(()=>{if(this.pointerNum>1)return;clearTimeout(this.textSelectionTimerMobile),this.textSelectionTimerMobile=null;const t=this.context.calcTextStartPosition({x:i.pageX,y:i.pageY},n);if(t){this.isTextSelectionMode=!0,this.isStartTextSelection=!0,this.context.textSelectionService.clearSelectedTexts(),this.startTextPosition=t,this.endTextPosition=t;const{textPages:n,startCharRect:s,endCharRect:o,startTextPosition:r,endTextPosition:a}=this.context.textSelectionService.calcSelectedText(this.startTextPosition,this.endTextPosition);e.setTextSelection(n,s,o,r,a),this.hasSelectedText=!0,this.textPages=n,this.context.viewerConfig.enableTextMagnifier&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:i.pageX,y:i.pageY}),this.context.render(30),this.context.hooks.beforeTextSelected.emit()}},this.context.viewerConfig.enterTextModeTimeMobile))}else r.deactivateAnnotation();if(this.canPan&&(this.context.cursorService.applyCursorState(15),this.context.cursorService.lockCursor()),!this.isStartTextSelection){const{scrollLeft:e,scrollTop:i}=s.getMaxScrollValue();e>0||i>0?(this.isMove=!0,this.isSlide=!1,l.startHandler(t)):"single"===g&&u&&(this.isMove=!1,this.isSlide=!0,c.startHandler(t))}}else if(n){a.startHandler(t);const[e]=this.context.toCanvas(t),{page:i}=this.context.getPointerOverPageInfo(e.pageX,e.pageY).pageInfo;i&&!po(t)?(this.startX=t.pageX,this.startY=t.pageY,oy(t)?oy(t)&&(p?(this.isDragPages=!0,h.startHandler(t)):(this.isMoveForThumbnail=!0,l.startHandler(t))):p?this.dragTimer=setTimeout(()=>{this.isMoveForThumbnail||(this.isDragPages=!0,h.startHandler(t))},d):(this.isMoveForThumbnail=!0,l.startHandler(t))):(this.isMoveForThumbnail=!0,l.startHandler(t))}}selectClickedText(t,e,i,n,s){if(!t)return;const o=this.context.getActiveTab();this.context.clearSelectedTexts();const r=this.context.core.pageService.getPage(i);if(!r.isTextPage)return;const a=r.lineMap.get(t).visibleIndex;let l;if(s){if(l=r.getSelectedTextWord(a,e),!l)return}else l=r.getSelectedTextSegment(a,e);if(!l)return;const{start:h,end:c}=l,d={...h,pageUid:r.uid,pageIndex:n,mediaBoxPoint:{...e}},u={...c,pageUid:r.uid,pageIndex:n,mediaBoxPoint:{...e}};this.startTextPosition=d,this.endTextPosition=u;const{textPages:p,startCharRect:g,endCharRect:f,startTextPosition:m,endTextPosition:v}=this.context.textSelectionService.calcSelectedText(this.startTextPosition,this.endTextPosition);o.setTextSelection(p,g,f,m,v),this.hasSelectedText=!0,this.textPages=p,this.context.render(31)}pointerMoveForAutoScroll(t){const e=this.context.getActiveTab();if(null!=e&&e.total&&!(this.pointerNum>1)&&this.isPanMode)if(this.context.isDefaultViewer&&this.isAutoScroll){if((e.context.maxScrollTop||e.context.maxScrollLeft)&&this.context.viewerConfig.enableAutoScrollForTextSelection){const e=this.checkPointermoveDirection(t);this.autoScroll(e)}}else if(this.context.isThumbnailViewer&&(e.context.maxScrollTop||e.context.maxScrollLeft)&&this.isDragPages&&this.context.viewerConfig.enableAutoScrollForDragPages){const e=this.checkPointermoveDirection(t);this.context.dragService.pointermoveForAutoScroll(t,e)}}autoScroll(t){const e=this.context.getActiveTab();if(null==e||!e.total)return;const{maxScrollTop:i,scrollTop:n,maxScrollLeft:s,scrollLeft:o}=e.context,r=this.context.viewerConfig.autoScrollStepSize/ao();let a=!1;i&&t.top&&0!==n&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollTop:t,scrollTop:i}=e.context;var n;t&&(0!==i?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(0,-r),this.pointermoveHandler(this.lastAutoScrollEvent,!1,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(0,-r)),i&&t.bottom&&n!==i&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollTop:t,scrollTop:i}=e.context;var n;t&&(i!==t?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(0,r),this.pointermoveHandler(this.lastAutoScrollEvent,!1,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(0,r)),s&&t.left&&0!==o&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollLeft:t,scrollLeft:i}=e.context;var n;t&&(0!==i?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(-r,0),this.pointermoveHandler(this.lastAutoScrollEvent,!1,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(-r,0)),s&&t.right&&o!==s&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollLeft:t,scrollLeft:i}=e.context;var n;t&&(i!==t?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(r,0),this.pointermoveHandler(this.lastAutoScrollEvent,!1,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(r,0)),this.autoScrollTimer&&!a&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null)}checkPointermoveDirection(t){const e={left:!1,top:!1,right:!1,bottom:!1};if(!this.context.getActiveTab())return e;const i=this.context.rendererService.getCanvasDom(),{top:n,bottom:s,left:o,right:r}=i.getBoundingClientRect();return t.clientY<n&&(e.top=!0),t.clientY>s&&(e.bottom=!0),t.clientX<o&&(e.left=!0),t.clientX>r&&(e.right=!0),e}pointermoveHandler(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(this.pointerNum>1)return;const n=this.context.getActiveTab();if(null==n||!n.total)return;if(!this.isPanMode)return;const{isDefaultViewer:s,isThumbnailViewer:o,viewService:r,moveService:a,slideService:l,annotationEditService:h,dragService:c,selectPagesService:d,textSelectionService:u}=this.context,{displayMode:p}=n.context;if(s&&!e){const[e]=this.context.toCanvas(t),{page:s}=this.context.getPointerOverPageInfo(e.pageX,e.pageY).pageInfo;if(s){this.hitPage=s;const e=this.context.rendererService.getCanvasDom().getBoundingClientRect();!i&&e.top<=t.clientY&&e.bottom>=t.clientY&&e.left<=t.clientX&&e.right>=t.clientX&&(this.lastAutoScrollEvent=t)}if(this.autoScrollTimer&&!i&&(clearTimeout(this.autoScrollTimer),this.autoScrollTimer=null),this.isMovedForMultiClick=!0,this.isPointerdown){const i=qs(this.startPoint,{x:e.pageX,y:e.pageY});if(i>this.textSelectionThreshold&&(this.isMovedForTextSelection=!0),this.isPointerOnAnnotation&&!this.isAnnotationActive&&this.isFirstMove){i>this.activeAnnotationThreshold&&(this.isActivateAnnotation=!1);const{scrollLeft:e,scrollTop:n}=r.getMaxScrollValue();e>0||n>0?(this.isMove=!0,this.isSlide=!1,a.startHandler(t)):"single"===p&&(this.isMove=!1,this.isSlide=!0,l.startHandler(t))}if(i>=this.clearSelectionTimerThreshold&&!this.isStartTextSelection&&this.textSelectionTimerMobile&&(clearTimeout(this.textSelectionTimerMobile),this.textSelectionTimerMobile=null),this.isEditAnnotation)h.moveHandler(t,!s);else if(this.isEditTextStart)this.isStartTextSelection=!0,this.isEditTextStart=!1,this.startTextPosition={...n.endTextPosition};else if(this.isEditTextEnd)this.isStartTextSelection=!0,this.isEditTextEnd=!1,this.startTextPosition={...n.startTextPosition};else if(this.context.viewerConfig.enableTextSelection&&this.isStartTextSelection){const{maxScrollTop:i,maxScrollLeft:o}=n.context;(i||o)&&this.context.viewerConfig.enableAutoScrollForTextSelection&&(this.isAutoScroll=!0);const r=this.context.core.pageService.getPage(null==s?void 0:s.uid);if(null!=r&&r.isTextPage&&r.visibleLines){this.context.cursorService.lockCursor();const i=this.context.calcTextEndPosition({x:e.pageX,y:e.pageY},s,n,this.startTextPosition.mediaBoxPoint);if(i){this.endTextPosition=i;const{textPages:s,startCharRect:o,endCharRect:r,startTextPosition:a,endTextPosition:l}=u.calcSelectedText(this.startTextPosition,this.endTextPosition);n.setTextSelection(s,o,r,a,l),this.hasSelectedText=!0,this.textPages=s,this.context.render(32),!oy(t)&&this.context.viewerConfig.enableTextMagnifier&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:e.pageX,y:e.pageY})}}}else this.isMove&&i>this.moveThreshold?(this.isActivateAnnotation=!1,a.moveHandler(t)):this.isSlide&&i>this.slideThreshold&&(this.isActivateAnnotation=!1,l.moveHandler(t));this.isFirstMove=!1}else if(oy(t)){this.textSelectionTimer&&(clearTimeout(this.textSelectionTimer),this.textSelectionTimer=null,this.isTextSelectionMode=!1);const i=this.context.core.pageService.getPage(null==s?void 0:s.uid);if(null!=i&&i.isTextPage&&null!=i&&i.visibleLines){if(this.context.viewerConfig.enableTextSelection&&!this.isStartTextSelection){const n=fw(s.mediaBox,e.pageX,e.pageY,s.rotation),o={x:n.pointerX,y:n.pointerY},r=s.isPointOnTextStart(o),a=s.isPointOnTextEnd(o);r||a?(this.isOverTextCtrlPoint=!0,this.context.cursorService.applyCursorState(16),this.canPan=!1):this.isOverTextCtrlPoint=!1;let l=!1;i.annotations.length&&(l=this.context.annotationEditService.isHitAnnotation(t).isHit),l||this.isOverTextCtrlPoint?(this.isTextSelectionMode=!1,this.canPan=!1,this.context.cursorService.applyCursorState(14)):-1!==i.getHoveredTextLineIndex(o)?s.isPointOnTextSelection(o)||this.isTextSelectionMode||(this.textSelectionTimer&&clearTimeout(this.textSelectionTimer),this.textSelectionTimer=setTimeout(()=>{this.isTextSelectionMode=!0,this.context.cursorService.applyCursorState(16),clearTimeout(this.textSelectionTimer),this.textSelectionTimer=null,this.canPan=!1},this.context.viewerConfig.enterTextModeTime)):(this.isTextSelectionMode=!1,this.textSelectionTimer&&(clearTimeout(this.textSelectionTimer),this.textSelectionTimer=null),this.context.cursorService.applyCursorState(14),this.canPan=!0)}}else this.isTextSelectionMode=!1,this.context.cursorService.applyCursorState(14),this.canPan=!0}}else if(o&&e)if(d.moveHandler(t),"touch"===t.pointerType){const e=qs({x:this.startX,y:this.startY},{x:t.pageX,y:t.pageY});this.isPointerdown&&this.dragTimer&&(this.isDragPages||a.startHandler(t),e>5&&(clearTimeout(this.dragTimer),this.dragTimer=null)),this.isDragPages?(this.isMoved=!0,c.moveHandler(t)):!this.isDragPages&&this.isPointerdown&&(e>5&&(this.isMoveForThumbnail=!0,a.moveHandler(t)),this.isMoved=!0)}else this.isPointerdown&&this.dragTimer&&(this.isDragPages||a.startHandler(t),clearTimeout(this.dragTimer),this.dragTimer=null),this.isDragPages?(this.isMoved=!0,c.moveHandler(t)):!this.isDragPages&&this.isPointerdown&&(this.isMoveForThumbnail=!0,a.moveHandler(t),this.isMoved=!0);this.lastMoveEvent=t}cursorHandler(t){if(!oy(t))return;if(!this.context.isDefaultViewer)return;if("pan"!==this.context.viewerConfig.toolMode)return;if(this.isTextSelectionMode||this.isOverTextCtrlPoint)return void this.context.cursorService.applyCursorState(16);const[e]=this.context.toCanvas(t),{page:i}=this.context.getPointerOverPageInfo(e.pageX,e.pageY).pageInfo;i&&this.context.annotationEditService.cursorHandler(t)}pointerupHandler(t){if(!this.isPointerdown)return;this.context.cursorService.unlockCursor();const{isDefaultViewer:e,isThumbnailViewer:i,annotationEditService:n,moveService:s,slideService:o,dragService:r,selectPagesService:a,textSelectionService:l}=this.context;if(e){if(this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null),this.isAutoScroll=!1,this.hitPage&&(this.hitPage=null),this.isEditAnnotation?n.endHandler(t):this.isActivateAnnotation?(n.activateAnnotation(this.activeShape,po(t)),this.context.render(33)):this.isMove?s.endHandler(t):this.isSlide&&o.endHandler(t),this.isStartTextSelection||this.isMovedForTextSelection||this.isZoomedForTextSelection||l.clearSelectedTexts(),this.isTextSelectionMode&&oy(t)&&this.lastClickPoint){const[e]=this.context.toCanvas(t);e.pageX===this.lastClickPoint.x&&e.pageY===this.lastClickPoint.y||(this.clickCount=0,this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null))}if(this.textSelectionTimerMobile&&clearTimeout(this.textSelectionTimerMobile),this.textSelectionTimer&&clearTimeout(this.textSelectionTimer),this.needRenderMagnifier&&this.context.magnifierService.hide(),this.magnifierPoint=null,this.needRenderMagnifier=!1,this.hasSelectedText){this.hasSelectedText=!1;const t=Ff.create(this.context.textSelectionService.getSelectedTexts(),this.textPages);this.textPages=[],this.context.hooks.textSelected.emit(t),this.context.hooks.afterTextSelected.emit(),this.context.render(34)}}else if(i){this.dragTimer&&(clearTimeout(this.dragTimer),this.dragTimer=null);const e=qs({x:this.startX,y:this.startY},{x:t.pageX,y:t.pageY});(!this.isMoved||e<this.context.viewerConfig.dragThreshold)&&a.endHandler(t),this.isDragPages?r.endHandler():s.endHandler(t)}this.isHitTextCtrlPoint=!1,this.isPointerdown=!1,this.isFirstMove=!0,this.isEditAnnotation=!1,this.isMove=!1,this.isSlide=!1,this.isActivateAnnotation=!1,this.isPointerOnAnnotation=!1,this.isAnnotationActive=!1,this.activeShape=null,this.isMoveForThumbnail=!1,this.isDragPages=!1,this.isMoved=!1,this.canScroll=!0,this.startPoint=null,this.isStartTextSelection=!1,0===this.clickCount&&this.isMovedForMultiClick&&(this.isTextSelectionMode=!1),this.isMovedForTextSelection=!1,this.isEditTextStart=!1,this.isEditTextEnd=!1,this.isZoomedForTextSelection=!1,this.isOverTextCtrlPoint=!1,this.canPan&&this.context.applyCursorState(14)}visibilityChangedHandler(){this.lastMoveEvent&&(this.pointerupHandler(this.lastMoveEvent),this.lastMoveEvent=null)}touchstartHandler(t){if(this.pointerNum=t.targetTouches.length,this.context.isDefaultViewer){const{enableZoom:e,enableZoomInPanMode:i,enableZoomWithTouch:n}=this.context.viewerConfig;if(!this.isPanMode||2!==t.targetTouches.length||this.isTouchstart||!e||!n||!i)return;this.isTouchstart=!0,this.context.zoomService.touchstartHandler(t)}}touchmoveHandler(t){this.pointerNum=t.targetTouches.length,2===t.targetTouches.length&&this.isTouchstart&&this.context.isDefaultViewer&&(this.context.zoomService.touchmoveHandler(t),this.isZoomedForTextSelection=!0)}touchendHandler(t){this.pointerNum=t.targetTouches.length,this.isTouchstart&&(this.isTouchstart=!1,this.context.isDefaultViewer&&this.context.zoomService.touchendHandler(t))}wheelHandler(t){if(this.pointerNum=0,!this.isPanMode)return;if(!this.canScroll)return void t.preventDefault();const{isDefaultViewer:e,isThumbnailViewer:i,viewerConfig:{enableZoom:n,enableZoomInPanMode:s,enableZoomWithCtrl:o},zoomService:r,scrollService:a}=this.context;if(e)if(go(t)){if(!n||!s||!o)return;r.wheelHandler(t)}else a.wheelHandler(t);else i&&a.wheelHandler(t)}scrollHandler(t){this.isPanMode&&this.canScroll&&(this.context.isDefaultViewer||this.context.isThumbnailViewer)&&this.context.scrollService.scrollHandler(t)}keydownHandler(t){if(!this.isPanMode)return;const{context:e,context:{keyboardService:i,annotationEditService:n,viewerConfig:{enableKeyboardInteraction:s,enableZoom:o,enableZoomInPanMode:r,enableCopyCutPasteWithKeyboard:a},isPointerWorking:l}}=this;if(!s||l)return;const h=po(t);if(e.isDefaultViewer){if(this.context.annotationEditService.hasActiveAnnotation()){if(h)switch(t.key){case"c":case"C":a&&n.copyAnnotations();break;case"x":case"X":a&&n.cutAnnotations();break;case"v":case"V":a&&n.pasteAnnotations();break;case"y":case"Y":i.redoHandler(t);break;case"z":case"Z":i.undoHandler(t);break;case"-":o&&r&&i.zoomOutHandler(t);break;case"=":o&&r&&i.zoomInHandler(t)}else if(fo(t)||mo(t)){const e=this.context.annotationEditService.containerPage;if(e){let{x:t,y:i}=e.cropBox.getPosition(),{width:s,height:o}=e.cropBox;const r=(e.rotation%360+360)%360/90;if(1===r?t-=o:2===r?(t-=s,i-=o):3===r&&(i-=s),1===r||3===r){const t=s;s=o,o=t}n.setAnnotationContainer(e),n.setAnnotationInteractionArea({left:t,top:i,width:s,height:o})}n.keydownHandler(t)}return}if(h)switch(t.key){case"c":case"C":{const e=this.context.getActiveTab();e&&e.hasSelectedTexts()&&(t.preventDefault(),this.context.copySelectedTexts());break}case"v":case"V":a&&n.pasteAnnotations();break;case"y":case"Y":i.redoHandler(t);break;case"z":case"Z":i.undoHandler(t);break;case"-":o&&r&&i.zoomOutHandler(t);break;case"=":o&&r&&i.zoomInHandler(t)}switch(t.key){case"Escape":i.escapeHandler(t);break;case"Enter":i.enterHandler(t);break;case"PageUp":i.pageUpHandler(t);break;case"PageDown":i.pageDownHandler(t);break;case"Home":i.homeHandler(t);break;case"End":i.endHandler(t);break;case"ArrowLeft":i.arrowLeftHandler(t);break;case"ArrowRight":i.arrowRightHandler(t);break;case"ArrowUp":i.arrowUpHandler(t);break;case"ArrowDown":i.arrowDownHandler(t)}}else if(e.isThumbnailViewer)switch(t.key){case"a":case"A":i.selectAllHandler(t);break;case"PageUp":i.pageUpHandler(t);break;case"PageDown":i.pageDownHandler(t);break;case"Home":i.homeHandler(t);break;case"End":i.endHandler(t);break;case"ArrowLeft":i.arrowLeftHandler(t);break;case"ArrowRight":i.arrowRightHandler(t);break;case"ArrowUp":i.arrowUpHandler(t);break;case"ArrowDown":i.arrowDownHandler(t)}}keyupHandler(t){if(!this.isPanMode)return;const{context:e,context:{annotationEditService:i,viewerConfig:{enableKeyboardInteraction:n}}}=this;n&&e.isDefaultViewer&&i.keyupHandler(t)}}class hC{constructor(t){Yi(this,"context",void 0),Yi(this,"isEditCropBox",!1),Yi(this,"isTouchstart",!1),Yi(this,"isPointerdown",!1),Yi(this,"pointerNum",0),Yi(this,"lastMoveEvent",void 0),this.context=t}get isCropMode(){return"crop"===this.context.viewerConfig.toolMode}pointerdownHandler(t){if(this.isPointerdown||!this.isCropMode)return;if(!this.context.isPointerOverCanvas(t))return;const e=oy(t);this.isPointerdown=!0;const{context:i}=this;i.hasBoxRendererModule?(i.isDefaultViewer?(this.isEditCropBox=i.cropBoxEditService.isEditCropBox(t),this.isEditCropBox?i.cropBoxEditService.startHandler(t):(i.moveService.startHandler(t),e&&i.applyCursorState(15))):i.isPerspectiveViewer&&(i.perspectiveQuadEditService.startHandler(t),e&&i.perspectiveQuadEditService.isNotOverQuadCtrl(t)&&i.applyCursorState(15)),i.cursorService.lockCursor()):i.isDefaultViewer&&i.moveService.startHandler(t)}pointermoveHandler(t){if(this.pointerNum>1||!this.isCropMode)return;const e=oy(t),{context:i}=this;if(i.isDefaultViewer){i.cropBoxEditService.moveHandler(t);const n=this.context.getActiveTab(),[s]=this.context.toCanvas(t),{page:o}=this.context.getPointerOverPageInfo(s.pageX,s.pageY).pageInfo;(!o||o.uid!==n.currentUid||e&&i.cropBoxEditService.isNotOverCropBox(t))&&i.cursorService.applyCursorState(14),!this.isEditCropBox&&this.isPointerdown&&i.moveService.moveHandler(t)}else if(i.isPerspectiveViewer){const n=i.perspectiveQuadEditService.isNotOverQuadCtrl(t);i.perspectiveQuadEditService.moveHandler(t),e&&n&&i.cursorService.applyCursorState(14)}this.lastMoveEvent=t}pointerupHandler(t){if(!this.isPointerdown||!this.isCropMode)return;const{context:e}=this;e.cursorService.unlockCursor(),e.isDefaultViewer?this.isEditCropBox?e.cropBoxEditService.endHandler(t):e.moveService.endHandler(t):e.isPerspectiveViewer&&e.perspectiveQuadEditService.endHandler(t),this.isPointerdown=!1,this.isEditCropBox=!1}visibilityChangedHandler(){this.lastMoveEvent&&(this.pointerupHandler(this.lastMoveEvent),this.lastMoveEvent=null)}touchstartHandler(t){this.pointerNum=t.targetTouches.length;const{context:e,context:{viewerConfig:i}}=this;if(e.isDefaultViewer){if(!this.isCropMode||2!==t.targetTouches.length||this.isTouchstart||!i.enableZoom||!i.enableZoomWithTouch||!i.enableZoomInCropMode)return;this.isTouchstart=!0,e.zoomService.touchstartHandler(t)}}touchmoveHandler(t){this.pointerNum=t.targetTouches.length,2===t.targetTouches.length&&this.isTouchstart&&this.context.isDefaultViewer&&this.context.zoomService.touchmoveHandler(t)}touchendHandler(t){this.pointerNum=t.targetTouches.length,this.isTouchstart&&(this.isTouchstart=!1,this.context.isDefaultViewer&&this.context.zoomService.touchendHandler(t))}wheelHandler(t){if(this.pointerNum=0,!this.isCropMode)return;const{context:e,context:{viewerConfig:i}}=this;if(e.isDefaultViewer)if(po(t)){if(!i.enableZoom||!i.enableZoomInCropMode||!i.enableZoomWithCtrl)return;e.zoomService.wheelHandler(t)}else e.isPointerWorking||e.scrollService.wheelHandler(t)}scrollHandler(t){if(!this.isCropMode)return;const{context:e}=this;(e.isDefaultViewer||e.isThumbnailViewer)&&e.scrollService.scrollHandler(t)}keydownHandler(t){if(!this.isCropMode)return;const{keyboardService:e,isDefaultViewer:i,viewerConfig:{enableKeyboardInteraction:n,enableZoom:s,enableZoomInCropMode:o},isPointerWorking:r}=this.context;if(i&&n&&!r)switch(t.key){case"y":case"Y":e.redoHandler(t);break;case"z":case"Z":e.undoHandler(t);break;case"-":s&&o&&e.zoomOutHandler(t);break;case"=":s&&o&&e.zoomInHandler(t);break;case"Escape":e.escapeHandler(t);break;case"Enter":e.enterHandler(t);break;case"PageUp":e.pageUpHandler(t);break;case"PageDown":e.pageDownHandler(t);break;case"Home":e.homeHandler(t);break;case"End":e.endHandler(t);break;case"ArrowLeft":e.arrowLeftHandler(t);break;case"ArrowRight":e.arrowRightHandler(t);break;case"ArrowUp":e.arrowUpHandler(t);break;case"ArrowDown":e.arrowDownHandler(t)}}}class cC{constructor(t){Yi(this,"context",void 0),Yi(this,"isPointerdown",!1),Yi(this,"pointerId",null),Yi(this,"canScroll",!0),Yi(this,"lastMoveEvent",void 0),this.context=t}get isAnnotationMode(){return"annotation"===this.context.viewerConfig.toolMode}get isTextAssistMode(){return["highlight","underline","strikeout"].includes(this.context.viewerConfig.annotationMode)}pointerdownHandler(t){if(this.isPointerdown||!this.isAnnotationMode)return;if(this.pointerId)return;if(!this.context.hasBoxRendererModule||!this.context.isDefaultViewer)return;if(!this.context.isPointerOverCanvas(t))return;const[e]=this.context.toCanvas(t),{page:i}=this.context.getPointerOverPageInfo(e.pageX,e.pageY).pageInfo;if(!i)return;this.isPointerdown=!0,this.pointerId=t.pointerId;let{x:n,y:s}=i.cropBox.getPosition(),{width:o,height:r}=i.cropBox;const a=(i.rotation%360+360)%360/90;if(1===a?n-=r:2===a?(n-=o,s-=r):3===a&&(s-=o),1===a||3===a){const t=o;o=r,r=t}this.context.annotationEditService.setAnnotationContainer(i),this.context.annotationEditService.setAnnotationInteractionArea({left:n,top:s,width:o,height:r}),this.context.annotationEditService.startHandler(t,!0),this.context.annotationEditService.hasActiveAnnotation()&&(this.canScroll=!1)}pointermoveHandler(t){if((this.pointerId===t.pointerId||"touch"!==t.pointerType)&&this.isAnnotationMode){if(this.context.isDefaultViewer){const[e]=this.context.toCanvas(t),{page:i}=this.context.getPointerOverPageInfo(e.pageX,e.pageY).pageInfo;this.context.annotationEditService.moveHandler(t,!i)}this.lastMoveEvent=t}}cursorHandler(t){if(!oy(t))return;if(!this.context.isDefaultViewer)return;if(!this.isAnnotationMode)return;if(this.isTextAssistMode&&!this.context.annotationEditService.isMouseOverText)return void this.context.cursorService.applyCursorState(1);const[e]=this.context.toCanvas(t),{page:i}=this.context.getPointerOverPageInfo(e.pageX,e.pageY).pageInfo;i&&this.context.annotationEditService.cursorHandler(t)}pointerupHandler(t){this.isPointerdown&&(this.context.isDefaultViewer&&this.context.annotationEditService.endHandler(t),this.isPointerdown=!1,this.canScroll=!0,this.pointerId=null)}visibilityChangedHandler(){this.lastMoveEvent&&(this.pointerupHandler(this.lastMoveEvent),this.lastMoveEvent=null)}wheelHandler(t){if(this.isAnnotationMode)if(this.canScroll){if(this.context.isDefaultViewer)if(po(t)){const{enableZoom:e,enableZoomInAnnotationMode:i,enableZoomWithCtrl:n}=this.context.viewerConfig;if(!e||!i||!n)return;this.context.zoomService.wheelHandler(t)}else this.context.scrollService.wheelHandler(t)}else t.preventDefault()}scrollHandler(t){this.isAnnotationMode&&this.canScroll&&(this.context.isDefaultViewer||this.context.isThumbnailViewer)&&this.context.scrollService.scrollHandler(t)}keydownHandler(t){if(!this.isAnnotationMode)return;const{context:e,context:{keyboardService:i,annotationEditService:n,viewerConfig:{enableKeyboardInteraction:s,enableZoom:o,enableZoomInAnnotationMode:r,enableCopyCutPasteWithKeyboard:a},hasAnnotationModule:l,isPointerWorking:h}}=this;if(s&&!h&&e.isDefaultViewer)if(this.context.annotationEditService.hasActiveAnnotation()){if(po(t))switch(t.key){case"c":case"C":a&&n.copyAnnotations();break;case"x":case"X":a&&n.cutAnnotations();break;case"v":case"V":a&&n.pasteAnnotations();break;case"y":case"Y":i.redoHandler(t);break;case"z":case"Z":i.undoHandler(t);break;case"-":o&&r&&i.zoomOutHandler(t);break;case"=":o&&r&&i.zoomInHandler(t)}else if(fo(t)||mo(t)){const e=this.context.annotationEditService.containerPage;if(e){let{x:t,y:i}=e.cropBox.getPosition(),{width:s,height:o}=e.cropBox;const r=(e.rotation%360+360)%360/90;if(1===r?t-=o:2===r?(t-=s,i-=o):3===r&&(i-=s),1===r||3===r){const t=s;s=o,o=t}n.setAnnotationContainer(e),n.setAnnotationInteractionArea({left:t,top:i,width:s,height:o})}n.keydownHandler(t)}}else{if(po(t))switch(t.key){case"y":case"Y":i.redoHandler(t);break;case"z":case"Z":i.undoHandler(t);break;case"v":case"V":a&&n.pasteAnnotations();break;case"-":o&&r&&i.zoomOutHandler(t);break;case"=":o&&r&&i.zoomInHandler(t)}switch(t.key){case"Escape":i.escapeHandler(t);break;case"Enter":i.enterHandler(t);break;case"PageUp":i.pageUpHandler(t);break;case"PageDown":i.pageDownHandler(t);break;case"Home":i.homeHandler(t);break;case"End":i.endHandler(t);break;case"ArrowLeft":i.arrowLeftHandler(t);break;case"ArrowRight":i.arrowRightHandler(t);break;case"ArrowUp":i.arrowUpHandler(t);break;case"ArrowDown":i.arrowDownHandler(t)}}}keyupHandler(t){if(!this.isAnnotationMode)return;const{context:e,context:{annotationEditService:i,viewerConfig:{enableKeyboardInteraction:n}}}=this;n&&e.isDefaultViewer&&i.keyupHandler(t)}}class dC{constructor(t){Yi(this,"context",void 0),Yi(this,"isPointerdown",!1),this.context=t}get isZoomInMode(){return"zoomIn"===this.context.viewerConfig.toolMode}startHandler(t){!this.isPointerdown&&this.context.isDefaultViewer&&(this.context.zoomService.tapZoomHandler(t),this.isPointerdown=!0)}moveHandler(t){oy(t)&&this.context.isDefaultViewer&&"zoomIn"===this.context.viewerConfig.toolMode&&this.context.cursorService.applyCursorState(26)}endHandler(t){this.isPointerdown&&(this.isPointerdown=!1)}keydownHandler(t){if(!this.isZoomInMode||!this.context.isDefaultViewer)return;const{context:{viewerConfig:e}}=this;if(!e.enableKeyboardInteraction||!e.enableZoom||!e.enableZoomInWithKeyboard||this.context.isPointerWorking)return;const{keyboardService:i}=this.context;switch(t.key){case"-":i.zoomInHandler(t);break;case"PageUp":i.pageUpHandler(t);break;case"PageDown":i.pageDownHandler(t);break;case"Home":i.homeHandler(t);break;case"End":i.endHandler(t);break;case"ArrowLeft":i.arrowLeftHandler(t);break;case"ArrowRight":i.arrowRightHandler(t);break;case"ArrowUp":i.arrowUpHandler(t);break;case"ArrowDown":i.arrowDownHandler(t)}}}class uC{constructor(t){Yi(this,"context",void 0),Yi(this,"isPointerdown",!1),this.context=t}get isZoomOutMode(){return"zoomOut"===this.context.viewerConfig.toolMode}startHandler(t){!this.isPointerdown&&this.context.isDefaultViewer&&(this.context.zoomService.tapZoomHandler(t),this.isPointerdown=!0)}moveHandler(t){oy(t)&&this.context.isDefaultViewer&&"zoomOut"===this.context.viewerConfig.toolMode&&this.context.cursorService.applyCursorState(27)}endHandler(t){this.isPointerdown&&(this.isPointerdown=!1)}keydownHandler(t){if(!this.isZoomOutMode||!this.context.isDefaultViewer)return;const{context:{viewerConfig:e}}=this;if(!e.enableKeyboardInteraction||!e.enableZoom||!e.enableZoomOutWithKeyboard||this.context.isPointerWorking)return;const{keyboardService:i}=this.context;switch(t.key){case"=":i.zoomOutHandler(t);break;case"PageUp":i.pageUpHandler(t);break;case"PageDown":i.pageDownHandler(t);break;case"Home":i.homeHandler(t);break;case"End":i.endHandler(t);break;case"ArrowLeft":i.arrowLeftHandler(t);break;case"ArrowRight":i.arrowRightHandler(t);break;case"ArrowUp":i.arrowUpHandler(t);break;case"ArrowDown":i.arrowDownHandler(t)}}}class pC extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"lastSelectResult",void 0),Yi(this,"selectedTextPages",new Map),this.context=t,t.hooks.toolModeChanged.on(()=>{this.clearSelectedTexts()},this),this.context.hooks.annotationModeChanged.on(()=>{"annotation"===this.context.viewerConfig.toolMode&&this.clearSelectedTexts()},this)}calcSelectedText(t,e){const i=this.context.getActiveTab(),n=[];let s,o;const r=this.context.core.pageService.getPage(t.pageUid),a=this.context.core.pageService.getPage(e.pageUid),l=r.lineMap.get(t.lineUid),h=a.lineMap.get(e.lineUid);let c={...t,lineIndex:l.visibleIndex,charIndex:r.charMap.get(t.charUid).indexInMergeLine,pageIndex:i.uidToIndex(t.pageUid)},d={...e,lineIndex:h.visibleIndex,charIndex:a.charMap.get(e.charUid).indexInMergeLine,pageIndex:i.uidToIndex(e.pageUid),mediaBoxPoint:e.mediaBoxPoint};if(c.pageIndex===d.pageIndex&&(c.lineIndex>d.lineIndex||c.lineIndex===d.lineIndex&&c.charIndex>d.charIndex)||c.pageIndex>d.pageIndex){const t=c;c=d,d=t}const u={...c},p={...d},g=this.context.core.pageService.getPage(c.pageUid);let f=g.visibleLines.find(t=>t.uid===c.lineUid);f||([f]=g.visibleLines,c.lineIndex=0,c.charIndex=0,c.lineUid=f.uid,c.charUid=f.chars[f.startIndex].uid);const m=this.context.core.pageService.getPage(d.pageUid);let v=m.visibleLines.find(t=>t.uid===d.lineUid);v||(v=m.visibleLines[m.visibleLines.length-1],d.lineIndex=v.visibleIndex,d.charIndex=v.endIndex,d.lineUid=v.uid,d.charUid=v.chars[v.endIndex].uid);for(let t=c.pageIndex;t<=d.pageIndex;t++){var y;const e=i.getPageByIndex(t),r=this.context.core.pageService.getPage(e.uid);if(!r.isTextPage)continue;if(null===(y=r.visibleLines)||void 0===y||!y.length)continue;const a=this.selectedTextPages.get(e.uid);if(a&&t>c.pageIndex&&t<d.pageIndex){n.push(a);continue}const l={pageUid:e.uid,lines:[],text:""};let h=0,u=r.visibleLines.length-1;t===c.pageIndex&&(h=c.lineIndex),t===d.pageIndex&&(u=d.lineIndex);let p="";for(let e=h;e<=u;e++){const i=r.visibleLines[e];let n=i.startIndex,a=i.endIndex;t===c.pageIndex&&e===c.lineIndex&&(n=c.charIndex,s=r.getEndCharRect(e,n)),t===d.pageIndex&&e===d.lineIndex&&(a=d.charIndex,o=r.getEndCharRect(e,a)),a=Math.min(a,i.endIndex),n=Math.max(n,i.startIndex);const h=r.getSelectedTextLine(e,Math.min(n,a),Math.max(n,a));l.lines.push(h),p+=h.text}l.lines=r.doMergeAdjacentLines(l.lines),t===c.pageIndex&&(s.top=l.lines[0].selectedRect.top,s.height=l.lines[0].selectedRect.height),t===d.pageIndex&&(o.top=l.lines[l.lines.length-1].selectedRect.top,o.height=l.lines[l.lines.length-1].selectedRect.height),l.text=p,n.push(l),t>c.pageIndex&&t<d.pageIndex&&!a&&this.selectedTextPages.set(e.uid,l)}return{textPages:n,startCharRect:s,endCharRect:o,startTextPosition:u,endTextPosition:p}}getSelectedTexts(){let t="";const e=this.context.getActiveTab();if(!e)return"";if(e.selectedTextsCache)return e.selectedTextsCache;const i=e.startTextPosition,n=e.endTextPosition;if(!i||!n)return"";const s=this.context.core.pageService.getPage(i.pageUid),o=this.context.core.pageService.getPage(n.pageUid),r=s.lineMap.get(i.lineUid),a=o.lineMap.get(n.lineUid);let l={...i,lineIndex:r.visibleIndex,charIndex:s.charMap.get(i.charUid).indexInMergeLine,pageIndex:e.uidToIndex(i.pageUid)},h={...n,lineIndex:a.visibleIndex,charIndex:o.charMap.get(n.charUid).indexInMergeLine,pageIndex:e.uidToIndex(n.pageUid),mediaBoxPoint:n.mediaBoxPoint};if(l.pageIndex===h.pageIndex&&l.lineIndex>h.lineIndex||l.pageIndex>h.pageIndex){const t=l;l=h,h=t}for(let i=l.pageIndex;i<=h.pageIndex;i++){var c;const n=e.getPageByIndex(i),s=this.context.core.pageService.getPage(n.uid);if(!s.isTextPage)continue;if(null===(c=s.visibleLines)||void 0===c||!c.length)continue;let o="",r=0,a=s.visibleLines.length-1;i===l.pageIndex&&(r=l.lineIndex),i===h.pageIndex&&(a=h.lineIndex);for(let t=r;t<=a;t++){let e=s.visibleLines[t].startIndex,n=s.visibleLines[t].endIndex;i===l.pageIndex&&t===l.lineIndex&&(e=l.charIndex),i===h.pageIndex&&t===h.lineIndex&&(n=h.charIndex),o+=s.getSelectedTextsStr(t,Math.min(e,n),Math.max(e,n),t!==a||i!==h.pageIndex)}t+=o}return e.selectedTextsCache=t,t}clearSelectedTexts(){this.lastSelectResult=null,this.selectedTextPages.clear();const t=this.context.getActiveTab();if(t&&t.clearTextSelection()){const t=Ff.create("",[]);this.context.hooks.textSelected.emit(t),this.context.render(44)}}getTextSelectionLines(){const t=this.context.getActiveTab();return t?t.getTextSelectionLines():null}getTextSelectionControlPointsRect(){const t=this.context.getActiveTab();return t?t.getTextSelectionControlPointsRect():null}getTextSelection(){if(!this.context.getActiveTab())return[];const t=this.getTextSelectionLines();if(!t)return[];const e=[],i=Cr.displayResolution,n=Cr.dataResolution;return t.forEach(t=>{const s=[];t.lines.forEach(t=>{s.push({x:Bo(t.selectedRect.left,i,n),y:Bo(t.selectedRect.top,i,n),width:Bo(t.selectedRect.width,i,n),height:Bo(t.selectedRect.height,i,n)})}),e.push({pageUid:t.pageUid,text:t.text,rects:s})}),e}}class gC extends Wo{constructor(t){super(),Yi(this,"currentCursor","default"),Yi(this,"lastCursor","default"),Yi(this,"lastCursorState",void 0),Yi(this,"context",void 0),Yi(this,"isLocked",!1),this.context=t}applyCursorState(t){if(!t||this.isLocked)return;const{cursorStyle:e}=this.context.viewerConfig;let i=null;switch(t){case 1:i=e.default;break;case 2:i=e.annotationSelect;break;case 3:i=e.annotationDraw;break;case 4:i=e.annotationMove;break;case 5:i=e.annotationNSResize;break;case 6:i=e.annotationEWResize;break;case 7:i=e.annotationNWResize;break;case 8:i=e.annotationNEResize;break;case 10:i=e.annotationSEResize;break;case 9:i=e.annotationSWResize;break;case 11:i=e.annotationRotate;break;case 12:i=e.annotationErase;break;case 13:i=e.annotationActivable;break;case 14:i=e.pan;break;case 15:i=e.panning;break;case 16:i=e.text;break;case 18:i=e.cropDraw;break;case 19:i=e.cropMove;break;case 20:i=e.cropNSResize;break;case 21:i=e.cropEWResize;break;case 22:i=e.cropNWResize;break;case 23:i=e.cropNEResize;break;case 25:i=e.cropSEResize;break;case 24:i=e.cropSWResize;break;case 26:i=e.zoomIn;break;case 27:i=e.zoomOut}i&&(this.lastCursorState=t,this.setCursor(i))}setCursor(t){this.lastCursor=this.currentCursor,this.currentCursor=t,this.applyCursor()}resetCursor(){this.currentCursor=this.lastCursor,this.applyCursor()}applyCursor(){if(!this.context.viewerConfig.enableCursorService)return;const{eventDom:t}=this.context;(null==t?void 0:t.style.cursor)!==this.currentCursor&&(t.style.cursor=this.currentCursor)}lockCursor(){this.isLocked=!0}unlockCursor(){this.isLocked=!1}}class fC{constructor(t,e,i){Yi(this,"service",void 0),Yi(this,"text",void 0),Yi(this,"options",void 0),Yi(this,"cacheMap",new Map),Yi(this,"uid",Us()),Yi(this,"isStopped",!1),Yi(this,"searchType",void 0),Yi(this,"pageUids",[]),Yi(this,"curSearch",void 0),Yi(this,"isComplete",!1),Yi(this,"isNotFound",!1),Yi(this,"tasks",new Map),Yi(this,"curTask",null),Yi(this,"deletePageTimer",void 0),this.service=t,this.text=e,this.options=i;const n=this.service.context.getActiveTab();this.pageUids=(null==n?void 0:n.getAllPageUids())||[]}hasResult(){return this.cacheMap.size>0}async searchNextText(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.breakTask(),this.isStopped)return null;if(this.isNotFound)return null;this.isNotFound=!1;let i=!1;if(this.curSearch){const t=this.cacheMap.get(this.curSearch.pageUid);this.curSearch.index===t.texts.length-1?(this.curSearch.pageIndex!==this.pageUids.length-1?this.curSearch.pageIndex+=1:this.curSearch.pageIndex=0,this.curSearch.pageUid=this.pageUids[this.curSearch.pageIndex],i=!0):this.curSearch.index+=1}else this.curSearch={pageUid:this.pageUids[0],pageIndex:0,index:0};const n=this.pageUids.slice(this.curSearch.pageIndex).concat(this.pageUids.slice(0,this.curSearch.pageIndex));for(let t=0;t<n.length;t++){const e=n[t];if(this.cacheMap.has(e)){this.curSearch.pageUid=e,this.curSearch.pageIndex=this.pageUids.indexOf(e),i&&(this.curSearch.index=0);break}const s=await this.service.context.core.getSearchedTextsByPageUid(e,this.text,this.options);if(this.isStopped)return null;if(null!=s&&s.length){this.cacheMap.set(e,{pageUid:e,texts:s}),this.curSearch={pageUid:e,pageIndex:this.pageUids.indexOf(e),index:0};break}}return this.handleSearchResults(t,e)}async searchPrevText(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this.breakTask(),this.isStopped)return null;if(this.isNotFound)return null;this.isNotFound=!1;let e=!1,i=!1;this.curSearch?0===this.curSearch.index?(0!==this.curSearch.pageIndex?this.curSearch.pageIndex-=1:this.curSearch.pageIndex=this.pageUids.length-1,this.curSearch.pageUid=this.pageUids[this.curSearch.pageIndex],e=!0):this.curSearch.index-=1:(this.curSearch={pageUid:this.pageUids[0],pageIndex:0,index:0},i=!0);const n=this.curSearch.pageIndex+1,s=this.pageUids.slice(n).concat(this.pageUids.slice(0,n)).reverse();for(let t=0;t<s.length;t++){const n=s[t];if(this.cacheMap.has(n)){this.curSearch.pageUid=n,this.curSearch.pageIndex=this.pageUids.indexOf(n),i?this.curSearch.index=0:e&&(this.curSearch.index=this.cacheMap.get(n).texts.length-1);break}const o=await this.service.context.core.getSearchedTextsByPageUid(n,this.text,this.options);if(this.isStopped)return null;if(null!=o&&o.length){this.cacheMap.set(n,{pageUid:n,texts:o}),this.curSearch.pageUid=n,this.curSearch.pageIndex=this.pageUids.indexOf(n),i?this.curSearch.index=0:e&&(this.curSearch.index=o.length-1);break}}return this.handleSearchResults(t)}handleSearchResults(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];this.cacheMap.has(this.curSearch.pageUid)&&(i=[{pageUid:this.curSearch.pageUid,texts:[this.cacheMap.get(this.curSearch.pageUid).texts[this.curSearch.index]]}]),this.setSearchTextToPage(i),i.length&&this.select(t);const n=new Vf(this.text,{...this.options},i,this.uid,this.searchType,[],!0,e);return this.service.context.hooks.searchTextChanged.emit(n),i.length&&this.emitSearchTextSelected(),i.length?i:(this.curSearch=null,this.isNotFound=!0,null)}createTask(){const t={taskUid:Us(),isBreak:!1};return this.tasks.set(t.taskUid,t),t}async searchFullText(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.breakTask(),this.service.context.hooks.searchTextCleared.emit(!0),this.isStopped)return null;const i=this.createTask();this.curTask=i,this.isComplete=!1;let n=!0,s=0,o=2;const r=[];for(let a=0;a<this.pageUids.length;a++){s+=1;const l=this.pageUids[a];if(this.cacheMap.has(l)){this.curSearch||(this.curSearch={pageUid:l,pageIndex:this.pageUids.indexOf(l),index:0});const t=this.cacheMap.get(l);r.push(t)}else{const t=await this.service.context.core.getSearchedTextsByPageUid(l,this.text,this.options);if(this.isStopped||i.isBreak)return null;if(null!=t&&t.length){this.curSearch||(this.curSearch={pageUid:l,pageIndex:this.pageUids.indexOf(l),index:0});const e={pageUid:l,texts:t};this.cacheMap.set(l,e),r.push(e)}}if(r.length&&(n||s%o==0||a===this.pageUids.length-1)){const l=!!n&&e;s=0,o<20&&(o+=1),this.curSearch||(this.curSearch={pageUid:r[0].pageUid,pageIndex:this.pageUids.indexOf(r[0].pageUid),index:0}),this.setSearchTextToPage(r),this.select(t);const h=new Vf(this.text,{...this.options},r,this.uid,this.searchType,[],a===this.pageUids.length-1,l);if(this.service.context.hooks.searchTextChanged.emit(h),this.emitSearchTextSelected(),n=!1,i.isBreak||this.isStopped)return null}if(0===a&&!r.length){const t=new Vf(this.text,{...this.options},r,this.uid,this.searchType,[],!1,!1);this.service.context.hooks.searchTextChanged.emit(t)}}if(this.isComplete=!0,!this.pageUids.length)return this.service.clearSearchText(),null;if(!r.length){this.setSearchTextToPage(r);const t=new Vf(this.text,{...this.options},r,this.uid,this.searchType,[],!0,e);return this.service.context.hooks.searchTextChanged.emit(t),this.curSearch=null,null}return r}setSearchTextToPage(t){const e=this.service.context.getActiveTab();if(!e)return;const i=new Map;t.forEach(t=>{i.set(t.pageUid,t)}),e.allPages.forEach(t=>{i.has(t.uid)?t.setSearchedText(i.get(t.uid)):t.clearSearchedText()})}selectText(t,e){var i,n;const s=`${null===(i=this.curSearch)||void 0===i?void 0:i.pageUid}_${null===(n=this.curSearch)||void 0===n?void 0:n.index}`;if(e===s){const e=this.service.context.getActiveTab();if(!e)return;const i=e.uidToIndex(t);return void(e.current!==i&&this.service.context.viewer.gotoPage(i))}if(!this.cacheMap)return;const o=this.cacheMap.get(t);this.curSearch={pageUid:t,index:o.texts.findIndex(t=>t.textUid===e),pageIndex:this.pageUids.indexOf(t)},this.select(),this.emitSearchTextSelected()}select(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=this.service.context.getActiveTab();if(!i)return;const n=this.cacheMap.get(this.curSearch.pageUid),s=n.texts[this.curSearch.index];if(i.allPages.forEach(t=>{t.uid!==n.pageUid?t.selectSearchedText(null):t.selectSearchedText(s.textUid)}),t){const t=i.uidToIndex(this.curSearch.pageUid);this.service.context.viewer.gotoPage(t)}e&&this.service.context.render(50)}emitSearchTextSelected(){const t=this.cacheMap.get(this.curSearch.pageUid).texts[this.curSearch.index];this.service.context.hooks.searchTextSelected.emit(t.textUid)}next(){if("single"===this.searchType)return;if(this.isStopped)return;if(!this.curSearch)return;if(!this.isComplete)return;const t=this.cacheMap.get(this.curSearch.pageUid);this.curSearch.index===t.texts.length-1?this.pageUids.slice(this.curSearch.pageIndex+1).concat(this.pageUids.slice(0,this.curSearch.pageIndex+1)).some(t=>{const e=this.cacheMap.get(t);return!!(e&&e.texts.length>0)&&(this.curSearch={pageUid:t,pageIndex:this.pageUids.indexOf(t),index:0},!0)}):this.curSearch.index+=1,this.select(),this.emitSearchTextSelected()}previous(){"single"!==this.searchType&&(this.isStopped||this.curSearch&&this.isComplete&&(0===this.curSearch.index?this.pageUids.slice(this.curSearch.pageIndex).concat(this.pageUids.slice(0,this.curSearch.pageIndex)).reverse().some(t=>{const e=this.cacheMap.get(t);return!!(e&&e.texts.length>0)&&(this.curSearch={pageUid:t,pageIndex:this.pageUids.indexOf(t),index:e.texts.length-1},!0)}):this.curSearch.index-=1,this.select(),this.emitSearchTextSelected()))}reset(){this.cacheMap.clear(),this.curSearch=null,this.isStopped=!1,this.searchType=null,this.tasks.forEach(t=>{t.isBreak=!0}),this.tasks.clear(),this.curTask=null}updateSearchType(t){this.searchType=t}stop(){this.isStopped=!0,this.curTask&&(this.curTask.isBreak=!0)}breakTask(){this.curTask&&(this.curTask.isBreak=!0,this.tasks.delete(this.curTask.taskUid))}refreshPageUids(){const t=this.service.context.getActiveTab();t&&(this.pageUids=t.allPages.map(t=>t.uid))}async addPages(t){this.refreshPageUids(),this.curSearch&&(this.curSearch.pageIndex=this.pageUids.indexOf(this.curSearch.pageUid)),this.isNotFound=!1,"full"===this.searchType?await this.searchFullText(!1):"single"===this.searchType&&(this.curSearch=null,await this.searchNextText(!1))}async deletePages(t){this.refreshPageUids(),this.deleteCacheByPageUids(t),this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),this.deletePageTimer&&(clearTimeout(this.deletePageTimer),this.deletePageTimer=null),this.deletePageTimer=setTimeout(()=>{this.deletePageTimer=null,this.reSearch(!1)},40)}async updatePage(t){this.deleteCacheByPageUids([t]),this.isNotFound=!1,this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),await this.reSearch(!1)}async filterPages(t){this.deleteCacheByPageUids(t),this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),await this.reSearch(!1)}async perspectivePage(t){this.deleteCacheByPageUids([t]),this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),await this.reSearch(!1)}async cropPages(t){this.deleteCacheByPageUids(t),this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),await this.reSearch(!1)}async reorderPages(){this.refreshPageUids(),this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),await this.reSearch(!1)}async swapPages(){this.refreshPageUids(),this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),await this.reSearch(!1)}async movePages(){this.refreshPageUids(),this.curSearch=null,this.service.context.hooks.searchTextCleared.emit(),await this.reSearch(!1)}async reSearch(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];"single"===this.searchType?await this.searchNextText(t,!0):"full"===this.searchType&&await this.searchFullText(t,!0)}deleteCacheByPageUids(t){t.forEach(t=>{this.cacheMap.delete(t)})}}class mC extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"searchers",new Map),Yi(this,"curSearcher",void 0),Yi(this,"lastOptions",{caseSensitive:!1,wholeWord:!1}),Yi(this,"curText",void 0),Yi(this,"lastSearchType",void 0),Yi(this,"isCleared",!1),Yi(this,"taskUid",void 0),Yi(this,"cancelQueue",[]),Yi(this,"searchTimer",null),Yi(this,"defaultOptions",{caseSensitive:!1,wholeWord:!1}),Yi(this,"lastSearchRes",void 0),Yi(this,"reorderTimer",void 0),this.context=t,this.listenEvents()}listenEvents(){const{documentService:t}=this.context.core,{hooks:e}=this.context;e.closeDocument.on(t=>{this.clearSearchText()},this),t.onBeforeDeleteDocs.on(async t=>{const e=this.context.getActiveTab();e&&t.docUids.forEach(t=>{e.uid===t&&this.curSearcher&&this.clearSearchText()})},this),e.deletePages.on(async t=>{var e;const{docUid:i,pageUids:n}=t;if(this.isMeetEventConditions(i))return this.context.getActiveTab().total?(await this.curSearcher.deletePages(n),void(this.lastSearchRes=null===(e=this.lastSearchRes)||void 0===e?void 0:e.filter(t=>!n.includes(t.pageUid)))):(this.clearSearchText(),void(this.lastSearchRes=null))},this),e.addPagesToDoc.on(async t=>{const{docUid:e,pageUids:i}=t;this.isMeetEventConditions(e)&&await this.curSearcher.addPages(i)},this),e.updatePage.on(async t=>{const{docUid:e,pageUid:i}=t;this.isMeetEventConditions(e)&&await this.curSearcher.updatePage(i)},this),e.reorderPages.on(async t=>{this.isMeetEventConditions(t.docUid)&&(this.reorderTimer&&(clearTimeout(this.reorderTimer),this.reorderTimer=null),this.reorderTimer=setTimeout(()=>{this.reorderTimer=null,this.curSearcher.reorderPages()},40))},this),e.movePages.on(async t=>{this.isMeetEventConditions(t.docUid)&&await this.curSearcher.movePages()},this),e.swapPages.on(async t=>{this.isMeetEventConditions(t.docUid)&&await this.curSearcher.swapPages()},this),this.context.core.onFilterChanged.on(async t=>{this.isMeetEventConditions(t.docUid)&&await this.curSearcher.filterPages(t.pageUids)},this),this.context.core.onAfterPerspective.on(async t=>{this.isMeetEventConditions(t.docUid)&&await this.curSearcher.perspectivePage(t.pageUid)},this),this.context.core.editService.onAfterCropPages.on(async t=>{this.isMeetEventConditions(t.docUid)&&(await this.curSearcher.cropPages(t.pageUids),this.context.render(45))},this)}isMeetEventConditions(t){const e=this.context.getActiveTab();return!(!(e&&(null==e?void 0:e.uid)===t&&this.curSearcher&&this.curText)||this.curSearcher.isStopped)}createTextSearcher(t,e,i){let n=this.searchers.get(t);return n||(this.context.getActiveTab(),n=new fC(this,e,i),this.searchers.set(n.uid,n)),n}async searchNextText(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i={...this.defaultOptions,...i},this.isTextChanged(e)||this.isOptionsChanged(i)){this.curSearcher&&this.stopSearch(this.curSearcher.uid),Object.assign(this.lastOptions,i||{}),this.curText=e;const n=this.createTextSearcher(t,e,i);this.curSearcher=n}else this.isSearchTypeChanged("single")&&this.curSearcher.reset();this.lastSearchType="single",this.curSearcher.updateSearchType("single");const n=await this.curSearcher.searchNextText();return!this.curSearcher.isStopped&&(this.context.render(46),!!n)}async searchPrevText(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i={...this.defaultOptions,...i},this.isTextChanged(e)||this.isOptionsChanged(i)){this.curSearcher&&this.stopSearch(this.curSearcher.uid),Object.assign(this.lastOptions,i||{}),this.curText=e;const n=this.createTextSearcher(t,e,i);this.curSearcher=n}else this.isSearchTypeChanged("single")&&this.curSearcher.reset();this.lastSearchType="single",this.curSearcher.updateSearchType("single");const n=await this.curSearcher.searchPrevText();return!this.curSearcher.isStopped&&(this.context.render(47),!!n)}async searchFullText(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i={...this.defaultOptions,...i},this.isCleared=!1,this.isTextChanged(e)||this.isOptionsChanged(i)){this.curSearcher&&this.stopSearch(this.curSearcher.uid),this.cancelQueue.forEach(t=>{t()}),this.cancelQueue=[],this.curText=e;const n=Us();if(this.taskUid=n,!await new Promise(t=>{this.searchTimer=setTimeout(()=>{t(!0)},this.context.viewerConfig.textSearchDelay),this.cancelQueue.push(()=>{t(!1)})})||this.taskUid!==n||this.isCleared||this.curText&&this.curText!==e)return null;Object.assign(this.lastOptions,i||{});const s=this.createTextSearcher(t,e,i);this.curSearcher=s}else{if(!this.isSearchTypeChanged("full"))return!!this.lastSearchRes;if(!this.curSearcher)return!1;this.curSearcher.reset()}this.lastSearchType="full",this.curSearcher.updateSearchType("full");const n=this.curSearcher,s=await n.searchFullText(!1);return!n.isStopped&&(this.isCleared&&this.clearSearchTextFromPage(),this.context.render(48),this.lastSearchRes=s,!!s)}isTextChanged(t){return this.curText!==t}isSearchTypeChanged(t){return this.lastSearchType!==t}isOptionsChanged(t){if(!t||0===Object.keys(t).length)return!1;const e={...this.lastOptions,...t};return this.lastOptions.caseSensitive!==e.caseSensitive||this.lastOptions.wholeWord!==e.wholeWord}stopSearch(t){const e=this.searchers.get(t);e&&(e.stop(),this.searchers.delete(t))}nextText(){const t=this.curSearcher;t&&!t.isStopped&&t.next()}previousText(){const t=this.curSearcher;t&&!t.isStopped&&t.previous()}selectText(t,e){const i=this.curSearcher;i&&!i.isStopped&&i.selectText(t,e)}clearSearchText(){this.searchers.forEach(t=>{t.stop()}),this.searchers.clear(),this.isCleared=!0,this.clearSearchTextFromPage(),this.context.render(49),this.curSearcher=null,this.curText=null,this.lastSearchType=null,this.context.hooks.searchTextCleared.emit()}clearSearchTextFromPage(){const t=this.context.getActiveTab();t&&t.allPages.forEach(t=>{t.clearSearchedText()})}dispose(){this.context=null,this.searchers.forEach(t=>{t.stop()}),super.dispose()}}class vC{constructor(t){Yi(this,"context",void 0),Yi(this,"isPointerdown",!1),Yi(this,"isStartTextSelection",!1),Yi(this,"startTextPosition",void 0),Yi(this,"endTextPosition",void 0),Yi(this,"textSelectionTimerMobile",void 0),Yi(this,"isEditTextStart",!1),Yi(this,"isEditTextEnd",!1),Yi(this,"isMovedForTextSelection",!1),Yi(this,"isZoomedForTextSelection",!1),Yi(this,"textSelectionThreshold",1),Yi(this,"clearSelectionTimerThreshold",3),Yi(this,"startPoint",void 0),Yi(this,"hasSelectedText",!1),Yi(this,"textPages",[]),Yi(this,"clickTimer",void 0),Yi(this,"clickCount",0),Yi(this,"lastClickPoint",void 0),Yi(this,"canvas",void 0),Yi(this,"needRenderMagnifier",!1),Yi(this,"magnifierPoint",void 0),Yi(this,"canPan",!1),Yi(this,"isMove",!1),Yi(this,"moveThreshold",2),Yi(this,"autoScrollTimer",void 0),Yi(this,"hitPage",void 0),Yi(this,"autoScrollStepSize",6/ao()),Yi(this,"isAutoScroll",!1),Yi(this,"lastAutoScrollEvent",void 0),Yi(this,"lastMoveEvent",void 0),Yi(this,"pointerNum",0),Yi(this,"isTouchstart",!1),this.context=t,this.canvas=this.context.rendererService.getCanvasDom(),this.context.hooks.afterRender.on(()=>{this.needRenderMagnifier&&this.context.magnifierService.render("text",this.canvas,this.magnifierPoint)},this.context)}get isTextSelectionMode(){return"textSelection"===this.context.viewerConfig.toolMode}pointerdownHandler(t){if(this.isPointerdown||!this.isTextSelectionMode)return;const e=this.context.getActiveTab();if(null==e||!e.total)return;if(!this.context.isDefaultViewer)return;this.isAutoScroll=!1,this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null);const[i]=this.context.toCanvas(t),{page:n}=this.context.getPointerOverPageInfo(i.pageX,i.pageY).pageInfo;if(!n)return;const s=this.context.core.pageService.getPage(n.uid);if(this.context.annotationEditService.hasActiveAnnotation()&&this.context.annotationEditService.deactivateAnnotation(),s.isTextPage&&s.visibleLines){const s=!oy(t),o=fw(n.mediaBox,i.pageX,i.pageY,n.rotation),r={x:o.pointerX,y:o.pointerY},a=n.isPointOnTextStart(r),l=n.isPointOnTextEnd(r);if((a||l)&&this.clickCount<1)this.isEditTextStart=a,this.isEditTextEnd=l,this.context.hooks.beforeTextSelected.emit(),s&&this.context.viewerConfig.enableTextMagnifier&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:i.pageX,y:i.pageY},this.context.render(35));else if(s)!this.isStartTextSelection&&this.pointerNum<2&&(this.textSelectionTimerMobile&&clearTimeout(this.textSelectionTimerMobile),this.textSelectionTimerMobile=setTimeout(()=>{if(this.pointerNum>1)return;clearTimeout(this.textSelectionTimerMobile),this.textSelectionTimerMobile=null;const t=this.context.calcTextStartPosition({x:i.pageX,y:i.pageY},n);if(t){this.context.textSelectionService.clearSelectedTexts(),this.startTextPosition=t,this.endTextPosition=t,this.isStartTextSelection=!0;const{textPages:n,startCharRect:s,endCharRect:o,startTextPosition:r,endTextPosition:a}=this.context.textSelectionService.calcSelectedText(this.startTextPosition,this.endTextPosition);e.setTextSelection(n,s,o,r,a),this.hasSelectedText=!0,this.textPages=n,this.context.viewerConfig.enableTextMagnifier&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:i.pageX,y:i.pageY}),this.context.render(36),this.context.hooks.beforeTextSelected.emit()}},this.context.viewerConfig.enterTextModeTimeMobile));else if(oy(t)){const t=this.context.calcTextStartPosition({x:i.pageX,y:i.pageY},n);if(t&&(this.startTextPosition=t,this.context.textSelectionService.clearSelectedTexts(),this.isStartTextSelection=!0,this.context.hooks.beforeTextSelected.emit()),this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null),this.clickTimer=setTimeout(()=>{this.clickCount=0,this.clickTimer=null},this.context.viewerConfig.multipleClickTimeout),this.clickCount>0)if(this.lastClickPoint.x===i.pageX&&this.lastClickPoint.y===i.pageY){const i=e.uidToIndex(n.uid);1===this.clickCount?t&&t.lineUid&&this.selectClickedText(t.lineUid,r,n.uid,i,!0):this.clickCount>1&&t&&t.lineUid&&this.selectClickedText(t.lineUid,r,n.uid,i,!1),this.clickCount+=1}else this.clickCount=1,this.lastClickPoint={x:i.pageX,y:i.pageY};else this.clickCount=1,this.lastClickPoint={x:i.pageX,y:i.pageY}}}if(this.canPan?(this.context.cursorService.applyCursorState(15),this.context.cursorService.lockCursor()):(this.context.cursorService.applyCursorState(16),this.context.cursorService.lockCursor()),!this.isStartTextSelection){const{scrollLeft:e,scrollTop:i}=this.context.viewService.getMaxScrollValue();(e>0||i>0)&&(this.isMove=!0,this.context.moveService.startHandler(t))}this.startPoint={x:i.pageX,y:i.pageY},this.isPointerdown=!0}selectClickedText(t,e,i,n,s){if(!t)return;this.context.clearSelectedTexts();const o=this.context.core.pageService.getPage(i);if(!o.isTextPage)return;const r=o.lineMap.get(t).visibleIndex;if(-1===r)return;let a;if(s){if(a=o.getSelectedTextWord(r,e),!a)return}else a=o.getSelectedTextSegment(r,e);if(!a)return;const{start:l,end:h}=a,c={...l,pageUid:o.uid,pageIndex:n,mediaBoxPoint:{...e}},d={...h,pageUid:o.uid,pageIndex:n,mediaBoxPoint:{...e}};this.startTextPosition=c,this.endTextPosition=d;const{textPages:u,startCharRect:p,endCharRect:g,startTextPosition:f,endTextPosition:m}=this.context.textSelectionService.calcSelectedText(this.startTextPosition,this.endTextPosition);this.context.getActiveTab().setTextSelection(u,p,g,f,m),this.hasSelectedText=!0,this.textPages=u,this.context.render(37)}pointerMoveForAutoScroll(t){if(!this.isTextSelectionMode||!this.context.viewerConfig.enableTextSelection)return;const e=this.context.getActiveTab();if(null!=e&&e.total&&!(this.pointerNum>1)&&this.context.isDefaultViewer&&this.context.isDefaultViewer&&this.isAutoScroll&&(e.context.maxScrollTop||e.context.maxScrollLeft)&&this.context.viewerConfig.enableAutoScrollForTextSelection){const e=this.checkPointermoveDirection(t);this.autoScroll(e)}}autoScroll(t){const e=this.context.getActiveTab();if(null==e||!e.total)return;const{maxScrollTop:i,scrollTop:n,maxScrollLeft:s,scrollLeft:o}=e.context,r=this.context.viewerConfig.autoScrollStepSize/ao();let a=!1;i&&t.top&&0!==n&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollTop:t,scrollTop:i}=e.context;var n;t&&(0!==i?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(0,-r),this.pointermoveHandler(this.lastAutoScrollEvent,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(0,-r)),i&&t.bottom&&n!==i&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollTop:t,scrollTop:i}=e.context;var n;t&&(i!==t?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(0,r),this.pointermoveHandler(this.lastAutoScrollEvent,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(0,r)),s&&t.left&&0!==o&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollLeft:t,scrollLeft:i}=e.context;var n;t&&(0!==i?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(-r,0),this.pointermoveHandler(this.lastAutoScrollEvent,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(-r,0)),s&&t.right&&o!==s&&(a=!0,this.autoScrollTimer||(this.autoScrollTimer=setInterval(()=>{const{maxScrollLeft:t,scrollLeft:i}=e.context;var n;t&&(i!==t?null!==(n=this.hitPage)&&void 0!==n&&n.isLoaded&&(this.context.viewService.scrollBy(r,0),this.pointermoveHandler(this.lastAutoScrollEvent,!0)):this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null))},40)),this.context.viewService.scrollBy(r,0)),this.autoScrollTimer&&!a&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null)}checkPointermoveDirection(t){const e={left:!1,top:!1,right:!1,bottom:!1};if(!this.context.getActiveTab())return e;const i=this.context.rendererService.getCanvasDom(),{top:n,bottom:s,left:o,right:r}=i.getBoundingClientRect();return t.clientY<n&&(e.top=!0),t.clientY>s&&(e.bottom=!0),t.clientX<o&&(e.left=!0),t.clientX>r&&(e.right=!0),e}pointermoveHandler(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!this.isTextSelectionMode||!this.context.viewerConfig.enableTextSelection||this.pointerNum>1)return;const i=this.context.getActiveTab();if(null==i||!i.total)return;if(!this.context.isDefaultViewer)return;const[n]=this.context.toCanvas(t),{page:s}=this.context.getPointerOverPageInfo(n.pageX,n.pageY).pageInfo;if(!s)return;const o=this.context.rendererService.getCanvasDom().getBoundingClientRect();!e&&o.top<=t.clientY&&o.bottom>=t.clientY&&o.left<=t.clientX&&o.right>=t.clientX&&(this.lastAutoScrollEvent=t),this.hitPage=s,this.autoScrollTimer&&!e&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null),this.autoScrollStepSize=this.context.viewerConfig.autoScrollStepSize/ao();const r=this.context.core.pageService.getPage(s.uid);if(this.isPointerdown){const e=(null==r?void 0:r.visibleLines)&&(null==r?void 0:r.isTextPage),o=qs(this.startPoint,{x:n.pageX,y:n.pageY});if(o>this.textSelectionThreshold&&(this.isMovedForTextSelection=!0),o>=this.clearSelectionTimerThreshold&&!this.isStartTextSelection&&this.textSelectionTimerMobile&&(clearTimeout(this.textSelectionTimerMobile),this.textSelectionTimerMobile=null),this.isEditTextStart&&e)this.isStartTextSelection=!0,this.isEditTextStart=!1,this.startTextPosition={...i.endTextPosition};else if(this.isEditTextEnd&&e)this.isStartTextSelection=!0,this.isEditTextEnd=!1,this.startTextPosition={...i.startTextPosition};else if(this.context.viewerConfig.enableTextSelection&&this.isStartTextSelection&&e){const{maxScrollTop:e,maxScrollLeft:o}=i.context;(e||o)&&this.context.viewerConfig.enableAutoScrollForTextSelection&&(this.isAutoScroll=!0),this.context.cursorService.lockCursor();const r=this.context.calcTextEndPosition({x:n.pageX,y:n.pageY},s,i,this.startTextPosition.mediaBoxPoint);if(r){this.endTextPosition=r;const{textPages:e,startCharRect:s,endCharRect:o,startTextPosition:a,endTextPosition:l}=this.context.textSelectionService.calcSelectedText(this.startTextPosition,this.endTextPosition);i.setTextSelection(e,s,o,a,l),this.hasSelectedText=!0,this.textPages=e,!oy(t)&&this.context.viewerConfig.enableTextMagnifier&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:n.pageX,y:n.pageY}),this.context.render(38)}}else!this.isEditTextEnd&&!this.isStartTextSelection&&this.isMove&&o>this.moveThreshold&&(this.context.moveService.moveHandler(t),this.context.cursorService.applyCursorState(14))}else{let t=1;if(!this.isStartTextSelection&&r.visibleLines&&null!=r&&r.isTextPage){const e=fw(s.mediaBox,n.pageX,n.pageY,s.rotation),i={x:e.pointerX,y:e.pointerY},o=s.isPointOnTextStart(i),a=s.isPointOnTextEnd(i);if(o||a)this.canPan=!1,t=16;else{const e=r.getHoveredTextLineIndex(i);s.isPointOnTextSelection(i)||-1!==e?(this.canPan=!1,t=16):(this.canPan=!0,t=14)}}this.context.cursorService.applyCursorState(t)}this.lastMoveEvent=t}pointerupHandler(t){if(this.isPointerdown){if(this.context.cursorService.unlockCursor(),this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null),this.isAutoScroll=!1,this.hitPage&&(this.hitPage=null),this.isStartTextSelection||this.isMovedForTextSelection||this.isZoomedForTextSelection||this.context.textSelectionService.clearSelectedTexts(),this.textSelectionTimerMobile&&clearTimeout(this.textSelectionTimerMobile),this.hasSelectedText){const t=Ff.create(this.context.textSelectionService.getSelectedTexts(),this.textPages);this.textPages=[],this.context.hooks.textSelected.emit(t),this.context.hooks.afterTextSelected.emit()}if(oy(t)&&this.lastClickPoint){const[e]=this.context.toCanvas(t);e.pageX===this.lastClickPoint.x&&e.pageY===this.lastClickPoint.y||(this.clickCount=0,this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null))}this.isMove&&this.context.moveService.endHandler(t),this.isMove=!1,this.hasSelectedText=!1,this.isStartTextSelection=!1,this.isPointerdown=!1,this.isMovedForTextSelection=!1,this.isEditTextStart=!1,this.isEditTextEnd=!1,this.isZoomedForTextSelection=!1,this.needRenderMagnifier&&this.context.magnifierService.hide(),this.needRenderMagnifier=!1,this.magnifierPoint=null,this.context.render(39),this.canPan&&this.context.cursorService.applyCursorState(14)}}visibilityChangedHandler(){this.lastMoveEvent&&(this.pointerupHandler(this.lastMoveEvent),this.lastMoveEvent=null)}touchstartHandler(t){if(this.pointerNum=t.targetTouches.length,this.context.isDefaultViewer){const{enableZoom:e,enableZoomInPanMode:i,enableZoomWithTouch:n}=this.context.viewerConfig;if(!this.isTextSelectionMode||2!==t.targetTouches.length||this.isTouchstart||!e||!n||!i)return;this.isTouchstart=!0,this.context.zoomService.touchstartHandler(t)}}touchmoveHandler(t){this.pointerNum=t.targetTouches.length,2===t.targetTouches.length&&this.isTouchstart&&this.context.isDefaultViewer&&(this.context.zoomService.touchmoveHandler(t),this.isZoomedForTextSelection=!0)}touchendHandler(t){this.pointerNum=t.targetTouches.length,this.isTouchstart&&(this.isTouchstart=!1,this.context.isDefaultViewer&&this.context.zoomService.touchendHandler(t))}wheelHandler(t){if(this.pointerNum=0,this.isTextSelectionMode&&this.context.isDefaultViewer)if(po(t)){const{enableZoom:e,enableZoomInTextSelectionMode:i,enableZoomWithCtrl:n}=this.context.viewerConfig;if(!e||!i||!n)return;this.context.zoomService.wheelHandler(t)}else this.context.scrollService.wheelHandler(t)}scrollHandler(t){this.isTextSelectionMode&&this.context.isDefaultViewer&&this.context.scrollService.scrollHandler(t)}keydownHandler(t){if(!this.isTextSelectionMode)return;const{context:e,context:{keyboardService:i,annotationEditService:n,isDefaultViewer:s,viewerConfig:{enableKeyboardInteraction:o,enableCopyCutPasteWithKeyboard:r,enableZoom:a,enableZoomInTextSelectionMode:l},isPointerWorking:h}}=this;if(!o||h||!s)return;const c=this.context.getActiveTab();if(null!=c&&c.total){if(po(t))switch(t.key){case"c":case"C":c.hasSelectedTexts&&r&&(t.preventDefault(),this.context.copySelectedTexts());break;case"y":case"Y":i.redoHandler(t);break;case"z":case"Z":i.undoHandler(t);break;case"-":a&&l&&i.zoomOutHandler(t);break;case"=":a&&l&&i.zoomInHandler(t)}switch(t.key){case"Escape":i.escapeHandler(t);break;case"Enter":i.enterHandler(t);break;case"PageUp":i.pageUpHandler(t);break;case"PageDown":i.pageDownHandler(t);break;case"Home":i.homeHandler(t);break;case"End":i.endHandler(t);break;case"ArrowLeft":i.arrowLeftHandler(t);break;case"ArrowRight":i.arrowRightHandler(t);break;case"ArrowUp":i.arrowUpHandler(t);break;case"ArrowDown":i.arrowDownHandler(t)}}}}class yC{constructor(t){Yi(this,"type",void 0),Yi(this,"magnifierCanvas",void 0),Yi(this,"tempCanvas",void 0),Yi(this,"ctx",void 0),Yi(this,"style",{type:"rect",size:100,borderColor:"#323232",borderWidth:3,magnification:3,crosshairWidth:1,crosshairColor:"#323232",background:"#fff"}),Yi(this,"isVisible",!1),Object.assign(this.style,t||{}),this.magnifierCanvas=document.createElement("canvas"),this.tempCanvas=document.createElement("canvas"),this.ctx=this.magnifierCanvas.getContext("2d"),this.magnifierCanvas.style.position="absolute";const e={position:"absolute",left:0,top:0,borderColor:this.style.borderColor,borderWidth:this.style.borderWidth,width:`${this.style.size}px`,height:`${this.style.size}px`,background:this.style.background,zIndex:6,display:"none"};"circle"===this.style.type&&(e.borderRadius="50%"),Object.assign(this.magnifierCanvas.style,e)}updatePosition(t){Object.assign(this.magnifierCanvas.style,{left:`${t.x}px`,top:`${t.y}px`})}show(){this.isVisible||(this.magnifierCanvas.style.display="block",this.isVisible=!0)}hide(){this.isVisible&&(this.magnifierCanvas.style.display="none",this.isVisible=!1)}render(t,e,i){if(!this.isVisible)return;const{type:n,size:s,borderColor:o,borderWidth:r,magnification:a,crosshairColor:l,crosshairWidth:h}=this.style,c=s/2*devicePixelRatio,d=s*devicePixelRatio,u=2*Math.PI;if(this.magnifierCanvas.width=d,this.magnifierCanvas.height=d,i.x*devicePixelRatio<d&&i.y*devicePixelRatio<d){const{width:t}=e.getBoundingClientRect();this.updatePosition({x:t-s,y:0})}else this.updatePosition({x:0,y:0});const p=e.getContext("2d",{willReadFrequently:!0});p.save();const g=p.getImageData(i.x*devicePixelRatio-c,i.y*devicePixelRatio-c,d,d);p.restore(),this.tempCanvas.width=d,this.tempCanvas.height=d,this.tempCanvas.getContext("2d").putImageData(g,0,0);const f=this.ctx;if(f.save(),f.setTransform(1,0,0,1,0,0),f.clearRect(-c,-c,2*c,2*c),f.translate(c,c),f.beginPath(),"circle"===n?f.arc(0,0,c,0,u):f.rect(-c,-c,d,d),f.clip(),f.scale(a,a),f.drawImage(this.tempCanvas,-c,-c,d,d),f.closePath(),f.strokeStyle=o,f.lineWidth=r,f.stroke(),"crop"===t){f.beginPath();const t=.5*c/a;f.moveTo(0,-t),f.lineTo(0,t),f.moveTo(-t,0),f.lineTo(t,0),f.closePath(),f.strokeStyle=l,f.lineWidth=h/a,f.stroke()}f.restore()}}class xC extends Wo{constructor(t){super(),Yi(this,"context",void 0),Yi(this,"canvas",void 0),Yi(this,"ctx",void 0),Yi(this,"magnifier",void 0),this.context=t}initMagnifier(t){this.magnifier||(this.magnifier=new yC(t)),this.context.viewService.scrollerAndCanvasContainer.appendChild(this.magnifier.magnifierCanvas)}render(t,e,i){"crop"===t&&!this.context.viewerConfig.enableMagnifier||"text"===t&&!this.context.viewerConfig.enableTextMagnifier||(this.show(),this.magnifier.render(t,e,i))}show(){this.magnifier.show()}hide(){this.magnifier.hide()}dispose(){super.dispose(),this.context=null}}const wC={isClearOptimization:!1,isThumbnail:!1,isResize:!1,renderReason:null};class CC extends Wo{constructor(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),Yi(this,"core",void 0),Yi(this,"viewer",void 0),Yi(this,"uid",void 0),Yi(this,"groupUid",void 0),Yi(this,"hooks",void 0),Yi(this,"mainViewerUid",null),Yi(this,"viewService",void 0),Yi(this,"rendererService",void 0),Yi(this,"tabService",void 0),Yi(this,"layoutService",void 0),Yi(this,"styleService",void 0),Yi(this,"configService",void 0),Yi(this,"visibilityService",void 0),Yi(this,"annotationEditService",void 0),Yi(this,"cropBoxEditService",void 0),Yi(this,"perspectiveQuadEditService",void 0),Yi(this,"eventsService",void 0),Yi(this,"dragService",void 0),Yi(this,"moveService",void 0),Yi(this,"scrollService",void 0),Yi(this,"zoomService",void 0),Yi(this,"slideService",void 0),Yi(this,"textSelectionService",void 0),Yi(this,"textSearchService",void 0),Yi(this,"optimizationService",void 0),Yi(this,"interactionService",void 0),Yi(this,"selectPagesService",void 0),Yi(this,"keyboardService",void 0),Yi(this,"cursorService",void 0),Yi(this,"magnifierService",void 0),Yi(this,"viewerConfig",_s(ew)),Yi(this,"postfix",void 0),Yi(this,"isDestroyed",!1),Yi(this,"viewportWidth",0),Yi(this,"viewportHeight",0),Yi(this,"scrollByCurrentChanged",!1),Yi(this,"isInitialized",!1),Yi(this,"addPagesTimer",null),Yi(this,"isPanning",void 0),Yi(this,"isZooming",void 0),Yi(this,"isSliding",void 0),Yi(this,"isFocusCanvas",!1),Yi(this,"isFocusViewer",!1),Yi(this,"isPointerWorking",!1),Yi(this,"isPointerOverScrollbar",!1),Yi(this,"hasBoxRendererModule",!1),Yi(this,"hasAnnotationModule",!1),Yi(this,"renderingMode","image"),this.core=t,this.viewer=e,this.postfix=e.postfix,this.hooks=e.hooks,this.uid=e.uid,this.groupUid=e.groupUid,_o(i,this.viewerConfig),this.styleService=new xw(this),this.viewService=this.register(new Mw(this,this.hooks)),this.rendererService=this.register(new Fw(this,this.hooks)),this.layoutService=new Xw(this,this.hooks),this.configService=this.register(new Zw(this)),this.tabService=this.register(new yw(this)),this.visibilityService=new _w(this),this.optimizationService=this.register(new sC(this)),this.handleViewerModeChanged(),this.eventsService=this.register(new Jw(this)),this.dragService=this.register(new Kw(this)),this.moveService=this.register(new Qw(this)),this.scrollService=this.register(new tC(this)),this.zoomService=this.register(new eC(this)),this.slideService=this.register(new nC(this)),this.textSelectionService=this.register(new pC(this)),this.textSearchService=this.register(new mC(this)),this.interactionService=this.register(new oC(this,new lC(this),new hC(this),new cC(this),new dC(this),new uC(this),new vC(this))),this.selectPagesService=this.register(new rC(this)),this.keyboardService=this.register(new aC(this)),this.cursorService=this.register(new gC(this)),(this.isDefaultViewer||this.isPerspectiveViewer)&&(this.magnifierService=this.register(new xC(this)),this.hooks.uiInitCompleted.on(()=>{this.magnifierService.initMagnifier(this.viewerConfig.magnifierStyle)},this)),this.eventsService.handleExternalEvents(),this.optimizationService.handleOptimizationEvents(),this.interactionService.handleEvents(),this.isThumbnailViewer&&this.viewer.on("thumbnailBind",t=>{this.mainViewerUid=t})}get eventDom(){return this.viewService.scrollContainer}get isCropToolMode(){return"crop"===this.viewerConfig.toolMode}get isVisible(){var t;return"visible"===(null===(t=this.viewerConfig)||void 0===t?void 0:t.visibility)}syncViewer(t){const e=t.getActiveTab();if(!e)return;const i=this.tabService.createTab(e.doc);if(i.isDocType){const{width:t,height:e}=this.viewService.getViewportSize();i.updateViewportSize(t,e)}i.currentUid=e.currentUid,i.selectPages([...e.selected]),this.tabService.activateTab(i.uid),this.hooks.syncDocument.emit(i.doc),this.emitPageChangedEvent(i),this.showTab(i,{renderReason:2}),this.emitPageChangedAfterRenderEvent(i)}toCanvas(t){const e=[];let i=null;i=t instanceof MouseEvent||t instanceof PointerEvent?[t]:arguments.length>1&&void 0!==arguments[1]&&arguments[1]?t.changedTouches:t.touches;const{left:n,top:s}=this.rendererService.getCanvasPageRect();for(let t=0;t<i.length;t++){const o=i[t];e.push({pageX:o.pageX-n,pageY:o.pageY-s})}return e}isPointerOverCanvas(t){const e=this.rendererService.getCanvasDom().getBoundingClientRect();return e.top<=t.clientY&&e.bottom>=t.clientY&&e.left<=t.pageX&&e.right>=t.pageX}getPointerOverPageInfo(t,e){const i=function(t,e,i){const n={pageInfo:{isOver:!1,pointerX:-1,pointerY:-1,page:null},imageInfo:{isOver:!1,pointerX:-1,pointerY:-1,page:null},index:-1};if(t)for(let s=0;s<t.visibleChildren.length;s++){const o=t.visibleChildren[s],r=Xv(o,e,i,o.isVisible,0);if(r.isOver){n.index=t.getPageIndex(o),Object.assign(n.pageInfo,r);const s=Xv(o.image,e,i,!0,o.rotation);return s.isOver&&Object.assign(n.imageInfo,s),n}}return n}(this.getActiveTab(),t,e);return i}getPointerOverMediaBoxInfo(t,e,i,n){return fw(t,e,i,n)}getPointerOverAutoScrollBoundaryInfo(t,e){const i={left:!1,top:!1,right:!1,bottom:!1};if(!this.getActiveTab())return i;const{width:n,height:s}=this.rendererService.getCanvasPageRect(),o=this.viewerConfig.autoScrollBoundarySize;return e<=o&&(i.top=!0),e>=s-o&&(i.bottom=!0),t<=o&&(i.left=!0),t>=n-o&&(i.right=!0),i}resize(){if(this.tabService.resizeScrollbar(),this.isCaptureViewer)return;this.viewService.resizeViewport(),this.updateViewportSize(),this.rendererService.updateCanvasSize(),this.styleService.isCheckboxStyleChanged=!0,this.styleService.isPageNumberStyleChanged=!0;const t=this.getActiveTab();t&&(this.clearCurrentTabOptimization(),this.showTab(t,{renderReason:3,isClearOptimization:!0,isThumbnail:!1,isResize:!0}))}updateViewportSize(){const{width:t,height:e}=this.viewService.getViewportSize();this.viewportWidth=t,this.viewportHeight=e,this.tabService.updateViewportSize(t,e)}handleViewerModeChanged(){const{postfix:t,viewService:e,isDefaultViewer:i,isPerspectiveViewer:n,isThumbnailViewer:s}=this;if(i||n||s){e.createMainAndThbContainer(t),e.createMainContainer(t),s||e.createThumbnailContainer(t),i&&(e.createVideoContainer(t),e.createAudioContainer(t)),iy(e.mainAndThbContainer,"flex");const{width:n,height:o}=e.getViewportSize();this.rendererService.initRenderer(e.canvasContainer,n,o),this.rendererService.updateCanvasSize()}}loadSource(t,e){const i=this.getActiveTab();let n=null==i?void 0:i.uid;if(!i){const t=this.core.createDocument({name:Dm(),type:"document"});this.viewer.openDocument(t),n=t.uid}const s=pp.buildInfo("loadSource",{docUid:n,current:0,total:Ts(t)?t.length:1});return pp.info(s),this.core.loadSource(t,n,{exception:e?"fail":"ignore"},s).catch(t=>{throw s.status="Failed",pp.info(s),t})}openDocument(t){const{tabService:e}=this;let i=e.getTab(t.uid);if(!i){const n=e.getActiveTab();if(n&&(clearTimeout(this.addPagesTimer),this.addPagesTimer=null,this.hooks.closeDocument.emit(n.doc)),i=e.createTab(t),i.isDocType){const{width:t,height:e}=this.viewService.getViewportSize();i.updateViewportSize(t,e)}}i.isActive||(this.tabService.activateTab(i.uid),this.emitPageChangedEvent(i),this.showTab(i,{renderReason:4}),this.hooks.openDocument.emit(t),this.emitPageChangedAfterRenderEvent(i))}closeTabs(t){const e=t.filter(t=>this.tabService.hasTab(t));if(!e.length)return;const i=e.reduce((t,e,i)=>{const n=this.tabService.getTab(e);return n&&t.push(n),t},[]);i.forEach(t=>{t.isActive&&(clearTimeout(this.addPagesTimer),this.addPagesTimer=null,this.clearCurrentTabOptimization()),this.tabService.closeTab(t.uid),this.hooks.closeDocument.emit(t.doc)});const n=this.tabService.getActiveTab();n?this.showTab(n,{renderReason:5}):(this.rendererService.docRenderer.clear(),this.resetCanvas(),this.hooks.pageChanged.emit(Pf.create(-1,0)))}resetCanvas(){this.isCaptureViewer||(this.viewService.resetViewport(),this.rendererService.updateCanvasSize(),this.rendererService.clearCanvas())}render(t){if("hidden"===this.viewerConfig.visibility)return;if(this.isDestroyed)return;const e=this.getActiveTab();e&&this.rendererService.render(e,t)}showCurrentTab(t){const e=this.getActiveTab();null!=e&&e.total&&this.showTab(e,t)}showTab(t,e){this.isDestroyed||t.isDestroyed||(e={...wC,...e||{}},this.tabService.activateTab(t.uid),"hidden"!==this.viewerConfig.visibility&&(this.isDefaultViewer?this.showTabDefault(t,e):this.isThumbnailViewer?this.showTabThumbnail(t,e):this.isPerspectiveViewer&&this.showTabPerspective(t,e)))}showTabDefault(t,e){const i=t;if(!i.isDocType)return;if(e.isResize){if(!t.context.placeholderPages.length)return;t.context.updateReference()}i.style.visibility="visible";const n=i.context.zoom;this.layoutService.layout(i,e.renderReason),this.viewerConfig.zoom=i.context.zoom;const s=i.context.zoom!==n;if(this.viewService.updateScrollerContentSize(i),this.rendererService.updateCanvasSize(),!i.total)return this.loadVisiblePartData(),void this.rendererService.render(i,e.renderReason);let{scrollLeft:o,scrollTop:r}=i.context.parseReferenceDefault();if(e.isResize){const t=i.context.parseReferenceResize();o=t.scrollLeft,r=t.scrollTop}i.context.setTabScrollValue(o,r),this.viewService.scrollTo(o,r),this.visibilityService.handleVisibility(i),this.loadVisiblePages(i),(e.isZoomChanged||s)&&this.clearCurrentTabOptimization(),this.loadVisiblePartData(),this.rendererService.render(i,e.renderReason),this.emitZoomChangedEvent(i)}showTabPerspective(t,e){const i=t;if(!i.isDocType)return;if(i.style.visibility="visible",this.layoutService.layout(i,e.renderReason),this.viewService.updateScrollerContentSize(i),this.rendererService.updateCanvasSize(),!i.total)return this.loadVisiblePartData(),void this.rendererService.render(i,e.renderReason);const{scrollLeft:n,scrollTop:s}=i.context.parseReferenceDefault();i.context.setTabScrollValue(n,s),this.viewService.scrollTo(n,s),this.visibilityService.handleVisibility(i),this.loadVisiblePages(i),this.loadVisiblePartData(),this.rendererService.render(i,e.renderReason)}showTabThumbnail(t,e){if(!t.isDocType)return;if(t.style.visibility="visible",this.layoutService.layout(t,e.renderReason),this.viewService.updateScrollerContentSize(t),this.rendererService.updateCanvasSize(),!t.total)return this.loadVisiblePartData(),void this.rendererService.render(t,e.renderReason);if(t.isActive&&this.isVisible&&this.viewerConfig.autoScroll&&!e.isThumbnail){const{scrollLeft:e,scrollTop:i}=t.context.getScrollValuesByCurrentChanged();t.context.setTabScrollValue(e,i)}const{scrollLeft:i,scrollTop:n}=t.context;this.viewService.scrollTo(i,n),this.visibilityService.handleVisibility(t),this.loadVisiblePages(t),e.isClearOptimization&&this.clearCurrentTabOptimization(),this.loadVisiblePartData(),this.rendererService.render(t,e.renderReason)}loadPageImage(t){return this.isDefaultViewer||this.isThumbnailViewer?this.core.imageLoadService.loadDisplayImage(t):this.isPerspectiveViewer?this.core.imageLoadService.loadRawImage(t):null}loadVisiblePages(t){if(t.isDestroyed||null==t||!t.total)return;const e=[],i=[],n=t.getCurrentPage();let s=!1;t.preloadChildren.forEach(t=>{!t.isPreload||t.isLoaded||t.isLoading||(t.uid===(null==n?void 0:n.uid)?s=!0:t.isVisible?i.push(t):t.isPreload&&e.push(t))});const o=[];s&&o.push(n),o.push(...e.reverse(),...i.reverse()),"image"===this.viewerConfig.renderingMode?o.forEach(e=>{!e.isPreload||e.isLoaded||e.isLoading||(e.isLoading=!0,this.loadPageImage(e.uid).then(i=>{e.isLoading=!1,i&&this.renderPage(t,e,i,!0);const n=this.core.pageService.getPage(e.uid);n&&n.isTextPage&&!n.parsedTexts&&this.core.textLoadService.loadText([n.uid])}).catch(t=>{e.isLoading=!1}))}):"rgba"===this.viewerConfig.renderingMode&&(o.forEach(e=>{if(e.isPreload&&!e.isLoaded&&!e.isLoading){this.renderPage(t,e,null,!1);const i=this.core.pageService.getPage(e.uid);i&&i.isTextPage&&!i.parsedTexts&&this.core.textLoadService.loadText([i.uid])}}),this.loadVisiblePartData())}loadVisiblePartData(){if("rgba"!==this.viewerConfig.renderingMode)return;const t=this.tabService.getActiveTab();null!=t&&t.total&&!t.isDestroyed&&(t.preloadChildren.forEach(t=>{const e=this.core.pageService.getPage(t.uid);e.defaultRenderPage?t.image.defaultRenderPage=e.defaultRenderPage:e.isLoadingDefaultRenderPage||this.core.imageDataService.getDefaultRenderPage(this.uid,t.uid)}),t.visibleChildren.forEach(e=>{const i=this.core.pageService.getPage(e.uid);i.defaultRenderPage&&(e.image.defaultRenderPage=i.defaultRenderPage);const n=this.calcVisiblePartPage(e.uid);n&&e.isVisible&&(n.rect.forEach(t=>{}),n.x<0||n.y<0||n.width<=0||n.height,this.core.imageDataService.getRenderPage(this.uid,e.uid,e.visiblePart.width,e.visiblePart.height,e.visiblePart.rect).then(i=>{var s;if(!i)return;if(!e.isVisible||!e.visiblePart||e.visiblePart.uid!==n.uid)return;let o;o=null!==(s=e.image)&&void 0!==s&&null!==(s=s.visiblePartData)&&void 0!==s&&s.data?e.image.visiblePartData.data:document.createElement("canvas"),o.width=Math.max(e.visiblePart.width,1),o.height=Math.max(e.visiblePart.height,1);const r=o.getContext("2d").createImageData(i.imageInfo.imageWidth,i.imageInfo.imageHeight);r.data.set(i.imageData),o.getContext("2d").putImageData(r,0,0),e.visiblePartData={data:o,visiblePart:e.visiblePart},e.image.visiblePartData={data:o,visiblePart:e.visiblePart},this.rendererService.render(t,51)}).catch(t=>{}))}))}cancelLoadVisiblePartData(t){"rgba"===this.viewerConfig.renderingMode&&this.core.imageDataService.cancelGetRenderPage(this.uid,t)}cancelGetDefaultRenderPage(t){"rgba"===this.viewerConfig.renderingMode&&this.core.imageDataService.cancelGetDefaultRenderPage(this.uid,t)}calcVisiblePartPage(t){const e=this.core.pageService.getPage(t);if(!e)return null;const i=this.getActiveTab().getPageByUid(t),n=this.rendererService.getCanvasDom();let{width:s,height:o}=n;s/=devicePixelRatio,o/=devicePixelRatio;const{image:r}=i,a=r.getPosition(),{x:l,y:h}=a,{width:c,height:d}=r,{rotation:u}=e,p=(u%360+360)%360/90;let g=0,f=0,m=0,v=0;if(0===p?(g=Math.max(0,-l),f=Math.max(0,-h),m=Math.min(c,s,c+l,s-l),v=Math.min(d,o,d+h,o-h)):1===p?(g=Math.max(0,-h),f=Math.max(0,l-s),m=Math.min(c,o,c+h,o-h),v=Math.min(d,s,d-f,l)):2===p?(g=Math.max(0,l-s),f=Math.max(0,h-o),m=Math.min(c,s,c-g,l),v=Math.min(d,o,d-f,h)):3===p&&(g=Math.max(0,h-o),f=Math.max(0,l),m=Math.min(c,o,h,c-g),v=Math.min(d,s,s-l,d-f)),m<=0||v<=0)return null;const y=r.getScale();y.x,y.y;const x=Bo(g/y.x,Cr.displayResolution,Cr.dataResolution);let w=Bo(f/y.y,Cr.displayResolution,Cr.dataResolution);const C=Bo(m/y.x,Cr.displayResolution,Cr.dataResolution),b=Bo(v/y.y,Cr.displayResolution,Cr.dataResolution),S=Bo(e.mediaBox,Cr.displayResolution,Cr.dataResolution);w=2*S.top+S.height-(w+b),w=Math.max(0,w);const T={uid:Us(),x:g,y:f,width:m*devicePixelRatio,height:v*devicePixelRatio,rect:[x,w,x+C,w+b],imageScale:y};let E=!1;return i.visiblePart&&function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height&&t.rect.join(",")===e.rect.join(",")&&t.imageScale.x===e.imageScale.x&&t.imageScale.y===e.imageScale.y}(i.visiblePart,T)||(E=!0),E?(i.visiblePart=T,T):null}renderPage(t,e,i,n){if(!this.isDestroyed&&this.isVisible&&t.isActive&&t.allPages.includes(e)&&!t.isDestroyed&&e.isPreload&&(e.isLoaded=!0,n&&e.setImgDom(i),e.isVisible)){if(this.isDefaultViewer&&t.context.isSingleDisplay){const e=t.getCurrentPage();if(e&&!e.isLoaded)return}this.rendererService.render(t,51)}}emitPageChangedEvent(t){this.hooks.pageChanged.emit(Pf.create(t.current,t.total))}emitPageChangedAfterRenderEvent(t){this.hooks.pageChangedAfterRender.emit(Pf.create(t.current,t.total))}emitZoomChangedEvent(t){const{oldZoom:e,zoom:i}=t.context;this.hooks.zoomChanged.emit(Xf.create(ny(e),ny(i)))}afterPerspective(t,e){const i=this.getActiveTab();if(i&&i.uid===t){const t=i.getTextSelectionLines();null!=t&&t.find(t=>t.pageUid===e)&&this.clearSelectedTexts()}}beforeLoadSource(t){const{tabService:e}=this,i=e.getDocTab(t);i&&i.updateOldInfo()}afterLoadSource(t){const{tabService:e}=this,i=e.getDocTab(t);i&&(this.emitPageChangedAfterRenderEvent(i),i.updateOldInfo())}addPages(t,e,i,n){const{tabService:s}=this,o=s.getDocTab(t);o&&(o.appendPages(e,i,n),this.emitPageChangedEvent(o),o.isActive&&!this.addPagesTimer&&(this.addPagesTimer=setTimeout(()=>{o.isActive&&(this.scrollByCurrentChanged=!0,this.showTab(o,{renderReason:16})),clearTimeout(this.addPagesTimer),this.addPagesTimer=null},200)))}deletePages(t,e){const{tabService:i}=this,n=i.getDocTab(t);n&&(this.clearOptimization(e),n.deletePages(e),this.textSelectionService.clearSelectedTexts(),this.hooks.deletePages.emit(gm.create(e,n.uid)),this.emitEventsForTab(n,{renderReason:23}))}deleteAllPages(t){const{tabService:e}=this,i=e.getDocTab(t);if(!i)return;const n=i.getAllPageUids();this.clearOptimization(n),i.deleteAllPages(),this.textSelectionService.clearSelectedTexts(),this.hooks.deletePages.emit(gm.create(n,i.uid)),this.emitEventsForTab(i,{renderReason:24})}setCurrentPage(t,e){const{tabService:i}=this,n=i.getDocTab(t);n&&n.current!==e&&(this.clearOptimizePageForSelectedPages([e]),n.gotoPage(e),this.emitEventsForTab(n,{renderReason:25}))}selectPages(t,e){const{tabService:i}=this,n=i.getDocTab(t);if(!n)return;const s=n.getSelected(),o=n.getSelectedIndices();let r=!1;if(o.length!==e.length)r=!0;else for(let t=0;t<e.length;t++)if(o[t]!==e[t]){r=!0;break}if(!r)return;this.clearOptimizePageForSelectedPages(e);const a=n.indicesToUids(e);if(n.selectPages(a),n.isActive){this.showTab(n,{isClearOptimization:!1,isThumbnail:!0,renderReason:17});const t=Sm.create(o,[...e],[...s],a);this.hooks.selectedPageChanged.emit(t)}}movePages(t,e,i){const n=this.tabService.getDocTab(t);n&&(n.movePages(e,i),this.textSelectionService.clearSelectedTexts(),this.emitEventsForTab(n,{isClearOptimization:this.isDefaultViewer,renderReason:26},!0))}switchPage(t,e,i){const n=this.tabService.getDocTab(t);n&&(n.switchPage(e,i),this.textSelectionService.clearSelectedTexts(),this.emitEventsForTab(n,{isClearOptimization:this.isDefaultViewer,renderReason:27},!0))}reorderPages(t,e){const i=this.tabService.getDocTab(t);i&&i.reorderPages(e)}afterReorderPages(t,e){const i=this.tabService.getDocTab(t);i&&(this.textSelectionService.clearSelectedTexts(),this.emitEventsForTab(i,{isClearOptimization:this.isDefaultViewer,renderReason:28},!0))}emitEventsForTab(t,e){t.isActive&&(this.emitPageChangedEvent(t),this.scrollByCurrentChanged=!0,this.showTab(t,e),this.emitPageChangedAfterRenderEvent(t))}updatePage(t,e,i){const n=this.tabService.getTab(t);if(n&&n.isActive){var s;const t=n.getPageByUid(e);t.isLoaded=!1,t.isLoading=!1,(t=>{const e=window.URL||window.webkitURL;/^blob:/.test(t)&&e.revokeObjectURL(t)})((null===(s=t.image.style)||void 0===s?void 0:s.img).src),this.clearOptimization([e]),this.clearSelectedTexts(),this.showTab(n,{renderReason:18})}}renameDoc(t,e){const{tabService:i}=this,n=i.getTab(t);n&&(n.rename(e),this.hooks.tabChanged.emit())}filter(t,e,i){if(this.isPerspectiveViewer||this.isCaptureViewer)return;const n=this.getActiveTab();n&&n.uid===t&&(e.forEach(t=>{const e=n.getPageByUid(t);e&&(e.isLoaded=!1)}),this.hooks.filterChanged.emit(kf.create(t,e,i)),this.loadVisiblePages(n),this.clearOptimization(e),this.loadVisiblePartData(),this.rendererService.render(n,52))}activateTab(t){const e=this.tabService.getTab(t);return!!e&&(this.showTab(e,{renderReason:19}),!0)}getActiveTab(){return this.tabService.getActiveTab()}getSelectedTexts(){const t=this.getActiveTab();return null!=t&&t.total?this.textSelectionService.getSelectedTexts():""}async copySelectedTexts(){const t=this.getActiveTab();if(null==t||!t.total)return Promise.reject(new Error("no text selected"));const e=this.textSelectionService.getSelectedTexts();return await navigator.clipboard.writeText(e),Promise.resolve(void 0)}clearSelectedTexts(){this.textSelectionService.clearSelectedTexts()}dispose(){this.tabService.getAllTabs().forEach(t=>{const e=[];if(t.allPages.forEach((t,i)=>{[...t.mediaBox.childNodes].forEach(t=>{null==t||t.destroy()}),t.isPreload&&e.push({from:!0,to:!1,pageUid:t.uid,index:i})}),e.length){const i=um.create(t.uid,this.uid,this.viewerConfig.viewerMode,e);this.core.viewerService.onPagePreloadChanged.emit(i)}}),this.isDestroyed=!0,this.hooks.destroy.emit(),super.dispose()}get isDefaultViewer(){return this.viewerConfig.viewerMode===jg.DEFAULT}get isThumbnailViewer(){return this.viewerConfig.viewerMode===jg.THUMBNAIL}get isPerspectiveViewer(){return this.viewerConfig.viewerMode===jg.PERSPECTIVE}get isCaptureViewer(){return this.viewerConfig.viewerMode===jg.CAPTURE}zoomTo(t,e,i){this.zoomService.zoomTo(t,e,i)}getPageRenderSize(t){const e=this.core.pageService.getPage(t);return this.isPerspectiveViewer?e.raw.getPageSize():e.mediaBox}emit(t,e){this.viewer.emit(t,e)}hasCallback(t){return this.viewer.emitter.hasCallback(t)}clearCurrentTabOptimization(){if(!this.viewerConfig.enableOptimizePage)return;const t=this.getActiveTab();if(t){const e=t.allPages.map(t=>t.uid);this.clearOptimization(e)}}clearOptimization(t){const e=[],i=this.getActiveTab();i&&t.forEach(t=>{const n=i.getPageByUid(t);n&&(e.push(n.optimizationUid),n.clearOptimization())}),this.optimizationService.cancelOptimization(e)}clearOptimizePageForSelectedPages(t){if(!this.isThumbnailViewer)return;if(!this.viewerConfig.enableOptimizePage)return;const e=this.getActiveTab();if(!e)return;const i=this.styleService.isSelectedBorderWidthEqualNormal(),n=this.styleService.isSelectedBorderWidthEqualHovered();if(i&&n)return;t.forEach(t=>{const s=e.getPageByIndex(t);(!n&&s.isHovered||!i&&!e.selected.includes(s.uid))&&this.clearOptimization([s.uid])});const s=e.indicesToUids(t);e.selected.forEach(t=>{const o=e.getPageByUid(t);(!n&&o.isHovered||!i&&!s.includes(t))&&this.clearOptimization([t])})}applyCursorState(t){this.cursorService.applyCursorState(t)}async searchNextText(t,e){const i=this.getActiveTab();return!!i&&this.textSearchService.searchNextText(i.uid,t,e)}async searchPrevText(t,e){const i=this.getActiveTab();return!!i&&this.textSearchService.searchPrevText(i.uid,t,e)}async searchFullText(t,e){const i=this.getActiveTab();return!!i&&this.textSearchService.searchFullText(i.uid,t,e)}selectSearchText(t,e){this.textSearchService.selectText(t,e)}nextSearchText(){this.textSearchService.nextText()}prevSearchText(){this.textSearchService.previousText()}clearSearchText(){this.textSearchService.clearSearchText()}getVisiblePagesInfo(){const t=this.getActiveTab();if(!t)return[];if(this.isCaptureViewer)return[];if("hidden"===this.viewerConfig.visibility)return[];const{visibleChildren:e}=t,i=[];if(e.length>0){var n;const{canvas:s}=this.rendererService.docRenderer;let o=null===(n=this.viewer)||void 0===n||null===(n=n.ui)||void 0===n?void 0:n.container;this.isThumbnailViewer&&this.mainViewerUid&&(o=this.core.viewerService.getViewer(this.mainViewerUid).ui.container);const{left:r,top:a}=o.getBoundingClientRect(),{left:l,top:h}=s.getBoundingClientRect();for(let n=0;n<e.length;n++){const s=e[n],o=t.getPageIndex(s),{x:c,y:d}=s.getPosition();i.push({pageUid:s.uid,pageIndex:o,width:s.bounds.width,height:s.bounds.height,isHovered:s.isHovered,isSelected:s.isSelected,canvasOffsetX:c,canvasOffsetY:d,containerOffsetX:l-r+c,containerOffsetY:h-a+d})}}return i}calcTextStartPosition(t,e){let i=t;if(!(arguments.length>2&&void 0!==arguments[2]&&arguments[2])){const n=this.getPointerOverMediaBoxInfo(e.mediaBox,t.x,t.y,e.rotation);i={x:n.pointerX,y:n.pointerY}}const n=this.core.pageService.getPage(e.uid),s=n.getHoveredTextLineIndex(i);if(-1!==s){const t=n.visibleLines[s],o=n.getSelectedTextCharIndex(s,i);return{lineUid:t.uid,charUid:t.chars[o].uid,pageUid:e.uid,mediaBoxPoint:i}}return null}calcTextEndPosition(t,e,i,n){let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const o=this.core.pageService.getPage(e.uid);if(!o.parsedTexts)return null;let r=t;if(!s){const i=this.getPointerOverMediaBoxInfo(e.mediaBox,t.x,t.y,e.rotation);r={x:i.pointerX,y:i.pointerY}}const a=o.getSelectedTextLineIndex(n,r);if(-1!==a){const t=o.visibleLines[a],n=o.getSelectedTextCharIndex(a,r);return{lineIndex:a,charIndex:n,lineUid:t.uid,charUid:t.chars[n].uid,pageUid:e.uid,pageIndex:i.uidToIndex(e.uid),mediaBoxPoint:r}}return null}getTextSelection(){return this.textSelectionService.getTextSelection()}}class bC extends Wo{constructor(t){super(),Yi(this,"uid",void 0),Yi(this,"groupUid",void 0),Yi(this,"group",void 0),Yi(this,"postfix",void 0),Yi(this,"context",void 0),Yi(this,"emitter",void 0),Yi(this,"hooks",void 0),Yi(this,"core",void 0),Yi(this,"isDisposed",!1),this.emitter=new Ws,t.core&&(this.core=t.core),this.uid=Us(),this.groupUid=t.groupUid,this.postfix=`-${this.uid}`,this.hooks=this.register(new Gg),this.context=new CC(this.core,this,t.viewerConfig),t.container&&!t.uiConfig&&this.context.viewService.bindContainer(t.container),this.listenGlobalEvents()}listenGlobalEvents(){const{documentService:t,viewerService:e}=this.core,{context:i}=this;this.core.onAfterPerspective.on(t=>{i.afterPerspective(t.docUid,t.pageUid)},this),this.core.onBeforeLoadSource.on(t=>{let{docUid:e}=t;i.beforeLoadSource(e)},this),this.core.onAfterLoadSource.on(t=>{i.afterLoadSource(t.docUid)},this),this.core.pageService.onUpdatePage.on(t=>{i.updatePage(t.docUid,t.pageUid,t.data),i.hooks.updatePage.emit(t)},this),t.onAddPagesToDoc.on(t=>{const{group:e}=this;let{scrollToLatest:n}=e.config;Ps(n)&&({scrollToLatest:n}=i.viewerConfig),i.addPages(t.docUid,t.pageUids,n,t.index),i.hooks.addPagesToDoc.emit(t)},this),t.onDeletePagesFromDoc.on(t=>{i.deletePages(t.docUid,t.pageUids)},this),t.onDeleteAllPagesFromDoc.on(t=>{i.deleteAllPages(t.docUid)},this),t.onMovePages.on(t=>{i.movePages(t.docUid,t.indices,t.insertBeforeIndex),this.hooks.movePages.emit(t)},this),t.onSwitchPage.on(t=>{i.switchPage(t.docUid,t.one,t.another),this.hooks.swapPages.emit(t)},this),t.onReorderPages.on(t=>{i.reorderPages(t.docUid,t.indices)},this),t.onAfterReorderPages.on(t=>{i.afterReorderPages(t.docUid,t.indices),this.hooks.reorderPages.emit(t)},this),t.onBeforeDeleteDocs.on(t=>{i.closeTabs(t.docUids)},this),t.onDocumentRenamed.on(t=>{i.renameDoc(t.docUid,t.newName)},this),t.onDocumentDeleted.on(t=>{i.closeTabs([t.docUid])},this),t.onOpenDocument.on(t=>{i.groupUid===t.groupUid&&i.openDocument(t.doc)},this),t.onCloseDocument.on(t=>{i.groupUid===t.groupUid&&i.closeTabs([t.doc.uid])},this),e.onGotoPage.on(t=>{i.groupUid===t.groupUid&&i.setCurrentPage(t.docUid,t.index)},this),e.onSelectPages.on(t=>{i.groupUid===t.groupUid&&i.selectPages(t.docUid,t.indices)},this),e.onResize.on(()=>{i.resize()},this),e.onCurrentChangedByScroll.on(t=>{i.groupUid===t.groupUid&&i.uid!==t.viewerUid&&i.setCurrentPage(t.docUid,t.current)},this),this.core.onFilterChanged.on(t=>{const e=i.getActiveTab();(null==e?void 0:e.uid)===t.docUid&&i.filter(t.docUid,t.pageUids,t.filterType)},this),this.core.commandService.onOperationsChanged.on(t=>{const e=i.getActiveTab();e?e.uid===t.docUid&&i.hooks.operationsChanged.emit(t):this.hooks.operationsChanged.emit({docUid:t.docUid,undo:0,redo:0})},this)}dispose(){this.isDisposed||(this.unbindContainer(),this.context.dispose(),this.context=null,this.isDisposed=!0,this.core.removeViewer(this),super.dispose())}undo(){const t=this.context.getActiveTab();return!!t&&this.core.commandService.undo(t.uid)}redo(){const t=this.context.getActiveTab();return!!t&&this.core.commandService.redo(t.uid)}getOperationState(){const t=this.context.getActiveTab();return t?this.core.commandService.getOperationState(t.uid):{undo:0,redo:0}}saveOperations(){const t=this.context.getActiveTab();return!!t&&this.core.commandService.saveOperations(t.uid)}setRowAndColumn(t,e){return this.context.configService.updateConfig({rows:t,columns:e}),!0}getRowAndColumn(){const t=this.context.getActiveTab();if(t)return{rows:t.context.rows,columns:t.context.columns};const{viewerConfig:e}=this.context;return{rows:e.rows||1,columns:e.columns||1}}on(t,e){this.emitter.on(t,e)}emit(t,e){this.emitter.emit(t,e)}off(t,e){this.emitter.off(t,e)}getViewerConfig(){return this.context.viewerConfig}updateViewerConfig(t){this.context.configService.updateConfig(t)}bindContainer(t){return this.context.viewService.bindContainer(t)}unbindContainer(){this.context.viewService.unbindContainer()}show(){"visible"!==this.getViewerConfig().visibility&&(this.updateViewerConfig({visibility:"visible"}),this.context.showCurrentTab({renderReason:6}))}hide(){"hidden"!==this.getViewerConfig().visibility&&this.updateViewerConfig({visibility:"hidden"})}render(t){this.context.render(t)}resize(){this.context.resize()}indexToUid(t){const e=this.context.getActiveTab();return null==e?void 0:e.indexToUid(t)}uidToIndex(t){const e=this.context.getActiveTab();return e?e.uidToIndex(t):-1}getCurrentPageIndex(){const t=this.context.getActiveTab();return t?t.current:-1}getPageCounts(){const t=this.context.getActiveTab();return t?t.total:0}getCurrentPageUid(){var t;const e=this.context.getActiveTab();return null==e||null===(t=e.getCurrentPage())||void 0===t?void 0:t.uid}selectAllPages(){const t=this.getPageCounts();return this.selectPagesByIndices(Array.from(Array(t).keys()))}selectPagesByIndices(t){const e=this.context.getActiveTab();if(!e)return[];const i=e.indicesToUids(t);return this.core.viewerService.onSelectPages.emit(mm.create(e.uid,this.groupUid,this.uid,t,i)),[...i]}getSelectedPageIndices(){const t=this.context.getActiveTab();return t?t.getSelectedIndices():[]}gotoPage(t){const e=this.context.getActiveTab();return e?(t=Bs(t,0,e.total-1),e.current===t||this.core.viewerService.onGotoPage.emit(Rf.create(e.uid,this.groupUid,this.uid,t)),t):-1}movePages(t,e){const i=this.context.getActiveTab();return!!i&&this.core.movePages(i.uid,t,e)}swapPages(t,e){const i=this.context.getActiveTab();return!!i&&this.core.swapPages(i.uid,t,e)}reorderPages(t){const e=this.context.getActiveTab();return!!e&&this.core.reorderPages(e.uid,t)}deletePages(t){const e=this.context.getActiveTab();if(!e)return!1;if(!t.every(t=>t>=0&&t<e.total))return!1;const i=e.indicesToUids(t);return this.core.deletePages(e.uid,i)}deleteAllPages(){const t=this.context.getActiveTab();return!!t&&this.core.deleteAllPages(t.uid)}openDocument(t){this.core.openDocument(t.uid,this.uid)}closeDocument(t){if(!t){const e=this.context.getActiveTab();if(!e)return;t=e.uid}this.core.closeDocument(t,this.uid)}activateTab(t){var e;return(null===(e=this.context)||void 0===e?void 0:e.activateTab(t))||!1}getActiveTab(){var t;return(null===(t=this.context)||void 0===t?void 0:t.getActiveTab())||null}getAllTabs(){var t;return(null===(t=this.context)||void 0===t?void 0:t.tabService.getAllTabs())||[]}getRealPageSize(t){const e=this.context.getActiveTab();if(!e)return{width:0,height:0};Ps(t)&&(t=e.current);const i=e.getPageByIndex(t);return{width:i.rWidth,height:i.rHeight}}getRealPtPageSize(t){const e=this.context.getActiveTab();if(!e)return{width:0,height:0};Ps(t)&&(t=e.current);const i=e.getPageByIndex(t);let n=Bo(i.rWidth,Cr.displayResolution,72),s=Bo(i.rHeight,Cr.displayResolution,72);const o=Math.round(n),r=Math.round(s);return Math.abs(n-o)<1e-6&&(n=o),Math.abs(s-r)<1e-6&&(s=r),{width:n,height:s}}getRealPixelSize(t){const e=this.context.getActiveTab();if(!e)return{width:0,height:0};Ps(t)&&(t=e.current);const i=e.getPageByIndex(t),n=this.core.pageService.getPage(i.uid),{rWidth:s,rHeight:o}=n.getEditResultForPerspective();return{width:Bo(s,Cr.displayResolution,n.resource.resolutionX),height:Bo(o,Cr.displayResolution,n.resource.resolutionY)}}zoomIn(){const t=this.getActiveTab();if(!t||!t.isDocType)return;const{maxZoom:e}=this.getViewerConfig(),{zoom:i}=t.context;let n=SC(i,"in");(null===n||n>e)&&(n=e),this.updateViewerConfig({zoom:n})}zoomOut(){const t=this.getActiveTab();if(!t||!t.isDocType)return;const{minZoom:e}=this.getViewerConfig(),{zoom:i}=t.context;let n=SC(i,"out");(null===n||n<e)&&(n=e),this.updateViewerConfig({zoom:n})}filter(t,e){const i=this.context.getActiveTab();if(!i)return!1;const n=i.indicesToUids(t);return n.forEach(t=>{const e=this.core.pageService.getPage(t);e&&(e.isTextPage=!1),this.context.textSelectionService.clearSelectedTexts()}),this.core.filterPages(i.uid,n,e),!0}async perspectivePage(t,e){const i=this.context.getActiveTab();if(!i)return null;let n=i.currentUid;Ps(e)||(n=i.indexToUid(e));const s=this.context.core.pageService.getPage(n);t=Bo(t,s.resource.resolutionX,Cr.displayResolution);const o=await this.core.perspectivePage(i.uid,n,t);return this.context.textSelectionService.clearSelectedTexts(),s.isTextPage=!1,o.data}perspectiveAllPage(){const t=this.context.getActiveTab();if(!t)return;this.context.textSelectionService.clearSelectedTexts();const e=[],i=[],n=[];t.allPages.forEach((t,s)=>{t.isVisible?e.push(s):t.isPreload?i.push(s):n.push(s)});const s=[...e,...i,...n],{displayResolution:o}=Cr;for(let e=0;e<s.length;e++){const i=this.indexToUid(s[e]),n=this.context.core.pageService.getPage(i);if(n.isFull){let{width:e,height:s}=n.raw.getImageDetail();const r=Math.abs((n.rotation%360+360)%360);if(90===r||270===r){const t=e;e=s,s=t}const a=[[0,0],[e,0],[e,s],[0,s]];this.context.core.perspectivePage(t.uid,i,Bo(a,n.resolutionX,o),!0)}else if(n.activeQuad&&n.activeQuad!==n.quad){n.isTextPage=!1;const{width:e,height:s}=n.raw.getPageSize(),o=Nm(n.activeQuad.flat(),n.rotation,e,s),r=Vm(o);this.context.core.perspectivePage(t.uid,i,r,!0)}}}getPerspectivePreviewImage(t,e,i,n){const s=this.context.getActiveTab();if(!s)return null;const o=s.getPageByIndex(t);if(!o)return null;const r=o.uid,{quadSelectionStyle:a}=this.getViewerConfig(),{borderColor:l}=lo(a.border),h=function(t){const e=t=>{const e=t.toString(16);return 1===e.length?`0${e}`:e};if(t.startsWith("rgb")){const i=t.match(/(\d+)/g);if(3===i.length){const t=parseInt(i[0],10),n=parseInt(i[1],10),s=parseInt(i[2],10);return`#${e(t)}${e(n)}${e(s)}`}}return!t.startsWith("#")||7!==t.length&&4!==t.length?"#FE8E14":t}(l);return this.context.core.getPerspectivePreviewData(r,{width:e||200,height:i||200},{strokeColor:h.substring(1),lineWidth:n})}async copySelectedTexts(){return this.context.copySelectedTexts()}getSelectedTexts(){return this.context.getSelectedTexts()}searchNextText(t,e){return this.context.searchNextText(t,e)}searchPrevText(t,e){return this.context.searchPrevText(t,e)}searchFullText(t,e){return this.context.searchFullText(t,e)}selectSearchText(t,e){this.context.selectSearchText(t,e)}nextSearchText(){this.context.nextSearchText()}prevSearchText(){this.context.prevSearchText()}clearSearchText(){this.context.clearSearchText()}getVisiblePagesInfo(){return this.context.getVisiblePagesInfo()}}function SC(t,e){const i=[.01,.0625,.125,.25,.333,.5,.667,.75,1,1.25,1.5,2,3,4,6,8,12,16,24,32,64];if("in"===e){for(let e=0;e<i.length;e++)if(i[e]>t)return i[e]}else for(let e=i.length-1;e>=0;e--)if(i[e]<t)return i[e];return null}class TC extends Wo{constructor(t){super(),Yi(this,"isDestroyed",!1),Yi(this,"viewers",new Map),Yi(this,"groups",new Map),Yi(this,"onGotoPage",void 0),Yi(this,"onSelectPages",void 0),Yi(this,"onCurrentChangedByScroll",void 0),Yi(this,"onResize",void 0),Yi(this,"onPagePreloadChanged",void 0),Yi(this,"onViewerCreated",void 0),Yi(this,"core",void 0),this.core=t,this.initEventEmitter()}initEventEmitter(){this.onGotoPage=jo(this),this.onSelectPages=jo(this),this.onCurrentChangedByScroll=jo(this),this.onResize=jo(this),this.onPagePreloadChanged=jo(this),this.onViewerCreated=jo(this)}reset(){for(const t of this.viewers.values())t.dispose();this.viewers.clear(),this.groups.clear()}destroy(){if(!this.isDestroyed){for(const t of this.viewers.values())t.dispose();this.viewers=null,this.groups=null,this.isDestroyed=!0}}createViewer(t,e){var i;const{groupUid:n}=e,s=this.groups.get(n)||new Wg(n);var o;Ps(null===(i=e.viewerConfig)||void 0===i?void 0:i.scrollToLatest)||s.isSetScrollToLatest||(s.updateConfig({scrollToLatest:null===(o=e.viewerConfig)||void 0===o?void 0:o.scrollToLatest}),s.isSetScrollToLatest=!0),e.groupConfig&&s.updateConfig(e.groupConfig);const r=new t(e);r.group=s,s.viewerUids.add(r.uid),this.groups.set(n,s),this.viewers.set(r.uid,r);const a=this.getViewersByGroupUid(n);if(a.length>0){r.context.syncViewer(a[0]);const t=a[0].getActiveTab();t&&this.core.commandService.emitOperationsChanged(t.uid)}return this.onViewerCreated.emit(Uf.create(r)),r}removeViewer(t){let e;if(e=Os(t)?this.getViewer(t):t,!e)return!1;const{uid:i,groupUid:n}=e,s=this.groups.get(n);return s&&(s.viewerUids.delete(i),s.viewerUids.size||this.groups.delete(n)),this.viewers.delete(e.uid),e.dispose(),!0}hasViewer(t){return this.viewers.has(t)}getViewer(t){return this.viewers.get(t)}getAllViewers(){return Array.from(this.viewers.values())}getViewersByViewerUid(t){const e=this.viewers.get(t);return this.getViewersByGroupUid(e.groupUid)}getViewersByGroupUid(t){return this.groups.has(t)?this.groups.get(t).getViewerUids().map(t=>this.viewers.get(t)):[]}hasGroup(t){return this.groups.has(t)}}const EC={apply(t){t.viewerService=new TC(t)},install(t){t.setClass("Viewer",bC)}},_C=/^<\/([^>]*)>/,PC=/^<([^\s>]+)[^>]*>/,AC=/^<slot>.*<\/slot>/,IC=/(:?[@\w-]+)\s*=\s*"(.*?)"/;function DC(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const{template:i,data:n,components:s,injection:o}=t,r=RC(i,n,s,o,e),a=r.length;return a&&(r[0].cpInstance=t,r[a-1].cpInstance=t),r}function RC(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],o=t.trim();const r=[];function a(t){o=o.substring(t)}function l(t){let[s,o]=t;if(o){const t=function(t){const e={},i=Eo(t,IC);return i?(i.forEach(t=>{let[,i,n]=t;e[i]=n}),e):e}(s),a=e[":for"];a&&(delete e[":for"],t[":for"]=a);const l={type:"start",name:o,data:e,attrs:t};if(r.push(l),(i[o]||n.components&&n.components[o])&&(l.cpOption={Component:i[o]||n.components[o],injection:n}),"input"===o||/\/>/.test(s)){const t={type:"end",name:o,data:e,attrs:{}};r.push(t)}}}function h(t){let[,e]=t;if(e){const t={type:"end",name:e,attrs:{}};r.push(t)}}function c(t){if(t.length){const i={type:"text",name:t,attrs:{},data:e};r.push(i)}}for(;o;){const t=o.indexOf("<");let e;if(0===t){const t=o.match(_C);if(t){a(t[0].length),h(t);continue}const i=o.match(AC);if(i){a(i[0].length),r.push(...s);continue}const n=o.match(PC);if(n&&n[0]!==n.input){a(n[0].length),l(n);continue}e=o}else e=t>0?o.substring(0,t):o;e&&(a(e.length),c(e))}return r}function kC(t){const{cpInstance:e,children:i}=t;e&&!e.isInserted&&(e.isInserted=!0,e.hooks.inserted.emit()),i.forEach(t=>{kC(t)})}function MC(t){const{cpInstance:e,children:i}=t;e&&e.hooks.destroyed.emit(t),i.forEach(t=>{MC(t)})}function LC(t){if(t){const{el:e,children:i,cpInstance:n}=t;if(null!=n&&n.emitDestroyByRender&&function(t){const{cpInstance:e}=t;e&&(e.dispose(),e.hooks.beforeDestroyed.emit(t))}(t),e){const i=e.parentElement;i&&i.removeChild(e),e.vNode=null,t.el=null}return null!=n&&n.emitDestroyByRender&&MC(t),t.text=null,t.parent=null,i.length&&i.forEach(t=>{LC(t)}),!0}return!1}class OC{constructor(t){Yi(this,"el",void 0),Yi(this,"tagName",void 0),Yi(this,"sel",""),Yi(this,"data",void 0),Yi(this,"children",void 0),Yi(this,"text",void 0),Yi(this,"key",void 0),Yi(this,"cpInstance",void 0),Yi(this,"cpOptions",void 0),Yi(this,"parent",void 0),this.createVNode(t)}renderDom(){if(this.el)return this.el;let t;if("FRAGMENT"===this.tagName)t=document.createDocumentFragment();else if("TEXT"===this.tagName){const e=function(t){return 0===t.length?"":t.replace(function(){if(no)return no;let t="";return so(io,e=>{t+=`${e}|`}),t+="&#(\\d{1,5});",no=new RegExp(t,"g"),no}(),(t,e)=>eo[t]||String.fromCharCode(+e))}(this.text);t=document.createTextNode(e)}else{t=document.createElement("IMAGE"===this.tagName?"IMG":this.tagName);for(const[e,i]of Object.entries(this.data))t.setAttribute(e,i)}return this.children.forEach(e=>{const i=e.renderDom();t.appendChild(i)}),t.vNode=this,this.el=t,function(t){const{cpInstance:e,el:i}=t;e&&(e.vNode=t,e.hooks.created.emit(i))}(this),t}patch(t){return function(t,e){const i=t.el,n=i.parentNode;null!==n&&(e.el=e.renderDom(),ro(e.el,i,n),LC(t));let s=-1;const o=t.parent;return null==o||o.children.forEach((e,i)=>{e===t&&(s=i)}),s>-1&&(o.children[s]=e,e.parent=o,t.el=null),e}(this,t)}destroy(){return LC(this)}createVNode(t){const{tagName:e,data:i={},children:n=[],el:s=null,key:o,text:r="",cpOptions:a,cpInstance:l}=t;let h=e;i.id&&(h+=`#${i.id}`),i.class&&(h+=`.${i.class}`),this.sel=h,this.data=i,this.tagName=e,this.children=n,this.el=s,this.key=o,this.text=r,this.cpInstance=l,this.cpOptions=a}}function BC(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=[],n=[];let s=[];return t.forEach(t=>{if("start"===t.type)i.push(t),n.push(s),s=[];else if("text"===t.type)s.push({type:"text",value:t.name,data:t.data});else if(t instanceof OC)s.push(t);else{let e=i.pop();for(;e.name!==t.name;)e=i.pop();if(e){const{name:t,cpInstance:i,attrs:o,cpOption:r,data:a}=e,l={type:"token",tagName:t,cpInstance:i,cpOption:r,attrs:o,data:a,children:s};s.forEach(t=>{t.parent=l}),s=n.pop(),s.push(l)}}}),e?s[0]:s}const NC=/'.+'|\\".+\\"|[\w$.]+/g,UC=/{{([^\s@}]+)}}/;function FC(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(Ts(t)){const e=[];return t.forEach(t=>{e.push(...WC(FC(t)))}),e}if(t instanceof OC)return t;if("token"===t.type){var i;const{tagName:n,attrs:s,cpInstance:o,children:r,data:a,cpOption:l}=t;if(s[":for"])return function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{attrs:i,data:n}=t,s=JSON.parse(JSON.stringify(i)),o={":for":i[":for"]};delete i[":for"],VC(o,{...n,...e});const r=[];return o[":for"].forEach(e=>{const i=FC(t,e);r.push(...WC(i))}),t.attrs=s,r}(t,e);const h={...a,...e},c={...s};let d;if(VC(s,h),Object.prototype.hasOwnProperty.call(s,"if")&&!s.if)d=null;else if(delete s.if,l)d=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{children:i,attrs:n,cpOption:s}=t,o=HC(i,e),{Component:r,injection:a}=s,l=BC(DC(new r({data:n,injection:a}),o));return l?WC(FC(l))[0]:null}(t,e);else{const{key:t}=s;void 0!==t&&delete s.key;const i=HC(r,e);d=new OC({tagName:n.toUpperCase(),data:s,cpInstance:o,key:t,children:i})}return t.attrs=c,null===(i=d)||void 0===i||i.children.forEach(t=>{t.parent=d}),d}return function(t){var e;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{value:n}=t;const s=null===(e=t.parent)||void 0===e||null===(e=e.attrs)||void 0===e?void 0:e.html;return n=function(t,e){const i=Eo(t,UC);return i.length&&i.forEach(i=>{const n=i[1].split(".").reduce((t,e)=>t[e],e),s=i[0];t=t.replace(s,n)}),t}(n,{...t.data,...i}),s?FC(BC(RC(n),!1)):new OC({tagName:"TEXT",text:n})}(t,e)}function VC(t,e){for(const s of Object.keys(t)){const[,o,r]=s.match(/^(:|@)(.+)/)||[];if(!r)continue;let a=t[s];if(delete t[s],"for"===r){var i,n;let[s,o]=a.split(" in "),[r,l]=s.split(",");r=r.trim(),l=null===(i=l)||void 0===i?void 0:i.trim(),o=null===(n=o)||void 0===n?void 0:n.trim();const h=[],c=o.split(".").reduce((t,e)=>t[e],e);if(Ts(c))c.forEach((t,e)=>{const i={};i[r]=t,l&&(i[l]=e),h.push(i)});else if(Es(c))for(const[t,e]of Object.entries(c)){const i={};i[r]=e,l&&(i[l]=t),h.push(i)}t[":for"]=h}else{const i="this"===a?e:a.split(".").reduce((t,e)=>null==t?void 0:t[e],e);if(void 0!==i)"class"===r&&t[r]?t[r]=`${t[r]} ${i}`:t[r]=i;else{a=a.replace(NC,t=>t.includes('"')||t.includes("'")||/^(true|false|\d+|undefined|null)$/.test(t)?t:t.split("."));try{const i=jC(a,e);So(i)&&(t[r]=void 0),"class"===r&&t[r]?t[r]=`${t[r]} ${i}`:t[r]=i}catch(e){t[r]=void 0}}"@"===o&&(t.events||(t.events={}),t.events[r]=t[r],delete t[`@${r}`])}}}function WC(t){return t?(Ts(t)||(t=[t]),t):[]}function HC(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=[];return t.forEach(t=>{const n=FC(t,e)||[];i.push(...WC(n))}),i}function jC(t,e){let i=null;try{const n=t.split(",");for(let t=0;t<n.length;t++){const i=n[t],s=/(\w+)(\[(\d+)\])?/,o=i.match(s);if(!o){e=null;break}{const t=o[1],i=o[3];if(!Object.prototype.hasOwnProperty.call(e,t)){e=null;break}e=e[t],void 0!==i&&Array.isArray(e)&&(e=e[i])}}i=e}catch(t){i=null}return i}class zC extends Wo{constructor(t){let{data:e={},template:i="",components:n={},injection:s={}}=t;super(),Yi(this,"el",void 0),Yi(this,"vNode",null),Yi(this,"template",""),Yi(this,"data",{}),Yi(this,"injection",{}),Yi(this,"components",{}),Yi(this,"emitter",void 0),Yi(this,"uiEmitter",void 0),Yi(this,"isInserted",!1),Yi(this,"emitDestroyByRender",!0),Yi(this,"hooks",{created:js.create(),inserted:js.create(),updated:js.create(),beforeDestroyed:js.create(),destroyed:js.create()}),Yi(this,"selfEvents",[]),Yi(this,"globalEvents",[]),Yi(this,"nativeEvents",[]),this.template=i,this.emitter=Ws.create(),this.setData(e),this.setComponents(n),this.setInjects(s),this.uiEmitter=this.injection.emitter,this.hooks.created.on(t=>{this.el=t}),this.hooks.destroyed.on(()=>{this.dispose()}),this.initEvents()}setInjects(t){Object.assign(this.injection,t)}initEvents(){var t=this;const e=(e,i)=>{this.on(e,function(){for(var e=arguments.length,n=new Array(e),s=0;s<e;s++)n[s]=arguments[s];Os(i)?t.$emit(i,...n):ks(i)&&i(...n)})};for(const[t,n]of Object.entries((null===(i=this.data)||void 0===i?void 0:i.events)||{})){var i;e(t,n)}for(const[t,i]of Object.entries((null===(n=this.data)||void 0===n||null===(n=n.options)||void 0===n?void 0:n.events)||{})){var n;e(t,i)}}setData(t){Object.assign(this.data,t)}setComponents(t){Object.assign(this.components,t)}on(t,e){this.emitter.on(t,e),this.selfEvents.push([t,e])}emit(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];this.emitter.emit(t,...i)}unbindSelfEvents(){this.selfEvents.forEach(t=>{let[e,i]=t;this.emitter.off(e,i)}),this.selfEvents=[]}$on(t,e){var i;this.uiEmitter&&(null===(i=this.uiEmitter)||void 0===i||i.on(t,e),this.globalEvents.push([t,e]))}$emit(t){for(var e,i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];null===(e=this.uiEmitter)||void 0===e||e.emit(t,...n)}unbindGlobalEvents(){this.globalEvents.forEach(t=>{let[e,i]=t;this.uiEmitter.off(e,i)}),this.globalEvents=[]}nativeOn(t,e,i){if(Ts(t))t.forEach(t=>{this.nativeOn(t,e,i)});else{const n=((t,e,i)=>t?(t.addEventListener(e,i,void 0),()=>{t.removeEventListener(e,i)}):null)(t,e,i);n&&this.nativeEvents.push(n)}}unbindNativeEvents(){this.nativeEvents.forEach(t=>{t()}),this.nativeEvents=[]}query(t){var e;return null===(e=this.el)||void 0===e?void 0:e.querySelector(t)}queryAll(t){var e;return null===(e=this.el)||void 0===e?void 0:e.querySelectorAll(t)}parseHTML(){return FC(BC(DC(this,[])))}reRenderVNode(){const t=function(t){return FC(BC(DC(t)))}(this);this.vNode.patch(t)}bindEventsEmitter(){var t=this;const{options:e}=this.data;if(null!=e&&e.events)for(const[i,n]of Object.entries(e.events))this.nativeOn(this.el,i,function(){for(var e=arguments.length,n=new Array(e),s=0;s<e;s++)n[s]=arguments[s];t.emit(i,...n)})}dispose(){this.unbindSelfEvents(),this.unbindGlobalEvents(),this.unbindNativeEvents(),super.dispose()}}const GC=(t,e,i,n)=>{const{id:s,tooltip:o,dataId:r,style:a,className:l}=t||{},h=(t=>{let e="";if(t)for(const[i,n]of Object.entries(t))e+=`${bs(i)}:${n};`;return e})(a);return(Ps(s)?"":` id="${s}"`)+` class="${e}${null!=i?i:""} ${l||""}"`+(Ps(n)?"":` :class="${n}"`)+(h?` style="${h}"`:"")+(Ps(o)?"":` title="${o}"`)+(Ps(r)?"":` data-id="${r}"`)};function YC(t){if(0===Object.keys(t).length||!t)return'<MainView :options="this"></MainView>';const e=-1!==["Root","DDVRoot","Layout","DDVLayout"].indexOf(null==t?void 0:t.type);return Os(t.type)&&!e?`<${t.type} :options="this"></${t.type}>`:'<Root :options="this"></Root>'}function $C(){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const e=_s(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return null!=e&&e.children&&(e.children=e.children.map(t=>Os(t)?{type:t}:Es(t)?$C(t):t)),t.length&&(e.children||Ts(e.children)||(e.children=[]),e.children.push(...t)),e}class XC{constructor(t){Yi(this,"options",void 0),Yi(this,"postfix",void 0),Yi(this,"uiEvents",[]),Yi(this,"parsedUiConfig",void 0),Yi(this,"injection",void 0),Yi(this,"rootComponent",void 0),Yi(this,"emitter",null),Yi(this,"rootDom",null),Yi(this,"rootVNode",void 0),Yi(this,"container",void 0),Yi(this,"uiConfig",{}),Yi(this,"popupUiConfig",[]);const{container:e,injection:i,postfix:n,uiConfig:s,emitter:o,popupUiConfig:r}=t;this.options=t,this.injection=i,this.uiConfig=s,this.popupUiConfig=r,this.parsedUiConfig=$C(s,r),this.emitter=o||Ws.create(),this.postfix=n||`-${Us()}`,Os(e)?this.container=document.getElementById(e):e instanceof HTMLElement&&(this.container=e),this.init()}static registerComponent(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(const[e,i]of Object.entries(t))XC.isAlreadyRegistered(e)||(this.components[`DDV${e}`]=i,this.components[e]=i)}static isAlreadyRegistered(t){return!!this.components[t]}static getComponents(){return this.components}init(){const t=new zC({data:this.parsedUiConfig,template:YC(this.parsedUiConfig),components:XC.getComponents(),injection:{...this.injection,components:XC.getComponents(),postfix:this.postfix,emitter:this.emitter}}),e=t.parseHTML();if(!e)return;const i=e.renderDom();this.rootComponent=t,this.rootVNode=e,this.rootDom=i,this.container&&(this.container.appendChild(i),kC(this.rootVNode))}updateUiConfig(t){const e=$C(t,this.popupUiConfig),i=new zC({data:e,template:YC(this.parsedUiConfig),components:XC.getComponents(),injection:{...this.injection,components:XC.getComponents(),postfix:this.postfix,emitter:this.emitter}}).parseHTML(),n=this.rootVNode.patch(i);return this.rootDom=n.el,this.rootVNode=n,this.uiConfig=t,kC(this.rootVNode),!0}bindContainer(t){let e;if(Vs(t)&&(e=t),Os(t)){const i=document.getElementById(t);Vs(i)&&(e=i)}return!!e&&(this.container=e,e.appendChild(this.rootDom),kC(this.rootVNode),!0)}unbindContainer(){if(this.container&&0!==this.container.children.length){for(let t=0;t<this.container.children.length;t++)if(this.container.children[t]===this.rootDom)return void this.container.removeChild(this.rootDom);this.container=null}}queryByDataId(t){var e;return null===(e=this.rootDom)||void 0===e?void 0:e.querySelector(`[data-id=${t}]`)}queryAllByDataId(t){var e;return null===(e=this.rootDom)||void 0===e?void 0:e.querySelectorAll(`[data-id=${t}]`)}getElementsByType(t,e){var i;const n=[];return(null===(i=t.cpInstance)||void 0===i||null===(i=i.constructor)||void 0===i?void 0:i.cpName)===e&&t.el&&n.push(t.el),t.children.length>0&&t.children.forEach(t=>{n.push(...this.getElementsByType(t,e))}),n}on(t,e){const i=this.emitter.on(t,e);this.uiEvents.push(i)}emit(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];this.emitter.emit(t,...i)}off(t,e){this.emitter.off(t,e)}offAllEvents(){this.uiEvents.forEach(t=>{let{name:e,fn:i,context:n,once:s}=t;this.emitter.off(e,i,n,s)})}dispose(){this.unbindContainer(),this.offAllEvents(),this.emitter=null,this.rootDom=null,this.uiConfig={},this.parsedUiConfig={},MC(this.rootVNode)}}Yi(XC,"components",{});class qC extends zC{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";super(t),Yi(this,"defaultClass","ddv-button"),this.initTemplate(e),this.bindBaseHooks()}bindBaseHooks(){this.hooks.inserted.on(t=>{this.bindEventsEmitter()})}initTemplate(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const{options:e}=this.data,i=""===t?this.defaultClass:`${this.defaultClass} ${t}`,n=`<button ${GC(e,i)} >`+(Ps(null==e?void 0:e.label)?"":`<span>${e.label}</span>`)+"<slot></slot></button>";this.template=n}}class ZC extends zC{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"row";super(t),Yi(this,"defaultClass","ddv-layout"),Yi(this,"enableScroll",!1),Yi(this,"showScrollArrow",!0),Yi(this,"scrollLeftOrTopBtn",void 0),Yi(this,"scrollRightOrBottomBtn",void 0);const{options:i}=this.data;this.enableScroll=(null==i?void 0:i.enableScroll)||!1,this.showScrollArrow=(null==i?void 0:i.showScrollArrow)||!0,this.initTemplate((null==i?void 0:i.flexDirection)||e),this.bindHooks()}bindHooks(){this.hooks.inserted.on(()=>{JC(this),this.bindCustomScroll()}),this.hooks.updated.on(()=>{JC(this)})}bindCustomScroll(){if(!this.enableScroll)return;this.showScrollArrow&&this.initCustomScrollButton();const t=new ResizeObserver(()=>{this.showScrollArrow&&this.updateCustomScrollButton()});t.observe(this.el),this.hooks.destroyed.on(()=>{t.disconnect()})}initCustomScrollButton(){const t=document.createElement("button"),e=document.createElement("button"),i=150;this.nativeOn(t,"click",()=>{const{scrollLeft:e,scrollTop:n}=this.el;t.classList.contains("ddv-scroll-top")?this.el.scroll(0,n-i):this.el.scroll(e-i,0)}),this.nativeOn(e,"click",()=>{const{scrollLeft:t,scrollTop:n}=this.el;e.classList.contains("ddv-scroll-bottom")?this.el.scroll(0,n+i):this.el.scroll(t+i,0)}),this.nativeOn(this.el,"scroll",t=>{this.showScrollArrow&&this.updateCustomScrollButton(),this.$emit("ui_layoutScroll",this.el)}),this.el.appendChild(t),this.el.appendChild(e),this.scrollLeftOrTopBtn=t,this.scrollRightOrBottomBtn=e,this.updateCustomScrollButton()}updateCustomScrollButton(){const{vertical:t,horizontal:e}=KC(this.el),{scrollLeft:i,scrollTop:n}=this.el,{scrollRightOrBottomBtn:s,scrollLeftOrTopBtn:o}=this;if(!o||!s)return;if(!t&&!e)return o.style.display="none",void(s.style.display="none");o.className="ddv-scroll-button "+(e?"ddv-scroll-left":"ddv-scroll-top"),s.className="ddv-scroll-button "+(e?"ddv-scroll-right":"ddv-scroll-bottom");const r=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const{vertical:i,horizontal:n}=KC(t);if(!i&&!n)return[!1,!1];const{scrollLeft:s,scrollTop:o,scrollHeight:r,scrollWidth:a,clientWidth:l,clientHeight:h}=t;return n?[s<=e,s+l+e>=a]:[o<=e,o+h+e>=r]}(this.el,3);e?(o.style.left=`${i}px`,s.style.right=-i+"px"):(o.style.top=`${n}px`,s.style.bottom=-n+"px"),o.style.display=r[0]?"none":"",s.style.display=r[1]?"none":""}initTemplate(t){const{options:e}=this.data,i=(null==e?void 0:e.children)||[],n="row"===t?"":"-col";let s=`${this.defaultClass}${n}`;this.enableScroll&&(s+=" ddv-custom-scroll-hidden");let o=`<div ${GC(e,s)}>`;i&&i.length&&i.forEach((t,e)=>{if(Es(t)){const{type:i}=t;i.trim(),i.length>0&&(o+=`<${i} :options="options.children[${e}]"></${i}>`)}}),o+="</div>",this.template=o}}function JC(t){const{options:e}=t.data,i=t.el.children;((null==e?void 0:e.children)||[]).forEach((e,n)=>{if(Vs(e)){const s=e;0===n?(t.el.append(s),t.el.insertBefore(s,i[0])):((t,e)=>{const i=e.parentNode;i.lastChild===e?i.appendChild(t):ro(t,e.nextSibling,i)})(s,i[n-1])}})}function KC(t){let e=t.scrollHeight>t.clientHeight,i=t.scrollWidth>t.clientWidth;return e&&i&&(t.scrollHeight-t.clientHeight>t.scrollWidth-t.clientWidth?i=!1:e=!1),{vertical:e,horizontal:i}}class QC extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-root"),this.initTemplate(),this.bindHooks()}initTemplate(){const{options:t}=this.data,{children:e}=t,i="column"===t.flexDirection?`ddv-column ${this.defaultClass}`:this.defaultClass;let n=`<div ${GC(t,i,"")} >`;e&&e.length&&e.forEach((t,e)=>{if(Es(t)){const{type:i}=t;i.trim(),i.length>0&&(n+=`<${i} :options="options.children[${e}]"></${i}>`)}}),n+="</div>",this.template=n}bindHooks(){this.hooks.inserted.on(()=>{JC(this)})}}class tb extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-split-row"),this.initTemplate(),this.bindHooks()}bindHooks(){this.hooks.inserted.on(()=>{this.updateClassName()}),this.hooks.updated.on(()=>{this.isInserted&&this.updateClassName()})}updateClassName(){const t=this.el.parentNode,e=window.getComputedStyle(t),{flexDirection:i}=e;"column"===i&&(this.el.classList.remove(this.defaultClass),this.el.classList.add("ddv-split-column"))}initTemplate(){const{options:t}=this.data,e=GC(t,this.defaultClass);this.template=`<div ${e}></div>`}}class eb extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-swipe-indicator"),Yi(this,"touchStartY",0),Yi(this,"touchEndY",0),Yi(this,"isSwiping",!1),Yi(this,"swipeLever",1),Yi(this,"handleTouchStart",t=>{1===t.touches.length&&(t.preventDefault(),this.touchStartY=t.touches[0].clientY,this.touchEndY=t.touches[0].clientY,this.isSwiping=!0)}),Yi(this,"handleTouchMove",t=>{this.isSwiping&&(t.preventDefault(),this.touchEndY=t.touches[0].clientY)}),Yi(this,"handleTouchEnd",()=>{if(!this.isSwiping)return;const t=this.touchEndY-this.touchStartY;Math.abs(t)<30||(t>0?this.updateContainer(!1):this.updateContainer(!0)),this.isSwiping=!1}),this.initTemplate(),this.hooks.inserted.on(()=>{this.bindNativeEvents()}),this.$on("ui_swipeReset",t=>{t===this.el.parentNode&&(this.swipeLever=1)})}bindNativeEvents(){const{el:t}=this;t&&(t.parentNode&&(t.parentNode.style.transition="top 0.25s ease-in-out, height 0.25s ease-in-out"),t.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),t.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),t.addEventListener("touchend",this.handleTouchEnd,{passive:!1}))}updateContainer(t){const e=this.el.parentNode;if(e)if(t){if(0===this.swipeLever)return this.swipeLever=1,e.style.height="",e.style.top="",void this.$emit("ui_swipeChanged",e);1===this.swipeLever&&(this.swipeLever=2,e.style.height="100%",e.style.top="0px",this.$emit("ui_swipeChanged",e))}else{if(2===this.swipeLever)return this.swipeLever=1,e.style.height="",void(e.style.top="");if(1===this.swipeLever)return this.swipeLever=0,e.style.height="25%",void(e.style.top="75%");0===this.swipeLever&&(e.style.height="0px",e.style.top="100%",setTimeout(()=>{this.$emit("ui_swipeHide",e)},300))}}initTemplate(){const{options:t}=this.data,e=`<div ${GC(t,this.defaultClass)}><div class="${this.defaultClass}-line"></div></div>`;this.template=e}}const ib={CameraResolution:"ddvCameraResolution",Capture:"ddvCapture",Flashlight:"ddvFlashlight",CameraConvert:"ddvCameraConvert",AutoDetect:"ddvAutoDetect",AutoCapture:"ddvAutoCapture",Rotate:"ddvRotate",RotateLeft:"ddvRotateLeft",RotateRight:"ddvRotateRight",Load:"ddvLoad",Delete:"ddvDelete",DeleteCurrent:"ddvDeleteCurrent",DeleteAll:"ddvDeleteAll",Zoom:"ddvZoom",ZoomIn:"ddvZoomIn",ZoomOut:"ddvZoomOut",ZoomByPercentage:"ddvZoomByPercentage",Crop:"ddvCrop",CropAll:"ddvCropAll",CropCurrent:"ddvCropCurrent",CropMode:"ddvCropMode",PerspectiveAll:"ddvPerspectiveAll",FullQuad:"ddvFullQuad",Undo:"ddvUndo",Redo:"ddvRedo",Restore:"ddvRestore",Pan:"ddvPan",Filter:"ddvFilter",Print:"ddvPrint",ThumbnailSwitch:"ddvThumbnailSwitch",DisplayMode:"ddvDisplayMode",ContinuousPage:"ddvContinuousPage",SinglePage:"ddvSinglePage",FitMode:"ddvFitMode",FitWidth:"ddvFitWidth",FitHeight:"ddvFitHeight",FitWindow:"ddvFitWindow",ActualSize:"ddvActualSize",Back:"ddvBack",Close:"ddvClose",Done:"ddvDone",Download:"ddvDownload",ImagePreview:"ddvImagePreview",FirstPage:"ddvFirstPage",LastPage:"ddvLastPage",NextPage:"ddvNextPage",PrevPage:"ddvPrevPage",FitMode_FitWidth:"ddvFitModeFitWidth",FitMode_FitHeight:"ddvFitModeFitHeight",FitMode_FitWindow:"ddvFitModeFitWindow",FitMode_ActualSize:"ddvFitModeActualSize",DisplayMode_SinglePage:"ddvDisplayModeSinglePage",DisplayMode_ContinuousPage:"ddvDisplayModeContinuousPage",Crop_CropAll:"ddvCropCropAll",Crop_CropCurrent:"ddvCropCropCurrent",Crop_CropCancel:"ddvCropCropCancel",Crop_CropApply:"ddvCropCropApply",Filter_FilterAll:"ddvFilterFilterAll",Delete_DeleteCurrent:"ddvDeleteDeleteCurrent",Delete_DeleteAll:"ddvDeleteDeleteAll",RectAnnotation:"ddvRect",EllipseAnnotation:"ddvEllipse",InkAnnotation:"ddvInk",PolygonAnnotation:"ddvPolygon",PolylineAnnotation:"ddvPolyline",LineAnnotation:"ddvLine",StampImageAnnotation:"ddvStampImage",StampIconAnnotation:"ddvStampIcon",TextTypewriterAnnotation:"ddvTypewriter",TextBoxAnnotation:"ddvTextBox",HighlightAnnotation:"ddvHighlight",StrikeoutAnnotation:"ddvStrikeout",UnderlineAnnotation:"ddvUnderline",EraseAnnotation:"ddvAnnotationEraser",SelectAnnotation:"ddvAnnotationSelect",SendBackward:"ddvSendBackward",SendToBack:"ddvSendToBack",BringToFront:"ddvBringToFront",BringForward:"ddvBringForward",AnnotationSet:"ddvAnnotationSet",TextSearchPanelSwitch:"ddvTextSearchPanelSwitch",TextSelectionMode:"ddvTextSelectionMode"},nb=["Arial","Courier","Helvetica","Times New Roman"],sb=function(){let t=0,e=0;return function(i){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:300,s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(t&&clearTimeout(t),s){const s=!t;t=setTimeout(()=>{e!==t&&(t=0,e=0,i())},n),s&&(e=t,i())}else t=setTimeout(()=>{i(),t=0},n)}}();function ob(t,e,i){const n=n=>{const s=(parseFloat(n.value)-e)/(i-e)*100;t.style.backgroundSize=`${s}% 100%`};n(t),t.oninput=e=>{n(t)},t.onchange=e=>{n(t)}}function rb(t,e){const{bottom:i,height:n}=t.parentNode.getBoundingClientRect(),{height:s}=t.getBoundingClientRect(),{bottom:o}=e.getBoundingClientRect();let r=n;return o-i<s&&(r=-s),r}function ab(t){t.$on("ui_hidePopup",e=>{e!==t&&ks(null==t?void 0:t.togglePopup)&&(null==t||t.togglePopup(!1))})}function lb(t){t.isRefactorCrop=!0,t.$on("ui_cropClick",e=>{const{viewer:i}=t.injection,n=i.getPageCounts()||0;(e||n)&&cb(t.el,e)})}function hb(t){t.isRefactorCrop=!0,t.isRefactorAnnotation=!0,t.$on("ui_toolModeRefactor",()=>{const{viewer:e}=t.injection,i=e.getPageCounts()||0,{toolMode:n}=e.context.viewerConfig;i&&cb(t.el,"annotation"===n||"crop"===n)})}function cb(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!t)return;const{classList:i}=t,n=i.contains("ddv-button-disabled");e?n||t.classList.add("ddv-button-disabled"):n&&!e&&t.classList.remove("ddv-button-disabled")}function db(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"base";if(!t)return;const{classList:n}=t;let s="ddv-button-activated";"deep"===i?s="ddv-button-activated-deep":"light"===i&&(s="ddv-button-activated-light");const o=n.contains(s);e?o||t.classList.add(s):t.classList.remove(s)}function ub(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const{left:o,right:r,bottom:a}=function(t,e){const i=(e||t.parentElement).getBoundingClientRect(),n=t.getBoundingClientRect(),s=n.top-i.top,o=i.right-n.right;return{top:s,bottom:i.bottom-n.bottom,left:n.left-i.left,right:o}}(e,t),{x:l,y:h,width:c}=t.getBoundingClientRect(),{height:d,width:u}=i.getBoundingClientRect(),{x:p,y:g,width:f,height:m}=e.getBoundingClientRect(),v=da(getComputedStyle(t).borderWidth);let y=Math.floor(p)-Math.floor(l)-v.value;y<5&&(y=0);const x=c-u,w=y-(Math.floor(u)-Math.floor(f))/2,C=w<5?"0px":`${w}px`;let b=Math.floor(g)-Math.floor(h)-v.value;i.style.left=s&&r>u/2&&o>u/2?C:c<u+5?"0px":r>u?`${y}px`:o>u?y-(Math.floor(u)-Math.floor(f))+"px":r>u/2&&o>u/2?C:x<5?"0px":`${x}px`,a>d?(n&&(b+=2),i.style.top=b+Math.floor(m)-1+"px"):(n&&(b-=4),i.style.top=b-Math.floor(d)+"px")}function pb(t,e,i){const n=MT.getTooltip(),s=MT.getDisplayTextConfig(),o=ib;null!=i&&i.id||!(t in o)||(i.id=o[t]+e.postfix),null!=i&&i.tooltip||!(t in n)||(i.tooltip=n[t]),null!=i&&i.displayText&&(i.label=null==i?void 0:i.displayText),null!=i&&i.label||!(t in s)||(i.label=s[t])}function gb(t){return(null==t?void 0:t.constructor.cpName)||""}function fb(t){const{value:e}=t,{fontSize:i,fontFamily:n,paddingLeft:s,paddingRight:o}=getComputedStyle(t),r=document.createElement("div");r.style.position="absolute",r.style.left="-9999px",r.style.top="-9999px",r.style.visibility="hidden",r.style.fontSize=i,r.style.fontFamily=n||"Arial, Helvetica, sans-serif",document.body.appendChild(r),r.textContent=e;const a=r.clientWidth+parseInt(s,10)+parseInt(o,10);return r.remove(),a}function mb(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];t.el&&(cb(t.el,"disabled"===e),function(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!t)return;const{classList:i}=t,n=i.contains("ddv-button-focused");e?n||t.classList.add("ddv-button-focused"):t.classList.remove("ddv-button-focused")}(t.el,"focused"===e),i&&db(t.el,"focused"===e,n?"deep":"base"),t.uiState=e)}function vb(t,e){let i=document.getElementById(`ddvMask${t.postfix}`);(i||e)&&(!i||e?(i||(i=document.createElement("div"),i.id=`ddvMask${t.postfix}`,i.className="ddv-mask"),t.context.viewService.rootDom.appendChild(i)):i.remove())}function yb(t,e){if(!e.context.isDefaultViewer)return!1;const i=e.getViewerConfig().toolMode,n="crop"===i&&t.isRefactorCrop,s="annotation"===i&&t.isRefactorAnnotation;return!(!n&&!s)}class xb extends qC{constructor(t,e){super(t,e.class),Yi(this,"callback",void 0),Yi(this,"isRefactorCrop",!1),Yi(this,"isRefactorAnnotation",!1),Yi(this,"uiState","normal"),Yi(this,"isFocused",!1),Yi(this,"isMenuButton",!1),this.callback=e.callback,this.bindHooks(),this.isMenuButton=t.data.menu||!1,"false"!==t.data.default&&this.bindDefaultUi()}bindEvent(){this.nativeOn(this.el,"click",()=>{this.callback()})}bindHidePopup(){this.nativeOn(this.el,"click",()=>{this.$emit("ui_hidePopup")})}setUiState(t){mb(this,t,!(arguments.length>1&&void 0!==arguments[1])||arguments[1],this.isMenuButton)}bindDefaultUi(){const{viewer:t}=this.injection,e=t=>{let e=this.isFocused?"focused":"normal";(Ps(null==t?void 0:t.pageCount)?this.injection.viewer.getPageCounts():t.pageCount)?yb(this,this.injection.viewer)&&(e="disabled"):e="disabled",this.setUiState(e,!Ms())};t.hooks.pageExistenceChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}bindHooks(){this.hooks.created.on(()=>{this.bindEvent(),this.bindHidePopup()}),this.hooks.updated.on(()=>{this.uiState="normal"})}initTemplate(t){const e=this.data;e.options||(e.options={});const{options:i,id:n}=this.data;n&&(i.id=n),pb(gb(this),this.injection.viewer,i),"false"===e.default&&(i.label=void 0),super.initTemplate(t)}}class wb extends zC{constructor(t){super(t),Yi(this,"uiState","normal"),Yi(this,"defaultClass",void 0),Yi(this,"pullDownBox",void 0),Yi(this,"isFirstClick",!0),Yi(this,"isRefactorCrop",!1),Yi(this,"isRefactorAnnotation",!1),Yi(this,"currentFocusedIndex",-1),this.bindViewerResized(),this.bindPopupSwitchEvent(),this.bindDefaultUi(),this.bindViewerHooks(),this.bindBaseHooks()}bindBaseHooks(){this.hooks.inserted.on(t=>{this.bindEventsEmitter()})}bindViewerResized(){const{viewer:t}=this.injection;t.hooks.resize.on(()=>{const{pullDownBox:t}=this;if(!t)return;const e="none"===t.style.display,i=this.injection.viewer.rootDom;e?this.isFirstClick=!0:ub(i,this.el,this.pullDownBox)},this)}bindPullDownBoxEvents(){this.nativeOn(this.el,"click",()=>{this.togglePopup(),this.isFirstClick&&(ub(this.injection.viewer.rootDom,this.el,this.pullDownBox),this.isFirstClick=!1)}),this.nativeOn(this.el,"keydown",t=>{if(-1===["ArrowUp","ArrowDown"].indexOf(t.key))return;t.stopPropagation(),t.preventDefault();const{children:e}=this.pullDownBox,{length:i}=e;switch(t.key){case"ArrowDown":e[0].focus(),this.currentFocusedIndex=0;break;case"ArrowUp":e[i-1].focus(),this.currentFocusedIndex=i-1}}),this.nativeOn(this.pullDownBox,"keydown",t=>{var e,i;if(-1===["ArrowUp","ArrowDown"].indexOf(t.key))return;const{children:n}=this.pullDownBox,{length:s}=n;switch(t.stopPropagation(),t.preventDefault(),t.key){case"ArrowUp":this.currentFocusedIndex-=1,"BUTTON"!==(null===(e=n[this.currentFocusedIndex])||void 0===e?void 0:e.tagName)&&(this.currentFocusedIndex-=1);break;case"ArrowDown":this.currentFocusedIndex+=1,"BUTTON"!==(null===(i=n[this.currentFocusedIndex])||void 0===i?void 0:i.tagName)&&(this.currentFocusedIndex+=1)}this.currentFocusedIndex<0?this.currentFocusedIndex=s-1:this.currentFocusedIndex>s-1&&(this.currentFocusedIndex=0),n[this.currentFocusedIndex].focus()})}bindPopupSwitchEvent(){ab(this)}bindDefaultUi(){const t=this.injection.viewer,e=e=>{let i=(Ps(null==e?void 0:e.pageCount)?this.injection.viewer.getPageCounts():e.pageCount)?"normal":"disabled";yb(this,t)&&(i="disabled"),this.isFirstClick=!0,this.setUiState(i)};t.hooks.pageExistenceChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}initPullDownBox(){this.hooks.created.on(()=>{this.pullDownBox=this.query(`.${this.defaultClass}-box`),this.pullDownBox.style.display="none",this.pullDownBox.remove(),this.bindPullDownBoxEvents()}),this.hooks.updated.on(()=>{this.uiState="normal",this.pullDownBox.style.display="none",this.isFirstClick=!0})}bindViewerHooks(){this.injection.viewer.hooks.visibleChanged.on(t=>{"hidden"===t.newVisibility&&this.togglePopup(!1)},this)}setUiState(t){mb(this,t)}togglePopup(t){const{pullDownBox:e}=this,{viewer:i}=this.injection;let n="none"===e.style.display;n=Ps(t)?!n:!t,n?e.remove():(this.$emit("ui_hidePopup",this),i.rootDom.appendChild(e)),db(this.el,!n),e.style.display=n?"none":""}}class Cb extends wb{constructor(t){super(t),Yi(this,"lastSelectedIndex",0),Yi(this,"defaultClass","ddv-pdl"),Yi(this,"pullDownBoxClass","ddv-pull-down"),Yi(this,"children",[]),Yi(this,"hasCheckIcon",!1);const{defaultClassName:e,children:i,showCheckIcon:n}=t.data.options;e&&(this.defaultClass=e),this.pullDownBoxClass=`${this.defaultClass}-box ddv-pull-down`,this.children=i,this.hasCheckIcon=n,this.initPullDownBox(),this.initTemplate(),this.$on("ui_layoutScroll",t=>{this.togglePopup(!1),this.isFirstClick=!0})}getChildrenTemplate(){let t="";return this.children.forEach((e,i)=>{const{id:n,label:s}=e;e.id=void 0,e.label=void 0,t+=`<${e.type} :options="options.children[${i}]" default="false"id="${n?n+this.injection.viewer.postfix:""}" ><span>${s}</span>`+(this.hasCheckIcon?'<i class="ddv-button-ok" style="visibility: hidden"></i>':"")+`</${e.type}>`}),t}selectChildren(t){if(!this.hasCheckIcon)return;const{pullDownBox:e}=this;if(-1!==t&&!e.childNodes[t])return;if(-1!==this.lastSelectedIndex){const t=e.children[this.lastSelectedIndex],i=t.getElementsByTagName("i")[0];t.classList.remove("ddv-pull-down-selected"),i.style.visibility="hidden"}if(-1===t)return void(this.lastSelectedIndex=-1);const i=e.children[t],n=i.getElementsByTagName("i")[0];i.classList.add("ddv-pull-down-selected"),n.style.visibility="visible",this.lastSelectedIndex=t}initTemplate(){const t=this.data;t.options||(t.options={});const{options:e}=this.data,{pullDownBox:i,showDropDownArrow:n}=e;pb(gb(this),this.injection.viewer,e);const s=`<button ${GC(e,`ddv-button ${this.defaultClass}`)}>`+(Ps(null==e?void 0:e.label)?"":`<span>${e.label}</span>`)+`<div ${GC(i,this.pullDownBoxClass)}>`+`${this.getChildrenTemplate()}</div>`+`<i style="display: ${n?"":"none"}" class="ddv-down-arrow"></i></button>`;this.template=s}}class bb extends wb{constructor(t){super(t),Yi(this,"defaultClass","ddv-pdm"),Yi(this,"pullDownBoxClass","ddv-pull-down"),Yi(this,"children",[]);const{defaultClassName:e,children:i,enableScroll:n}=t.data.options;e&&(this.defaultClass=e),this.pullDownBoxClass=`${this.defaultClass}-box ddv-pull-down`,n&&(this.pullDownBoxClass+=Ms()?" ddv-custom-scroll-hidden":" ddv-custom-scroll"),this.children=i,this.initPullDownBox(),this.initTemplate()}getChildrenTemplate(){let t="";return this.children.forEach((e,i)=>{t+=`<${e.type} :options="options.children[${i}]" menu="true"></${e.type}>`}),t}initTemplate(){const t=this.data;t.options||(t.options={});const{options:e}=this.data,{pullDownBox:i,showDropDownArrow:n}=e;pb(gb(this),this.injection.viewer,e);const s=`<button ${GC(e,`ddv-button ${this.defaultClass}`)}>`+(Ps(null==e?void 0:e.label)?"":`<span>${e.label}</span>`)+`<div ${GC(i,this.pullDownBoxClass)}>`+`${this.getChildrenTemplate()}</div>`+`<i style="display: ${n?"":"none"}" class="ddv-down-arrow"></i></button>`;this.template=s}}class Sb extends xb{constructor(t,e){super(t,{class:e.class,callback:()=>{const{viewer:t}=this.injection;Ms()&&this.el.classList.contains("ddv-button-focused")?t.updateViewerConfig({toolMode:"pan"}):(t.updateViewerConfig({toolMode:"annotation",annotationMode:e.annotationMode}),"stamp"===e.annotationMode&&t.updateAnnotationConfig({defaultStyleConfig:{stamp:{imageData:null,stampConfig:null}}}))}}),Yi(this,"annotationMode",void 0),this.annotationMode=e.annotationMode}bindDefaultUi(){const t=this.injection.viewer,e=()=>{if(!lg.annotationLicenseModuleIsExist())return void this.setUiState("disabled");const{toolMode:e,annotationMode:i}=t.getViewerConfig();t.getPageCounts()?"annotation"!==e?this.setUiState("normal"):i===this.annotationMode?this.setUiState("focused"):this.setUiState("normal"):this.setUiState("disabled")};t.hooks.pageExistenceChanged.on(e,this),t.hooks.toolModeChanged.on(e,this),t.hooks.annotationModeChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}class Tb extends Sb{constructor(t){super(t,{class:"ddv-ellipse",annotationMode:"ellipse"})}}Yi(Tb,"cpName","EllipseAnnotation");class Eb extends Sb{constructor(t){super(t,{class:"ddv-annot-eraser",annotationMode:"erase"})}}Yi(Eb,"cpName","EraseAnnotation");class _b extends Sb{constructor(t){super(t,{class:"ddv-ink",annotationMode:"ink"})}}Yi(_b,"cpName","InkAnnotation");class Pb extends Sb{constructor(t){super(t,{class:"ddv-line",annotationMode:"line"})}}Yi(Pb,"cpName","LineAnnotation");class Ab extends Sb{constructor(t){super(t,{class:"ddv-polygon",annotationMode:"polygon"})}}Yi(Ab,"cpName","PolygonAnnotation");class Ib extends Sb{constructor(t){super(t,{class:"ddv-polyline",annotationMode:"polyline"})}}Yi(Ib,"cpName","PolylineAnnotation");class Db extends Sb{constructor(t){super(t,{class:"ddv-rect",annotationMode:"rectangle"})}}Yi(Db,"cpName","RectAnnotation");class Rb extends Sb{constructor(t){super(t,{class:"ddv-annot-select",annotationMode:"select"})}}Yi(Rb,"cpName","SelectAnnotation");class kb extends Sb{constructor(t){super(t,{class:"ddv-stamp-icon",annotationMode:"stamp"})}bindDefaultUi(){const t=this.injection.viewer,e=()=>{if(!lg.annotationLicenseModuleIsExist())return void this.setUiState("disabled");const{toolMode:e,annotationMode:i}=t.getViewerConfig(),n=t.getPageCounts(),{defaultStyleConfig:s}=t.getAnnotationConfig(),{stamp:o}=s,r=null==o?void 0:o.imageData;n?"annotation"!==e||"stamp"!==i||r?this.setUiState("normal"):this.setUiState("focused"):this.setUiState("disabled")};t.hooks.pageExistenceChanged.on(e,this),t.hooks.toolModeChanged.on(e,this),t.hooks.annotationModeChanged.on(e,this),t.hooks.annotationDefaultStyleChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}Yi(kb,"cpName","StampIconAnnotation");class Mb extends xb{constructor(t){super(t,{class:"ddv-stamp-image",callback:()=>{this.annotationImageLoader.value=null,delete this.annotationImageLoader.files,Ms()&&this.el.classList.contains("ddv-button-focused")?this.injection.viewer.updateViewerConfig({toolMode:"pan"}):(this.injection.viewer.updateViewerConfig({toolMode:"pan"}),this.injection.viewer.selectAnnotations([]),this.annotationImageLoader.click())}}),Yi(this,"annotationImageLoader",void 0)}createAnnotationImageLoaderInput(){const t=document.createElement("input");return t.accept="image/png,image/jpeg,image/bmp",t.type="file",this.nativeOn(t,"change",()=>{const{files:e}=t,i=new Blob([e[0]],{type:e[0].type});["image/png","image/jpeg","image/bmp"].includes(e[0].type)&&(this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{stamp:{imageData:i}}}),t.value=null,t.files=null,this.injection.viewer.updateViewerConfig({toolMode:"annotation",annotationMode:"stamp"}))}),t}bindHidePopup(){this.nativeOn(this.el,"click",()=>{this.$emit("ui_hidePopup","AnnotationSet")})}bindHooks(){super.bindHooks(),this.hooks.inserted.on(()=>{const t=this.createAnnotationImageLoaderInput();t.style.display="none",this.el.appendChild(t),this.annotationImageLoader=t,this.nativeOn(t,"click",t=>{t.stopPropagation()})})}bindDefaultUi(){const t=this.injection.viewer,e=()=>{if(!lg.annotationLicenseModuleIsExist())return void this.setUiState("disabled");const{toolMode:e,annotationMode:i}=t.getViewerConfig(),n=t.getPageCounts(),{defaultStyleConfig:s}=t.getAnnotationConfig(),{stamp:o}=s,r=null==o?void 0:o.imageData;n?"annotation"!==e?this.setUiState("normal"):"stamp"===i&&r?this.setUiState("focused"):this.setUiState("normal"):this.setUiState("disabled")};t.hooks.pageExistenceChanged.on(e,this),t.hooks.toolModeChanged.on(e,this),t.hooks.annotationModeChanged.on(e,this),t.hooks.annotationDefaultStyleChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}Yi(Mb,"cpName","StampImageAnnotation");class Lb extends Sb{constructor(t){super(t,{class:"ddv-text-box",annotationMode:"textBox"})}}Yi(Lb,"cpName","TextBoxAnnotation");class Ob extends Sb{constructor(t){super(t,{class:"ddv-typewriter",annotationMode:"textTypewriter"})}}Yi(Ob,"cpName","TextTypewriterAnnotation");class Bb extends Sb{constructor(t){super(t,{class:"ddv-highlight-mode",annotationMode:"highlight"})}}Yi(Bb,"cpName","HighlightAnnotation");class Nb extends Sb{constructor(t){super(t,{class:"ddv-underline-mode",annotationMode:"underline"})}}Yi(Nb,"cpName","UnderlineAnnotation");class Ub extends Sb{constructor(t){super(t,{class:"ddv-strikeout-mode",annotationMode:"strikeout"})}}Yi(Ub,"cpName","StrikeoutAnnotation");class Fb extends bb{constructor(t){const{AnnotationSet:e}=MT.getDisplayTextConfig(),i=t.data;i.options={children:[{type:"SelectAnnotation"},{type:"EraseAnnotation"},{type:"SeparatorLine"},{type:"HighlightAnnotation"},{type:"UnderlineAnnotation"},{type:"StrikeoutAnnotation"},{type:"TextTypewriterAnnotation"},{type:"TextBoxAnnotation"},{type:"SeparatorLine"},{type:"StampIconAnnotation"},{type:"StampImageAnnotation"},{type:"SeparatorLine"},{type:"InkAnnotation"},{type:"RectAnnotation"},{type:"EllipseAnnotation"},{type:"PolygonAnnotation"},{type:"PolylineAnnotation"},{type:"LineAnnotation"},{type:"SeparatorLine"},{type:"BringForward"},{type:"BringToFront"},{type:"SendBackward"},{type:"SendToBack"}],defaultClassName:"ddv-annotation-mode",label:e,enableScroll:!0,showDropDownArrow:!0,...i.options},super(t),this.$on("ui_cropClick",t=>{const{viewer:e}=this.injection,i=e.getPageCounts()||0;(t||i)&&lg.annotationLicenseModuleIsExist()&&cb(this.el,t)})}bindDefaultUi(){lg.annotationLicenseModuleIsExist()?(super.bindDefaultUi(),this.hooks.inserted.on(t=>{const{toolMode:e}=this.injection.viewer.getViewerConfig(),i=this.injection.viewer.getPageCounts();"annotation"===e&&i>0&&this.setUiState("focused")})):this.hooks.inserted.on(t=>{this.setUiState("disabled")})}togglePopup(t){if((!0!==t||""!==this.pullDownBox.style.display)&&(!1!==t||"none"!==this.pullDownBox.style.display)&&(super.togglePopup(t),""===this.pullDownBox.style.display&&Vb(this.pullDownBox).horizontal)){this.pullDownBox.style.justifyContent="start";let t=0;for(let e=0;e<this.pullDownBox.children.length;e++){const i=this.pullDownBox.children[e];i.classList.contains("ddv-button-focused")&&(t=i.offsetLeft+i.clientWidth/2-this.pullDownBox.clientWidth/2)}this.pullDownBox.scroll(t,0)}}bindPopupSwitchEvent(){this.$on("ui_hidePopup",t=>{if(t===this||"viewer"===t||t===Fb.cpName)return;const{toolMode:e}=this.injection.viewer.getViewerConfig();"annotation"!==e&&this.togglePopup(!1)})}bindViewerHooks(){if(!lg.annotationLicenseModuleIsExist())return;const t=this.injection.viewer;t.hooks.resize.on(()=>{Vb(this.pullDownBox).horizontal?this.pullDownBox.style.justifyContent="start":this.pullDownBox.style.justifyContent=""},this),t.hooks.pageExistenceChanged.on(()=>{const{toolMode:e}=t.getViewerConfig();let i="disabled";t.getPageCounts()>0?(i="crop"===t.getViewerConfig().toolMode?"disabled":"normal","annotation"===e&&(this.isFirstClick?(this.togglePopup(!1),this.el.click()):this.togglePopup(!0),i="focused")):this.togglePopup(!1),this.setUiState(i)},this),t.hooks.toolModeChanged.on(e=>{const i="crop"===e.newToolMode,n="annotation"===e.newToolMode;if(i)return this.togglePopup(!1),void this.setUiState("disabled");t.getPageCounts()>0&&(this.setUiState(n?"focused":"normal"),db(this.el,"none"!==this.pullDownBox.style.display),this.$emit("ui_annotationModeClick",n),n&&(this.isFirstClick?(this.togglePopup(!1),this.el.click()):this.togglePopup(!0)))},this)}setUiState(t){super.setUiState(t)}}function Vb(t){return{vertical:t.scrollHeight>t.clientHeight,horizontal:t.scrollWidth>t.clientWidth}}Yi(Fb,"cpName","AnnotationSet");class Wb extends xb{constructor(t,e){super(t,{class:e.class,callback:()=>{const{viewer:t}=this.injection,e=t.getSelectedAnnotations();if(1!==e.length)return;const i=e[0].uid;switch(this.layerType){case"bringForward":t.bringForward(i);break;case"bringToFront":t.bringToFront(i);break;case"sendBackward":t.sendBackward(i);break;case"sendToBack":t.sendToBack(i)}}}),Yi(this,"layerType",void 0),this.layerType=e.layerType}bindHidePopup(){this.nativeOn(this.el,"click",()=>{this.$emit("ui_hidePopup","AnnotationSet")})}bindDefaultUi(){const t=this.injection.viewer,e=lg.annotationLicenseModuleIsExist(),i=()=>{if(!e)return void this.setUiState("disabled");const{viewer:i}=this.injection,n=i.getSelectedAnnotations();t.getPageCounts()&&1===n.length?this.setUiState("normal"):this.setUiState("disabled")};t.hooks.annotationLayerStateChanged.on(i=>{let{state:n}=i;if(!e)return void this.setUiState("disabled");const s=t.getSelectedAnnotations();if(!s.length||s.length>1)return void this.setUiState("disabled");const o=t.getAnnotationObject(s[0].uid);if(o&&!o.context.isActive)return void this.setUiState("disabled");let r=!1;switch(this.layerType){case"bringForward":r=n.forward;break;case"bringToFront":r=n.front;break;case"sendBackward":r=n.backward;break;case"sendToBack":r=n.back}this.setUiState(r?"normal":"disabled")},this),t.hooks.pageExistenceChanged.on(i,this),this.hooks.inserted.on(i),this.hooks.updated.on(i)}}class Hb extends Wb{constructor(t){super(t,{class:"ddv-bring-forward",layerType:"bringForward"})}}Yi(Hb,"cpName","BringForward");class jb extends Wb{constructor(t){super(t,{class:"ddv-bring-to-front",layerType:"bringToFront"})}}Yi(jb,"cpName","BringToFront");class zb extends Wb{constructor(t){super(t,{class:"ddv-send-backward",layerType:"sendBackward"})}}Yi(zb,"cpName","SendBackward");class Gb extends Wb{constructor(t){super(t,{class:"ddv-send-to-back",layerType:"sendToBack"})}}Yi(Gb,"cpName","SendToBack");class Yb extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-annotation-toolbar"),Yi(this,"lastAnnotation",void 0),Yi(this,"toolbarOffset",20),Yi(this,"toolbarType",void 0),Yi(this,"lastScrollTop",0),Yi(this,"lastScrollLeft",0),Yi(this,"updateToolBarPosition",()=>{if("text"===this.toolbarType)return void this.togglePopup(!1);if(!this.lastAnnotation)return;const{viewer:t}=this.injection,e=t.getActiveTab();if(e&&"single"===e.context.displayMode&&this.lastAnnotation.pageUid!==e.getCurrentPage().uid)return;const i=e.childNodes.find(t=>t.uid===this.lastAnnotation.pageUid);if(!i)return void this.togglePopup(!1);this.setToolbarType("annotation");const{show:n,x:s,y:o}=$b(t.context.viewService.mainContainer,this.lastAnnotation,this.el,this.toolbarOffset);this.togglePopup(n,s,o)}),this.bindHooks(),this.initTemplate(),this.bindViewerHooks(),this.$on("ui_toolbarToggle",()=>{this.togglePopup()})}bindHooks(){const t=t=>{this.el.style.display="none",this.setToolbarType("annotation")};this.hooks.inserted.on(t),this.hooks.updated.on(t),this.hooks.destroyed.on(()=>{this.el.remove()})}bindViewerHooks(){const{viewer:t}=this.injection;t.hooks.visibleChanged.on(()=>{this.togglePopup(!1)},this),t.hooks.pageExistenceChanged.on(t=>{0===t.pageCount&&(this.togglePopup(!1),this.lastAnnotation=null)},this),t.hooks.pageChanged.on(()=>{const e=t.getActiveTab();if(!e||"single"!==e.context.displayMode)return;const i=t.getSelectedAnnotations();if(1!==i.length)return;const n=i[0].pageUid===e.getCurrentPage().uid;this.togglePopup(n)},this),t.hooks.resize.on(this.updateToolBarPosition,this),t.hooks.scroll.on(t=>{if("text"===this.toolbarType&&"none"!==this.el.style.display){const{scrollTop:e,scrollLeft:i}=t.target;if(Math.abs(this.lastScrollTop-e)<=10&&Math.abs(this.lastScrollLeft-i)<=10)return;this.lastScrollTop=e,this.lastScrollLeft=i}this.updateToolBarPosition()},this),t.hooks.fitModeChanged.on(this.updateToolBarPosition,this),t.hooks.displayModeChanged.on(this.updateToolBarPosition,this),t.hooks.zoomChanged.on(this.updateToolBarPosition,this),this.bindViewerAnnotationHooks(),this.bindViewerTextSelectedHooks()}bindViewerAnnotationHooks(){const{viewer:t}=this.injection;if(t.hooks.selectedAnnotationsChanged.on(e=>{if(1!==e.newAnnotationUids.length)return this.togglePopup(!1),void(this.lastAnnotation=null);const i=e.newAnnotationUids[0],n=t.getAnnotationObject(i);if(!n)return;this.setToolbarType("annotation");const{show:s,x:o,y:r}=$b(t.context.viewService.mainContainer,n,this.el,this.toolbarOffset);this.togglePopup(s,o,r),this.lastAnnotation=n},this),t.hooks.beforeAnnotationEdit.on(()=>{this.togglePopup(!1)},this),t.hooks.afterAnnotationEdit.on(e=>{if(e instanceof cc)return;this.setToolbarType("annotation");const{show:i,x:n,y:s}=$b(t.context.viewService.mainContainer,e,this.el,this.toolbarOffset);this.lastAnnotation=e,this.togglePopup(i,n,s)},this),t.hooks.annotationsUpdated.on(t=>{this.lastAnnotation instanceof hc&&"freeTextWriter"===this.lastAnnotation.textType?setTimeout(()=>{this.updateToolBarPosition()},16):this.updateToolBarPosition()},this),t.hooks.annotationTextContentUpdated.on(this.updateToolBarPosition,this),null!=t&&t.annotationViewerContext){const{annotationViewerContext:e}=t,{hooks:i}=e.annotationController;i.enableAnnotationTextEditMode.on(this.updateToolBarPosition,this),i.disableAnnotationTextEditMode.on(this.updateToolBarPosition,this)}}bindViewerTextSelectedHooks(){const{viewer:t}=this.injection;t.hooks.textSelected.on(e=>{const i=t.context.textSelectionService.getTextSelectionControlPointsRect();if(i.length){const n=t.getActiveTab();let s=[i[1],i[0]];1===e.detail.length&&180===n.getPageByUid(e.detail[0].pageUid).getRotation()&&(s=[i[0],i[1]]),this.setToolbarType("text");const{show:o,x:r,y:a}=function(t,e,i,n){i.style.display="flex";const{width:s,height:o}=t.getBoundingClientRect(),r=getComputedStyle(i),a=da(r.width).value,l=da(r.height).value;i.style.display="none";const h=(t,e)=>{if(t<0){if(t<-a/2)return null;t=0}else if(t+a>s){if(t+a>s+a/2)return null;t=s-a}if(e<0){if(e<-l/2)return null;e=0}else if(e+l>o){if(e+l>o+l/2)return null;e=o-l}return{x:t,y:e}},c=t=>({left:t.left+t.width/2-a/2,topInTop:t.top-n-l,topInBottom:t.top+t.height+n});if(e[0]){const{left:t,topInBottom:i,topInTop:n}=c(e[0]),s=h(t,i);if(s)return{show:!0,x:s.x,y:s.y};const o=h(t,n);if(o)return{show:!0,x:o.x,y:o.y}}if(e[1]){const{left:t,topInBottom:i,topInTop:n}=c(e[1]),s=h(t,i);if(s)return{show:!0,x:s.x,y:s.y};const o=h(t,n);if(o)return{show:!0,x:o.x,y:o.y}}return{show:!1}}(t.context.viewService.mainContainer,s,this.el,this.toolbarOffset);o&&(this.lastScrollTop=t.context.viewService.scrollContainer.scrollTop,this.lastScrollLeft=t.context.viewService.scrollContainer.scrollLeft),this.togglePopup(o,r,a)}else"text"===this.toolbarType&&this.togglePopup(!1)},this),t.hooks.beforeTextSelected.on(()=>{this.togglePopup(!1)},this)}togglePopup(t,e,i){const{viewer:n}=this.injection;t?(n.context.viewService.mainContainer.appendChild(this.el),this.el.style.display="",this.el.style.left=`${e||0}px`,this.el.style.top=`${i||0}px`):this.el.style.display="none"}setToolbarType(t){var e,i,n,s,o,r;const{options:a}=this.data;this.toolbarType=t;const l={highlight:this.el.querySelector(".ddv-highlight-mode"),strikeout:this.el.querySelector(".ddv-strikeout-mode"),underline:this.el.querySelector(".ddv-underline-mode"),copyText:this.el.querySelector(".ddv-copy-text"),palette:this.el.querySelector(".ddv-palette"),delete:this.el.querySelector(".ddv-delete-annot")},h={highlight:"none"===(null===(e=a.highlightButton)||void 0===e||null===(e=e.style)||void 0===e?void 0:e.display),strikeout:"none"===(null===(i=a.strikeoutButton)||void 0===i||null===(i=i.style)||void 0===i?void 0:i.display),underline:"none"===(null===(n=a.underlineButton)||void 0===n||null===(n=n.style)||void 0===n?void 0:n.display),copyText:"none"===(null===(s=a.copyButton)||void 0===s||null===(s=s.style)||void 0===s?void 0:s.display),palette:"none"===(null===(o=a.paletteButton)||void 0===o||null===(o=o.style)||void 0===o?void 0:o.display),delete:"none"===(null===(r=a.deleteButton)||void 0===r||null===(r=r.style)||void 0===r?void 0:r.display)};["copyText","highlight","strikeout","underline"].forEach(e=>{!h[e]&&l[e]&&(l[e].style.display="text"===t?"":"none")}),["palette","delete"].forEach(e=>{!h[e]&&l[e]&&(l[e].style.display="annotation"===t?"":"none")}),this.toolbarOffset="text"===t?10:20}initTemplate(){const{options:t}=this.data;pb(gb(this),this.injection.viewer,t);let e=`<div ${GC(t,this.defaultClass,"")}>`;null!=t&&t.isPaletteEnabled&&(e+='<AnnotationPaletteButton :options="options.paletteButton"></AnnotationPaletteButton>'),e+='<TextCopyButton :options="options.copyButton"></TextCopyButton>',e+='<HighlightCreateButton :options="options.highlightButton"></HighlightCreateButton>',e+='<UnderlineCreateButton :options="options.underlineButton"></UnderlineCreateButton>',e+='<StrikeoutCreateButton :options="options.strikeoutButton"></StrikeoutCreateButton>',e+='<AnnotationDeleteButton :options="options.deleteButton"></AnnotationDeleteButton></div>',this.template=e}}function $b(t,e,i,n){i.style.display="flex";const{width:s,height:o}=t.getBoundingClientRect(),r=e.context.getRealTimeBoundingBox(),a=getComputedStyle(i),l=da(a.width).value,h=da(a.height).value;if(i.style.display="none",r.right<0||r.left>s||r.top>o||r.bottom<0)return{show:!1,x:0,y:0};const c=r.left+r.width/2-l/2;let d=r.bottom+n;return d+h>o&&(d=r.top-h-n),d<0&&(d=0),{show:!0,x:c,y:d}}Yi(Yb,"cpName","AnnotationToolBar");class Xb extends xb{constructor(t){super(t,{class:"ddv-palette",callback:()=>{this.$emit("ui_changePalette_visible","AnnotationPalette")}}),lb(this)}bindHidePopup(){this.nativeOn(this.el,"click",()=>{this.$emit("ui_hidePopup","AnnotationSet"),this.focusTexture()})}focusTexture(){const t=this.injection.viewer.getSelectedAnnotations();if(1===t.length){const e=this.injection.viewer.getAnnotationObject(t[0].uid);e instanceof hc&&e.isEditMode&&e.focusTexture()}}}Yi(Xb,"cpName","AnnotationPaletteButton");class qb extends xb{constructor(t){super(t,{class:"ddv-delete-annot",callback:()=>{const{viewer:t}=this.injection,e=t.getSelectedAnnotations(),i=[];e.forEach(t=>{i.push(t.uid)}),t.deleteAnnotations(i)}}),lb(this)}bindHidePopup(){this.nativeOn(this.el,"click",()=>{this.$emit("ui_hidePopup","AnnotationSet")})}bindDefaultUi(){const t=this.injection.viewer,e=()=>{const{viewer:e}=this.injection,i=e.getSelectedAnnotations();t.getPageCounts()&&i.length?this.setUiState("normal"):this.setUiState("disabled")};t.hooks.selectedAnnotationsChanged.on(e,this),t.hooks.pageExistenceChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}Yi(qb,"cpName","AnnotationDeleteButton");class Zb extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-palette-color-panel"),Yi(this,"colorList",void 0),Yi(this,"enableChangeColor",void 0),Yi(this,"paletteType",void 0),Yi(this,"colorInput",void 0),Yi(this,"selectedColorButton",void 0),Yi(this,"lastUpdatedAnnotation",void 0),Yi(this,"lastInputColor",void 0),Yi(this,"lastTextContents",void 0),Yi(this,"lastPaletteType",void 0),Yi(this,"dblClickButtons",[]),this.colorList=t.data.colorList,this.enableChangeColor=t.data.enableChangeColor,this.initTemplate(),this.bindHooks(),this.bindViewerHooks(),this.$on("ui_changePalette_type",t=>{this.el.style.display="stamp"===t?"none":"",this.paletteType=t,this.showNoFill("fill"===t),this.updateButtonSelected()})}bindHooks(){this.hooks.inserted.on(()=>{const t=document.createElement("input");t.type="color",this.colorInput=t,this.el.appendChild(this.colorInput),this.bindEvents(),this.bindColorInputEvents()})}bindEvents(){const t=this.el.querySelector(".ddv-palette-color-grid");this.nativeOn(t,"click",t=>{const e=t.target;if(!(e instanceof HTMLButtonElement))return;if(this.dblClickButtons.push(e),this.dblClickButtons.length>2&&this.dblClickButtons.shift(),e.classList.contains("ddv-color-selected"))return;const i=e.value,{viewer:n}=this.injection;if(""===i)this.colorInput.focus(),this.colorInput.click(),this.selectedColorButton=e;else{const t=n.getSelectedAnnotations();1===t.length&&this.updateColorByData(t[0],i),this.updateDefaultColor(i)}}),this.nativeOn(t,"dblclick",t=>{if(!this.enableChangeColor)return;const e=t.target;if(!(e instanceof HTMLButtonElement))return;if(2===this.dblClickButtons.length&&this.dblClickButtons[0]!==this.dblClickButtons[1])return;const i=e.value;"transparent"!==i&&""!==i&&(this.colorInput.value=i,Ms()&&this.colorInput.focus(),this.colorInput.click(),this.selectedColorButton=e)})}bindColorInputEvents(){this.nativeOn(this.colorInput,"input",t=>{sb(()=>{const{viewer:t}=this.injection,e=this.colorInput.value;this.selectedColorButton.classList.contains("ddv-add-color")&&this.addColor(),this.selectedColorButton.children[0].style.background=e,this.selectedColorButton.value=e,1===t.getSelectedAnnotations().length&&this.updateColorByShape(e),this.updateDefaultColor(e),this.selectedColor(e)},60)}),this.nativeOn(this.colorInput,"change",t=>{this.lastUpdatedAnnotation&&(this.updateColorByData(this.lastUpdatedAnnotation,this.lastInputColor,this.lastPaletteType),this.lastUpdatedAnnotation=null,this.lastInputColor=null,this.lastPaletteType=null)})}bindViewerHooks(){const t=this.injection.viewer;t.hooks.selectedAnnotationsChanged.on(()=>{this.updateButtonSelected()},this),t.hooks.annotationsUpdated.on(()=>{this.updateButtonSelected()},this),t.hooks.annotationModeChanged.on(()=>{this.updateButtonSelected()},this),t.hooks.annotationDefaultStyleChanged.on(()=>{this.updateButtonSelected()},this),t.hooks.annotationTextCharsSelected.on(t=>{const e=t.freeTextContentStyle,{color:i}=e;"text"===this.paletteType?this.selectedColor(i):this.updateButtonSelected()},this)}updateColorByShape(t){const e=this.injection.viewer.getSelectedAnnotations();if(1!==e.length)return;const i=this.injection.viewer.getAnnotationObject(e[0].uid),n=i instanceof Lc,s=i instanceof hc;if("fill"===this.paletteType||"textAssist"===this.paletteType&&n)i.style.background=t;else if(["stroke","textAssist"].includes(this.paletteType))i.style.borderColor=t;else if("text"===this.paletteType&&s){if(i.hasSelectedChars){const e=zh(i,{color:t});i.style.textContents=e,i.textEditEventHandler.updateTextSelection()}else{if(i.isEditMode)return void this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[e[0].type]:{textContent:{color:t}}}});{const e=jh(i,{color:t});e.length&&(i.style.textContents=e)}}this.lastTextContents=i.style.textContents}this.lastUpdatedAnnotation=e[0],this.lastInputColor=t,this.lastPaletteType=this.paletteType,this.injection.viewer.context.render(93)}updateColorByData(t,e,i){const{viewer:n}=this.injection,{uid:s}=t,o={},r=this.injection.viewer.getAnnotationObject(s),a=i||this.paletteType;if("text"===a&&r instanceof hc){const{hasSelectedChars:i}=r;if(i){const t=zh(r,{color:e});o.textContents=t}else{if(r.isEditMode)return void this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[t.type]:{textContent:{color:e}}}});{const t=jh(r,{color:e});t.length&&(o.textContents=t)}}return this.lastTextContents&&(o.textContents=this.lastTextContents,this.lastTextContents=null),n.updateAnnotation(s,{style:o},["appearanceChanged"]),void(r.hasSelectedChars&&r.textEditEventHandler.updateTextSelection())}"fill"===a?o.background="transparent"===e?"":e:"stroke"===a?o.borderColor=e:"textAssist"===a&&(r instanceof Lc?o.background=e:o.borderColor=e),n.updateAnnotation(s,{style:o},["appearanceChanged"])}updateDefaultColor(t,e){const{annotationMode:i}=this.injection.viewer.getViewerConfig(),n=this.injection.viewer.getSelectedAnnotations();let s=i;n.length&&n[0]&&(s=n[0].type);const o={};switch(e||this.paletteType){case"fill":o.background=t;break;case"textAssist":"highlight"===s?o.background=t:o.borderColor=t;break;case"stroke":o.borderColor=t;break;case"text":o.textContent={},o.textContent.color=t}this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[s]:o}})}selectedColor(t){const e=this.el.querySelector(".ddv-palette-color-grid").getElementsByTagName("button");for(let i=0;i<e.length;i++){const n=e[i];if(!n.value)continue;const s=wa(n.value),o=wa(t);s.formatted===o.formatted?n.classList.add("ddv-color-selected"):n.classList.contains("ddv-color-selected")&&n.classList.remove("ddv-color-selected")}}updateButtonSelected(){const{viewer:t}=this.injection,e=t.getSelectedAnnotations();if(1===e.length){let n=null;const s="highlight"===e[0].type;if("fill"===this.paletteType||"textAssist"===this.paletteType&&s)n=e[0].style.background||"transparent";else if(["stroke","textAssist"].includes(this.paletteType))n=e[0].style.borderColor||"transparent";else if("text"===this.paletteType){const s=t.getAnnotationObject(e[0].uid);var i;s instanceof hc&&(n=(null===(i=e[0].style)||void 0===i||null===(i=i.textContents[0])||void 0===i?void 0:i.color)||"transparent"),s instanceof hc&&(s.isEditMode||!s.style.textContents.length)&&(n=s.freeTextContentStyle.color)}return void(n&&this.selectedColor(n))}const{toolMode:n,annotationMode:s}=t.getViewerConfig();if("annotation"===n&&"select"!==s&&"erase"!==s){const{defaultStyleConfig:e}=t.getAnnotationConfig(),{background:i,borderColor:n,textContent:l}=qh,h="highlight"===s;let c=null;var o;if("fill"===this.paletteType||"textAssist"===this.paletteType&&h)c=(null===(o=e[s])||void 0===o?void 0:o.background)||i||"transparent";else if("stroke"===this.paletteType||"textAssist"===this.paletteType){var r;c=(null===(r=e[s])||void 0===r?void 0:r.borderColor)||n}else if("text"===this.paletteType){var a;c=(null===(a=e[s])||void 0===a||null===(a=a.textContent)||void 0===a?void 0:a.color)||(null==l?void 0:l.color)||"transparent"}c&&this.selectedColor(c)}}getColorTemplate(){const t=document.createElement("div");let e="<div>",i=0;for(let n=0;n<this.colorList.length;n++){const s=this.colorList[n];if(t.style.background=s,""!==t.style.background){if(i>26)break;i+=1,e+=`<button value="${s}"><div style="background:${s}"></div></button>`,0!==i&&i%7==0&&(e+="</div><div>"),t.style.background=""}}const n=i>26?0:27-i;for(let t=0;t<n;t++)e+=0===t?'<button value="" class="ddv-add-color"><div></div></button>':'<button value="" class="ddv-color-placeholder"><div></div></button>',(i+t+1)%7==0&&(e+="</div><div>");return e+='<button value="transparent" class="ddv-color-transparent"><div></div></button>',e+="</div>",t.remove(),e}showNoFill(t){this.el.querySelectorAll(".ddv-color-transparent").forEach(e=>{e.style.visibility=t?"":"hidden",e.style.pointerEvents=t?"":"none"})}addColor(){const t=this.el.querySelector(".ddv-palette-color-grid"),e=t.querySelector(".ddv-add-color"),i=t.querySelector(".ddv-color-placeholder");e&&e.classList.remove("ddv-add-color"),i&&(i.classList.remove("ddv-color-placeholder"),i.classList.add("ddv-add-color"))}initTemplate(){const t=`<div class="${this.defaultClass}"><div class="ddv-palette-color-grid">${this.getColorTemplate()}</div></div>`;this.template=t}}const Jb=Cr.displayResolution/Cr.dataResolution;class Kb extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-palette-font-panel"),Yi(this,"fontFamilyEl",void 0),Yi(this,"fontSizeEl",void 0),Yi(this,"fontList",[...nb]),Yi(this,"inputIsBlur",!0),Yi(this,"currentFontSizeValue",void 0),Yi(this,"isArrowKeyPressed",!1),Yi(this,"maxFontSize",72),this.maxFontSize=t.data.maxFontSize,this.maxFontSize<72&&(this.maxFontSize=72),this.initTemplate(),this.bindHooks(),this.bindViewerHooks(),this.$on("ui_shrinkSelectionBox",t=>{"fontFamily"!==t&&this.toggleSelect("fontFamily",!1),"fontSize"!==t&&this.toggleSelect("fontSize",!1)}),this.$on("ui_changePalette_type",t=>{this.el.style.display="text"===t?"":"none"}),this.$on("ui_addFont",t=>{this.addFont(t)})}updateTextStyle(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{toolMode:i,annotationMode:n}=this.injection.viewer.getViewerConfig(),s=this.injection.viewer.getSelectedAnnotations();if(1!==s.length||"textTypewriter"!==s[0].type&&"textBox"!==s[0].type)"annotation"!==i||"textBox"!==n&&"textTypewriter"!==n||this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[n]:{textContent:t}}});else{const{uid:e,type:i}=s[0],n=this.injection.viewer.getAnnotationObject(e);if(n.isEditMode)n.hasSelectedChars&&(this.injection.viewer.updateAnnotation(e,{style:{textContents:zh(n,t)}},["appearanceChanged"]),n.textEditEventHandler.updateTextSelection());else{const i=jh(n,t);i.length&&this.injection.viewer.updateAnnotation(e,{style:{textContents:i}},["appearanceChanged"])}this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[i]:{textContent:t}}})}e&&this.focusTexture()}bindHooks(){this.hooks.created.on(()=>{this.fontFamilyEl=this.el.querySelector(".ddv-palette-font-family"),this.fontSizeEl=this.el.querySelector(".ddv-palette-font-size")}),this.hooks.inserted.on(()=>{this.bindToggleEvent(),this.bindSelectEvent(),this.bindFontSizeInputEvent(),this.bindTextAlignEvents(),this.bineFontStyleEvents()})}bindToggleEvent(){const t=this.fontSizeEl.querySelector(".ddv-down-arrow");zo(this.fontFamilyEl,"click",this).on(t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox","fontFamily"),this.toggleSelect("fontFamily")},this),zo(t,"click",this).on(t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox","fontSize"),this.toggleSelect("fontSize")},this)}bindSelectEvent(){const t=this.fontFamilyEl.querySelector(".ddv-palette-font-family-select"),e=this.fontSizeEl.querySelector(".ddv-palette-font-size-select"),i=this.fontSizeEl.getElementsByTagName("input")[0],n=this.fontFamilyEl.getElementsByTagName("span")[0];this.nativeOn(t,"click",t=>{t.stopPropagation(),this.toggleSelect("fontFamily",!1);const e=t.target.value;e&&n.innerText!==e&&this.updateTextStyle({fontFamily:e})}),this.nativeOn(e,"click",t=>{t.stopPropagation(),this.toggleSelect("fontSize",!1);const e=t.target.value,n=`${e}pt`===i.value;e&&!n&&this.updateTextStyle({fontSize:da(e).value*Jb})})}bindFontSizeInputEvent(){const t=this.fontSizeEl.getElementsByTagName("input")[0];this.nativeOn(t,"keydown",t=>{t.stopPropagation(),"ArrowUp"!==t.key&&"ArrowDown"!==t.key||(this.isArrowKeyPressed=!0)}),this.nativeOn(t,"keyup",e=>{if(e.stopPropagation(),this.isArrowKeyPressed){let e=Math.round(da(t.value).value);e>this.maxFontSize&&(e=this.maxFontSize,t.value=`${this.maxFontSize}`),e<1&&(e=1,t.value="1"),this.updateTextStyle({fontSize:e*Jb},!1),this.isArrowKeyPressed=!1}}),this.nativeOn(t,"focus",()=>{const e=t.value,i=da(e).value;t.value=i,t.type="number",this.inputIsBlur=!1,this.currentFontSizeValue=i,this.$emit("ui_shrinkSelectionBox")}),this.nativeOn(t,"blur",e=>{this.inputIsBlur=!0,"text"!==t.type&&(this.currentFontSizeValue=t.value,t.type="text",t.value+="pt",e.relatedTarget instanceof HTMLInputElement||this.focusTexture())});const e=()=>{if(this.inputIsBlur||this.isArrowKeyPressed)return;t.type="text",t.value+="pt",t.removeEventListener("change",e),t.blur(),t.addEventListener("change",e);let i=Math.round(da(t.value).value);i>this.maxFontSize&&(i=this.maxFontSize),i<1&&(i=1),this.updateTextStyle({fontSize:i*Jb})};this.nativeOn(t,"change",e)}bindTextAlignEvents(){const t=this.el.querySelector(".ddv-align-left"),e=this.el.querySelector(".ddv-align-center"),i=this.el.querySelector(".ddv-align-right"),n=this.el.querySelector(".ddv-justify-center"),s=t=>{const{toolMode:e,annotationMode:i}=this.injection.viewer.getViewerConfig(),n=this.injection.viewer.getSelectedAnnotations();if(1!==n.length||"textTypewriter"!==n[0].type&&"textBox"!==n[0].type)"annotation"!==e||"textBox"!==i&&"textTypewriter"!==i||this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[i]:{textAlign:t}}});else{if(t===n[0].style.textAlign)return;this.injection.viewer.updateAnnotation(n[0].uid,{style:{textAlign:t}},["appearanceChanged"])}};this.nativeOn(t,"click",()=>{s("left")}),this.nativeOn(e,"click",()=>{s("center")}),this.nativeOn(i,"click",()=>{s("right")}),this.nativeOn(n,"click",()=>{s("justify")})}bineFontStyleEvents(){const t=this.el.querySelector(".ddv-bold"),e=this.el.querySelector(".ddv-italic"),i=this.el.querySelector(".ddv-underline"),n=this.el.querySelector(".ddv-line-through");this.nativeOn(t,"click",e=>{this.updateTextStyle({fontWeight:t.classList.contains("ddv-button-activated-light")?"normal":"bold"})}),this.nativeOn(e,"click",t=>{this.updateTextStyle({fontStyle:e.classList.contains("ddv-button-activated-light")?"normal":"italic"})}),this.nativeOn(i,"click",t=>{this.updateTextStyle({underline:!i.classList.contains("ddv-button-activated-light")})}),this.nativeOn(n,"click",t=>{this.updateTextStyle({lineThrough:!n.classList.contains("ddv-button-activated-light")})})}bindViewerHooks(){const{viewer:t}=this.injection;t.hooks.selectedAnnotationsChanged.on(e=>{if(1!==e.newAnnotationUids.length)return;const i=t.getSelectedAnnotations()[0];if("textTypewriter"!==i.type&&"textBox"!==i.type)return;this.showTextAlignList("textBox"===i.type),this.selectTextAlign(i.style.textAlign||"left");const{defaultStyleConfig:n}=this.injection.viewer.getAnnotationConfig(),{textContent:s}=n[i.type],o=i.style.textContents.length?i.style.textContents[0]:s,{fontFamily:r,fontSize:a,fontWeight:l,fontStyle:h,underline:c,lineThrough:d}=o;this.selectFontStyle(r,Math.round(da(a).value/Jb),"bold"===l,"italic"===h,c,d)},this),t.hooks.annotationDefaultStyleChanged.on(()=>{const{toolMode:t,annotationMode:e}=this.injection.viewer.getViewerConfig(),i=this.injection.viewer.getSelectedAnnotations();let n,s,o=!1;if("annotation"!==t||"textBox"!==e&&"textTypewriter"!==e||(o=!0,n=e),1===i.length){const t=this.injection.viewer.getAnnotationObject(i[0].uid);t instanceof hc&&(n=i[0].type,s=i[0].style.textAlign,t.isEditMode&&!t.hasSelectedChars?o=!0:t.isEditMode||t.style.textContents.length?(this.selectTextAlign(s),o=!1):o=!0)}if(!o)return;const{defaultStyleConfig:r}=this.injection.viewer.getAnnotationConfig(),{textAlign:a}=r[n],{fontFamily:l,fontSize:h,fontWeight:c,fontStyle:d,underline:u,lineThrough:p}=r[n].textContent||{},{textContent:g}=qh;this.selectTextAlign(s||a||qh.textAlign),this.selectFontStyle(l||g.fontFamily,Math.round(da(h||g.fontSize).value/Jb),"bold"===(c||g.fontWeight),"italic"===(d||g.fontStyle),u||g.underline,p||g.lineThrough)},this),t.hooks.annotationTextCharsSelected.on(t=>{const e=t.freeTextContentStyle,{fontFamily:i,fontSize:n,fontStyle:s,fontWeight:o,underline:r,lineThrough:a}=e;this.selectFontStyle(i,Math.round(da(n).value/Jb),"bold"===o,"italic"===s,r,a)},this),t.hooks.annotationsUpdated.on(t=>{const{actions:e,uids:i}=t,n=this.injection.viewer.getSelectedAnnotations();if(1!==n.length||!i.includes(n[0].uid))return;if("textTypewriter"!==n[0].type&&"textBox"!==n[0].type)return;if(!e.includes("appearanceChanged")&&!e.includes("contentChanged"))return;if(this.selectTextAlign(n[0].style.textAlign||"left"),this.injection.viewer.getAnnotationObject(n[0].uid).isEditMode)return;let s=null;if(n[0].style.textContents.length)s=n[0].style.textContents[0];else{const{defaultStyleConfig:t}=this.injection.viewer.getAnnotationConfig();s=t[n[0].type].textContent}const{fontFamily:o,fontSize:r,fontWeight:a,fontStyle:l,underline:h,lineThrough:c}=s;this.selectFontStyle(o,Math.round(da(r).value/Jb),"bold"===a,"italic"===l,h,c)},this);const e=t=>{if(["textBox","textTypewriter"].includes(t)){this.showTextAlignList("textBox"===t);const{defaultStyleConfig:e}=this.injection.viewer.getAnnotationConfig(),{textContent:i,textAlign:n}=e[t],{fontFamily:s,fontSize:o,fontWeight:r,fontStyle:a,underline:l,lineThrough:h}=i;this.selectTextAlign(n),this.selectFontStyle(s,Math.round(da(o).value/Jb),"bold"===r,"italic"===a,l,h)}};t.hooks.annotationModeChanged.on(i=>{t.getSelectedAnnotations().length||e(i.newAnnotationMode)},this),t.hooks.toolModeChanged.on(i=>{if("annotation"!==i.newToolMode)return;const{annotationMode:n}=t.getViewerConfig();e(n)},this)}toggleSelect(t,e){const i="fontFamily"===t?"ddv-palette-font-family-select":"ddv-palette-font-size-select",n="fontFamily"===t?this.fontFamilyEl:this.fontSizeEl,s=n.querySelector(`.${i}`),o=n.querySelector(".ddv-down-arrow"),r="none"!==s.style.display,a=Ps(e)?!r:e,l=this.injection.viewer.context.viewService.mainContainer;r!==a&&(a?(s.style.display="block",s.style.top=`${rb(s,l)}px`,o.style.transform="rotate(180deg)","fontSize"===t&&this.scrollFontSizeSelect()):(s.style.display="none",o.style.transform=""))}getFontFamilySelectTemplate(){let t="";for(let e=0;e<nb.length;e++){const i=nb[e];t+=`<button title="${i}" style="font-family:${i}" value="${i}">${i}</button>`}return`<div class="ddv-palette-font-family"><span>Helvetica</span><i class="ddv-down-arrow"></i><div class="ddv-palette-font-family-select" style="display: none;">${t}</div></div>`}getFontSizeTemplate(){let t="";for(let e=1;e<=12;e++)t+=`<button value="${e}">${e}pt</button>`;for(let e=14;e<=36;e+=2)t+=`<button value="${e}">${e}pt</button>`;for(let e=40;e<=72;e+=4)t+=`<button value="${e}">${e}pt</button>`;if(this.maxFontSize>72){let e=72;for(;e+8<this.maxFontSize;)e+=8,t+=`<button value="${e}">${e}pt</button>`;t+=`<button value="${this.maxFontSize}">${this.maxFontSize}pt</button>`}return`<div class="ddv-palette-font-size"><input type="string"/><i class="ddv-down-arrow"></i><div class="ddv-palette-font-size-select" style="display: none;">${t}</div></div>`}selectTextAlign(t){const e=this.el.querySelector(".ddv-align-left"),i=this.el.querySelector(".ddv-align-center"),n=this.el.querySelector(".ddv-align-right"),s=this.el.querySelector(".ddv-justify-center");db(e,"left"===t,"light"),db(i,"center"===t,"light"),db(n,"right"===t,"light"),db(s,"justify"===t,"light")}selectFontStyle(t,e,i,n,s,o){const r=this.fontFamilyEl.getElementsByTagName("span")[0],a=this.fontSizeEl.getElementsByTagName("input")[0],l=this.el.querySelector(".ddv-bold"),h=this.el.querySelector(".ddv-italic"),c=this.el.querySelector(".ddv-underline"),d=this.el.querySelector(".ddv-line-through");r.innerText=t,this.isArrowKeyPressed||("number"===a.type&&(a.type="text"),this.currentFontSizeValue=e,a.value=`${e}pt`),db(l,i,"light"),db(h,n,"light"),db(c,s,"light"),db(d,o,"light")}focusTexture(){const t=this.injection.viewer.getSelectedAnnotations();if(1===t.length){const e=this.injection.viewer.getAnnotationObject(t[0].uid);e instanceof hc&&e.isEditMode&&e.focusTexture()}}addFont(t){if(this.fontList.includes(t))return;this.fontList.push(t);const e=this.fontFamilyEl.querySelector(".ddv-palette-font-family-select"),i=document.createElement("button");i.style.fontFamily=t,""===i.style.fontFamily&&(i.style.fontFamily=`"${t}"`),i.value=t,i.innerText=t,i.title=t,e.appendChild(i)}showTextAlignList(t){const e=this.el.querySelector(".ddv-text-align-list");e&&(e.style.display=t?"":"none")}scrollFontSizeSelect(){if(!this.fontSizeEl)return;const t=this.fontSizeEl.querySelector(".ddv-palette-font-size-select"),{currentFontSizeValue:e}=this;let i=0;for(let n=0;n<t.children.length;n++){const s=t.children[n];if(!(e>=s.value))break;i=s.offsetTop}t.scrollTo(0,i)}initTemplate(){const t=`<div class="${this.defaultClass}"><div style="display:flex; justify-content: space-between; position:relative; z-index:2">${this.getFontFamilySelectTemplate()}${this.getFontSizeTemplate()}</div><div><div class="ddv-button ddv-bold"></div><div class="ddv-button ddv-italic"></div><div class="ddv-button ddv-underline"></div><div class="ddv-button ddv-line-through"></div></div><div class="ddv-text-align-list"><div class="ddv-button ddv-align-left"></div><div class="ddv-button ddv-align-center"></div><div class="ddv-button ddv-align-right"></div><div class="ddv-button ddv-justify-center"></div></div></div>`;this.template=t}}const Qb=["None","ClosedArrow","OpenArrow","ROpenArrow","RClosedArrow","Butt","Circle","Diamond","Square","Slash"],tS=[[0,0],[3,3],[5,5],[7,7],[7,6,3,6],[5,4,21,4],[11,5,5,5]],eS={None:"ddv-solid",OpenArrow:"ddv-line-open",ROpenArrow:"ddv-line-r-open",ClosedArrow:"ddv-line-closed",RClosedArrow:"ddv-line-r-closed",Butt:"ddv-line-butt",Square:"ddv-line-square",Diamond:"ddv-line-diamond",Circle:"ddv-line-circle",Slash:"ddv-line-slash"},iS={33:"ddv-dashed-33",55:"ddv-dashed-55",77:"ddv-dashed-77",7636:"ddv-dashed-7636",54214:"ddv-dashed-54214",11555:"ddv-dashed-11555"};class nS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-palette-line-panel"),Yi(this,"commonClass","ddv-palette-line-panel-common"),Yi(this,"LineStyleClass","ddv-palette-border-style"),Yi(this,"lineStyleClassSmall","ddv-palette-border-style-small"),Yi(this,"startLineEndingClass","ddv-palette-line-start"),Yi(this,"endLineEndingClass","ddv-palette-line-end"),Yi(this,"selectionClass","ddv-palette-line-panel-selection"),Yi(this,"startLineEndingSelect",void 0),Yi(this,"borderStyleSelect",void 0),Yi(this,"endLineEndingSelect",void 0),Yi(this,"isStrokePalette",void 0),this.bindHooks(),this.initTemplate(),this.$on("ui_shrinkSelectionBox",t=>{"lineEndingStart"!==t&&this.toggleSelect(0,!1),"borderStyle"!==t&&this.toggleSelect(1,!1),"lineEndingEnd"!==t&&this.toggleSelect(2,!1)}),this.$on("ui_changePalette_type",t=>{this.el.style.display="stroke"===t?"":"none",this.isStrokePalette="stroke"===t;const{toolMode:e,annotationMode:i}=this.injection.viewer.getViewerConfig(),n=this.injection.viewer.getSelectedAnnotations();("annotation"===e&&"ink"===i||1===n.length&&"ink"===n[0].type)&&(this.el.style.display="none")})}bindHooks(){this.hooks.inserted.on(()=>{const t=this.el.querySelectorAll(`.${this.commonClass}`);this.startLineEndingSelect=t[0],this.borderStyleSelect=t[1],this.endLineEndingSelect=t[2],this.bindViewerHooks(),this.bindToggleEvent(),this.bindSelectEvent()})}bindSelectEvent(){const t=this.startLineEndingSelect.querySelector(`.${this.selectionClass}`),e=this.borderStyleSelect.querySelector(`.${this.selectionClass}`),i=this.endLineEndingSelect.querySelector(`.${this.selectionClass}`),n=(t,e)=>{const i=e.target,n="BUTTON"===i.tagName?i:i.parentNode;return Array.from(t.childNodes).indexOf(n)||0};this.nativeOn(t,"click",e=>{const i=n(t,e),s=Qb[i]||"None";this.updateLineEndingByData(!0,s),this.updateDefaultLineEnding(!0,s)}),this.nativeOn(e,"click",t=>{const i=n(e,t),s=tS[i]||[0,0];this.updateLineDashByData(s),this.updateDefaultLineDash(s)}),this.nativeOn(i,"click",t=>{const e=n(i,t),s=Qb[e]||"None";this.updateLineEndingByData(!1,s),this.updateDefaultLineEnding(!1,s)})}bindToggleEvent(){this.nativeOn(this.startLineEndingSelect,"click",t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox","lineEndingStart"),this.toggleSelect(0)}),this.nativeOn(this.borderStyleSelect,"click",t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox","borderStyle"),this.toggleSelect(1)}),this.nativeOn(this.endLineEndingSelect,"click",t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox","lineEndingEnd"),this.toggleSelect(2)})}bindViewerHooks(){const t=this.injection.viewer,e=(t,e,i,n)=>{if(this.startLineEndingSelect.style.display=t?"":"none",this.endLineEndingSelect.style.display=t?"":"none",this.borderStyleSelect.classList.remove(t?this.LineStyleClass:this.lineStyleClassSmall),this.borderStyleSelect.classList.add(t?this.lineStyleClassSmall:this.LineStyleClass),t){const[t,e]=i;this.updateLineEndingSelect(!0,eS[t]||"ddv-solid"),this.updateLineEndingSelect(!1,eS[e]||"ddv-solid")}this.el.style.display=n||!this.isStrokePalette?"none":"",this.updateBorderStyleSelect(e||[0,0])};t.hooks.selectedAnnotationsChanged.on(i=>{var n,s;if(1!==i.newAnnotationUids.length)return;const o=t.getSelectedAnnotations()[0];if(!o)return;const r="line"===o.type||"polyline"===o.type;e(r,null===(n=o.style)||void 0===n?void 0:n.lineDash,null===(s=o.style)||void 0===s?void 0:s.lineEnding,"ink"===o.type||"stamp"===o.type)},this),t.hooks.annotationModeChanged.on(t=>{const i=t.newAnnotationMode,n="polyline"===i||"line"===i,s="ink"===i;if("select"!==i&&"erase"!==i&&"stamp"!==i){var o,r;const{defaultStyleConfig:t}=this.injection.viewer.getAnnotationConfig(),a=(null===(o=t[i])||void 0===o?void 0:o.lineEnding)||(null==qh?void 0:qh.lineEnding),l=(null===(r=t[i])||void 0===r?void 0:r.lineDash)||(null==qh?void 0:qh.lineDash);e(n,l,a,s)}},this),t.hooks.annotationDefaultStyleChanged.on(()=>{var i;const{toolMode:n,annotationMode:s}=this.injection.viewer.getViewerConfig();if("annotation"!==n)return;if("select"===s||"erase"===s||"stamp"===s)return;if(t.getSelectedAnnotations().length)return;const{defaultStyleConfig:o}=this.injection.viewer.getAnnotationConfig(),r="line"===s||"polyline"===s,a="ink"===s,l=(null===(i=o[s])||void 0===i?void 0:i.lineEnding)||qh.lineEnding,h=o[s].lineDash||qh.lineDash;e(r,h,l,a)},this),t.hooks.annotationsUpdated.on(i=>{const{actions:n,uids:s}=i,o=t.getSelectedAnnotations();if(!n.includes("appearanceChanged")||1!==o.length||!s.includes(o[0].uid))return;if("ink"===o[0].type||"stamp"===o[0].type)return;const r="line"===o[0].type||"polyline"===o[0].type,a=o[0].style.lineEnding||["None","None"],l=o[0].style.lineDash||[0,0];e(r,l,a,!1)},this)}toggleSelect(t,e){let i=this.borderStyleSelect;0===t?i=this.startLineEndingSelect:2===t&&(i=this.endLineEndingSelect);const n=i.querySelector(`.${this.selectionClass}`),s=i.querySelector(".ddv-down-arrow"),o="none"!==n.style.display,r=Ps(e)?!o:e,a=this.injection.viewer.context.viewService.mainContainer;o!==r&&(r?(n.style.display="block",n.style.top=`${rb(n,a)}px`,s.style.transform="rotate(180deg)"):(n.style.display="none",s.style.transform=""))}updateLineEndingSelect(t,e){(t?this.startLineEndingSelect:this.endLineEndingSelect).querySelector("div").className=`ddv-button ${e}`}updateBorderStyleSelect(t){const e=this.borderStyleSelect,i=t.join("")||"0",n=e.querySelector("div");let s="ddv-solid";Fo(t)||(s=iS[i]||"ddv-dashed-33"),n.className=`ddv-button ${s}`}updateLineDashByData(t){const e=this.injection.viewer.getSelectedAnnotations();1===e.length&&(e[0].style.lineDash||[0,0]).toString()!==t.toString()&&this.injection.viewer.updateAnnotation(e[0].uid,{style:{lineDash:t}},["appearanceChanged"])}updateLineEndingByData(t,e){const i=this.injection.viewer.getSelectedAnnotations();if(1!==i.length)return;const n=i[0].style.lineEnding||["None","None"];t&&e===n[0]||!t&&e===n[1]||this.injection.viewer.updateAnnotation(i[0].uid,{style:{lineEnding:t?[e,n[1]]:[n[0],e]}},["appearanceChanged"])}updateDefaultLineEnding(t,e){var i;const{annotationMode:n}=this.injection.viewer.getViewerConfig(),s=this.injection.viewer.getSelectedAnnotations(),{defaultStyleConfig:o}=this.injection.viewer.getAnnotationConfig();let r=(null===(i=o[n])||void 0===i?void 0:i.lineEnding)||qh.lineEnding,a=n;s.length&&s[0]&&(r=s[0].style.lineEnding,a=s[0].type);const l=[...r];t?l[0]=e:l[1]=e,this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[a]:{lineEnding:l}}})}updateDefaultLineDash(t){const{annotationMode:e}=this.injection.viewer.getViewerConfig(),i=this.injection.viewer.getSelectedAnnotations();let n=e;i.length&&i[0]&&(n=i[0].type),this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[n]:{lineDash:t}}})}getBaseLineDashTemplate(){const t=["ddv-solid","ddv-dashed-33","ddv-dashed-55","ddv-dashed-77","ddv-dashed-7636","ddv-dashed-54214","ddv-dashed-11555"];let e="";for(let i=0;i<t.length;i++)e+=`<button><i class="ddv-button ${t[i]}"></i></button>`;return`<div class="${this.commonClass} ${this.lineStyleClassSmall}"><div class="ddv-button ddv-solid"></div><i class="ddv-down-arrow"></i><div style="display:none;" class="${this.selectionClass}" >${e}</div></div>`}getLineEndingTemplate(t){const e=["ddv-solid","ddv-line-closed","ddv-line-open","ddv-line-r-open","ddv-line-r-closed","ddv-line-butt","ddv-line-circle","ddv-line-diamond","ddv-line-square","ddv-line-slash"];let i="";for(let t=0;t<e.length;t++)i+=`<button><i class="ddv-button ${e[t]}"></i></button>`;const n=t?this.startLineEndingClass:this.endLineEndingClass;return`<div class="${this.commonClass} ${n}"><div class="ddv-button ddv-solid"></div><i class="ddv-down-arrow"></i><div style="display:none;" class="${this.selectionClass}" >${i}</div></div>`}initTemplate(){const{label:t}=this.data,e=`<div class="${this.defaultClass}"><span>${t}</span><div style="margin-top:10px">${this.getLineEndingTemplate(!0)}${this.getBaseLineDashTemplate()}${this.getLineEndingTemplate(!1)}</div></div>`;this.template=e}}class sS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-palette-opacity-panel"),Yi(this,"isPointerDown",!1),Yi(this,"lastPointerValue",void 0),Yi(this,"range",void 0),Yi(this,"input",void 0),Yi(this,"inputIsBlur",!0),Yi(this,"isArrowKeyPressed",!1),this.initTemplate(),this.bindHooks()}bindHooks(){this.hooks.inserted.on(()=>{this.range=this.el.querySelector(".ddv-palette-opacity-range"),this.input=this.el.querySelector(".ddv-palette-opacity-input"),ob(this.range,0,100),this.bindViewerHooks(),this.bindRangeEvent(),this.bineInputEvent()})}bineInputEvent(){const{input:t}=this;this.nativeOn(t,"keydown",t=>{t.stopPropagation(),"ArrowUp"!==t.key&&"ArrowDown"!==t.key||(this.isArrowKeyPressed=!0)}),this.nativeOn(t,"keyup",e=>{if(e.stopPropagation(),this.isArrowKeyPressed){const e=ua(t.value).value;e>100&&(t.value=100),e<0&&(t.value=0);let i=parseInt(t.value,10);Ls(i)||(i=100,this.updateInput(100)),this.updateDefaultOpacity(i),this.updateOpacityByData(i),this.isArrowKeyPressed=!1}}),this.nativeOn(t,"focus",e=>{const i=t.value,n=ua(i).value;t.value=n,t.type="number",this.inputIsBlur=!1}),this.nativeOn(t,"blur",e=>{this.inputIsBlur=!0,e.relatedTarget instanceof HTMLInputElement||this.focusTexture(),"text"!==t.type&&(t.type="text",t.value+="%")});const e=()=>{if(this.inputIsBlur||this.isArrowKeyPressed)return;t.type="text",t.value+="%",t.removeEventListener("change",e),t.blur(),t.addEventListener("change",e);const i=ua(t.value).value;i>100&&(t.value=100),i<0&&(t.value=0);let n=parseInt(t.value,10);Ls(n)||(n=100,this.updateInput(100)),this.updateDefaultOpacity(n),this.updateOpacityByData(n)};this.nativeOn(t,"change",e)}bindRangeEvent(){const{range:t}=this,e=()=>{const e=parseInt(t.value,10);this.updateOpacityByShape(e),this.input.value=`${e}%`;const{toolMode:i,annotationMode:n}=this.injection.viewer.getViewerConfig();"annotation"===i&&"select"!==n&&"erase"!==n&&this.updateInput(e)};this.nativeOn(t,"click",()=>{const e=parseInt(t.value,10);this.injection.viewer.context.isFocusCanvas=!1,e!==this.lastPointerValue&&(this.updateOpacityByData(e),this.updateDefaultOpacity(e))}),this.nativeOn(t,"pointerdown",t=>{t.stopPropagation(),this.isPointerDown=!0,this.injection.viewer.context.isFocusCanvas=!1,this.$emit("ui_shrinkSelectionBox");const i=this.injection.viewer.getSelectedAnnotations();if(1!==i.length)return;const n=this.injection.viewer.getAnnotationObject(i[0].uid);n instanceof hc&&n.isEditMode&&(n.textEditEventHandler.disableEditMode(),this.injection.viewer.context.render(95)),e()}),this.nativeOn(t,"pointermove",()=>{this.isPointerDown&&e()}),this.nativeOn(t,"pointerup",()=>{if(this.isPointerDown){const e=parseInt(t.value,10);this.lastPointerValue=e,this.updateOpacityByData(e),this.updateDefaultOpacity(e)}this.isPointerDown=!1}),this.nativeOn(t,"keydown",t=>{["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t.key)&&e()}),this.nativeOn(t,"keyup",e=>{if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key)){const e=parseInt(t.value,10);this.updateOpacityByData(e),this.updateDefaultOpacity(e)}})}bindViewerHooks(){const t=this.injection.viewer,e=()=>{const{annotationMode:t}=this.injection.viewer.getViewerConfig();if("select"===t||"erase"===t)return;const{defaultStyleConfig:e}=this.injection.viewer.getAnnotationConfig(),i=Ls(e[t].opacity)?e[t].opacity:qh.opacity;this.updateInput(Math.round(100*i))};t.hooks.selectedAnnotationsChanged.on(e=>{if(1!==e.newAnnotationUids.length)return;const i=t.getSelectedAnnotations()[0];i&&this.updateInput(Math.round(100*i.style.opacity))},this),t.hooks.annotationsUpdated.on(e=>{const{actions:i,uids:n}=e,s=t.getSelectedAnnotations();i.includes("appearanceChanged")&&1===s.length&&n.includes(s[0].uid)&&this.updateInput(Math.round(100*s[0].style.opacity))},this),t.hooks.annotationModeChanged.on(t=>{e()},this),t.hooks.toolModeChanged.on(t=>{"annotation"===t.newToolMode&&e()},this),t.hooks.annotationDefaultStyleChanged.on(()=>{const{toolMode:e,annotationMode:i}=this.injection.viewer.getViewerConfig();if("annotation"!==e)return;if("select"===i||"erase"===i)return;if(t.getSelectedAnnotations().length)return;const{defaultStyleConfig:n}=this.injection.viewer.getAnnotationConfig(),s=Ls(n[i].opacity)?n[i].opacity:qh.opacity;this.updateInput(100*s)},this)}updateInput(t){let e=t;t>100&&(e=100),t<0&&(e=0),e=Math.round(e),this.range.value=`${e}`,this.range.dispatchEvent(new Event("change")),this.input.value="number"===this.input.type?e:`${e}%`}updateOpacityByShape(t){const e=this.injection.viewer.getSelectedAnnotations();if(1!==e.length)return;const i=this.injection.viewer.getAnnotationObject(e[0].uid);if(!i)return;const n=100*i.style.opacity;(t=Math.round(t))!==n&&(i.style.opacity=t/100,this.injection.viewer.context.render(94))}updateOpacityByData(t){const e=this.injection.viewer.getSelectedAnnotations();if(1!==e.length)return;const i=100*e[0].style.opacity;(t=Math.round(t))!==i&&this.injection.viewer.updateAnnotation(e[0].uid,{style:{opacity:t/100}},["appearanceChanged"])}updateDefaultOpacity(t){const{viewer:e}=this.injection,{annotationMode:i}=e.getViewerConfig(),n=e.getSelectedAnnotations();let s=i;n.length&&n[0]&&(s=n[0].type),t=Math.round(t),this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[s]:{opacity:t/100}}})}focusTexture(){const t=this.injection.viewer.getSelectedAnnotations();if(1===t.length){const e=this.injection.viewer.getAnnotationObject(t[0].uid);e instanceof hc&&e.isEditMode&&e.focusTexture()}}initTemplate(){const{label:t}=this.data,e=`<div class="${this.defaultClass}"><span>${t}</span><div class="ddv-palette-opacity-range-container"><input class="ddv-palette-opacity-range" type="range" min="0" max="100" value="100"/><input class="ddv-palette-opacity-input" type="string" value="100%"/></div></div>`;this.template=e}}const oS=[Yh.DRAFT,Yh.FINAL,Yh.VOID,Yh.REJECTED,Yh.ACCEPTED,Yh.APPROVED,Yh.NOT_APPROVED,Yh.COMPLETED,Yh.CONFIDENTIAL,Yh.INITIAL_HERE,Yh.SIGN_HERE,Yh.WITNESS];class rS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-palette-stamp-panel"),Yi(this,"select",void 0),Yi(this,"selectBox",void 0),Yi(this,"iconName",Yh.DRAFT),Yi(this,"enableCustomStamp",!1),Yi(this,"customStampSelect",void 0),Yi(this,"customStampSelectBox",void 0),Yi(this,"customStampList",[]),this.enableCustomStamp=t.data.enableCustomStamp,this.initTemplate(),this.bindHooks(),this.bindViewerHooks(),this.$on("ui_shrinkSelectionBox",t=>{"stampIcon"!==t&&this.toggleSelect(!1,!1),this.enableCustomStamp&&"customStamp"!==t&&this.toggleSelect(!0,!1)})}bindHooks(){this.hooks.inserted.on(()=>{this.select=this.el.querySelector(".ddv-palette-stamp-icon"),this.selectBox=this.el.querySelector(".ddv-palette-stamp-icon-select"),this.enableCustomStamp&&(this.customStampSelect=this.el.querySelector(".ddv-palette-custom-stamp"),this.customStampSelectBox=this.el.querySelector(".ddv-palette-custom-stamp-select")),this.bindToggleEvent(),this.bindSelectEvent(),this.bindCreateCustomStampEvent()})}bindToggleEvent(){this.nativeOn(this.select,"click",t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox","stampIcon"),this.toggleSelect(!1)}),this.enableCustomStamp&&this.nativeOn(this.customStampSelect,"click",t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox","customStamp"),this.toggleSelect(!0)})}bindSelectEvent(){this.nativeOn(this.selectBox,"click",t=>{const e=t.target.value;this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{stamp:{stampIcon:e,stampConfig:null}}})}),this.nativeOn(this.selectBox,"pointermove",t=>{t.stopPropagation()})}bindViewerHooks(){const t=this.injection.viewer,e=()=>{var e;const{toolMode:i,annotationMode:n}=t.getViewerConfig(),s=t.getAnnotationConfig();"annotation"!==i||"stamp"!==n||null!==(e=s.defaultStyleConfig)&&void 0!==e&&null!==(e=e.stamp)&&void 0!==e&&e.imageData?this.el.style.display="none":this.el.style.display=""};this.hooks.inserted.on(()=>{e();const{defaultStyleConfig:i}=t.getAnnotationConfig(),{stamp:n}=i,s=(null==n?void 0:n.stampIcon)||(null==qh?void 0:qh.stampIcon);this.updateStampSpan(s)}),t.hooks.annotationDefaultStyleChanged.on(t=>{var i;if(e(),null===(i=t.newStyle)||void 0===i||!i.stamp)return;const{stamp:n}=t.newStyle,s=(null==n?void 0:n.stampIcon)||(null==qh?void 0:qh.stampIcon);(null==n?void 0:n.stampConfig)?this.updateStampSpan("SBCustom Stamp"):s!==this.iconName&&this.updateStampSpan(s)},this),t.hooks.toolModeChanged.on(e,this),t.hooks.annotationModeChanged.on(e,this)}toggleSelect(t,e){const i=t?this.customStampSelect:this.select,n=t?this.customStampSelectBox:this.selectBox,s=i.querySelector(".ddv-down-arrow"),o="none"!==n.style.display,r=Ps(e)?!o:e,a=this.injection.viewer.context.viewService.mainContainer;o!==r&&(r?(n.style.display="block",n.style.top=`${rb(n,a)}px`,s.style.transform="rotate(180deg)"):(n.style.display="none",s.style.transform=""))}updateStampSpan(t){this.el.getElementsByTagName("span")[1].innerText=t.slice(2),this.iconName=t}getStampIconSelectTemplate(){let t="";for(let e=0;e<oS.length;e++){const i=oS[e];t+=`<button value="${i}">${i.slice(2)}</button>`}return`<div class="ddv-palette-stamp-icon"><span>${Yh.DRAFT.slice(2)}</span><i class="ddv-down-arrow"></i><div class="ddv-palette-stamp-icon-select" style="display: none;">${t}</div></div>${this.getCustomStampTemplate()}`}initTemplate(){const{label:t}=this.data,e=`<div class="${this.defaultClass}"><span>${t}</span>${this.getStampIconSelectTemplate()}</div>`;this.template=e}bindCreateCustomStampEvent(){if(!this.enableCustomStamp)return;const t=this.customStampSelectBox.querySelector(".ddv-palette-custom-stamp-button");this.nativeOn(t,"click",()=>{vb(this.injection.viewer,!0),this.$emit("ui_changePalette_visible","AnnotationCustomStampPanel",!0)}),this.$on("ui_customStampCreated",t=>{const{stampConfig:e,stampImage:i}=t,n=URL.createObjectURL(i),s={stampConfig:_s(e),imgUrl:n};this.customStampList.push(s),this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{stamp:{stampConfig:s.stampConfig}}}),this.addCustomStamp(s)}),this.nativeOn(this.customStampSelectBox,"click",t=>{const e=t.target;if(e instanceof HTMLImageElement){const t=oo(e.parentElement),{stampConfig:i}=this.customStampList[t-1];this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{stamp:{stampConfig:i}}})}if("i"===e.tagName.toLocaleLowerCase()){t.stopPropagation();const i=oo(e.parentElement),{imgUrl:n}=this.customStampList[i-1];URL.revokeObjectURL(n),e.parentElement.remove(),this.customStampList.splice(i-1,1)}})}getCustomStampTemplate(){return this.enableCustomStamp?'<div class="ddv-palette-custom-stamp"><span>Custom Stamp</span><i class="ddv-down-arrow"></i><div class="ddv-palette-custom-stamp-select" style="display: none;"><div><button class="ddv-palette-custom-stamp-button">Create New Stamp</button></div></div></div>':""}addCustomStamp(t){const e=document.createElement("div");e.className="ddv-palette-custom-stamp-item";const i=document.createElement("img");i.src=t.imgUrl,i.draggable=!1,e.appendChild(i);const n=document.createElement("i");n.className="ddv-button ddv-delete-annot",e.appendChild(n),this.customStampSelectBox.appendChild(e)}}const aS=Cr.displayResolution/Cr.dataResolution;class lS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-palette-stroke-panel"),Yi(this,"isPointerDown",!1),Yi(this,"lastPointerValue",void 0),Yi(this,"range",void 0),Yi(this,"input",void 0),Yi(this,"inputIsBlur",!0),Yi(this,"isArrowKeyPressed",!1),Yi(this,"maxBorderWidth",20),this.maxBorderWidth=t.data.maxBorderWidth,this.maxBorderWidth<20&&(this.maxBorderWidth=20),this.initTemplate(),this.bindHooks(),this.$on("ui_changePalette_type",t=>{this.el.style.display="stroke"===t?"":"none"})}bindHooks(){this.hooks.inserted.on(()=>{this.range=this.el.querySelector(".ddv-palette-stroke-range"),this.input=this.el.querySelector(".ddv-palette-stroke-input"),ob(this.range,0,this.maxBorderWidth),this.bindViewerHooks(),this.bindRangeEvent(),this.bineInputEvent()})}bineInputEvent(){const{input:t}=this;this.nativeOn(t,"keydown",t=>{t.stopPropagation(),"ArrowUp"!==t.key&&"ArrowDown"!==t.key||(this.isArrowKeyPressed=!0)}),this.nativeOn(t,"keyup",e=>{if(e.stopPropagation(),this.isArrowKeyPressed){const e=da(t.value).value;e>this.maxBorderWidth&&(t.value=this.maxBorderWidth),e<0&&(t.value=0);let i=parseInt(t.value,10);Ls(i)||(i=1,this.updateInput(1*aS)),this.updateDefaultBorderWidth(i),this.updateBorderWidthByData(i),this.isArrowKeyPressed=!1}}),this.nativeOn(t,"focus",e=>{const i=t.value,n=parseFloat(i);t.value=n,t.type="number",this.inputIsBlur=!1}),this.nativeOn(t,"blur",e=>{this.inputIsBlur=!0,e.relatedTarget instanceof HTMLInputElement||this.focusTexture(),"text"!==t.type&&(t.type="text",t.value+="pt")});const e=()=>{if(this.inputIsBlur||this.isArrowKeyPressed)return;t.type="text",t.value+="pt",t.removeEventListener("change",e),t.blur(),t.addEventListener("change",e);const i=da(t.value).value;i>this.maxBorderWidth&&(t.value=this.maxBorderWidth),i<0&&(t.value=0);let n=parseInt(t.value,10);Ls(n)||(n=1,this.updateInput(1*aS)),this.updateDefaultBorderWidth(n),this.updateBorderWidthByData(n)};this.nativeOn(t,"change",e)}bindRangeEvent(){const{range:t}=this,e=()=>{const e=da(t.value).value;this.updateBorderWidthByShape(e),this.input.value=`${e}pt`;const{toolMode:i,annotationMode:n}=this.injection.viewer.getViewerConfig();"annotation"===i&&"select"!==n&&"erase"!==n&&this.updateInput(e*aS)};this.nativeOn(t,"click",()=>{const e=da(t.value).value;this.injection.viewer.context.isFocusCanvas=!1,e!==this.lastPointerValue&&(this.updateBorderWidthByData(e),this.updateDefaultBorderWidth(e))}),this.nativeOn(t,"pointerdown",t=>{t.stopPropagation(),this.isPointerDown=!0,this.injection.viewer.context.isFocusCanvas=!1,this.$emit("ui_shrinkSelectionBox");const i=this.injection.viewer.getSelectedAnnotations();if(1!==i.length)return;const n=this.injection.viewer.getAnnotationObject(i[0].uid);n instanceof hc&&n.isEditMode&&(n.textEditEventHandler.disableEditMode(),this.injection.viewer.context.render(96)),e()}),this.nativeOn(t,"pointermove",()=>{this.isPointerDown&&e()}),this.nativeOn(t,"pointerup",()=>{if(this.isPointerDown){const e=da(t.value).value;this.lastPointerValue=e,this.updateBorderWidthByData(e),this.updateDefaultBorderWidth(e)}this.isPointerDown=!1}),this.nativeOn(t,"keydown",t=>{["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t.key)&&e()}),this.nativeOn(t,"keyup",e=>{if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key)){const e=da(t.value).value;this.updateBorderWidthByData(e),this.updateDefaultBorderWidth(e)}})}bindViewerHooks(){const t=this.injection.viewer,e=()=>{const{annotationMode:t}=this.injection.viewer.getViewerConfig();if("select"===t||"erase"===t)return;const{defaultStyleConfig:e}=this.injection.viewer.getAnnotationConfig(),i=Ls(e[t].borderWidth)?e[t].borderWidth:qh.borderWidth;this.updateInput(i)};t.hooks.selectedAnnotationsChanged.on(e=>{if(1!==e.newAnnotationUids.length)return;const i=t.getSelectedAnnotations()[0];i&&this.updateInput(da(i.style.borderWidth).value,!0)},this),t.hooks.annotationsUpdated.on(e=>{const{actions:i,uids:n}=e,s=t.getSelectedAnnotations();i.includes("appearanceChanged")&&1===s.length&&n.includes(s[0].uid)&&this.updateInput(da(s[0].style.borderWidth).value)},this),t.hooks.annotationModeChanged.on(t=>{e()},this),t.hooks.toolModeChanged.on(t=>{"annotation"===t.newToolMode&&e()},this),t.hooks.annotationDefaultStyleChanged.on(()=>{const{toolMode:e,annotationMode:i}=this.injection.viewer.getViewerConfig();if("annotation"!==e)return;if("select"===i||"erase"===i||"stamp"===i)return;if(t.getSelectedAnnotations().length)return;const{defaultStyleConfig:n}=this.injection.viewer.getAnnotationConfig(),s=Ls(n[i].borderWidth)?n[i].borderWidth:qh.borderWidth;this.updateInput(s)},this)}updateInput(t,e){let i=t/aS;this.isPointerDown||e?i=Math.round(i):(i=i.toFixed(1),i.endsWith(".0")&&(i=parseInt(i,10))),this.range.value=i,this.range.dispatchEvent(new Event("change")),this.input.value="number"===this.input.type?parseFloat(i):`${i}pt`}updateBorderWidthByShape(t){const e=this.injection.viewer.getSelectedAnnotations();if(1!==e.length)return;const i=this.injection.viewer.getAnnotationObject(e[0].uid);if(!i)return;const n=t*aS,{borderWidth:s}=i.style;s!==n&&(i.style.borderWidth=n,this.injection.viewer.context.render(97))}updateBorderWidthByData(t){const e=this.injection.viewer.getSelectedAnnotations();if(1!==e.length)return;const i=t*aS,{borderWidth:n}=e[0].style;n!==i&&this.injection.viewer.updateAnnotation(e[0].uid,{style:{borderWidth:i}},["appearanceChanged"])}updateDefaultBorderWidth(t){const{annotationMode:e}=this.injection.viewer.getViewerConfig(),i=this.injection.viewer.getSelectedAnnotations();let n=e;i.length&&i[0]&&(n=i[0].type),this.injection.viewer.updateAnnotationConfig({defaultStyleConfig:{[n]:{borderWidth:t*aS}}})}focusTexture(){const t=this.injection.viewer.getSelectedAnnotations();if(1===t.length){const e=this.injection.viewer.getAnnotationObject(t[0].uid);e instanceof hc&&e.isEditMode&&e.focusTexture()}}initTemplate(){const{label:t}=this.data,e=`<div class="${this.defaultClass}"><span>${t}</span><div><input class="ddv-palette-stroke-range" type="range" min="0" max="${this.maxBorderWidth}" value="0"/><input class="ddv-palette-stroke-input" type="string" value="0pt"/></div></div>`;this.template=e}}class hS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-palette-box"),Yi(this,"header",void 0),Yi(this,"fillSpan",void 0),Yi(this,"textSpan",void 0),Yi(this,"strokeSpan",void 0),Yi(this,"thumbnail",void 0),XC.registerComponent({ColorPanel:Zb,FontPanel:Kb,LinePanel:nS,StampPanel:rS,OpacityPanel:sS,StrokePanel:lS}),this.bindHooks(),this.initTemplate(),this.bindViewerHooks(),this.$on("ui_changePalette_visible",(t,e)=>{t===hS.cpName&&this.togglePopup(e)}),this.injection.viewer.on("thumbnailBind",t=>{if(this.thumbnail)return;const e=this.injection.viewer.context.core.getViewer(t);e&&(this.thumbnail=e,this.bindThumbnailHooks())})}bindHooks(){const t=t=>{this.header=this.el.querySelector(`.${this.defaultClass}-header`);const e=this.header.getElementsByTagName("span");this.textSpan=e[0],this.strokeSpan=e[1],this.fillSpan=e[2],this.bindEvents(),this.injection.viewer.context.viewService.mainContainer.appendChild(this.el);const{enableDrag:i}=this.data.options;this.el.dataset.enableDrag=`${i}`,function(t){let e,i,n,s,o=!1;function r(r){if(!o)return;r.preventDefault();const a=r.clientX-e,l=r.clientY-i,h=n+a,c=s+l;t.style.left=`${h}px`,t.style.top=`${c}px`}function a(){o=!1,document.removeEventListener("pointermove",r),document.removeEventListener("pointerup",a)}t.addEventListener("pointerdown",function(l){const h=l.target;h.classList.contains("ddv-button")||"false"===t.dataset.enableDrag||h instanceof HTMLInputElement||h instanceof HTMLButtonElement||(o=!0,e=l.clientX,i=l.clientY,n=t.offsetLeft,s=t.offsetTop,document.addEventListener("pointermove",r),document.addEventListener("pointerup",a))})}(this.el)};this.hooks.inserted.on(t),this.hooks.updated.on(t)}bindEvents(){this.nativeOn(this.el,"click",t=>{t.stopPropagation(),this.$emit("ui_shrinkSelectionBox",t)}),this.nativeOn(this.el,"pointerup",t=>{t.target instanceof HTMLInputElement&&!(t.target instanceof HTMLInputElement&&"range"===t.target.type)||this.focusTexture()}),this.nativeOn(this.textSpan,"click",()=>{this.setPaletteType("text")}),this.nativeOn(this.fillSpan,"click",()=>{this.setPaletteType("fill")}),this.nativeOn(this.strokeSpan,"click",()=>{this.setPaletteType("stroke")})}bindViewerHooks(){const t=this.injection.viewer,e=()=>{const{toolMode:e,annotationMode:i}=t.getViewerConfig(),n=t.getSelectedAnnotations();return!t.getPageCounts()||"annotation"!==e&&!n.length||"annotation"===e&&("select"===i||"erase"===i)},i=t=>{"stamp"===t?this.setPaletteType("stamp"):"textAssist"===t?this.setPaletteType("textAssist"):"text"===t?(this.textSpan.style.display="",this.setPaletteType("text")):(this.textSpan.style.display="none",this.setPaletteType("stroke"))};this.hooks.inserted.on(()=>{e()&&this.togglePopup(!1)}),t.hooks.resize.on(()=>{if("none"===this.el.style.display)return;const{isOutOf:t}=cS(this.el,!1);if(t){var e;const t=this.el.getBoundingClientRect(),i=null===(e=this.el.parentElement)||void 0===e?void 0:e.getBoundingClientRect();this.el.style.right=i.width-t.width+"px"}},this),t.hooks.beforeAnnotationEdit.on(()=>{this.togglePopup(!1)},this),t.hooks.beforeAnnotationDraw.on(()=>{this.togglePopup(!1)},this),t.hooks.beforeTextSelected.on(()=>{this.togglePopup(!1)}),t.hooks.pageChanged.on(e=>{e.total||this.togglePopup(!1);const i=t.getActiveTab();i&&"single"===i.context.displayMode&&1===t.getSelectedAnnotations().length&&this.togglePopup(!1)},this),t.hooks.toolModeChanged.on(n=>{if(e())return void this.togglePopup(!1);const{annotationMode:s}=t.getViewerConfig(),o=["erase","select"].includes(s);if("annotation"===n.newToolMode&&!o&&!Ms()){const t=["textBox","textTypewriter"].includes(s),e=["highlight","underline","strikeout"].includes(s),n="textTypewriter"===s,o="ink"===s,r="stamp"===s?"stamp":t?"text":e?"textAssist":"common";i(r),("text"===r&&n||o)&&(this.header.style.display="none"),this.togglePopup(!0)}},this),t.hooks.selectedAnnotationsChanged.on(n=>{e()&&this.togglePopup(!1);const s=t.getSelectedAnnotations();if(1!==s.length)return;const o=s[0],r=["textBox","textTypewriter"].includes(o.type),a="textTypewriter"===o.type,l="ink"===o.type,h=["highlight","underline","strikeout"].includes(o.type),c="stamp"===o.type?"stamp":r?"text":h?"textAssist":"common";i(c),("text"===c&&a||l)&&(this.header.style.display="none")},this),t.hooks.annotationModeChanged.on(e=>{if(t.getSelectedAnnotations().length)return;const n=e.newAnnotationMode;if(["erase","select"].includes(n))return void this.togglePopup(!1);const s=["textBox","textTypewriter"].includes(n),o=["highlight","underline","strikeout"].includes(n),r="textTypewriter"===n,a="ink"===n,l="stamp"===n?"stamp":s?"text":o?"textAssist":"common";i(l),("text"===l&&r||a)&&(this.header.style.display="none");const{toolMode:h}=this.injection.viewer.getViewerConfig(),c=this.injection.viewer.getPageCounts();if(Ms()&&"stamp"!==l)this.togglePopup(!1);else{const{options:t}=this.data;this.togglePopup(c>0&&"annotation"===h&&t.autoDisplay)}},this)}bindThumbnailHooks(){this.thumbnail.hooks.visibleChanged.on(()=>{this.updatePosition()},this),this.$on("ui_searchVisibilityChanged",()=>{this.updatePosition()})}updatePosition(){if("none"===this.el.style.display)return;const{isOutOf:t,outOfLeft:e,outOfRight:i}=cS(this.el,!1);if(t){var n;const t=this.el.getBoundingClientRect(),s=null===(n=this.el.parentElement)||void 0===n?void 0:n.getBoundingClientRect();e&&(this.el.style.left="0px"),i&&(this.el.style.left=s.width-t.width+"px")}}setPaletteType(t){const{header:e,textSpan:i,strokeSpan:n,fillSpan:s}=this;if(this.$emit("ui_changePalette_type",t),"stamp"===t||"textAssist"===t)return void(e.style.display="none");const{backgroundColor:o}=getComputedStyle(this.el);e.style.display="";const r=(e,i,n)=>{e.style.background=t===i?n:"",e.style.borderBottom=t===i?"none":""};r(i,"text",o),r(n,"stroke",o),r(s,"fill",o)}togglePopup(t,e,i){const n="none"!==this.el.style.display,s=Ps(t)?!n:t;if(n===s)return;const{options:o}=this.data;s?(this.el.style.display="",null!=o&&o.positionRocked&&(this.el.style.left="",this.el.style.top="")):(this.el.style.display="none",this.$emit("ui_shrinkSelectionBox")),Ps(e)||(this.el.style.right=`${e||0}px`),Ps(i)||(this.el.style.top=`${i||0}px`),this.injection.viewer.emit("annotationPaletteToggle",s),cS(this.el).isOutOf&&(this.el.style.left="",this.el.style.top="")}focusTexture(){const t=this.injection.viewer.getSelectedAnnotations();if(1===t.length){const e=this.injection.viewer.getAnnotationObject(t[0].uid);e instanceof hc&&e.isEditMode&&e.focusTexture()}}initTemplate(){const{options:t}=this.data;pb(gb(this),this.injection.viewer,t),null!=t&&t.labels||(t.labels={}),t.labels={text:"Text",stroke:"Stroke",fill:"Fill",opacity:"Opacity",style:"Style",standardBusiness:"Standard Business",...t.labels},t.style={...t.style,display:"none"};const e=`<div ${GC(t,this.defaultClass,"")}><div class="${this.defaultClass}-header"><span>${t.labels.text}</span><span>${t.labels.stroke}</span><span>${t.labels.fill}</span></div><FontPanel :maxFontSize="options.maxFontSize"></FontPanel><ColorPanel :enableChangeColor="options.enableChangeColor" :colorList="options.colorList"></ColorPanel><StampPanel :enableCustomStamp="options.enableCustomStamp" label="${t.labels.standardBusiness}"></StampPanel><OpacityPanel label="${t.labels.opacity}"></OpacityPanel><StrokePanel :maxBorderWidth="options.maxBorderWidth" label="${t.labels.stroke}"></StrokePanel><LinePanel label="${t.labels.style}"></LinePanel></div>`;this.template=e}}function cS(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:25;if("none"===t.style.display||!t.parentElement)return{isOutOf:!1};const n=t.getBoundingClientRect(),s=t.parentElement.getBoundingClientRect();if(!e){const t=n.left<s.left,e=n.left+n.width>s.right;return{isOutOf:t||e,outOfLeft:t,outOfRight:e}}const o=n.right-i<s.left,r=n.left+i>s.right,a=n.bottom-i<s.top,l=n.top+i>s.bottom;return{isOutOf:o||r||a||l,outOfLeft:o,outOfRight:r,outOfTop:a,outOfBottom:l}}Yi(hS,"cpName","AnnotationPalette");class dS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-custom-stamp-panel"),Yi(this,"stampBoard",void 0),Yi(this,"fontList",[...nb]),Yi(this,"colorType",void 0),this.stampBoard=new Kx(260,100),this.bindHooks(),this.initTemplate(),this.$on("ui_addFont",t=>{this.addFont(t)}),this.$on("ui_changePalette_visible",(t,e)=>{t===dS.cpName&&this.togglePopup(e)})}getFontFamilySelectTemplate(){let t="";for(let e=0;e<nb.length;e++){const i=nb[e];t+=`<button style="font-family:${i}" value="${i}">${i}</button>`}return`<div class="ddv-stamp-font-family"><p>${this.stampBoard.signatureStyle.fontFamily}</p><i class="ddv-down-arrow"></i><div class="ddv-stamp-font-family-select" style="display: none;">${t}</div></div>`}bindHooks(){this.hooks.inserted.on(t=>{this.injection.viewer.context.viewService.rootDom.appendChild(this.el);const e=this.stampBoard.getCanvas();this.el.querySelector(`.${this.defaultClass}-canvas-container`).appendChild(e),this.bindEvents(),this.updateFontStyleButton(),this.selectColorType("background"),this.updateColorSelected()})}bindEvents(){const t=this.el.querySelector(".ddv-bold"),e=this.el.querySelector(".ddv-italic"),i=this.el.querySelector(".ddv-underline"),n=this.el.querySelector(".ddv-line-through");this.nativeOn(t,"click",()=>{const{fontWeight:t}=this.stampBoard.signatureStyle;this.stampBoard.updateSignatureStyle({fontWeight:"bold"===t?"normal":"bold"}),this.updateFontStyleButton()}),this.nativeOn(e,"click",()=>{const{fontStyle:t}=this.stampBoard.signatureStyle;this.stampBoard.updateSignatureStyle({fontStyle:"italic"===t?"normal":"italic"}),this.updateFontStyleButton()}),this.nativeOn(i,"click",()=>{const{underline:t}=this.stampBoard.signatureStyle;this.stampBoard.updateSignatureStyle({underline:!t}),this.updateFontStyleButton()}),this.nativeOn(n,"click",()=>{const{strikeout:t}=this.stampBoard.signatureStyle;this.stampBoard.updateSignatureStyle({strikeout:!t}),this.updateFontStyleButton()});const s=this.el.querySelectorAll(`.${this.defaultClass}-color-type span`),[o,r,a]=Array.from(s);this.nativeOn(o,"click",()=>{this.selectColorType("background")}),this.nativeOn(r,"click",()=>{this.selectColorType("border")}),this.nativeOn(a,"click",()=>{this.selectColorType("text")});const l=this.el.querySelector(`.${this.defaultClass}-color-container`);this.nativeOn(l,"click",t=>{const e=t.target;if(!(e.dataset.color||e instanceof HTMLButtonElement))return;const i=(e instanceof HTMLButtonElement?e.parentNode:e).dataset.color;"background"===this.colorType?this.stampBoard.updateSignatureStyle({background:i}):"border"===this.colorType?this.stampBoard.updateSignatureStyle({borderColor:i}):this.stampBoard.updateSignatureStyle({color:i}),this.updateColorSelected()});const h=this.el.querySelector(`.${this.defaultClass}-ok`);this.nativeOn(h,"click",async t=>{const e=this.stampBoard.getStampConfig(),i=await this.stampBoard.getSignatureImage(),{options:n}=this.data,{autoDisplay:s}=n;this.$emit("ui_customStampCreated",{stampConfig:e,stampImage:i}),s&&this.togglePopup(!1)});const c=this.el.querySelector(".ddv-button-close");this.nativeOn(c,"click",t=>{this.togglePopup(!1)}),this.bindInputEvent(),this.bindToggleEvent(),this.bindSelectEvent()}bindInputEvent(){const t=this.el.querySelector(`.${this.defaultClass}-stamp-text input`);this.nativeOn(t,"input",()=>{const e=t.value;this.stampBoard.updateSignatureStyle({stampText:e})});const e=this.el.querySelectorAll(`.${this.defaultClass}-time-stamp input`),[i,n,s,o]=Array.from(e);this.nativeOn(i,"input",()=>{const t=i.value;this.stampBoard.updateSignatureStyle({userName:t})}),this.nativeOn(n,"change",()=>{this.stampBoard.updateSignatureStyle({hasUserName:n.checked})}),this.nativeOn(s,"change",()=>{this.stampBoard.updateSignatureStyle({hasDate:s.checked})}),this.nativeOn(o,"change",()=>{this.stampBoard.updateSignatureStyle({hasTime:o.checked})})}bindSelectEvent(){const t=this.el.querySelector(".ddv-stamp-font-family"),e=t.querySelector(".ddv-stamp-font-family-select"),i=t.querySelector("p");this.nativeOn(e,"click",t=>{t.stopPropagation(),this.toggleSelect(!1);const e=t.target.value;e&&(this.stampBoard.updateSignatureStyle({fontFamily:e}),i.innerText=e)})}bindToggleEvent(){const t=this.el.querySelector(".ddv-stamp-font-family");this.nativeOn(t,"click",t=>{t.stopPropagation(),this.toggleSelect()})}toggleSelect(t){const e=this.el.querySelector(".ddv-stamp-font-family"),i=e.querySelector(".ddv-stamp-font-family-select"),n=e.querySelector(".ddv-down-arrow"),s="none"!==i.style.display,o=Ps(t)?!s:t,r=this.injection.viewer.context.viewService.rootDom;s!==o&&(o?(i.style.display="block",i.style.top=`${rb(i,r)}px`,n.style.transform="rotate(180deg)"):(i.style.display="none",n.style.transform=""))}addFont(t){const e=this.el.querySelector(".ddv-stamp-font-family");if(this.fontList.includes(t))return;this.fontList.push(t);const i=e.querySelector(".ddv-stamp-font-family-select"),n=document.createElement("button");n.style.fontFamily=t,n.value=t,n.innerText=t,i.appendChild(n)}updateFontStyleButton(){const{fontStyle:t,fontWeight:e,underline:i,strikeout:n}=this.stampBoard.signatureStyle,s=this.el.querySelector(".ddv-bold"),o=this.el.querySelector(".ddv-italic"),r=this.el.querySelector(".ddv-underline"),a=this.el.querySelector(".ddv-line-through");db(s,"bold"===e,"light"),db(o,"italic"===t,"light"),db(r,i,"light"),db(a,n,"light")}getColorSelector(t){const{options:e}=this.data,{colorList:i}=e,n=document.createElement("div");let s=`<div class="${t}">`,o=0,r=!1;for(let e=0;e<i.length;e++){const a=i[e];if(n.style.background=a,""!==n.style.background){if(o>20)break;o+=1,s+=`<div data-color="${a}"><button style="background:${a}"></button></div>`,0!==o&&o%10==0&&(r=!1,s+="</div>",e!==i.length-1&&(r=!0,s+=`<div class="${t}">`)),n.style.background=""}}return r&&(s+="</div>"),n.remove(),s}selectColorType(t){if(t===this.colorType)return;const e=this.el.querySelectorAll(`.${this.defaultClass}-color-type span`),[i,n,s]=Array.from(e);this.colorType=t,[{element:i,type:"background"},{element:n,type:"border"},{element:s,type:"text"}].forEach(e=>{let{element:i,type:n}=e;n===t?(i.style.color="#3183c8",i.style.borderBottom="2px solid #3183c8"):(i.style.color="",i.style.borderBottom="")}),this.updateColorSelected()}updateColorSelected(){const{colorType:t}=this,{background:e,borderColor:i,color:n}=this.stampBoard.signatureStyle,s="background"===t?e:"border"===t?i:n,o=this.el.querySelectorAll(".ddv-custom-stamp-panel-color-container div");Array.from(o).forEach(t=>{t.style.border=t.dataset.color===s?"1px solid #aaa":""})}togglePopup(t){const e="none"!==this.el.style.display,i=Ps(t)?!e:t;e!==i&&(this.el.style.display=i?"":"none",i||vb(this.injection.viewer,!1))}initTemplate(){const{options:t}=this.data;pb(gb(this),this.injection.viewer,t),t.style={...t.style,display:"none"};const{hasUserName:e,hasDate:i,hasTime:n}=this.stampBoard.signatureStyle,s=`<div ${GC(t,this.defaultClass,"")}><div class="${this.defaultClass}-header"><span>${(null==t?void 0:t.title)||"Create New Stamp"}</span><div class="ddv-button ddv-button-close"></div></div><div class="${this.defaultClass}-content"><div class="${this.defaultClass}-canvas-container"></div><div class="${this.defaultClass}-stamp-text"><span>${t.labels.stampText}</span><input type="text" value="${this.stampBoard.signatureStyle.stampText}"/></div><div class="${this.defaultClass}-font-style"><span>${t.labels.fontStyle}</span><div style="margin-top: 10px; display: flex; justify-content: space-between">${this.getFontFamilySelectTemplate()}<div class="ddv-button ddv-bold"></div><div class="ddv-button ddv-italic"></div><div class="ddv-button ddv-underline"></div><div class="ddv-button ddv-line-through"></div></div></div><div class="${this.defaultClass}-time-stamp"><span>${t.labels.timeStampText}</span><div style="margin-top: 10px; display: flex; justify-content: space-between; align-items: center;"><input type="text" value="${this.stampBoard.signatureStyle.userName}"/><label><input checked="${e?"checked":""}" type="checkbox"/>${t.labels.userName}</label><label><input checked="${i?"checked":""}" type="checkbox" />${t.labels.date}</label><label><input checked="${n?"checked":""}" type="checkbox" />${t.labels.time}</label></div></div><div class="${this.defaultClass}-color-picker"><div class="${this.defaultClass}-color-type"><span>${t.labels.backgroundColor}</span><span>${t.labels.borderColor}</span><span>${t.labels.textColor}</span></div><div class="${this.defaultClass}-color-container">${this.getColorSelector(`${this.defaultClass}-color-list`)}</div></div><div class="${this.defaultClass}-footer"><div class="${this.defaultClass}-ok">${t.labels.create}</div></div></div></div>`;this.template=s}}Yi(dS,"cpName","AnnotationCustomStampPanel");class uS extends xb{constructor(t,e){super(t,{class:e.class,callback:()=>{const{viewer:t}=this.injection;t.context.annotationEditService.applyTextSelectionToAnnotation(this.textAssistType),t.context.textSelectionService.clearSelectedTexts()}}),Yi(this,"textAssistType",void 0),this.textAssistType=e.textAssistType}bindHidePopup(){this.nativeOn(this.el,"click",()=>{this.$emit("ui_hidePopup","AnnotationSet")})}}class pS extends uS{constructor(t){super(t,{class:"ddv-highlight-mode",textAssistType:"highlight"})}}class gS extends uS{constructor(t){super(t,{class:"ddv-strikeout-mode",textAssistType:"strikeout"})}}class fS extends uS{constructor(t){super(t,{class:"ddv-underline-mode",textAssistType:"underline"})}}class mS extends xb{constructor(t){super(t,{class:"ddv-copy-text",callback:()=>{this.injection.viewer.copySelectedTexts(),this.$emit("ui_toolbarToggle")}})}bindHidePopup(){this.nativeOn(this.el,"click",()=>{this.$emit("ui_hidePopup","AnnotationSet")})}}class vS extends xb{constructor(t){super(t,{class:"ddv-auto-capture",callback:()=>{const{viewer:t}=this.injection,{viewerMode:e}=t.getViewerConfig(),{enableAutoCapture:i}=t.getCameraConfig();e===jg.CAPTURE&&t.updateCameraConfig({enableAutoCapture:!i})}}),this.bindViewerHooks()}bindDefaultUi(){const t=()=>{const t=this.injection.viewer;t.isVideoPlaying()?t.getCameraConfig().enableAutoCapture?this.setUiState("focused",!Ms()):this.setUiState("normal"):this.setUiState("disabled")};this.hooks.inserted.on(t),this.hooks.updated.on(t)}bindViewerHooks(){const{hooks:t}=this.injection.viewer;t.autoCaptureChanged.on(t=>{const e=t.enableAutoCapture?"focused":"normal";this.setUiState(e,!Ms())},this),t.cameraPlayed.on(()=>{const{enableAutoCapture:t}=this.injection.viewer.getCameraConfig();this.setUiState(t?"focused":"normal",!Ms())},this),t.cameraClosed.on(()=>{this.setUiState("disabled")},this)}}Yi(vS,"cpName","AutoCapture");class yS extends xb{constructor(t){super(t,{class:"ddv-auto-detect",callback:()=>{const{viewer:t}=this.injection,{viewerMode:e}=t.getViewerConfig(),{enableAutoDetect:i}=t.getCameraConfig();e===jg.CAPTURE&&t.updateCameraConfig({enableAutoDetect:!i})}}),this.bindViewerHooks()}bindDefaultUi(){const t=()=>{const t=this.injection.viewer;t.isVideoPlaying()&&t.context.core.detectorService.enableDetect?t.getCameraConfig().enableAutoDetect?this.setUiState("focused",!Ms()):this.setUiState("normal"):this.setUiState("disabled")};this.hooks.inserted.on(t),this.hooks.updated.on(t)}bindViewerHooks(){const{hooks:t}=this.injection.viewer;t.autoDetectChanged.on(t=>{const e=t.enableAutoDetect?"focused":"normal";this.setUiState(e,!Ms())},this),t.cameraPlayed.on(()=>{const{core:t}=this.injection.viewer.context;if(!t.detectorService.enableDetect)return;const{enableAutoDetect:e}=this.injection.viewer.getCameraConfig();this.setUiState(e?"focused":"normal",!Ms())},this),t.cameraClosed.on(()=>{this.setUiState("disabled")},this)}}Yi(yS,"cpName","AutoDetect");class xS extends xb{constructor(t){super(t,{class:"ddv-capture-image",callback:()=>{if(this.isCapturing)return;const t=this.injection.viewer;this.isCapturing=!0,this.setUiState("disabled"),t.capture().finally(()=>{this.isCapturing=!1,this.setUiState("normal")})}}),Yi(this,"isCapturing",!1),this.bindViewerHooks()}bindDefaultUi(){const t=()=>{this.setUiState(this.injection.viewer.isVideoPlaying()?"normal":"disabled")};this.hooks.inserted.on(t),this.hooks.updated.on(t)}bindViewerHooks(){const{hooks:t}=this.injection.viewer;t.cameraPlayed.on(()=>{this.setUiState("normal")},this),t.cameraClosed.on(()=>{this.setUiState("disabled")},this)}}Yi(xS,"cpName","Capture");class wS extends xb{constructor(t){super(t,{class:"ddv-camera-flashlight",callback:()=>{const{viewer:t}=this.injection;t.cameraContext.turnOnTheTorch?t.turnOffTorch():t.turnOnTorch()}}),this.bindViewerHooks()}bindDefaultUi(){const t=()=>{const{viewer:t}=this.injection;t.isVideoPlaying()&&t.cameraContext.torchSupported?t.cameraContext.turnOnTheTorch?this.setUiState("focused"):this.setUiState("normal"):this.setUiState("disabled")};this.hooks.inserted.on(t),this.hooks.updated.on(t)}bindViewerHooks(){this.injection.viewer.hooks.torchChanged.on(t=>{switch(t.torchState){case"supported":case"off":this.setUiState("normal");break;case"on":this.setUiState("focused",!Ms());break;default:this.setUiState("disabled")}},this)}}Yi(wS,"cpName","Flashlight");class CS extends xb{constructor(t){super(t,{class:"ddv-camera-convert",callback:()=>{const{viewer:t}=this.injection;t.cameraContext.convertCamera()}}),this.bindViewerHooks()}bindDefaultUi(){const t=()=>{const t=this.injection.viewer;t.isVideoPlaying()?this.setUiState(t.cameraContext.canFrontCamera?"normal":"disabled"):this.setUiState("disabled")};this.hooks.inserted.on(t),this.hooks.updated.on(t)}bindViewerHooks(){const{hooks:t}=this.injection.viewer;t.cameraPlayed.on(()=>{const t=this.injection.viewer.cameraContext.canFrontCamera;this.setUiState(t?"normal":"disabled")},this),t.cameraClosed.on(()=>{this.setUiState("disabled")},this)}}Yi(CS,"cpName","CameraConvert");const bS=[{label:" 720P",value:{width:1280,height:720}},{label:" 1080P",value:{width:1920,height:1080}},{label:" 1440P",value:{width:2560,height:1440}},{label:" 2160P",value:{width:3840,height:2160}}];class SS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-resolution"),Yi(this,"cssPrefix",`${this.defaultClass}-`),Yi(this,"checkedClassName",`${this.cssPrefix}checkbox-checked`),Yi(this,"resolutionOptions",[]),Yi(this,"isFirstClick",!0),Yi(this,"fakeResolution",!1),Yi(this,"lastCheckIndex",0),Yi(this,"box",void 0),this.bindHooks(),this.initTemplate(),ab(this)}bindHooks(){this.hooks.created.on(t=>{this.box=this.query(`.${this.cssPrefix}box`),this.box.style.display="none",this.box.remove(),this.updateResolution(),this.bindEvents(),this.bindViewerHooks(),this.bindEventsEmitter(),cb(this.el,!0)}),this.hooks.updated.on(()=>{this.box.style.display="none",this.isFirstClick=!0,this.injection.viewer.isVideoPlaying()||cb(this.el,!0)})}bindEvents(){const t=this.box.getElementsByTagName("ul")[0];this.nativeOn(this.el,"click",()=>{const t=this.injection.viewer.rootDom;this.togglePopup(),this.isFirstClick&&(ub(t,this.el,this.box),this.isFirstClick=!1)}),this.ulEvent(t)}ulEvent(t){t&&this.nativeOn(t,"click",t=>{const e=this.injection.viewer,i=t.target,n=i.parentNode;if("LI"===i.tagName||"LI"===n.tagName){const t="LI"===i.tagName?i.value:n.value;if(t===this.lastCheckIndex)return;const{width:s,height:o}=this.resolutionOptions[t].value;this.fakeResolution=!0,e.setResolution(s,o).catch(t=>{pp.error(t)}),this.updateChecked(s,o)}this.togglePopup(!1)})}bindViewerHooks(){const{viewer:t}=this.injection,{hooks:e}=t;e.cameraPlayed.on(t=>{if(cb(this.el,!1),this.fakeResolution)return;const{width:e,height:i}=t.resolution;this.updateChecked(e,i),this.fakeResolution=!1},this),e.cameraClosed.on(()=>{cb(this.el,!0)},this),e.visibleChanged.on(t=>{"hidden"===t.newVisibility&&this.togglePopup(!1)},this)}updateChecked(t,e){const i=function(t,e){let i=-1;const n=e.width*e.height;for(let e=0;e<t.length;e++){const{value:s}=t[e],o=s.width*s.height;if(0===e&&n<=o)return 0;if(e===t.length&&n>=o)return t.length-1;n>o&&(i=e+1)}return i}(this.resolutionOptions,{width:t,height:e}),{box:n,checkedClassName:s}=this,o=n.getElementsByClassName(`${this.cssPrefix}checkbox`)[i],r=n.getElementsByClassName(s)[0];o!==r&&(this.lastCheckIndex=i,null==o||o.classList.add(s),null==r||r.classList.remove(s))}initTemplate(){const{options:t}=this.data,{popupBox:e}=t;pb(gb(this),this.injection.viewer,t);const i=`<div ${GC(t,`${this.defaultClass} ddv-button`)}>`+(Ps(null==t?void 0:t.label)?"":`<span>${t.label}</span>`)+'<i class="ddv-down-arrow"></i>'+`<div ${GC(e,this.cssPrefix,"box")}><ul></ul></div></div>`;this.template=i}getOptionTemplate(){const{options:t}=this.data;let e=bS;if(Ts(null==t?void 0:t.valueList))e=t.valueList;else{const{CameraResolution_720P:t,CameraResolution_1080P:i,CameraResolution_1440P:n,CameraResolution_2160P:s}=MT.getDisplayTextConfig(),o=[t,i,n,s];e.forEach((t,e)=>{o[e]&&(t.label=o[e])})}let i="";return e.forEach((t,e)=>{const{width:n,height:s}=t.value;Ls(n)&&Ls(s)&&(i+=[`<li value="${e}">`,`<i class="${this.cssPrefix}checkbox"></i>`,`<span>${(null==t?void 0:t.label)||""}</span>`,"</li>"].join(""))}),this.resolutionOptions=e,i}updateResolution(){const t=this.getOptionTemplate();this.box.getElementsByTagName("ul")[0].innerHTML=t}togglePopup(t){const{box:e}=this,{viewer:i}=this.injection;let n="none"!==e.style.display;n=Ps(t)?!n:t,n?(this.$emit("ui_hidePopup",this),i.rootDom.appendChild(e)):e.remove(),db(this.el,n),e.style.display=n?"":"none"}}Yi(SS,"cpName","CameraResolution");class TS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-image-preview"),Yi(this,"cssPrefix",`${this.defaultClass}-`),Yi(this,"uiState",void 0),Yi(this,"image",void 0),Yi(this,"counter",void 0),Yi(this,"imagePageUid",void 0),Yi(this,"hasTask",!1),Yi(this,"isUpdateTask",!1),Yi(this,"lastPageUid",void 0),Yi(this,"pageTaskUids",[]),Yi(this,"currentTimer",void 0),this.initTemplate(),this.bindHooks()}bindHooks(){this.hooks.created.on(t=>{this.setState("disabled"),this.bindViewerHooks(),this.bindEventsEmitter()}),this.hooks.inserted.on(t=>{this.image=this.el.getElementsByTagName("img")[0],this.counter=this.query(`.${this.cssPrefix}counter`)}),this.hooks.destroyed.on(()=>{var t;clearTimeout(this.currentTimer),null!=this&&this.image&&null!=this&&null!==(t=this.image)&&void 0!==t&&t.src&&URL.revokeObjectURL(this.image.src)})}bindViewerHooks(){const t=this.injection.viewer,e=Ms()?10:4;t.hooks.updatePage.on(async i=>{if(i.pageUid!==this.lastPageUid)return;if(this.hasTask)return this.pageTaskUids.push(i.pageUid),void(this.isUpdateTask=!0);this.hasTask=!0;const n=t.getPageCounts(),s=await t.getPerspectivePreviewImage(n-1,400,400,e);s&&(this.image.src&&URL.revokeObjectURL(this.image.src),this.image.src=Fs(s.data).data),this.hasTask=!1,this.pageTaskUids.length>0&&this.createTask()},this),t.hooks.pageChanged.on(async e=>{var i;if(0===e.total)return null!=this&&this.image&&null!=this&&null!==(i=this.image)&&void 0!==i&&i.src&&URL.revokeObjectURL(this.image.src),this.image.src="",this.setState("disabled"),this.imagePageUid=void 0,this.lastPageUid=void 0,void(this.pageTaskUids.length=0);if(null==this||!this.counter)return;this.counter.innerText=`${e.total}`;const n=t.getActiveTab();if(!n)return;const s=n.allPages[e.total-1].uid;this.pageTaskUids.push(s),this.hasTask||s!==this.lastPageUid&&this.createTask()},this)}async createTask(){this.hasTask||(this.hasTask=!0,await this.updateImage(),this.currentTimer=setTimeout(()=>{this.hasTask=!1,0!==this.pageTaskUids.length&&this.createTask()},300))}async updateImage(){var t;const e=this.injection.viewer;if(!e||!e.context)return;const i=e.getActiveTab(),n=Ms()?10:4;if(!i)return;const s=i.allPages.length;if(!s)return;const o=this.pageTaskUids[this.pageTaskUids.length-1],r=i.allPages[s-1].uid;if(this.pageTaskUids.length=0,this.lastPageUid=i.allPages[s-1].uid,this.lastPageUid===o&&this.imagePageUid===o&&!this.isUpdateTask)return;let a;this.isUpdateTask&&(this.isUpdateTask=!1);try{a=await e.getPerspectivePreviewImage(s-1,400,400,n)}catch(t){}const l=e.getActiveTab(),h=(null==l||null===(t=l.allPages)||void 0===t?void 0:t.length)||0;this.image.src&&URL.revokeObjectURL(this.image.src),a&&!e.isDestroy&&l&&h&&(this.image.src=Fs(a.data).data,this.imagePageUid=r,this.setState(h>0?"normal":"disabled"))}setState(t){this.uiState!==t&&this.el&&("normal"===t?(this.el.style.visibility="",this.el.style.pointerEvents=""):(this.el.style.visibility="hidden",this.el.style.pointerEvents="none"),this.uiState=t)}initTemplate(){const{options:t}=this.data,{imageCounter:e}=t,i=this.injection.viewer.getPageCounts();pb(gb(this),this.injection.viewer,t);const n=`<div ${GC(t,this.defaultClass)}> <img src=""></img><div ${GC(e,this.cssPrefix,"counter")}>${i}</div></div>`;this.template=n}}Yi(TS,"cpName","ImagePreview");class ES extends xb{constructor(t){super(t,{class:"ddv-load-image",callback:()=>{this.fileLoader.value=null,delete this.fileLoader.files,this.fileLoader.click()}}),Yi(this,"fileLoader",void 0),this.$on("ui_cropClick",t=>{const{viewer:e}=this.injection;0!==(e.getPageCounts()||0)&&this.setUiState(t?"disabled":"normal")})}createFileInput(){var t;const e=document.createElement("input");e.accept="image/png,image/jpeg,image/bmp,image/tiff,application/pdf",e.type="file",e.multiple=!0;const i={renderAnnotations:lg.annotationLicenseModuleIsExist()?cu.LOAD_ANNOTATIONS:cu.NO_ANNOTATIONS},n="image"===this.injection.viewer.context.viewerConfig.renderingMode?hu.CM_AUTO:hu.CM_RENDERALL;return!0===(null===(t=this.injection.viewer)||void 0===t||null===(t=t.popupConfig)||void 0===t||null===(t=t.passwordLoaderConfig)||void 0===t?void 0:t.enabled)?this.nativeOn(e,"change",async()=>{const{files:t}=e,s=t.length;for(let e=0;e<s;e++){const s=new Blob([t[e]],{type:t[e].type});await this.injection.viewer.context.core.isPdfEncrypted(s)?await new Promise(i=>{this.$emit("ui_showPasswordLoader",{blob:s,fileName:t[e].name,resolve:i})}):await this.injection.viewer.context.loadSource({fileData:s,convertMode:n,renderOptions:i})}e.value=null,e.files=null}):this.nativeOn(e,"change",()=>{const{files:t}=e,s=t.length,o=[];for(let e=0;e<s;e++){const s=new Blob([t[e]],{type:t[e].type});"application/pdf"===t[e].type?o.push({fileData:s,convertMode:n,renderOptions:i}):o.push({fileData:s})}this.injection.viewer.context.loadSource(o),e.value=null,e.files=null}),e}bindHooks(){super.bindHooks(),this.hooks.inserted.on(()=>{const t=this.createFileInput();t.style.display="none",this.el.appendChild(t),this.fileLoader=t,this.nativeOn(t,"click",t=>{t.stopPropagation()})})}bindDefaultUi(){this.injection.viewer.hooks.pageExistenceChanged.on(t=>{null!=t&&t.pageCount||this.setUiState("normal")},this)}}Yi(ES,"cpName","Load");class _S extends xb{constructor(t){super(t,{class:"ddv-delete-all",callback:()=>{this.injection.viewer.deleteAllPages()}}),hb(this)}}Yi(_S,"cpName","DeleteAll");class PS extends xb{constructor(t){super(t,{class:"ddv-delete-current",callback:()=>{const t=this.injection.viewer,e=t.getCurrentPageIndex();t.deletePages([e])}}),hb(this)}}function AS(t){try{t.dispatchEvent(new MouseEvent("click"))}catch(e){const i=document.createEvent("MouseEvents");i.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),t.dispatchEvent(i)}}function IS(t,e,i){if("download"in HTMLAnchorElement.prototype){const i=document.createElementNS("http://www.w3.org/1999/xhtml","a");e=e||t.name||"download",i.download=e,i.rel="noopener","string"==typeof t?(i.href=t,i.origin!==window.location.origin?function(t){const e=new XMLHttpRequest;e.open("HEAD",t,!1);try{e.send()}catch(t){}return e.status>=200&&e.status<=299}(i.href)?function(t,e){const i=new XMLHttpRequest;i.open("GET",t),i.responseType="blob",i.onload=()=>{IS(i.response,e)},i.onerror=()=>{},i.send()}(t,e):(i.target="_blank",AS(i)):AS(i)):(i.href=URL.createObjectURL(t),setTimeout(()=>{URL.revokeObjectURL(i.href),i.href="",i.remove()},3e3),setTimeout(()=>{AS(i)},0))}}Yi(PS,"cpName","DeleteCurrent");class DS extends xb{constructor(t){super(t,{class:"ddv-button-download",callback:()=>{const t=this.injection.viewer,e=t.getActiveTab(),i=pp.buildInfo("save",{docUid:e.doc.uid,pageUids:e.doc.pages,current:0,total:e.doc.pages.length});pp.info(i),t.context.core.fileSaveService.saveToPdf(e.doc.pages,{mimeType:"application/octet-stream",saveAnnotation:lg.annotationLicenseModuleIsExist()?"annotation":"none"},i).then(t=>{IS(t,`${e.docName}.pdf`)}).catch(t=>{pp.error(t)})}}),lb(this)}}Yi(DS,"cpName","Download");class RS extends Cb{constructor(t){const{Delete_DeleteCurrent:e,Delete_DeleteAll:i}=MT.getDisplayTextConfig(),{Delete_DeleteCurrent:n,Delete_DeleteAll:s}=ib;t.data.options={showCheckIcon:!0,showDropDownArrow:!0,...t.data.options,children:[{type:"DeleteCurrent",label:e,id:n},{type:"DeleteAll",label:i,id:s}],defaultClassName:"ddv-delete-btn"},super(t),hb(this)}}Yi(RS,"cpName","Delete");class kS extends xb{constructor(t){super(t,{class:"ddv-print-page",callback:()=>{const t=this.injection.viewer,e=t.getCurrentPageIndex(),i=t.getActiveTab(),{displayMode:n}=i.context;"single"===n?t.context.core.printPages(i.uid,[e]):t.context.core.printPages(i.uid)}}),lb(this)}}Yi(kS,"cpName","Print");class MS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-password-loader"),Yi(this,"errorTimes",0),Yi(this,"fileData",null),Yi(this,"fileName",null),Yi(this,"loaderResolve",null),this.initTemplate(),this.bindHooks(),this.$on("ui_showPasswordLoader",t=>{this.show(t.blob,t.fileName,t.resolve)})}bindHooks(){this.hooks.inserted.on(t=>{this.bindEvents()})}bindEvents(){const t=this.el.querySelector(".ddv-button-close"),e=this.el.querySelector(`.${this.defaultClass}-button`),i=this.el.querySelector(`.${this.defaultClass}-input`);i.addEventListener("input",()=>{this.setErrorTimesVisible(!1)}),i.addEventListener("keydown",t=>{"Enter"===t.key&&(t.preventDefault(),this.reloadFile())}),t.addEventListener("click",()=>{this.loaderResolve&&(this.loaderResolve(),this.hide())}),e.addEventListener("click",()=>{this.reloadFile()})}show(t,e,i){const n=this.el.querySelector(`.${this.defaultClass}-input`);this.el.style.display="block",this.fileData=t,this.fileName=e,this.loaderResolve=i,this.updateFileInfo(),vb(this.injection.viewer,!0),n.focus()}hide(){this.el.querySelector(`.${this.defaultClass}-input`).value="",this.el.style.display="none",this.fileData=null,this.fileName=null,this.loaderResolve=null,this.errorTimes=0,this.setErrorTimesVisible(!1),this.setErrorVisible(!1),vb(this.injection.viewer,!1)}reloadFile(){if(!this.fileData)return;if(this.errorTimes>3)return void this.hide();const t=this.el.querySelector(`.${this.defaultClass}-input`),e={renderAnnotations:lg.annotationLicenseModuleIsExist()?cu.LOAD_ANNOTATIONS:cu.NO_ANNOTATIONS},i="image"===this.injection.viewer.context.viewerConfig.renderingMode?hu.CM_AUTO:hu.CM_RENDERALL;this.injection.viewer.context.loadSource({fileData:this.fileData,convertMode:i,password:t.value,renderOptions:e},!0).then(()=>{this.loaderResolve(),this.hide()}).catch(()=>{3===this.errorTimes&&this.setErrorVisible(!0),this.setErrorTimesVisible(!0,3-this.errorTimes),this.errorTimes+=1})}updateFileInfo(){const t=this.el.querySelector(`.${this.defaultClass}-name`);t&&(t.innerText=` ${this.fileName} `)}setErrorTimesVisible(t,e){const i=this.el.querySelector(`.${this.defaultClass}-times`);i.style.display=t?"block":"none",t&&(i.innerText=`The password is incorrect. Remaining input times: ${e}`)}setErrorVisible(t){const e=this.el.querySelector(`.${this.defaultClass}-error`),i=this.el.querySelector(`.${this.defaultClass}-container`),n=this.el.querySelector(`.${this.defaultClass}-button`);e.style.display=t?"block":"none",i.style.display=t?"none":"block",n.innerText=t?"Ok":"Submit"}initTemplate(){const{options:t}=this.data;pb(gb(this),this.injection.viewer,t);const e=`<div ${GC(t,this.defaultClass,"")}><div class="${this.defaultClass}-header"><span>Password required</span><div class="ddv-button ddv-button-close"></div></div><div class="${this.defaultClass}-container"><span class="${this.defaultClass}-info">The<span class="${this.defaultClass}-name">file</span>has been encrypted. Please enter your password.</span><form style="width: 100%"><input autocomplete="off" type="password" class="${this.defaultClass}-input" /></form><span style="display:none" class="${this.defaultClass}-times">The password is incorrect. Remaining input times:3</span></div><div style="display:none" class="${this.defaultClass}-error"><span>Unable to load the document, too many attempts.</span></div><div class="${this.defaultClass}-button">OK</div></div>`;this.template=e}}Yi(MS,"cpName","PasswordLoader");class LS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-search-result"),Yi(this,"searchedResult",[]),Yi(this,"bufferSize",3),Yi(this,"lastSearchUid",""),Yi(this,"lastSearchType",""),Yi(this,"lastSelectedTextUid",""),Yi(this,"isDirty",!1),Yi(this,"isFocusResultItem",!1),Yi(this,"startIndex",0),Yi(this,"endIndex",0),Yi(this,"titleIndex",[]),Yi(this,"renderDataArr",[]),Yi(this,"pageIndices",[]),Yi(this,"totalHeight",0),Yi(this,"domHightList",[]),Yi(this,"tempDiv",null),Yi(this,"container",null),Yi(this,"scrollTimer",null),Yi(this,"canScroll",!0),Yi(this,"getResultItemDom",t=>{const e=this.renderDataArr[t],{length:i}=e.text,{startIndex:n,context:s}=e,o=s.substring(0,n),r=OS(s.substring(n,n+i)),a=OS(s.substring(n+i)),l=document.createElement("div");return l.dataset.textUid=e.textUid,l.className=`${this.defaultClass}-item`,l.innerHTML=`${o}<span>${r}</span>${a}`,l.addEventListener("click",t=>{this.injection.viewer.selectSearchText(e.pageUid,e.textUid)}),l}),this.initTemplate(),this.bindHooks(),this.$on("ui_clearTextSearch",()=>{this.resetSelf(),this.updateSearchResultCount()}),this.$on("ui_searchVisibilityChanged",t=>{this.isDirty&&t&&(this.calculatePhantomHeight(),this.updateSearchResultCount(),this.updateVisibleItems(),this.renderItem(),this.selectResultItem(this.lastSelectedTextUid))}),this.$on("ui_swipeChanged",t=>{t===this.el.parentNode&&setTimeout(()=>{this.isDirty&&(this.calculatePhantomHeight(),this.updateSearchResultCount()),this.updateVisibleItems(),this.renderItem(),this.selectResultItem(this.lastSelectedTextUid)},250)}),this.tempDiv=document.createElement("div"),this.tempDiv.className=`${this.defaultClass}-item`}bindHooks(){this.hooks.inserted.on(()=>{this.container=this.el.querySelector(`.${this.defaultClass}-container-body`),this.bindViewerHooks(),this.bindEvents()}),this.hooks.destroyed.on(()=>{this.tempDiv=null})}bindEvents(){const t=this.el.querySelector(`.${this.defaultClass}-prev`),e=this.el.querySelector(`.${this.defaultClass}-next`);this.nativeOn(t,"click",()=>{this.injection.viewer.prevSearchText(),this.autoScrollToItem()}),this.nativeOn(e,"click",()=>{this.injection.viewer.nextSearchText(),this.autoScrollToItem()}),this.nativeOn(this.container,"scroll",()=>{this.updateVisibleItems(),this.renderItem(),this.selectResultItem(this.lastSelectedTextUid)}),Ms()||(this.container.tabIndex=0,this.nativeOn(this.container,"focus",()=>{this.injection.viewer.context.isFocusCanvas=!1}),this.nativeOn(this.container,"blur",()=>{this.isFocusResultItem=!1}),this.nativeOn(this.container,"click",t=>{this.container.focus(),this.injection.viewer.context.isFocusCanvas=!1,this.renderDataArr.length&&(t.target.classList.contains(`${this.defaultClass}-item`)||t.target.parentNode.classList.contains(`${this.defaultClass}-item`)?this.isFocusResultItem=!0:this.isFocusResultItem=!1)}),this.nativeOn(this.container,"keydown",t=>{this.isFocusResultItem&&(t.preventDefault(),t.stopPropagation(),"ArrowDown"===t.key&&this.injection.viewer.nextSearchText(),"ArrowUp"===t.key&&this.injection.viewer.prevSearchText(),this.autoScrollToItem())}))}bindViewerHooks(){const{viewer:t}=this.injection,e=this.el.querySelector(`.${this.defaultClass}-content`);t.hooks.searchTextChanged.on(i=>{const n=t.getActiveTab(),s=this.container.offsetHeight,o=e.offsetHeight;this.pageIndices=[],this.searchedResult=i.searchResults,this.searchedResult.forEach(t=>{const e=n.uidToIndex(t.pageUid);this.pageIndices.push(e)});const r=this.lastSearchUid!==i.searchUid||this.lastSearchType!==i.searchType||"single"===i.searchType||i.isEditPages;r&&(this.container.scrollTo({top:0}),this.domHightList=[],this.renderDataArr=[],this.titleIndex=[],this.lastSearchType=i.searchType,this.lastSearchUid=i.searchUid,this.totalHeight=0),0!==this.container.clientHeight?(this.calculatePhantomHeight(),this.updateSearchResultCount(),(r||o<s)&&(this.updateVisibleItems(),this.renderItem())):this.isDirty=!0},this),t.hooks.searchTextSelected.on(t=>{this.lastSelectedTextUid=t,this.selectResultItem(t)},this),t.hooks.visibleChanged.on(t=>{this.isDirty&&"visible"===t.newVisibility&&(this.calculatePhantomHeight(),this.updateSearchResultCount(),this.updateVisibleItems(),this.renderItem(),this.selectResultItem(this.lastSelectedTextUid))})}resetSelf(){this.searchedResult=[],this.renderDataArr=[],this.titleIndex=[],this.domHightList=[],this.totalHeight=0,this.calculatePhantomHeight();const t=this.el.querySelector(`.${this.defaultClass}-content`);t.style.transform="",t.innerHTML=""}autoScrollToItem(){if(!this.canScroll)return this.scrollTimer&&clearTimeout(this.scrollTimer),void(this.scrollTimer=setTimeout(()=>{this.performScroll(),this.scrollTimer=null},100));this.canScroll=!1,this.performScroll(),setTimeout(()=>{this.canScroll=!0},100)}performScroll(){const t=this.el.querySelector(`.${this.defaultClass}-container-body`);if(!t||!this.lastSelectedTextUid)return;let e=-1;for(let t=0;t<this.renderDataArr.length;t++){const i=this.renderDataArr[t];if(i&&i.textUid===this.lastSelectedTextUid){e=t;break}}if(-1===e)return;if(1===e)return void t.scrollTo({top:0,behavior:"smooth"});let i=0;for(let t=0;t<e;t++)i+=this.domHightList[t];const n=i+this.domHightList[e],s=t.scrollTop,o=s+t.clientHeight;i<s?t.scrollTo({top:i,behavior:"smooth"}):n>o&&t.scrollTo({top:n-t.clientHeight,behavior:"smooth"})}calculatePhantomHeight(){const t=this.el.querySelector(`.${this.defaultClass}-phantom`);for(let t=this.titleIndex.length;t<this.searchedResult.length;t++){const e=this.renderDataArr.length;this.titleIndex.push(e),this.renderDataArr.push(t),this.renderDataArr.push(...this.searchedResult[t].texts);for(let t=e;t<this.renderDataArr.length;t++)this.domHightList[t]=this.titleIndex.includes(t)?27:81,this.totalHeight+=this.domHightList[t]}t.style.height=`${this.totalHeight}px`}updateVisibleItems(){const t=this.el.querySelector(`.${this.defaultClass}-container-body`);if(!t)return;const{scrollTop:e,clientHeight:i}=t;let n=0;const s=this.domHightList.map(t=>(n+=t)-t);let o=0;const r=this.findIndex(e,s),a=this.findIndex(e+i,s);this.isDirty=!1,this.startIndex=Math.max(0,r-this.bufferSize),this.endIndex=Math.min(this.renderDataArr.length,a+this.bufferSize);for(let t=0;t<this.startIndex;t++)o+=this.domHightList[t];this.el.querySelector(`.${this.defaultClass}-content`).style.transform=`translateY(${o}px)`}renderItem(){const t=this.el.querySelector(`.${this.defaultClass}-content`),e=this.el.querySelector(`.${this.defaultClass}-phantom`);if(!t)return;t.innerHTML="";let i=0;for(let e=this.startIndex;e<this.endIndex;e++)if(this.titleIndex.includes(e)){const i=document.createElement("span");i.className=`${this.defaultClass}-split`,i.textContent=`Page ${this.pageIndices[this.titleIndex.indexOf(e)]+1}`,t.appendChild(i)}else{const n=this.getResultItemDom(e);t.appendChild(n);const s=this.domHightList[e],o=n.offsetHeight+5;this.domHightList[e]=o,i+=o-s}i&&(this.totalHeight+=i,e.style.height=`${this.totalHeight}px`)}updateSearchResultCount(){const t=this.el.querySelector(`.${this.defaultClass}-count`);if(!t)return;const e=this.renderDataArr.length-this.titleIndex.length;t.textContent=1===e?`${e} result found`:`${e} results found`}selectResultItem(t){const e=this.el.querySelector(`.${this.defaultClass}-content`);if(!e)return;const i=e.querySelectorAll(`.${this.defaultClass}-item`),n=`${this.defaultClass}-item-selected`;i.forEach(e=>{e.dataset.textUid===t?e.classList.add(n):e.classList.remove(n)})}findIndex(t,e){let i=0,n=e.length-1;for(;i<=n;){const s=Math.floor((i+n)/2);e[s]<=t?i=s+1:n=s-1}return i}async initTemplate(){const t=`<div class="${this.defaultClass}-container"><div class="${this.defaultClass}-container-header"><span class="${this.defaultClass}-count">0 results found</span><div style="display:flex; align-items: center;"><button class="${this.defaultClass}-prev"></button><button class="${this.defaultClass}-next"></button></div></div><div class="${this.defaultClass}-container-body"><div class="${this.defaultClass}-phantom"></div><div class="${this.defaultClass}-content"></div></div></div>`;this.template=t}}function OS(t){return t.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[t]||t))}Yi(LS,"cpName","TextSearchResult");class BS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-search"),Yi(this,"clearBySelf",!1),this.initTemplate(),XC.registerComponent({TextSearchResult:LS}),this.bindHooks(),this.bindUiEvents()}bindUiEvents(){this.$on("ui_searchToggle",()=>{var t;null!=this&&null!==(t=this.injection)&&void 0!==t&&t.viewer.getPageCounts()&&this.toggle()}),this.$on("ui_swipeHide",t=>{t===this.el&&(this.toggle(),this.el.style.height="",this.el.style.top="")})}toggle(){const t="none"!==getComputedStyle(this.el).display;if(this.el.style.display=t?"none":"flex",this.$emit("ui_searchVisibilityChanged",!t),t)Ms()&&(this.el.style.height="",this.el.style.top="",this.$emit("ui_swipeReset",this.el));else{const t=this.el.querySelector(`.${this.defaultClass}-input`);this.injection.viewer.context.isFocusCanvas=!1,t.focus()}}bindHooks(){this.hooks.inserted.on(t=>{var e,i;this.bindEvents(),this.bindViewerHooks();const{options:n}=this.data,{postfix:s}=this.injection.viewer,o=null!==(e=n.defaultCaseSensitive)&&void 0!==e&&e,r=null!==(i=n.defaultWholeWord)&&void 0!==i&&i;o&&(this.el.querySelector(`#ddvCaseSensitive${s}`).checked=o),r&&(this.el.querySelector(`#ddvWholeWord${s}`).checked=r),this.injection.viewer.getPageCounts()>0&&this.el.querySelector(`.${this.defaultClass}-header`).classList.remove("ddv-button-disabled")})}bindViewerHooks(){const{viewer:t}=this.injection,e=this.el.querySelector(`.${this.defaultClass}-header`),i=this.el.querySelector(`.${this.defaultClass}-input`),n=this.el.querySelector(`#ddvCaseSensitive${t.postfix}`),s=this.el.querySelector(`#ddvWholeWord${t.postfix}`);t.hooks.pageExistenceChanged.on(t=>{if(t.pageCount){e.classList.remove("ddv-button-disabled");const t="none"!==getComputedStyle(this.el).display;t&&this.$emit("ui_searchVisibilityChanged",t)}else e.classList.add("ddv-button-disabled"),this.$emit("ui_clearTextSearch"),i.value=""},this),t.hooks.searchTextCleared.on(t=>{this.clearBySelf||!0!==t&&(this.$emit("ui_clearTextSearch"),i.value="")},this),t.hooks.searchTextChanged.on(t=>{var e,o;i.value=t.text,n.checked=null===(e=t.searchConfig)||void 0===e?void 0:e.caseSensitive,s.checked=null===(o=t.searchConfig)||void 0===o?void 0:o.wholeWord},this)}bindEvents(){const{viewer:t}=this.injection,e=this.el.querySelector(`.${this.defaultClass}-input`),i=this.el.querySelector(`#ddvCaseSensitive${t.postfix}`),n=this.el.querySelector(`#ddvWholeWord${t.postfix}`),s=()=>{const s=e.value;s.length?t.searchFullText(s,{caseSensitive:i.checked,wholeWord:n.checked}):(this.clearBySelf=!0,this.injection.viewer.clearSearchText(),this.$emit("ui_clearTextSearch"),this.clearBySelf=!1)},o=()=>{e.value.length&&(this.clearBySelf=!0,this.injection.viewer.clearSearchText(),this.$emit("ui_clearTextSearch"),this.clearBySelf=!1,s())},r=t=>{var e;!0===(null==this||null===(e=this.injection)||void 0===e||null===(e=e.viewer)||void 0===e||null===(e=e.context)||void 0===e?void 0:e.isFocusCanvas)&&(t.ctrlKey||t.metaKey)&&"f"===t.key&&(t.preventDefault(),this.$emit("ui_searchToggle"))};e.addEventListener("input",s),i.addEventListener("change",o),n.addEventListener("change",o),document.addEventListener("keydown",r),this.hooks.destroyed.on(()=>{document.removeEventListener("keydown",r)})}initTemplate(){var t,e,i;const{options:n}=this.data,{postfix:s}=this.injection.viewer;pb(gb(this),this.injection.viewer,n),delete n.label,delete n.tooltip;const o=null===(t=n.showCaseSensitive)||void 0===t||t,r=null===(e=n.showWholeWord)||void 0===e||e,a=null===(i=n.enableSwipeForMobile)||void 0===i||i,l=`<div ${GC(n,this.defaultClass,"")}>`+(Ms()&&a?"<SwipeIndicator></SwipeIndicator>":"")+`<div class="${this.defaultClass}-header ddv-button-disabled">`+`<div class="${this.defaultClass}-input-container"><i class="ddv-icon-search"></i>`+`<input type="search" class="${this.defaultClass}-input" /></div>`+`<label ${o?"":'style="display:none"'} for="ddvCaseSensitive${s}" >`+`<input id="ddvCaseSensitive${s}" type="checkbox"/>Case sensitive</label>`+`<label ${r?"":'style="display:"none""'} for="ddvWholeWord${s}" >`+`<input id="ddvWholeWord${s}" type="checkbox"/>Whole word</label></div>`+`<div class="${this.defaultClass}-split-line"></div><TextSearchResult></TextSearchResult></div>`;this.template=l}}Yi(BS,"cpName","TextSearchPanel");class NS extends xb{constructor(t){super(t,{class:"ddv-search-switch",callback:()=>{this.$emit("ui_searchToggle")}}),this.bindUiEvents()}bindUiEvents(){const t=Ms();this.$on("ui_searchVisibilityChanged",e=>{this.setUiState(e?"focused":"normal",!t)}),Ms()&&this.$on("ui_cropClick",t=>{const{viewer:e}=this.injection,i=e.getPageCounts()||0;(t||i)&&(this.el.classList.contains("ddv-button-focused")&&this.$emit("ui_searchToggle"),cb(this.el,t))}),lb(this)}}Yi(NS,"cpName","TextSearchPanelSwitch");class US extends xb{constructor(t){super(t,{class:"ddv-crop-current",callback:()=>{this.cropEvent()}})}bindDefaultUi(){FS(this)}cropEvent(){const t=this.injection.viewer,e=t.getRectBox(),i=t.getCurrentPageIndex();e&&t.cropPages(e,[i])}}function FS(t){const e=t.injection.viewer,i=i=>{const n=Ps(null==i?void 0:i.pageCount)?e.getPageCounts():i.pageCount,s=e.getRectBox();n&&s?t.setUiState("normal"):t.setUiState("disabled")};t.hooks.inserted.on(i),t.hooks.updated.on(i),e.hooks.pageExistenceChanged.on(i,t),e.hooks.cropRectDrawn.on(e=>{t.setUiState("normal")},t),e.hooks.cropRectDeleted.on(e=>{t.setUiState("disabled")},t)}Yi(US,"cpName","CropCurrent");class VS extends xb{constructor(t){super(t,{class:"ddv-crop-all",callback:()=>{this.cropEvent()}})}bindDefaultUi(){FS(this)}cropEvent(){const{viewer:t}=this.injection,e=t.getRectBox(),i=t.getCropIndices();e&&t.cropPages(e,i)}}Yi(VS,"cpName","CropAll");class WS extends xb{constructor(t){super(t,{class:"ddv-perspective",callback:()=>{this.perspectiveEvent()}})}perspectiveEvent(){const{viewer:t}=this.injection;t.perspectiveAllPage()}}Yi(WS,"cpName","PerspectiveAll");class HS extends xb{constructor(t){super(t,{class:"ddv-full-quad",callback:()=>{this.toggleFull()}}),this.bindViewerHooks()}toggleFull(){const{viewer:t}=this.injection;t.toggleFullPerspective()}bindViewerHooks(){const{hooks:t}=this.injection.viewer;t.perspectiveQuadChanged.on(t=>{this.isFocused=t.isFull||!1,this.setUiState(t.isFull?"focused":"normal",!Ms())},this)}}Yi(HS,"cpName","FullQuad");class jS extends xb{constructor(t){super(t,{class:"ddv-redo-page",callback:()=>{this.injection.viewer.redo()}}),this.$on("ui_cropClick",()=>{const t=this.injection.viewer.getOperationState().redo>0?"normal":"disabled";this.setUiState(t)})}bindDefaultUi(){zS("redo",this)}}function zS(t,e){const{viewer:i}=e.injection,n=()=>{const n=i.getOperationState(),s=("redo"===t?n.redo:n.undo)>0?"normal":"disabled";e.setUiState(s)};e.hooks.inserted.on(n),e.hooks.updated.on(n),i.hooks.operationsChanged.on(i=>{let n="disabled";n="redo"===t?i.redo>0?"normal":"disabled":i.undo>0?"normal":"disabled",e.setUiState(n)},e),i.hooks.pageExistenceChanged.on(t=>{0===t.pageCount&&e.setUiState("disabled")},e)}Yi(jS,"cpName","Redo");class GS extends xb{constructor(t){super(t,{class:"ddv-restore-page",callback:()=>{const{viewer:t}=this.injection,e=t.getCurrentPageIndex();t.reset(e)}}),hb(this)}}Yi(GS,"cpName","Restore");class YS extends xb{constructor(t){super(t,{class:"ddv-rotate-left",callback:()=>{const{viewer:t}=this.injection,e=t.getCurrentPageIndex();t.rotatePages(-90,[e])}}),hb(this)}}Yi(YS,"cpName","RotateLeft");class $S extends xb{constructor(t){super(t,{class:"ddv-rotate-right",callback:()=>{const{viewer:t}=this.injection,e=t.getCurrentPageIndex();t.rotatePages(90,[e])}}),hb(this)}}Yi($S,"cpName","RotateRight");class XS extends xb{constructor(t){super(t,{class:"ddv-undo-page",callback:()=>{this.injection.viewer.undo()}}),this.$on("ui_cropClick",()=>{const t=this.injection.viewer.getOperationState().undo>0?"normal":"disabled";this.setUiState(t)})}bindDefaultUi(){zS("undo",this)}}Yi(XS,"cpName","Undo");class qS extends wb{constructor(t){super(t),this.defaultClass="ddv-crop",this.initPullDownBox(),this.initTemplate(),this.initHooks(),this.$on("ui_layoutScroll",t=>{t===this.el.parentElement&&ub(this.injection.viewer.rootDom,this.el,this.pullDownBox)})}initHooks(){const t=this.injection.viewer;t.hooks.toolModeChanged.on(t=>{const e="crop"===t.newToolMode;this.injection.viewer.getPageCounts()>0&&(this.setUiState(e?"focused":"normal"),this.togglePopup(e),this.isFirstClick&&e&&this.el.click()),this.$emit("ui_cropClick",e)},this),t.hooks.cropRectDrawn.on(()=>{cb(this.pullDownBox.querySelector(`.${this.defaultClass}-buttonGroup`).children[1],!1)},this),t.hooks.pageChanged.on(()=>{cb(this.pullDownBox.querySelector(`.${this.defaultClass}-buttonGroup`).children[1],!this.injection.viewer.getRenderedRectBoxCount())},this)}bindPullDownBoxEvents(){const{viewer:t}=this.injection,e=this.pullDownBox.querySelector(`.${this.defaultClass}-buttonGroup`),i=this.pullDownBox.getElementsByTagName("input")[1],n=this.pullDownBox.getElementsByTagName("input")[0],s=e.children[0],o=e.children[1],r=()=>{this.togglePopup(!1),t.updateViewerConfig({toolMode:"pan",canvasStyle:{cursor:"default"}})};this.nativeOn(o,"click",()=>{const e=t.getRectBox(),i=t.getCropIndices();e&&(t.cropPages(e,i),r())}),this.nativeOn(s,"click",r),this.nativeOn(this.el,"click",()=>{const e=t.rootDom,i=this.pullDownBox.querySelector(`.${this.defaultClass}-buttonGroup`).children[1];t.updateViewerConfig({toolMode:"crop"}),this.togglePopup(!0),this.setUiState("focused"),this.$emit("ui_cropClick",!0),cb(i,!t.getRectBox()),this.isFirstClick&&(ub(e,this.el,this.pullDownBox),this.isFirstClick=!1)}),this.nativeOn(i,"change",()=>{t.cropMode="all"}),this.nativeOn(n,"change",()=>{t.cropMode="current"})}bindPopupSwitchEvent(){}bindDefaultUi(){const t=this.injection.viewer,e=()=>{const{toolMode:e}=t.getViewerConfig();let i="disabled";t.getPageCounts()>0?("crop"===e&&this.el.click(),i=""===this.pullDownBox.style.display?"focused":"normal"):this.togglePopup(!1),this.setUiState(i)};t.hooks.pageExistenceChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}bindViewerHooks(){this.injection.viewer.hooks.cropModeChanged.on(t=>{const{newCropMode:e}=t,i=this.pullDownBox.getElementsByTagName("input")[1],n=this.pullDownBox.getElementsByTagName("input")[0];i.checked="all"===e,n.checked="current"===e},this)}initTemplate(){const{defaultClass:t}=this,{options:e}=this.data,{popupBox:i}=e,{postfix:n,cropMode:s}=this.injection.viewer,{Crop_CropCurrent:o,Crop_CropAll:r,Crop_CropApply:a,Crop_CropCancel:l}=MT.getDisplayTextConfig(),{Crop_CropCurrent:h,Crop_CropAll:c,Crop_CropApply:d,Crop_CropCancel:u}=ib,p="current"===s?'checked="checked"':"",g="all"===s?'checked="checked"':"";pb(gb(this),this.injection.viewer,e);const f=`<button ${GC(e,`ddv-button ${t}`)}>`+(Ps(null==e?void 0:e.label)?"":`<span>${e.label}</span>`)+`<div ${GC(i,`${t}-box`)}><div>`+`<input ${p} type="radio" id="${h+n}" name="cropType" value="cropCurrent" />`+`<label for="${h+n}">${o}</label>`+`<input ${g} type="radio" id="${c+n}" name="cropType" value="cropAll" />`+`<label for="${c+n}">${r}</label></div>`+`<div class= "${t}-buttonGroup">`+`<div id="${u+n}"><span>${l}</span></div>`+`<div id="${d+n}"><span>${a}</span></div></div></div></button>`;this.template=f}}Yi(qS,"cpName","Crop");class ZS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-filter-item"),Yi(this,"cssPrefix",`${this.defaultClass}-`),Yi(this,"checkedClass",`${this.cssPrefix}checked`),this.initTemplate(),this.bindHooks()}bindHooks(){this.hooks.created.on(t=>{this.bindEvents()}),this.hooks.inserted.on(()=>{this.bindFilterEvents()}),this.hooks.destroyed.on(()=>{const t=this.el.getElementsByTagName("img")[0];t.src&&URL.revokeObjectURL(t.src)})}bindEvents(){const{el:t}=this;this.nativeOn(t,"click",()=>{if(""===this.el.getElementsByTagName("img")[0].getAttribute("src"))return;const{itemValue:t}=this.data;this.$emit("ui_filterClick",t.type)})}bindFilterEvents(){this.$on("ui_filterReset",t=>{this.resetSelect(t.currentFilter);const{filterList:e}=t,{itemValue:i}=this.data,n=this.el.getElementsByTagName("img")[0];n.src&&URL.revokeObjectURL(n.src),e.forEach(t=>{if(t.type===i.type){let e="";t.imageData&&(e=Fs(t.imageData).data),n.src=e}})}),this.$on("ui_filterLoading",t=>{const e=this.el.getElementsByTagName("img")[0],i=this.el.getElementsByTagName("div")[0];e.style.display=t?"none":"",i.style.display=t?"":"none",this.el.style.pointerEvents=t?"none":""}),this.injection.viewer.hooks.filterChanged.on(t=>{this.resetSelect(t.filterType)},this)}resetSelect(t){const{itemValue:e}=this.data;t===e.type?this.el.classList.add(this.checkedClass):this.el.classList.remove(this.checkedClass)}initTemplate(){const{options:t,itemValue:e}=this.data,i=`<div ${GC(t,this.defaultClass)}><img src=""></img><div class="ddv-filter-loading" style="display:none"></div><span>${e.label}</span></div>`;this.template=i}}const JS=[{type:"none",label:"Original"}];class KS extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-filter"),Yi(this,"cssPrefix",`${this.defaultClass}-`),Yi(this,"isFirstClick",!0),Yi(this,"box",void 0),Yi(this,"applyAll",!1),Yi(this,"filterList",void 0),Yi(this,"filterUpdateStatus",!1),Yi(this,"enableFilter",!1),Yi(this,"uiState","normal"),this.bindHooks(),this.initTemplate(),this.bindDefaultUi(),ab(this);const{filterService:e}=this.injection.viewer.context.core;e.enableFilter&&(this.enableFilter=!0,hb(this),this.bindViewerHooks(),this.bindFilterEvents(),this.bindViewerResized()),XC.registerComponent({FilterItem:ZS}),this.$on("ui_layoutScroll",t=>{this.togglePopup(!1),this.isFirstClick=!0})}bindHooks(){this.hooks.created.on(t=>{this.box=this.query(`.${this.cssPrefix}list`),this.box.style.display="none",this.box.remove(),this.filterUpdateStatus=!0,this.bindNativeEvents()}),this.hooks.updated.on(()=>{this.uiState="normal"})}bindViewerResized(){const{viewer:t}=this.injection;t.hooks.resize.on(()=>{const{box:t}=this,e="none"===t.style.display,i=this.injection.viewer.rootDom;e?this.isFirstClick=!0:ub(i,this.el,this.box)},this)}bindViewerHooks(){const t=this.injection.viewer;t.hooks.pageChanged.on(async e=>{if(0===e.total)return this.filterUpdateStatus=!0,void this.togglePopup(!1);const i=t.context.getActiveTab();if(!i||!this.box)return;const{currentUid:n,oldCurrentUid:s}=i;s!==n&&(this.filterUpdateStatus=!0,this.togglePopup(!1))},this),t.hooks.updatePage.on(e=>{var i;const n=t.context.getActiveTab();n&&this.box&&(null===(i=n.getCurrentPage())||void 0===i?void 0:i.uid)===e.pageUid&&(this.filterUpdateStatus=!0,this.togglePopup(!1))},this),t.hooks.visibleChanged.on(t=>{"hidden"===t.newVisibility&&this.togglePopup(!1)},this)}bindNativeEvents(){const{el:t,box:e}=this,i=e.querySelector(`.${this.cssPrefix}list-header`),n=i.getElementsByTagName("span")[0],s=i.getElementsByTagName("div")[0];this.nativeOn(t,"click",async t=>{this.togglePopup(),this.isFirstClick&&(ub(this.injection.viewer.rootDom,this.el,this.box),this.isFirstClick=!1)}),this.nativeOn(e,"click",t=>{t.stopPropagation()}),this.nativeOn([n,s],"click",()=>{if(this.clickApplyToAll(),this.applyAll){const{viewer:t}=this.injection,e=t.getPageCounts(),i=t.getCurrentPageUid(),n=t.context.core.pageService.getPage(i);t.filter(Array.from(Array(e).keys()),n.filter)}})}bindFilterEvents(){this.$on("ui_filterClick",t=>{const{viewer:e}=this.injection,i=e.getPageCounts();if(i<1)return;let n=Array.from(Array(i).keys());if(!this.applyAll){const i=e.getCurrentPageUid();if(e.context.core.pageService.getPage(i).filter===t)return;n=[e.getCurrentPageIndex()]}e.filter(n,t)})}clickApplyToAll(t){const e=this.injection.viewer,i=ib.Filter_FilterAll+e.postfix,n=document.getElementById(i);if(Ps(t))return this.applyAll?n.classList.remove(`${this.cssPrefix}checked`):n.classList.add(`${this.cssPrefix}checked`),void(this.applyAll=!this.applyAll);t?n.classList.add(`${this.cssPrefix}checked`):n.classList.remove(`${this.cssPrefix}checked`),this.applyAll=t}async updateFilterPreview(){const t=this.injection.viewer,e=t.getCurrentPageUid(),i=await t.context.core.imageDataService.getOriginal(e);if(!i)return;this.$emit("ui_filterLoading",!0);const n=[],s=t.context.core.pageService.getPage(e);let o;try{o=await t.context.core.processService.resize(i.data,3,i.width,i.height,200)}catch(t){}for(let e=0;e<this.filterList.length;e++){const s=this.filterList[e];if("none"===s.type)n.push({type:"none",imageData:i.data});else{let e;try{var r;o&&null!==(r=o)&&void 0!==r&&r.data&&(e=await t.context.core.filterService.applyFilter({data:o.data,type:tr.JPEG,width:o.width,height:o.height},s.type))}catch(t){e=null}n.push({type:s.type,imageData:e})}}this.$emit("ui_filterLoading",!1),this.$emit("ui_filterReset",{currentFilter:s.filter||"none",filterList:n}),this.filterUpdateStatus=!1}initTemplate(){var t;const e=this.data,{options:i}=e,{popupBox:n,filterHeader:s,filterContent:o,valueList:r}=i,{filterService:a}=this.injection.viewer.context.core,l=ib.Filter_FilterAll+this.injection.viewer.postfix;pb(gb(this),this.injection.viewer,i);const h=(null===(t=MT.getDisplayTextConfig())||void 0===t?void 0:t.Filter_FilterAll)||"Apply to All";e.valueList=r||JS,a.enableFilter&&(e.valueList=a.getSupportedFilters()),this.filterList=e.valueList;const c=`<button ${GC(i,`ddv-button ${this.defaultClass}`)}>`+(Ps(null==i?void 0:i.label)?"":`<span>${i.label}</span>`)+'<i class="ddv-down-arrow"></i>'+`<div ${GC(n,this.cssPrefix,"list")}>`+`<div id="${l}"`+`${GC(s,this.cssPrefix,"list-header")}><div></div>`+`<span>${h}</span></div>`+`<div ${GC(o,this.cssPrefix,"list-content")}><FilterItem :for="item in valueList":options="options.filterItem" :itemValue="item"></FilterItem></div></div></button>`;this.template=c}async togglePopup(t){const{box:e}=this,{viewer:i}=this.injection;let n="none"===e.style.display;n=Ps(t)?!n:!t,n?e.remove():(this.$emit("ui_hidePopup",this),i.rootDom.appendChild(e),this.filterUpdateStatus&&this.updateFilterPreview()),db(this.el,!n),e.style.display=n?"none":""}bindDefaultUi(){const t=this.injection.viewer,e=()=>{let e="normal";0!==t.getPageCounts()&&this.enableFilter||(e="disabled"),yb(this,t)&&(e="disabled"),mb(this,e)};t.hooks.pageChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}Yi(KS,"cpName","Filter");class QS extends xb{constructor(t){super(t,{class:"ddv-button-blank",callback:()=>{}})}bindDefaultUi(){}}class tT extends xb{constructor(t){super(t,{class:"ddv-button-close",callback:()=>{}})}bindDefaultUi(){}}Yi(tT,"cpName","Close");class eT extends xb{constructor(t){super(t,{class:"ddv-button-back",callback:()=>{}})}bindDefaultUi(){}}Yi(eT,"cpName","Back");class iT extends xb{constructor(t){super(t,{class:"ddv-button-done",callback:()=>{}})}bindDefaultUi(){}}Yi(iT,"cpName","Done");const nT=[{displayName:"continuous",className:"ddv-continuous-mode"},{displayName:"single",className:"ddv-single-mode"}];class sT extends Cb{constructor(t){const{DisplayMode_ContinuousPage:e,DisplayMode_SinglePage:i}=MT.getDisplayTextConfig(),{DisplayMode_ContinuousPage:n,DisplayMode_SinglePage:s}=ib;t.data.options={showCheckIcon:!0,showDropDownArrow:!0,...t.data.options,children:[{type:"ContinuousPage",label:e,id:n},{type:"SinglePage",label:i,id:s}],defaultClassName:"ddv-display-mode"},super(t),hb(this)}updateUiState(t){const{el:e}=this;nT.forEach((i,n)=>{t===i.displayName?(e.classList.add(i.className),this.selectChildren(n)):e.classList.remove(i.className)})}bindDefaultUi(){super.bindDefaultUi();const t=this.injection.viewer,e=()=>{const{displayMode:e}=t.getViewerConfig(),i=t.context.getActiveTab();i?this.updateUiState(i.context.displayMode):this.updateUiState(e)};t.hooks.displayModeChanged.on(t=>{this.updateUiState(t.newDisplayMode)},this),t.hooks.openDocument.on(()=>{const e=t.context.getActiveTab();e&&this.updateUiState(e.context.displayMode)},this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}Yi(sT,"cpName","DisplayMode");class oT extends xb{constructor(t,e){super(t,{class:e.class,callback:()=>{this.injection.viewer.updateViewerConfig({displayMode:e.displayMode})}}),Yi(this,"displayMode",void 0),this.displayMode=e.displayMode,hb(this)}bindDefaultUi(){const t=this.injection.viewer,e=e=>{var i;const n=t.getActiveTab(),s=(null==e?void 0:e.pageCount)||t.getPageCounts(),o=(null==n||null===(i=n.context)||void 0===i?void 0:i.displayMode)||t.getViewerConfig().displayMode;s?o===this.displayMode?this.setUiState("focused"):this.setUiState("normal"):this.setUiState("disabled")};t.hooks.pageExistenceChanged.on(e,this),t.hooks.displayModeChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}class rT extends oT{constructor(t){super(t,{class:"ddv-continuous-mode",displayMode:"continuous"})}}Yi(rT,"cpName","ContinuousPage");class aT extends oT{constructor(t){super(t,{class:"ddv-multiple-mode",displayMode:"multiple"})}}Yi(aT,"cpName","MultiPage");class lT extends oT{constructor(t){super(t,{class:"ddv-single-mode",displayMode:"single"})}}Yi(lT,"cpName","SinglePage");const hT=[{displayName:"window",className:"ddv-fit-window"},{displayName:"width",className:"ddv-fit-width"},{displayName:"height",className:"ddv-fit-height"},{displayName:"actualSize",className:"ddv-fit-actual"}];class cT extends Cb{constructor(t){const{FitMode_FitWindow:e,FitMode_FitWidth:i,FitMode_FitHeight:n,FitMode_ActualSize:s}=MT.getDisplayTextConfig(),{FitMode_FitWindow:o,FitMode_FitWidth:r,FitMode_FitHeight:a,FitMode_ActualSize:l}=ib;t.data.options={showCheckIcon:!0,showDropDownArrow:!0,...t.data.options,children:[{type:"FitWindow",label:e,id:o},{type:"FitWidth",label:i,id:r},{type:"FitHeight",label:n,id:a},{type:"ActualSize",label:s,id:l}],defaultClassName:"ddv-fit-type"},super(t),hb(this)}updateUiState(t){const{el:e}=this;if("none"===t)return this.selectChildren(-1),hT.forEach(t=>{e.classList.remove(t.className)}),void e.classList.add(hT[0].className);hT.forEach((i,n)=>{t===i.displayName?(e.classList.add(i.className),this.selectChildren(n)):e.classList.remove(i.className)})}bindDefaultUi(){super.bindDefaultUi();const t=this.injection.viewer,e=()=>{const{fitMode:e}=t.getViewerConfig();this.updateUiState(e)};t.hooks.fitModeChanged.on(t=>{this.updateUiState(t.newFitMode)},this),t.hooks.openDocument.on(()=>{const e=t.context.getActiveTab();e&&this.updateUiState(e.context.fitMode)},this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}Yi(cT,"cpName","FitMode");class dT extends xb{constructor(t,e){super(t,{class:e.class,callback:()=>{const{viewer:t}=this.injection;t.updateViewerConfig({fitMode:e.fitMode})}}),Yi(this,"fitMode",void 0),this.fitMode=e.fitMode,hb(this)}bindDefaultUi(){const t=this.injection.viewer,e=()=>{const e=t.getPageCounts(),i=t.getActiveTab();let{fitMode:n}=t.getViewerConfig();i&&(n=i.context.fitMode);const s=e>0&&n===this.fitMode;e>0?s?this.setUiState("focused"):this.setUiState("normal"):this.setUiState("disabled")};t.hooks.pageExistenceChanged.on(e,this),t.hooks.fitModeChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}}class uT extends dT{constructor(t){super(t,{class:"ddv-fit-height",fitMode:"height"})}}Yi(uT,"cpName","FitHeight");class pT extends dT{constructor(t){super(t,{class:"ddv-fit-width",fitMode:"width"})}}Yi(pT,"cpName","FitWidth");class gT extends dT{constructor(t){super(t,{class:"ddv-fit-window",fitMode:"window"})}}Yi(gT,"cpName","FitWindow");class fT extends dT{constructor(t){super(t,{class:"ddv-fit-actual",fitMode:"actualSize"})}}Yi(fT,"cpName","ActualSize");class mT extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-main-canvas"),this.initTemplate(),this.bindHooks(),this.bindViewerHooks()}bindHooks(){const{inserted:t}=this.hooks;t.on(()=>{var t;null===(t=this.injection.viewer)||void 0===t||t.context.viewService.bindContainer(this.el)})}bindViewerHooks(){this.injection.viewer.hooks.toolModeChanged.on(()=>{this.$emit("ui_toolModeRefactor")},this)}initTemplate(){const{options:t}=this.data;t.id=t.id||`ddvMainView${this.injection.viewer.postfix}`;const e=`<div ${GC(t,this.defaultClass,"")} ><slot></slot></div>`;this.template=e}}Yi(mT,"cpName","MainView");class vT extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-pagination"),Yi(this,"cssPrefix",`${this.defaultClass}-`),Yi(this,"uiState","normal"),Yi(this,"input",void 0),Yi(this,"totalSpan",void 0),this.initTemplate(),this.bindHooks(),this.bindDefaultUi()}bindHooks(){this.hooks.created.on(t=>{this.bindEvents(),this.input=this.query(`.${this.cssPrefix}goto`),this.totalSpan=this.query(`.${this.cssPrefix}total`)})}bindEvents(){const t=this.injection.viewer,e=this.query(`.${this.cssPrefix}goto`);this.nativeOn(e,"input",t=>{const i=fb(e),n=Math.min(i,this.totalSpan.clientWidth);e.style.width=`${n}px`}),this.nativeOn(e,"blur",()=>{const i=t.getPageCounts(),n=t.getCurrentPageIndex();let s=parseInt(e.value,10);Ls(s)?s<1?s=1:s>i&&(s=i):s=n+1,e.value=`${s}`,e.style.width=`${fb(e)}px`,t.gotoPage(s-1)}),this.nativeOn(e,"keydown",t=>{t.stopPropagation(),"Enter"===t.key&&e.blur()})}setState(t){this.uiState!==t&&this.el&&("normal"===t?this.el.classList.remove(`${this.cssPrefix}disabled`):this.el.classList.add(`${this.cssPrefix}disabled`),this.uiState=t)}bindDefaultUi(){const t=this.injection.viewer,e=e=>{const i=Ps(null==e?void 0:e.total)?t.getPageCounts():null==e?void 0:e.total,n=Ps(null==e?void 0:e.current)?t.getCurrentPageIndex():null==e?void 0:e.current;this.setState(i>0?"normal":"disabled"),this.input.value=`${n+1}`,this.totalSpan.innerText=`${i}`,this.input.style.width=`${fb(this.input)}px`};t.hooks.pageChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(()=>{this.uiState="normal",e(null)})}initTemplate(){const{options:t}=this.data,{gotoPage:e,total:i,separator:n}=t,{cssPrefix:s,injection:o,defaultClass:r}=this,{viewer:a}=o,l=a.getCurrentPageIndex()+1,h=a.getPageCounts(),c=`<div ${GC(t,r,"")}><FirstPage :options="options.firstPage"></FirstPage><PrevPage :options="options.prevPage"></PrevPage><input ${GC(e,s,"goto")} value="${l}" type="number" ><div ${GC(n,s,"separator")}></div><span ${GC(i,s,"total")} >${h}</span><NextPage :options="options.nextPage"></NextPage><LastPage :options="options.lastPage"></LastPage></div>`;this.template=c}}Yi(vT,"cpName","Pagination");class yT extends xb{constructor(t,e){super(t,{class:e.class,callback:e.callback}),Yi(this,"type",void 0),this.type=e.type}bindDefaultUi(){const t=this.injection.viewer,e=()=>{const e=t.getPageCounts(),i=t.getCurrentPageIndex();let n=!1;switch(this.type){case"previous":case"first":n=e>0&&0!==i;break;case"last":case"next":n=i<e-1}0===e&&(n=!1),this.setUiState(n?"normal":"disabled")};this.hooks.inserted.on(e),this.hooks.updated.on(e),t.hooks.pageChanged.on(e,this)}}class xT extends yT{constructor(t){super(t,{class:"ddv-first-page",type:"first",callback:()=>{this.injection.viewer.gotoPage(0)}})}}Yi(xT,"cpName","FirstPage");class wT extends yT{constructor(t){super(t,{class:"ddv-last-page",type:"last",callback:()=>{const t=this.injection.viewer,e=t.getPageCounts();t.gotoPage(e-1)}})}}Yi(wT,"cpName","LastPage");class CT extends yT{constructor(t){super(t,{class:"ddv-next-page",type:"next",callback:()=>{const t=this.injection.viewer,e=t.getCurrentPageIndex();t.gotoPage(e+1)}})}}Yi(CT,"cpName","NextPage");class bT extends yT{constructor(t){super(t,{class:"ddv-prev-page",type:"previous",callback:()=>{const t=this.injection.viewer,e=t.getCurrentPageIndex();t.gotoPage(e-1)}})}}Yi(bT,"cpName","PrevPage");class ST extends xb{constructor(t){super(t,{class:"ddv-thumbnail-switch",callback:()=>{const{thumbnail:t}=this;if(!t)return;const{visibility:e}=t.getViewerConfig();t.updateViewerConfig({visibility:"visible"===e?"hidden":"visible"})}}),Yi(this,"thumbnail",void 0),this.injection.viewer.on("thumbnailBind",t=>{if(this.thumbnail)return;const e=this.injection.viewer.context.core.getViewer(t);e&&(this.thumbnail=e,this.bindThumbnailHooks(e));const{visibility:i}=e.getViewerConfig();this.setUiState("visible"===i?"focused":"normal",!Ms())}),this.injection.viewer.hooks.destroy.on(()=>{this.thumbnail=null},this)}bindThumbnailHooks(t){t.hooks.visibleChanged.on(t=>{this.setUiState("visible"===t.newVisibility?"focused":"normal",!Ms())},this)}bindDefaultUi(){const t=()=>{if(!this.thumbnail)return;const{visibility:t}=this.thumbnail.getViewerConfig();this.setUiState("visible"===t?"focused":"normal",!Ms())};this.injection.viewer.hooks.pageExistenceChanged.on(t,this),this.hooks.updated.on(t)}}Yi(ST,"cpName","ThumbnailSwitch");class TT extends xb{constructor(t,e){super(t,{class:e.class,callback:()=>{const t=this.injection.viewer;Ms()&&this.el.classList.contains("ddv-button-focused")&&"textSelection"===this.toolMode?t.updateViewerConfig({toolMode:"pan"}):t.updateViewerConfig({toolMode:e.toolMode})}}),Yi(this,"toolMode",void 0),this.toolMode=e.toolMode,this.bindViewerHooks()}bindDefaultUi(){const t=this.injection.viewer,e=()=>{const{toolMode:e}=t.getViewerConfig();t.getPageCounts()>0?e===this.toolMode?this.setUiState("focused"):this.setUiState("normal"):this.setUiState("disabled")};t.hooks.pageExistenceChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}bindViewerHooks(){const t=this.injection.viewer;t.hooks.toolModeChanged.on(e=>{const i=e.newToolMode===this.toolMode;t.getPageCounts()>0?i?this.setUiState("focused"):this.setUiState("normal"):this.setUiState("disabled")},this)}}class ET extends TT{constructor(t){super(t,{class:"ddv-pan-mode",toolMode:"pan"})}}Yi(ET,"cpName","Pan"),Yi(class extends TT{constructor(t){super(t,{class:"ddv-zoom-mode",toolMode:"zoomIn"})}},"cpName","ZoomMode");class _T extends TT{constructor(t){super(t,{class:"ddv-crop-mode",toolMode:"crop"})}}Yi(_T,"cpName","CropMode");class PT extends TT{constructor(t){super(t,{class:"ddv-text-selection-mode",toolMode:"textSelection"})}}Yi(PT,"cpName","TextSelectionMode");class AT extends xb{constructor(t){super(t,{class:"ddv-zoom-in",callback:()=>{this.injection.viewer.zoomIn()}}),this.bindViewerHooks(),hb(this)}bindViewerHooks(){const t=this.injection.viewer;t.hooks.zoomChanged.on(e=>{const{maxZoom:i}=t.getViewerConfig();t.getPageCounts()<1||e.newZoomRatio>=i?this.setUiState("disabled"):this.setUiState("normal"),yb(this,t)&&this.setUiState("disabled")},this)}}Yi(AT,"cpName","ZoomIn");class IT extends xb{constructor(t){super(t,{class:"ddv-zoom-out",callback:()=>{this.injection.viewer.zoomOut()}}),this.bindViewerHooks(),hb(this)}bindViewerHooks(){const t=this.injection.viewer;t.hooks.zoomChanged.on(e=>{const{minZoom:i}=t.getViewerConfig();t.getPageCounts()<1||e.newZoomRatio<=i?this.setUiState("disabled"):this.setUiState("normal"),yb(this,t)&&this.setUiState("disabled")},this)}}Yi(IT,"cpName","ZoomOut");class DT extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-zoom-controller"),XC.registerComponent({ZoomIn:AT,ZoomOut:IT}),this.initTemplate()}initTemplate(){const{options:t}=this.data;pb(gb(this),this.injection.viewer,t);const e=`<div ${GC(t,this.defaultClass)}><ZoomOut :options:"options.ZoomOut"></ZoomOut><ZoomByPercentage :options:"options.ZoomByPercentage"></ZoomByPercentage><ZoomIn :options:"options.ZoomIn"></ZoomIn></div>`;this.template=e}}Yi(DT,"cpName","Zoom");const RT=[10,25,50,75,100,125,150,200,400,800,1600,2400,3200,6400];class kT extends zC{constructor(t){super(t),Yi(this,"defaultClass","ddv-zoom-percentage"),Yi(this,"cssPrefix",`${this.defaultClass}-`),Yi(this,"isFirstClick",!0),Yi(this,"box",void 0),Yi(this,"uiState","normal"),Yi(this,"isRefactorCrop",!1),Yi(this,"isRefactorAnnotation",!1),this.initTemplate(),this.bindHooks(),this.bindDefaultUi(),this.bindViewerHooks(),this.bindViewerResized(),hb(this),ab(this),this.hooks.destroyed.on(()=>{this.dispose()}),this.$on("ui_layoutScroll",t=>{this.togglePopup(!1),this.isFirstClick=!0})}bindHooks(){this.hooks.created.on(t=>{this.box=this.query(`.${this.cssPrefix}box`),this.box.style.display="none",this.box.remove(),this.bindEvents()}),this.hooks.inserted.on(()=>{const t=this.injection.viewer,{zoom:e}=t.getViewerConfig();this.updateZoom(e),this.updateZoomOption()}),this.hooks.updated.on(()=>{this.uiState="normal",this.box.style.display="none",this.isFirstClick=!0})}bindDefaultUi(){const t=this.injection.viewer,e=()=>{let e=0===t.getPageCounts()?"disabled":"normal";yb(this,t)&&(e="disabled"),mb(this,e),this.updateZoom(t.getViewerConfig().zoom)};t.hooks.pageChanged.on(e,this),this.hooks.inserted.on(e),this.hooks.updated.on(e)}bindViewerHooks(){const{viewer:t}=this.injection,{hooks:e}=t;e.zoomChanged.on(t=>{this.updateZoom(t.newZoomRatio)},this),e.visibleChanged.on(e=>{if("hidden"===e.newVisibility)return void this.togglePopup(!1);const{zoom:i}=t.getViewerConfig();this.updateZoom(i)},this)}bindEvents(){const{el:t,box:e}=this,i=t.querySelector(`.${this.cssPrefix}selector`),n=t.getElementsByTagName("input")[0],s=e.getElementsByTagName("ul")[0];this.nativeOn(i,"click",()=>{const t=this.injection.viewer.rootDom;this.togglePopup(),this.isFirstClick&&(ub(t,this.el,this.box,!0,!0),this.isFirstClick=!1)}),this.inputEvent(n),this.ulEvent(s)}bindViewerResized(){const{viewer:t}=this.injection;t.hooks.resize.on(()=>{const{box:t}=this,e="none"===t.style.display,i=this.injection.viewer.rootDom;e?this.isFirstClick=!0:ub(i,this.el,this.box,!0,!0)},this)}inputEvent(t){const e=this.injection.viewer,{maxZoom:i,minZoom:n}=e.getViewerConfig();t.value=`${i}`;const s=fb(t);function o(){const s=t.value/100,o=Bs(s,n,i);e.updateViewerConfig({zoom:o})}this.nativeOn(t,"input",()=>{this.adaptInputWidth(s)}),this.nativeOn(t,"blur",o),this.nativeOn(t,"keydown",t=>{t.stopPropagation(),"Enter"===t.key&&o()})}ulEvent(t){this.nativeOn(t,"click",t=>{t.stopPropagation();const{viewer:e}=this.injection,{maxZoom:i,minZoom:n}=e.getViewerConfig(),s=t.target;if("LI"===s.tagName){const t=Bs(s.value,100*n,100*i);e.updateViewerConfig({zoom:t/100})}this.togglePopup(!1)})}getZoomOptionTemplate(){var t;const e=(null===(t=this.data.options)||void 0===t?void 0:t.valueList)||null,i=this.injection.viewer,{maxZoom:n,minZoom:s}=i.getViewerConfig(),o=Ts(e)?e:RT,r=s<1e-4?.01:parseFloat((100*s).toFixed(2)),a=Math.floor(100*n);o.push(r,a);const l=Array.from(new Set(o)).sort((t,e)=>t-e);let h="";return l.forEach(t=>{Ls(t)&&t<=100*n&&t>=100*s&&(h+=`<li value="${t}">${t}%</li>`)}),h}updateZoomOption(){const t=this.getZoomOptionTemplate();this.box.getElementsByTagName("ul")[0].innerHTML=t}updateZoom(t){const e=this.el.getElementsByTagName("input")[0],i=100*t;if(Number.isInteger(i))e.value=`${i}`;else{let t=i;t=t>=1e3?+t.toFixed(0).toString():t>=100?+t.toFixed(1).toString():t>=10?+t.toFixed(2).toString():+t.toFixed(3).toString(),e.value=`${t}`}this.adaptInputWidth()}initTemplate(){const{options:t={}}=this.data,{input:e,selector:i,popupBox:n}=t,{cssPrefix:s}=this,{viewer:o}=this.injection;pb(gb(this),o,t);const r=`<div ${GC(t,this.defaultClass)}><div style="display: flex"><div ${GC(e,s,"input")}><input type="number"><span>%</span></div><button ${GC(i,s,"selector")}></button></div><div ${GC({id:`ddvZoomByPercentageSelectBox${o.postfix}`,...n},s,"box")}><ul></ul></div></div>`;this.template=r}adaptInputWidth(t){const e=this.el.getElementsByTagName("input")[0];let i=fb(e);t&&i>t&&(i=t),e.style.width=`${i}px`}togglePopup(t){const{viewer:e}=this.injection,{box:i}=this;let n="none"!==i.style.display;n=Ps(t)?!n:t,n?(this.$emit("ui_hidePopup",this),e.rootDom.appendChild(i)):i.remove(),i.style.display=n?"":"none"}}Yi(kT,"cpName","ZoomByPercentage");class MT{static getTooltip(){return this.tooltip}static setTooltip(t){this.tooltip={...this.tooltip,...t}}static getDisplayTextConfig(){return this.displayTextConfig}static setDisplayTextConfig(t){this.displayTextConfig={...this.displayTextConfig,...t}}static registerAll(){XC.registerComponent({Capture:xS,Flashlight:wS,CameraConvert:CS,CameraResolution:SS,AutoDetect:yS,AutoCapture:vS,ImagePreview:TS,RotateLeft:YS,RotateRight:$S,Delete:RS,DeleteAll:_S,DeleteCurrent:PS,Zoom:DT,ZoomIn:AT,ZoomOut:IT,ZoomByPercentage:kT,PerspectiveAll:WS,FullQuad:HS,Restore:GS,Undo:XS,Redo:jS,FitMode:cT,FitWidth:pT,FitHeight:uT,FitWindow:gT,ActualSize:fT,DisplayMode:sT,SinglePage:lT,MultiPage:aT,ContinuousPage:rT,Pan:ET,Print:kS,Filter:KS,ThumbnailSwitch:ST,Back:eT,Done:iT,Pagination:vT,FirstPage:xT,LastPage:wT,NextPage:CT,PrevPage:bT,Root:QC,Layout:ZC,Button:qC,SwipeIndicator:eb,MainView:mT,Load:ES,Download:DS,Close:tT,Blank:QS,SeparatorLine:tb,PasswordLoader:MS,TextSearchPanel:BS,TextSearchPanelSwitch:NS,CropCurrent:US,CropAll:VS,CropMode:_T,Crop:qS,AnnotationSet:Fb,EllipseAnnotation:Tb,EraseAnnotation:Eb,InkAnnotation:_b,LineAnnotation:Pb,PolygonAnnotation:Ab,PolylineAnnotation:Ib,RectAnnotation:Db,SelectAnnotation:Rb,StampIconAnnotation:kb,StampImageAnnotation:Mb,TextBoxAnnotation:Lb,TextTypewriterAnnotation:Ob,HighlightAnnotation:Bb,UnderlineAnnotation:Nb,StrikeoutAnnotation:Ub,BasePullDownButton:wb,PullDownListButton:Cb,PullDownMenuButton:bb,BringForward:Hb,BringToFront:jb,SendBackward:zb,SendToBack:Gb,TextSelectionMode:PT,AnnotationToolBar:Yb,AnnotationDeleteButton:qb,AnnotationPaletteButton:Xb,AnnotationPalette:hS,AnnotationCustomStampPanel:dS,HighlightCreateButton:pS,StrikeoutCreateButton:gS,UnderlineCreateButton:fS,TextCopyButton:mS})}}Yi(MT,"tooltip",{}),Yi(MT,"displayTextConfig",{FitMode_FitWidth:"Fit Width",FitMode_FitHeight:"Fit Height",FitMode_FitWindow:"Fit Window",FitMode_ActualSize:"Actual Size",DisplayMode_SinglePage:"Single Page",DisplayMode_ContinuousPage:"Continuous Page",Crop_CropAll:"Crop All",Crop_CropCurrent:"Crop Current",Crop_CropCancel:"Cancel",Crop_CropApply:"Apply",Filter_FilterAll:"Apply to All",Delete_DeleteCurrent:"Delete current",Delete_DeleteAll:"Delete all",CameraResolution_720P:"720P",CameraResolution_1080P:"1080P",CameraResolution_1440P:"1440P",CameraResolution_2160P:"2160P"});const LT={install(t){const e=function(t){var e,i,n,s;return e=new WeakMap,i=new WeakMap,n=new WeakMap,s=new WeakSet,class extends t{constructor(t){super(t),an(this,s),Yi(this,"ui",void 0),Yi(this,"rootDom",void 0),Yi(this,"popupConfig",null),rn(this,e,{writable:!0,value:!1}),rn(this,i,{writable:!0,value:0}),rn(this,n,{writable:!0,value:0}),MT.registerAll();const{popupConfig:o}=t,r=t.viewerConfig.enablePopup?this.getPopupUiConfig({annotationToolBarConfig:(null==o?void 0:o.annotationToolBarConfig)||{},annotationPaletteConfig:(null==o?void 0:o.annotationPaletteConfig)||{},annotationCustomStampPanelConfig:(null==o?void 0:o.annotationCustomStampPanelConfig)||{},passwordLoaderConfig:(null==o?void 0:o.passwordLoaderConfig)||{}}):[];this.popupConfig=null==t?void 0:t.popupConfig,this.ui=new XC({container:t.container,emitter:this.emitter,postfix:this.uid,uiConfig:t.uiConfig,popupUiConfig:r,injection:{viewer:this}}),t.container&&(t.uiConfig?(this.bindContainer(t.container),this.rootDom=this.ui.rootDom):this.rootDom=this.context.viewService.rootDom),this.hooks.uiInitCompleted.emit(),this.listenNativeEventsForUi()}listenNativeEventsForUi(){this.on("click",()=>{this.emit("ui_hidePopup","viewer")})}getPopupUiConfig(t){const e={enabled:!0,isPaletteEnabled:!0,...t.annotationToolBarConfig,type:"AnnotationToolBar"},i={enabled:!0,colorList:["#F01314","#FD7C10","#FFEE5F","#07C37F","#0E68F5","#9D3BFE","#000000","#FF9494","#87440C","#B7A514","#046743","#50C9FF","#EBA3ED","#FFFFFF","#CECECE"],enableChangeColor:!0,enableDrag:!0,autoDisplay:!0,enableCustomStamp:!1,...t.annotationPaletteConfig,type:"AnnotationPalette"},n={labels:{stampText:"Stamp Text",fontStyle:"Font Style",textColor:"TextColor",backgroundColor:"Background",borderColor:"BorderColor",timeStampText:"Timestamp Text",userName:"Username",date:"Date",time:"Time",create:"Create"},colorList:["#fdcccc","#f7fc7b","#c7d2e4","#d6e4cd","#910f05","#d5b142","#182564","#416a1c","#ffffff","#000000"],enabled:!1,autoDisplay:!0,...t.annotationCustomStampPanelConfig,type:"AnnotationCustomStampPanel"},s={enabled:!0,...t.passwordLoaderConfig,type:"PasswordLoader"},o=[],r="default"===this.getViewerConfig().viewerMode;return e.enabled&&r&&o.push(e),i.enabled&&r?o.push(i):e.isPaletteEnabled=!1,n.enabled&&r&&o.push(n),s.enabled&&o.push(s),o}addFontToUi(t){this.emit("ui_addFont",t)}toggleUiPopup(t,e){this.ui.emit("ui_changePalette_visible",t,e)}getUiConfig(){return _s(this.ui.uiConfig)}updateUiConfig(t){const{resizeService:i}=this.context.core;i&&(i.unobserve(this.ui.rootDom),Xi(this,e,!1));const n=this.ui.updateUiConfig(t);return this.rootDom=this.ui.rootDom,this.context.viewService.rootDom=this.rootDom,sn(this,s,o).call(this,this.ui.rootDom),n}getElementsByType(t){return Os(t)?this.ui.getElementsByType(this.ui.rootVNode,t):""}bindContainer(t){let e=t;return Os(t)&&(e=document.querySelector(`#${t}`)),e instanceof HTMLElement&&(sn(this,s,o).call(this,this.ui.rootDom),this.ui.bindContainer(e),this.context.viewService.container=e,this.context.viewService.rootDom=this.ui.rootDom,this.rootDom=this.ui.rootDom,"hidden"===this.context.viewerConfig.visibility&&(this.context.viewService.rootDom.style.display="none"),this.context.viewService.isBindContainer=!0,!0)}unbindContainer(){this.rootDom&&this.ui.container&&(this.ui.unbindContainer(),this.context.viewService.container=null,this.context.viewService.isBindContainer=!1)}dispose(){var t;super.dispose(),null===(t=this.ui)||void 0===t||t.dispose()}};function o(t){if($i(this,e))return;const{resizeService:s}=this.context.core;s.observe(t),this.register(s.onResizeObserver.on(e=>{if(e.target===t){var s;let o=0,r=0;if((null===(s=e.borderBoxSize)||void 0===s?void 0:s.length)>0){const t=e.borderBoxSize[0];o=t.inlineSize,r=t.blockSize}else o=t.offsetWidth,r=t.offsetHeight;const a=qf.create($i(this,i),$i(this,n),o,r);Xi(this,i,o),Xi(this,n,r),this.hooks.resize.emit(a)}})),this.hooks.destroy.on(()=>{s.unobserve(t)},this),Xi(this,e,!0)}}(t.getClass("Viewer"));t.setClass("Viewer",e)}};function OT(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function BT(t,e,i,n,s){if("function"==typeof e||!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const NT="undefined"==typeof self;let UT,FT,VT,WT,HT;function jT(t,e,i,n){if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function zT(t,e,i,n,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s?s.value=i:e.set(t,i),i}"undefined"!=typeof navigator&&(UT=navigator,FT=UT.userAgent,VT=UT.platform,WT=UT.mediaDevices),function(){if(!NT){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",n=0,s="unknownOS";for(let e in t){const s=t[e]||{};let o=s.str||FT,r=s.search||e,a=s.verStr||FT,l=s.verSearch||e;if(l instanceof Array||(l=[l]),-1!=o.indexOf(r)){i=e;for(let t of l){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||FT,o=i.search||t;if(-1!=n.indexOf(o)){s=t;break}}"Linux"==s&&-1!=FT.indexOf("Windows NT")&&(s="HarmonyOS"),HT={browser:i,version:n,OS:s}}NT&&(HT={browser:"ssr",version:0,OS:"ssr"})}(),WT&&WT.getUserMedia,"Chrome"===HT.browser&&HT.version>66||"Safari"===HT.browser&&HT.version>13||"OPR"===HT.browser&&HT.version>43||"Edge"===HT.browser&&HT.version,"function"==typeof SuppressedError&&SuppressedError;class GT{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const s=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*s[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return GT.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return GT.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return GT.multiply(t,[e,0,0,0,i,0,0,0,1])}}var YT,$T,XT,qT,ZT,JT,KT,QT,tE,eE,iE,nE,sE,oE,rE,aE,lE,hE,cE,dE,uE,pE,gE,fE,mE,vE,yE,xE,wE,CE,bE,SE,TE,EE,_E,PE,AE,IE,DE,RE,kE,ME,LE,OE,BE,NE,UE,FE,VE,WE,HE,jE;!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"}(YT||(YT={}));class zE{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(zT(zE,$T,!1,0,XT),!1):(zT(zE,$T,!0,0,XT),!0)}get disposed(){return jT(this,tE,"f")}constructor(){qT.set(this,YT.RGBA),ZT.set(this,null),JT.set(this,null),KT.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,QT.set(this,null),tE.set(this,!1)}drawImage(t,e,i,n,s,o){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==jT(zE,$T,"f",XT)&&zE.checkWebGLSupport(),(null==o?void 0:o.bUseWebGL)&&!jT(zE,$T,"f",XT))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 r;zE._onLog&&(r=Date.now(),zE._onLog("drawImage(), START: "+r));let a=0,l=0,h=i,c=n,d=0,u=0,p=i,g=n;s&&(s.sx&&(a=Math.round(s.sx)),s.sy&&(l=Math.round(s.sy)),s.sWidth&&(h=Math.round(s.sWidth)),s.sHeight&&(c=Math.round(s.sHeight)),s.dx&&(d=Math.round(s.dx)),s.dy&&(u=Math.round(s.dy)),s.dWidth&&(p=Math.round(s.dWidth)),s.dHeight&&(g=Math.round(s.dHeight)));let f,m=YT.RGBA;if((null==o?void 0:o.pixelFormat)&&(m=o.pixelFormat),(null==o?void 0:o.bufferContainer)&&(f=o.bufferContainer,f.length<4*p*g))throw new Error("Unexpected size of the 'bufferContainer'.");const v=t;if(!jT(zE,$T,"f",XT)||!(this.useWebGLByDefault&&null==(null==o?void 0:o.bUseWebGL)||(null==o?void 0:o.bUseWebGL))){zE._onLog&&zE._onLog("drawImage() in context2d."),v.ctx2d||(v.ctx2d=v.getContext("2d",{willReadFrequently:!0}));const t=v.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(v.width<d+p||v.height<u+g)&&(v.width=d+p,v.height=u+g),t.drawImage(e,a,l,h,c,d,u,p,g),zE._onLog&&zE._onLog("drawImage() in context2d end. Costs: "+(Date.now()-r)),{context:t,pixelFormat:YT.RGBA,bUseWebGL:!1}}zE._onLog&&zE._onLog("drawImage() in WebGL.");try{(v.width<d+p||v.height<u+g)&&(v.width=d+p,v.height=u+g,v.ctxWebGL&&v.ctxWebGL.viewport(0,0,d+p,u+g));const t=v.ctxWebGL||v.getContext("webgl",{antialias:!1})||v.getContext("experimental-webgl",{antialias:!1});if(!t){zE._onLog&&zE._onLog("Browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");const t=new Error("Unable to get 'WebGLRenderingContext'. Your browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");throw t.name="WebGLError",t}if(!v.ctxWebGL||m!==jT(this,qT,"f")){v.ctxWebGL=t;const e=t=>{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},n=(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},s=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},o="\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 r="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(m)&&(r=m.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.${r} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n                  }\n              `,l=n(t,[s(t,t.VERTEX_SHADER,o),s(t,t.FRAGMENT_SHADER,a)]);zT(this,JT,{program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}}),zT(this,KT,e(t)),zT(this,ZT,i(t)),zT(this,qT,m)}const s=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},o=(t,e,i)=>{const n=t.RGBA,s=t.RGBA,o=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,s,o,i)},y=(t,e,o,r)=>{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),s(t,o.positions,e.attribLocations.vertexPosition),s(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,r),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[YT.GREY,YT.GREY32].includes(m)?1:0);let f,v,y=GT.translate(GT.identity(),-1,-1);y=GT.scale(y,2,2),y=GT.scale(y,1/t.canvas.width,1/t.canvas.height),f=GT.translate(y,d,u),f=GT.scale(f,p,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,f),v=GT.translate(GT.identity(),a/i,l/n),v=GT.scale(v,h/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};o(t,jT(this,ZT,"f"),e),y(t,jT(this,JT,"f"),jT(this,KT,"f"),jT(this,ZT,"f"));const x=f||new Uint8Array(4*p*g);if(t.readPixels(d,u,p,g,t.RGBA,t.UNSIGNED_BYTE,x),255!==x[3]){zE._onLog&&zE._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return zE._onLog&&zE._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-r)),{context:t,pixelFormat:m===YT.GREY?YT.GREY32:m,bUseWebGL:!0}}catch(r){if(this.forceLoseContext(),null==(null==o?void 0:o.bUseWebGL))return zE._onLog&&zE._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,s,Object.assign({},o,{bUseWebGL:!1}));throw r.name="WebGLError",r}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,s=0,o=0,r=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(s=e.x),e.y&&(o=e.y),e.width&&(r=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*r*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(s,o,r,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*r*a)):(n=new Uint8Array(4*r*a),e.readPixels(s,o,r,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(s,o,r,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let s,o;if(zE._onLog&&(s=Date.now(),zE._onLog("transformPixelFormat(), START: "+s)),e===i)return zE._onLog&&zE._onLog("transformPixelFormat() end. Costs: "+(Date.now()-s)),n?new Uint8Array(t):t;const r=[YT.RGBA,YT.RBGA,YT.GRBA,YT.GBRA,YT.BRGA,YT.BGRA];if(r.includes(e))if(i===YT.GREY){o=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4){const i=.21*t[e]+.71*t[e+1]+.07*t[e+2];o[e/4]=i}}else if(i===YT.GREY32){o=n?new Uint8Array(t):t;for(let e=0;e<t.length;e+=4){const i=.21*t[e]+.71*t[e+1]+.07*t[e+2];o[e]=i,o[e+1]=i,o[e+2]=i}}else{if(!r.includes(i))throw new Error("Unable to transform.");if(n){o=new Uint8Array(t);const n=e.indexOf("r"),s=e.indexOf("g"),r=e.indexOf("b"),a=i.indexOf("r"),l=i.indexOf("g"),h=i.indexOf("b");for(let e=0;e<t.length;e+=4)o[e+a]=t[e+n],o[e+l]=t[e+s],o[e+h]=t[e+r]}else{o=t;const n=e.indexOf("r"),s=e.indexOf("g"),r=e.indexOf("b"),a=i.indexOf("r"),l=i.indexOf("g"),h=i.indexOf("b");for(let e=0;e<t.length;e+=4){let i=[t[e],t[e+1],t[e+2]];o[e+a]=i[n],o[e+l]=i[s],o[e+h]=i[r]}}}else if(e===YT.GREY){if(i!==YT.GREY32)throw new Error("Unable to transform.");o=new Uint8Array(4*t.length);for(let e=0;e<t.length;e++)o[4*e]=t[e],o[4*e+1]=t[e],o[4*e+2]=t[e],o[4*e+3]=255}else{if(e!==YT.GREY32)throw new Error("Unable to transform.");if(i!==YT.GREY)throw new Error("Unable to transform.");o=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4)o[e/4]=t[e]}return zE._onLog&&zE._onLog("transformPixelFormat() end. Costs: "+(Date.now()-s)),o}getImageData(t,e,i,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!e||!i)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==jT(zE,$T,"f",XT)&&zE.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!jT(zE,$T,"f",XT))throw new Error("Your browser or machine may not support WebGL.");if(n.sx>e||n.sy>i||n.sx+n.sWidth>e||n.sy+n.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 o;zE._onLog&&(o=Date.now(),zE._onLog("getImageData(), START: "+o));const r=Math.round(n.sx),a=Math.round(n.sy),l=Math.round(n.sWidth),h=Math.round(n.sHeight),c=Math.round(n.dWidth),d=Math.round(n.dHeight);let u=YT.RGBA;(null==s?void 0:s.pixelFormat)&&(u=s.pixelFormat);let p,g,f,m=null;if((null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer),jT(zE,$T,"f",XT)&&(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){zE._onLog&&zE._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),p=this._reusedWebGLCvs;try{if(m)if(u===YT.GREY){if(f=new Uint8Array(4*c*d),g=this.drawImage(p,t,e,i,{sx:r,sy:a,sWidth:l,sHeight:h,dWidth:c,dHeight:d},{pixelFormat:u,bUseWebGL:!0,bufferContainer:f}),f=this.transformPixelFormat(f,g.pixelFormat,u),m){if(m.length<f.length)throw new Error("Unexpected size of the 'bufferContainer'.");m.set(f)}}else g=this.drawImage(p,t,e,i,{sx:r,sy:a,sWidth:l,sHeight:h,dWidth:c,dHeight:d},{pixelFormat:u,bUseWebGL:!0,bufferContainer:m}),f=new Uint8Array(m.buffer,0,4*c*d),f=this.transformPixelFormat(f,g.pixelFormat,u);else u===YT.GREY?((!jT(this,QT,"f")||jT(this,QT,"f").length<4*c*d)&&zT(this,QT,new Uint8Array(4*c*d)),f=new Uint8Array(jT(this,QT,"f").buffer,0,4*c*d)):f=new Uint8Array(4*c*d),g=this.drawImage(p,t,e,i,{sx:r,sy:a,sWidth:l,sHeight:h,dWidth:c,dHeight:d},{pixelFormat:u,bUseWebGL:!0,bufferContainer:f}),f=this.transformPixelFormat(f,g.pixelFormat,u)}catch(n){if("WebGLError"===n.name&&(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL)))return zE._onLog&&zE._onLog("getImageData() in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.getImageData(t,e,i,{sx:r,sy:a,sWidth:l,sHeight:h,dWidth:c,dHeight:d},Object.assign({},s,{bUseWebGL:!1}));throw n}}else if(zE._onLog&&zE._onLog("getImageData() in context2d."),this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),p=this._reusedCvs,g=this.drawImage(p,t,e,i,{sx:r,sy:a,sWidth:l,sHeight:h,dWidth:c,dHeight:d},{pixelFormat:YT.RGBA,bUseWebGL:!1}),f=this.readCvsData(g.context,{width:c,height:d},null),f=this.transformPixelFormat(f,g.pixelFormat,u),m){if(m.length<f.length)throw new Error("Unexpected size of the 'bufferContainer'.");m.set(f)}return zE._onLog&&zE._onLog("getImageData() end. Costs: "+(Date.now()-o)),{data:f,pixelFormat:u,width:c,height:d,bUseWebGL:g.bUseWebGL}}convertDataToCvs(t,e,i,n){if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new TypeError("Invalid 'data'.");if("number"!=typeof e||e<=0)throw new Error("Invalid 'width'.");if("number"!=typeof i||i<=0)throw new Error("Invalid 'height'.");const s=document.createElement("canvas");let o;if(s.width=e,s.height=i,n===YT.GREY){o=new Uint8ClampedArray(4*e*i);for(let e=0;e<o.length;e+=4)o[e]=t[e/4],o[e+1]=t[e/4],o[e+2]=t[e/4],o[e+3]=255}else o=new Uint8ClampedArray(t.buffer);const r=new ImageData(o,e,i);return s.getContext("2d").putImageData(r,0,0),s}forceLoseContext(){if(!this._reusedWebGLCvs)return;const t=this._reusedWebGLCvs.ctxWebGL;t&&!t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").loseContext(),zT(this,ZT,null),zT(this,JT,null),zT(this,KT,null),this._reusedWebGLCvs=null}dispose(){this.forceLoseContext(),zT(this,tE,!0)}}$T=zE,qT=new WeakMap,ZT=new WeakMap,JT=new WeakMap,KT=new WeakMap,QT=new WeakMap,tE=new WeakMap,XT={value:void 0};class GE{constructor(){eE.set(this,new Map),iE.set(this,!1)}get disposed(){return OT(this,iE,"f")}on(t,e){t=t.toLowerCase();const i=OT(this,eE,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else OT(this,eE,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=OT(this,eE,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=OT(this,eE,"f").get(t);e&&(e.length=0)}fire(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{async:!1,copy:!0};e||(e=[]),t=t.toLowerCase();const n=OT(this,eE,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let s of n){if(!s)continue;let o=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}o.push(i)}else o=e;let r=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(s)&&s.apply(i.target,o)},0);else try{r=s.apply(i.target,o)}catch(t){}if(!0===r)break}}}dispose(){BT(this,iE,!0)}}eE=new WeakMap,iE=new WeakMap;const YE=(t,e,i,n)=>{if(!i)return t;let s=e+Math.round((t-e)/i)*i;return n&&(s=Math.min(s,n)),s};class $E{static get version(){return"2.0.12"}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"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","ç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"],s=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!s.length)return null;const o=s.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(o)return o.deviceId;const r=s.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return r?r.deviceId:s[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(HT.OS))return $E.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(HT.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(n,s)=>{let o;const r=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",d),t.removeEventListener("play",u),t.removeEventListener("error",p),t.removeEventListener("loadedmetadata",m)};let a=!1;const l=()=>{a=!0,o&&clearTimeout(o),r(),n(t)},h=t=>{o&&clearTimeout(o),r(),s(t)},c=()=>{t.addEventListener("abort",d,{once:!0})},d=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",h(t)},u=()=>{l()},p=()=>{h(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const f=new Promise(t=>{g=t}),m=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",u,{once:!0}),t.addEventListener("error",p,{once:!0}),t.addEventListener("loadedmetadata",m,{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&&(o=setTimeout(()=>{r(),s(new Error("Failed to play video. Timeout."))},i));try{t.src&&await t.load(),await t.play(),l()}catch(t){}if(!a){await f;try{await t.play(),l()}catch(t){h(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 n;try{n=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==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!OT(this,mE,"f"))return"closed";if("pending"===OT(this,mE,"f"))return"opening";if("fulfilled"===OT(this,mE,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t&&$E.isStorageAvailable("localStorage")?BT(this,uE,!0):BT(this,uE,!1)}get ifSaveLastUsedCamera(){return OT(this,uE,"f")}get isVideoPlaying(){return!(!OT(this,oE,"f")||OT(this,oE,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=OT(this,bE,"f"))||void 0===e||e.removeEventListener("click",OT(this,CE,"f")),null===(i=OT(this,bE,"f"))||void 0===i||i.removeEventListener("touchend",OT(this,CE,"f")),null===(n=OT(this,bE,"f"))||void 0===n||n.removeEventListener("touchmove",OT(this,wE,"f")),BT(this,bE,t),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(HT.OS)?(t.addEventListener("touchend",OT(this,CE,"f")),t.addEventListener("touchmove",OT(this,wE,"f"))):t.addEventListener("click",OT(this,CE,"f")))}get tapFocusEventBoundEl(){return OT(this,bE,"f")}get disposed(){return OT(this,RE,"f")}constructor(t){var e,i;sE.add(this),oE.set(this,null),rE.set(this,void 0),aE.set(this,()=>{"opened"===this.state&&OT(this,_E,"f").fire("resumed",null,{target:this,async:!1})}),lE.set(this,()=>{OT(this,_E,"f").fire("paused",null,{target:this,async:!1})}),hE.set(this,void 0),cE.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],dE.set(this,void 0),uE.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,pE.set(this,void 0),gE.set(this,!0),fE.set(this,void 0),mE.set(this,void 0),vE.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},yE.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const s=window.getComputedStyle(OT(this,oE,"f")).objectFit,o=this.getResolution(),r=OT(this,oE,"f").getBoundingClientRect(),a=r.left,l=r.top,{width:h,height:c}=OT(this,oE,"f").getBoundingClientRect();if(h<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const d=h/c,u=o.width/o.height;let p=1;if("contain"===s)u>d?(p=h/o.width,i=(t-a)/p,n=(e-l-(c-h/u)/2)/p):(p=c/o.height,n=(e-l)/p,i=(t-a-(h-c*u)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");u>d?(p=c/o.height,n=(e-l)/p,i=(t-a+(c*u-h)/2)/p):(p=h/o.width,i=(t-a)/p,n=(e-l+(h/u-c)/2)/p)}return{x:i,y:n}},xE.set(this,!1),wE.set(this,()=>{BT(this,xE,!0)}),CE.set(this,async t=>{var e;if(OT(this,xE,"f"))return void BT(this,xE,!1);if(!OT(this,yE,"f"))return;if(!this.isVideoPlaying)return;if(!OT(this,rE,"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,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const s=this.getResolution(),o=2*Math.round(Math.min(s.width,s.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let r;try{r=this.calculateCoordInVideo(i,n)}catch(t){}if(r.x<0||r.x>s.width||r.y<0||r.y>s.height)return;const a={x:r.x+"px",y:r.y+"px"},l=o+"px",h=l;let c;$E._onLog&&(c=Date.now());try{await OT(this,sE,"m",WE).call(this,a,l,h,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if($E._onLog)throw $E._onLog(t),t}$E._onLog&&$E._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;$E._onLog&&$E._onLog("Back to continuous focus."),null===(t=OT(this,rE,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),OT(this,_E,"f").fire("tapfocus",null,{target:this,async:!1})}),bE.set(this,null),SE.set(this,1),TE.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!OT(this,oE,"f"))return;const t=OT(this,SE,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)OT(this,oE,"f").style.transform="";else{const e=window.getComputedStyle(OT(this,oE,"f")).objectFit,i=OT(this,oE,"f").videoWidth,n=OT(this,oE,"f").videoHeight,{width:s,height:o}=OT(this,oE,"f").getBoundingClientRect();if(s<=0||o<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const r=s/o,a=i/n;let l=1;"contain"===e?l=r<a?s/(i/t):o/(n/t):"cover"===e&&(l=a>r?o/(i/t):s/(n/t));const h=l*(1-1/t)*(i/2-OT(this,TE,"f").x),c=l*(1-1/t)*(n/2-OT(this,TE,"f").y);OT(this,oE,"f").style.transform=`translate(${h}px, ${c}px) scale(${t})`}},EE.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===YT.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t<e.length;t+=4)e[t]=this.data[t/4],e[t+1]=this.data[t/4],e[t+2]=this.data[t/4],e[t+3]=255}else e=new Uint8ClampedArray(this.data.buffer);const i=new ImageData(e,this.width,this.height);return t.getContext("2d").putImageData(i,0,0),t}),_E.set(this,void 0),PE.set(this,["before:open","opened","before:close","closed","before:camera:change","camera:changed","before:resolution:change","resolution:changed","played","paused","resumed","tapfocus"]),this.detectedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],AE.set(this,new Map),IE.set(this,!1),DE.set(this,async()=>{var t,e;if("visible"===document.visibilityState){if($E._onLog&&$E._onLog("document visible. video paused: "+(null===(t=OT(this,oE,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){$E._onLog&&$E._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){$E._onLog&&$E._onLog("document visible. 1st resume video failed, try open instead.")}e||await OT(this,sE,"m",BE).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){$E._onLog&&$E._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){$E._onLog&&$E._onLog("document visible. 2rd resume video failed, try open instead.")}e||await OT(this,sE,"m",BE).call(this)}}}else"hidden"===document.visibilityState&&($E._onLog&&$E._onLog("document hidden. video paused: "+(null===(e=OT(this,oE,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),RE.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(()=>{$E.onWarning&&$E.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),BT(this,_E,new GE),this.imageDataGetter=new zE,document.addEventListener("visibilitychange",OT(this,DE,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",OT(this,aE,"f")),t.addEventListener("pause",OT(this,lE,"f")),BT(this,oE,t)}getVideoEl(){return OT(this,oE,"f")}releaseVideoEl(){var t,e;null===(t=OT(this,oE,"f"))||void 0===t||t.removeEventListener("play",OT(this,aE,"f")),null===(e=OT(this,oE,"f"))||void 0===e||e.removeEventListener("pause",OT(this,lE,"f")),BT(this,oE,null)}isVideoLoaded(){return!!OT(this,oE,"f")&&4==OT(this,oE,"f").readyState}async open(){if(OT(this,fE,"f")&&!OT(this,gE,"f")){if("pending"===OT(this,mE,"f"))return OT(this,fE,"f");if("fulfilled"===OT(this,mE,"f"))return}OT(this,_E,"f").fire("before:open",null,{target:this}),await OT(this,sE,"m",BE).call(this),OT(this,_E,"f").fire("played",null,{target:this,async:!1}),OT(this,_E,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;OT(this,_E,"f").fire("before:close",null,{target:this});const t=OT(this,fE,"f");if(OT(this,sE,"m",UE).call(this),t&&"pending"===OT(this,mE,"f")){try{await t}catch(t){}if(!1===OT(this,gE,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}BT(this,fE,null),BT(this,mE,null),OT(this,_E,"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.");OT(this,oE,"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 OT(this,oE,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof OT(this,hE,"f").video&&(OT(this,hE,"f").video={}),delete OT(this,hE,"f").video.facingMode,OT(this,hE,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&OT(this,gE,"f"))){OT(this,_E,"f").fire("before:camera:change",[],{target:this,async:!1}),await OT(this,sE,"m",NE).call(this);try{this.resetSoftwareScale()}catch(t){}return OT(this,cE,"f")}}async switchToFrontCamera(t){if("object"!=typeof OT(this,hE,"f").video&&(OT(this,hE,"f").video={}),(null==t?void 0:t.resolution)&&(OT(this,hE,"f").video.width={ideal:t.resolution.width},OT(this,hE,"f").video.height={ideal:t.resolution.height}),delete OT(this,hE,"f").video.deviceId,OT(this,hE,"f").video.facingMode={exact:"user"},BT(this,dE,null),!("closed"===this.state||this.videoSrc||"opening"===this.state&&OT(this,gE,"f"))){OT(this,_E,"f").fire("before:camera:change",[],{target:this,async:!1}),OT(this,sE,"m",NE).call(this);try{this.resetSoftwareScale()}catch(t){}return OT(this,cE,"f")}}getCamera(){var t;if(OT(this,cE,"f"))return OT(this,cE,"f");{let e=(null===(t=OT(this,hE,"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 n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const s=[],o=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&o.push(t);for(let t=0;t<n.length;t++){let e,i=n[t];for(let t of o)if(i.deviceId==t.deviceId){e=t;break}e||(e={deviceId:i.deviceId,label:i.label?i.label:"camera "+t,_checked:!1}),e.deviceId&&s.push(e)}return this._arrCameras=s,$E._onLog&&$E._onLog(JSON.stringify(this._arrCameras)),s}async getCameras(){var t,e;if(!(null===(e=null===(t=null===window||void 0===window?void 0:window.navigator)||void 0===t?void 0:t.mediaDevices)||void 0===e?void 0:e.enumerateDevices))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");const i=(await navigator.mediaDevices.enumerateDevices()).filter(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 OT(this,hE,"f").video&&(OT(this,hE,"f").video={}),i?(OT(this,hE,"f").video.width={exact:t},OT(this,hE,"f").video.height={exact:e}):(OT(this,hE,"f").video.width={ideal:t},OT(this,hE,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&OT(this,gE,"f"))return null;OT(this,_E,"f").fire("before:resolution:change",[],{target:this,async:!1}),await OT(this,sE,"m",NE).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&OT(this,oE,"f"))return{width:OT(this,oE,"f").videoWidth,height:OT(this,oE,"f").videoHeight};if(OT(this,rE,"f")){const t=OT(this,rE,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:OT(this,oE,"f").videoWidth,height:OT(this,oE,"f").videoHeight};{const t={width:0,height:0};let e=OT(this,hE,"f").video.width||0,i=OT(this,hE,"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,n,s,o,r,a,l,h,c,d;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 u="";const p=(t,e)=>{const i=OT(this,AE,"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){u=null===(d=OT(this,cE,"f"))||void 0===d?void 0:d.deviceId;let e=OT(this,AE,"f").get(u);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],OT(this,AE,"f").set(u,e),BT(this,vE,!0);try{for(let t of this.detectedResolutions){await OT(this,rE,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),OT(this,sE,"m",ME).call(this);const i=OT(this,rE,"f").getSettings(),n={width:i.width,height:i.height};p(u,n)||e.push({width:n.width,height:n.height})}}catch(t){throw OT(this,sE,"m",UE).call(this),BT(this,vE,!1),t}try{await OT(this,sE,"m",BE).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{BT(this,vE,!1)}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let s=null;try{s=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!s)return null;const o=s.getVideoTracks();let r=null;try{const t=o[0].getSettings();r={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=s,r={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return o.forEach(t=>{t.stop()}),r};let i=(null===(o=null===(s=null===(n=OT(this,hE,"f"))||void 0===n?void 0:n.video)||void 0===s?void 0:s.deviceId)||void 0===o?void 0:o.exact)||(null===(l=null===(a=null===(r=OT(this,hE,"f"))||void 0===r?void 0:r.video)||void 0===a?void 0:a.deviceId)||void 0===l?void 0:l.ideal)||(null===(c=null===(h=OT(this,hE,"f"))||void 0===h?void 0:h.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let d=OT(this,AE,"f").get(i);if(d&&!t)return JSON.parse(JSON.stringify(d));d=[],OT(this,AE,"f").set(i,d);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!p(i,n)&&d.push({width:n.width,height:n.height})}return d}}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'.");BT(this,hE,JSON.parse(JSON.stringify(t))),BT(this,dE,null),e&&OT(this,sE,"m",NE).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(OT(this,hE,"f")))}resetMediaStreamConstraints(){BT(this,hE,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null)}getCameraCapabilities(){if(!OT(this,rE,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return OT(this,rE,"f").getCapabilities?OT(this,rE,"f").getCapabilities():{}}getCameraSettings(){if(!OT(this,rE,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return OT(this,rE,"f").getSettings()}async turnOnTorch(){if(!OT(this,rE,"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 OT(this,rE,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!OT(this,rE,"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 OT(this,rE,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!OT(this,rE,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=YE(t,n.min,n.step,n.max)),await OT(this,rE,"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(!OT(this,rE,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=YE(t,n.min,n.step,n.max)),await OT(this,rE,"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(!OT(this,rE,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(t<n.min?t=n.min:t>n.max&&(t=n.max));const s=this.getResolution();return await OT(this,rE,"f").applyConstraints({width:{ideal:Math.max(s.width,s.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(!OT(this,rE,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,s=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const o=t.mode.toLowerCase();if(!n.includes(o))throw Error("Unsupported focus mode.");if("manual"===o){if(!s)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(i<s.min?i=s.min:i>s.max&&(i=s.max),i=YE(i,s.min,s.step,s.max)),this._focusParameters.focusArea=null,await OT(this,rE,"f").applyConstraints({advanced:[{focusMode:o,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,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=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:n},await OT(this,sE,"m",WE).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await OT(this,rE,"f").applyConstraints({advanced:[{focusMode:o}]})}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(){BT(this,yE,!0)}disableTapToFocus(){BT(this,yE,!1)}isTapToFocusEnabled(){return OT(this,yE,"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?OT(this,sE,"m",HE).call(this,t.centerPoint):this.resetScaleCenter();try{if(OT(this,sE,"m",jE).call(this,OT(this,TE,"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*OT(this,SE,"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(!OT(this,rE,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=YE(t,n.min,n.step,n.max)),await OT(this,rE,"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&&OT(this,sE,"m",HE).call(this,e),BT(this,SE,t),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return OT(this,SE,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();BT(this,TE,{x:t.width/2,y:t.height/2})}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(OT(this,vE,"f"))return null;const e=Date.now();$E._onLog&&$E._onLog("getFrameData() START: "+e);const i=OT(this,oE,"f").videoWidth,n=OT(this,oE,"f").videoHeight;let s={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(s=JSON.parse(JSON.stringify(t.position)));let o=YT.RGBA;(null==t?void 0:t.pixelFormat)&&(o=t.pixelFormat);let r=OT(this,SE,"f");(null==t?void 0:t.scale)&&(r=t.scale);let a=OT(this,TE,"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,s=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"))s=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");s=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(s))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(s)}let l=null;if((null==t?void 0:t.bufferContainer)&&(l=t.bufferContainer),0==i||0==n)return null;1!==r&&(s.sWidth=Math.round(s.sWidth/r),s.sHeight=Math.round(s.sHeight/r),s.sx=Math.round((1-1/r)*a.x+s.sx/r),s.sy=Math.round((1-1/r)*a.y+s.sy/r));const h=this.imageDataGetter.getImageData(OT(this,oE,"f"),i,n,s,{pixelFormat:o,bufferContainer:l});if(!h)return null;const c=Date.now();return $E._onLog&&$E._onLog("getFrameData() END: "+c),{data:h.data,width:h.width,height:h.height,pixelFormat:h.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:OT(this,EE,"f")}}on(t,e){if(!OT(this,PE,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);OT(this,_E,"f").on(t,e)}off(t,e){OT(this,_E,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),OT(this,_E,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",OT(this,DE,"f")),BT(this,RE,!0)}}function XE(t,e){Ls(e)&&(t.config.maxFrameNumber=e)}function qE(t,e){Ls(e)&&(t.config.autoCaptureDelay=e)}function ZE(t,e){if(!Rs(e))return;const{context:i}=t.viewer;i.core.detectorService.enableDetect&&(t.config.enableAutoDetect=e,t.isVideoPlaying&&(t.viewer.hooks.autoDetectChanged.emit(tm.create(e)),e?t.loop.startLoop():t.config.enableAutoCapture?t.loop.cancelAnimation():t.loop.closeLoop()))}function JE(t,e){Rs(e)&&(t.config.enableAutoCapture=e,t.isVideoPlaying&&(t.viewer.hooks.autoCaptureChanged.emit(em.create(e)),e?t.loop.startLoop():t.config.enableAutoDetect||t.loop.closeLoop()))}function KE(t,e){Ls(e)&&(t.config.acceptedPolygonConfidence=e)}function QE(t,e){return!!t.videoEl&&(t.config.fullscreen=e,t.videoEl.style.objectFit=e?"cover":"contain",t.loop.updateVideoLayout(),!0)}oE=new WeakMap,rE=new WeakMap,aE=new WeakMap,lE=new WeakMap,hE=new WeakMap,cE=new WeakMap,dE=new WeakMap,uE=new WeakMap,pE=new WeakMap,gE=new WeakMap,fE=new WeakMap,mE=new WeakMap,vE=new WeakMap,yE=new WeakMap,xE=new WeakMap,wE=new WeakMap,CE=new WeakMap,bE=new WeakMap,SE=new WeakMap,TE=new WeakMap,EE=new WeakMap,_E=new WeakMap,PE=new WeakMap,AE=new WeakMap,IE=new WeakMap,DE=new WeakMap,RE=new WeakMap,sE=new WeakSet,kE=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(OT(this,dE,"f"))delete t.video.facingMode,t.video.deviceId={exact:OT(this,dE,"f")};else if(this.ifSaveLastUsedCamera&&$E.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(HT.OS)?(await this._getCameras(!1),OT(this,sE,"m",ME).call(this),e=$E.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(HT.OS)||(await this._getCameras(!1),OT(this,sE,"m",ME).call(this),e=$E.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 n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},ME=function(){if(OT(this,gE,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},LE=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 n;try{$E._onLog&&$E._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const s=async t=>{for(let s of e){s&&(await new Promise(t=>setTimeout(t,s)),OT(this,sE,"m",ME).call(this));try{$E._onLog&&$E._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),OT(this,sE,"m",ME).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,$E._onLog&&$E._onLog(t.message||t)}}};if(await s(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await s(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await s(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await s(t))),!n)throw i;return n}catch(t){throw null==n||n.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}},OE=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),BT(this,rE,null)},BE=async function(){BT(this,gE,!1);const t=BT(this,pE,Symbol());if(OT(this,fE,"f")&&"pending"===OT(this,mE,"f")){try{await OT(this,fE,"f")}catch(t){}OT(this,sE,"m",ME).call(this)}if(t!==OT(this,pE,"f"))return;const e=BT(this,fE,(async()=>{BT(this,mE,"pending");try{if(this.videoSrc){if(!OT(this,oE,"f"))throw new Error("'videoEl' should be set.");await $E.playVideo(OT(this,oE,"f"),this.videoSrc,this.cameraOpenTimeout),OT(this,sE,"m",ME).call(this)}else{let t=await OT(this,sE,"m",kE).call(this);OT(this,sE,"m",OE).call(this);let e=await OT(this,sE,"m",LE).call(this,t);await this._getCameras(!1),OT(this,sE,"m",ME).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;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,n=e;break}}return n},n=OT(this,hE,"f");if("object"==typeof n.video){let s=n.video.facingMode;if(s instanceof Array&&s.length&&(s=s[0]),"object"==typeof s&&(s=s.exact||s.ideal),!(OT(this,dE,"f")||this.ifSaveLastUsedCamera&&$E.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),o=$E.findBestCamera(this._arrCameras,s,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});o&&o!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:o},e=await OT(this,sE,"m",LE).call(this,t),OT(this,sE,"m",ME).call(this))}}const s=i();(null==s?void 0:s.deviceId)&&(BT(this,dE,s&&s.deviceId),this.ifSaveLastUsedCamera&&$E.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",OT(this,dE,"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))))),OT(this,oE,"f")&&(await $E.playVideo(OT(this,oE,"f"),e,this.cameraOpenTimeout),OT(this,sE,"m",ME).call(this)),this._mediaStream=e;const o=e.getVideoTracks();(null==o?void 0:o.length)&&BT(this,rE,o[0]),BT(this,cE,s)}}catch(t){throw OT(this,sE,"m",UE).call(this),BT(this,mE,null),t}BT(this,mE,"fulfilled")})());return e},NE=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=OT(this,cE,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await OT(this,sE,"m",BE).call(this);const n=this.getResolution();e&&e!==OT(this,cE,"f").deviceId&&OT(this,_E,"f").fire("camera:changed",[OT(this,cE,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||OT(this,_E,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),OT(this,_E,"f").fire("played",null,{target:this,async:!1})},UE=function(){OT(this,sE,"m",OE).call(this),BT(this,cE,null),OT(this,oE,"f")&&(OT(this,oE,"f").srcObject=null,this.videoSrc&&(OT(this,oE,"f").pause(),OT(this,oE,"f").currentTime=0)),BT(this,gE,!0);try{this.resetSoftwareScale()}catch(t){}},FE=async function t(e,i){const n=t=>{if(!OT(this,rE,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){OT(this,rE,"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 s;i=YE(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await OT(this,rE,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),s=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,s)}),n(e);let o=e.focusL-e.focusW/2,r=e.focusT-e.focusH/2,a=e.focusW,l=e.focusH;const h=this.getResolution();if(o>=h.width||r>=h.height)throw new Error("Invalid area.");o+a>h.width&&(a=h.width-o),r+l>h.height&&(l=h.height-r),o=Math.round(o),r=Math.round(r),a=Math.round(a),l=Math.round(l);const c=4*h.width*h.height*this._focusParameters.defaultTempBufferContainerLenRatio,d=4*a*l;let u=this._focusParameters.tempBufferContainer;if(u){const t=u.length;c>t&&c>=d?u=new Uint8Array(c):d>t&&d>=c&&(u=new Uint8Array(d))}else u=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,d));if(!this.imageDataGetter.getImageData(OT(this,oE,"f"),h.width,h.height,{sx:o,sy:r,sWidth:a,sHeight:l,dWidth:a,dHeight:l},{pixelFormat:YT.RGBA,bufferContainer:u}))return OT(this,sE,"m",t).call(this,e,i);const p=u;let g=0;for(let t=0,e=d-8;t<e;++t){let e=p[t]-p[t+8];++t;let i=p[t]-p[t+8];++t;let n=p[t]-p[t+8];++t,g+=e*e+i*i+n*n}return-g},VE=async function t(e,i,n,s,o,r,a){let l;if(i=YE(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=YE(s,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r?r=YE(r,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max):(r=YE(Math.sqrt((i||this._focusParameters.fds.step)*(s||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await OT(this,sE,"m",FE).call(this,e,r)),a<=n&&a<=o?l=3:n<o&&n<a?l=1:o<n&&o<a&&(l=2),(s-i)/2<=this._focusParameters.fds.step)return 3===l||(1===l?await OT(this,rE,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}):2===l&&await OT(this,rE,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:s}]})),!0;if(1===l)return await OT(this,sE,"m",t).call(this,e,i,n,r,a);if(2===l)return await OT(this,sE,"m",t).call(this,e,r,a,s,o);if(3!==l)return n=await OT(this,sE,"m",FE).call(this,e,i),o=await OT(this,sE,"m",FE).call(this,e,s),await OT(this,sE,"m",t).call(this,e,i,n,s,o);let h=YE(Math.sqrt((i||this._focusParameters.fds.step)*(r||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),c=YE(Math.sqrt((s||this._focusParameters.fds.step)*(r||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max);if(Math.abs(1/this._focusParameters.oldDistance-1/h)<=Math.abs(1/this._focusParameters.oldDistance-1/c)){let l=await OT(this,sE,"m",FE).call(this,e,h);if(l<a)return await OT(this,sE,"m",t).call(this,e,i,n,r,a,h,l);if(l==a)return await OT(this,sE,"m",t).call(this,e,h,l,r,a);let d=await OT(this,sE,"m",FE).call(this,e,c);if(l>a&&a<d)return await OT(this,sE,"m",t).call(this,e,h,l,c,d,r,a);if(a==d)return await OT(this,sE,"m",t).call(this,e,r,a,c,d);if(a>d)return await OT(this,sE,"m",t).call(this,e,r,a,s,o,c,d)}else{let l=await OT(this,sE,"m",FE).call(this,e,c);if(a>l)return await OT(this,sE,"m",t).call(this,e,r,a,s,o,c,l);if(a==l)return await OT(this,sE,"m",t).call(this,e,r,a,c,l);let d=await OT(this,sE,"m",FE).call(this,e,h);if(d>a&&a<l)return await OT(this,sE,"m",t).call(this,e,h,d,c,l,r,a);if(d==a)return await OT(this,sE,"m",t).call(this,e,h,d,r,a);if(d<a)return await OT(this,sE,"m",t).call(this,e,i,n,r,a,h,d)}return!1},WE=async function(t,e,i,n,s){var o;if(1==this._focusParameters.isDoingFocus)return!1;if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'centerPoint'.");if(!e||"string"!=typeof e)throw new Error("Invalid 'width'.");if(!i||"string"!=typeof i)throw new Error("Invalid 'height'.");const r=this.getResolution();let a=0,l=0;if(t.x.endsWith("px"))a=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid 'centerPoint'.");a=parseFloat(t.x)/100*r.width}if(t.y.endsWith("px"))l=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid 'centerPoint'.");l=parseFloat(t.y)/100*r.height}if(isNaN(a)||isNaN(l)||a<0||a>r.width||l<0||l>r.height)throw new Error("Invalid 'centerPoint'.");let h=0;if(e.endsWith("px"))h=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");h=parseFloat(e)/100*r.width}if(isNaN(h)||h<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*r.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==OT(this,SE,"f")){const t=OT(this,SE,"f"),e=OT(this,TE,"f");h/=t,c/=t,a=(1-1/t)*e.x+a/t,l=(1-1/t)*e.y+l/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(o=this.getCameraCapabilities())||void 0===o?void 0:o.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 d={focusL:a,focusT:l,focusW:h,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},u=async(t,e,i)=>{try{(null==e||e<this._focusParameters.fds.min)&&(e=this._focusParameters.fds.min),(null==i||i>this._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=YE(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=YE(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=YE(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=await OT(this,sE,"m",FE).call(this,t,o),a=await OT(this,sE,"m",FE).call(this,t,s),l=await OT(this,sE,"m",FE).call(this,t,n);if(a>l&&l<r){const e=await OT(this,sE,"m",VE).call(this,t,s,a,o,r,n,l);return this._focusParameters.isDoingFocus=0,e}if(a<l&&a<r){let i=await OT(this,sE,"m",FE).call(this,t,e);const o=await OT(this,sE,"m",VE).call(this,t,e,i,n,l,s,a);return this._focusParameters.isDoingFocus=0,o}if(l>r&&a>r){let e=await OT(this,sE,"m",FE).call(this,t,i);const s=await OT(this,sE,"m",VE).call(this,t,n,l,i,e,o,r);return this._focusParameters.isDoingFocus=0,s}if(a==l&&l<r){const e=await OT(this,sE,"m",VE).call(this,t,s,a,n,l);return this._focusParameters.isDoingFocus=0,e}if(l==r&&a>l){const e=await OT(this,sE,"m",VE).call(this,t,n,l,o,r);return this._focusParameters.isDoingFocus=0,e}return u(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return u(d,n,s)},HE=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,n=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"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");BT(this,TE,{x:i,y:n})},jE=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},$E.browserInfo=HT,$E.onWarning=null===(nE=null===window||void 0===window?void 0:window.console)||void 0===nE?void 0:nE.warn;class t_{constructor(t){Yi(this,"isLooping",!1),Yi(this,"lastDetectTime",(new Date).getTime()),Yi(this,"loopTimer",void 0),Yi(this,"autoCaptureStartTime",0),Yi(this,"lastRenderedQuad",void 0),Yi(this,"animation",void 0),Yi(this,"cameraContext",void 0),Yi(this,"videoLayout",void 0),this.cameraContext=t}getLoopState(){const{enableAutoCapture:t,enableAutoDetect:e}=this.cameraContext.config;return t||e}clearLoopTimer(){clearTimeout(this.loopTimer),this.loopTimer=null,this.isLooping=!1,this.autoCaptureStartTime=0,this.lastDetectTime=(new Date).getTime()}loopTimeout(){if(!this.cameraContext.isVideoPlaying&&!this.getLoopState())return;const t=this.getDetectRemainTime();this.loopTimer=setTimeout(async()=>{if(!this.getLoopState()||this.isLooping)return;this.isLooping=!0;const t=await this.loopTaskDetail();this.isLooping=!1,t&&this.getLoopState()&&setTimeout(()=>{this.getLoopState()&&this.loopTimeout()},10)},t)}async loopTaskDetail(){if(!(this.cameraContext&&this.cameraContext.isVideoPlaying&&this.cameraContext.videoEl&&this.cameraContext.canvasEl))return!1;if(!this.getLoopState())return!1;const{viewer:t}=this.cameraContext;if(this.lastDetectTime=(new Date).getTime(),!t.context.viewService.isBindContainer)return!0;if("hidden"===t.getViewerConfig().visibility)return!1;const{config:e}=this.cameraContext,{enableDetect:i}=t.context.core.detectorService,n=this.cameraContext.getFrameData();if(!n)return!1;const s={type:1,data:n.data.buffer,height:n.height,width:n.width};let o={success:!1};var r;i&&(o=await this.getDetectResult(s),0===n.data.length&&(n.data=new Uint8Array(s.data)),e.enableAutoDetect&&this.cameraContext.isVideoPlaying&&o.success&&null!==(r=o)&&void 0!==r&&r.location?(this.lastRenderedQuad?this.createDetectAnimation(this.lastRenderedQuad,o.location):this.drawQuadrilateral(o.location),this.lastRenderedQuad=o.location):(this.clearCanvas(),this.lastRenderedQuad=null));let a=!1;var l;if(e.enableAutoCapture?((null===(l=o)||void 0===l?void 0:l.status)===Fu.AUTO_CAPTURE&&(a=!0),i||(this.autoCaptureStartTime<=0?this.autoCaptureStartTime=(new Date).getTime():(new Date).getTime()-this.autoCaptureStartTime>e.autoCaptureDelay&&(this.autoCaptureStartTime=0,a=!0))):this.autoCaptureStartTime=0,a){var h,c,d;if(null===(h=this.cameraContext.viewer)||void 0===h||!h.context)return!1;const t=await this.cameraContext.viewer.context.core.processService.resize(n.data.buffer,1,n.width,n.height,-1);if(this.cameraContext.isCapturedPages=!0,null===(c=this.cameraContext.viewer)||void 0===c||!c.context)return!1;await this.cameraContext.viewer.context.loadSource({extraPageData:[{index:0,perspectiveQuad:null===(d=o)||void 0===d?void 0:d.location}],fileData:t.data}),this.startCaptureAnimation(),await e_(),this.closeCaptureAnimation()}return!0}getDetectRemainTime(){const t=(new Date).getTime(),{maxFrameNumber:e}=this.cameraContext.config,i=t-this.lastDetectTime;return Math.max(0,1e3/e-i)}startLoop(){this.loopTimer||(this.getLoopState()?this.loopTimeout():(this.clearLoopTimer(),this.clearCanvas()))}closeLoop(){if(!this.loopTimer)return;const{context:t}=this.cameraContext.viewer,{detectorService:e}=t.core;e.resetDetector(),this.clearLoopTimer(),this.clearCanvas(),cancelAnimationFrame(this.animation)}updateVideoLayout(){const{videoEl:t,config:e}=this.cameraContext,{fullscreen:i}=e,{videoWidth:n,videoHeight:s}=t,{width:o,height:r}=t.getBoundingClientRect(),a={zoom:1,left:0,top:0};if(i){const t=Math.max(o/n,r/s);a.zoom=t}else{const t=Math.min(o/n,r/s),e=(o-n*t)/2,i=(r-s*t)/2;a.zoom=t,a.left=e,a.top=i}this.videoLayout=a}async getDetectResult(t){const{cameraContext:e}=this,{context:i}=e.viewer,{detectorService:n}=i.core;if(!n.enableDetect)return Promise.resolve({success:!1});let s=t;if(!t){const t=e.getFrameData();s={type:1,data:t.data.buffer,height:t.height,width:t.width}}const{acceptedPolygonConfidence:o,enableAutoCapture:r,autoCaptureDelay:a}=e.config,l={acceptedPolygonConfidence:o,enableAutoCapture:r,autoCaptureDelay:a};return await n.detect(s,l)||Promise.resolve({success:!1})}drawQuadrilateral(t){if(!this.loopTimer)return;const{canvasEl:e,viewer:i}=this.cameraContext;if(!e)return;const{zoom:n,left:s,top:o}=this.videoLayout,r=e.getContext("2d");r.save(),r.clearRect(0,0,e.width,e.height),r.translate(s,o),r.scale(n,n),r.beginPath(),r.moveTo(t[0][0],t[0][1]);for(let e=1;e<t.length;e++)r.lineTo(t[e][0],t[e][1]);r.closePath();const{quadSelectionStyle:a}=i.getViewerConfig(),{border:l,background:h}=a,{borderWidth:c,borderColor:d,borderStyle:u}=lo(l);let p=da(c).value/n;0===p&&(p=1);const g="solid"===u?[0,0]:[5*p,2*p];r.strokeStyle=d,r.fillStyle=h,r.lineCap="round",r.lineWidth=p,r.setLineDash(g),r.fill(),r.stroke(),r.restore()}clearCanvas(){const{canvasEl:t}=this.cameraContext;t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}cancelAnimation(){this.clearCanvas(),cancelAnimationFrame(this.animation)}createDetectAnimation(t,e){let i=0;const n=()=>{this.clearCanvas();const s=t.map((t,n)=>{const s=e[n];return[t[0]+(s[0]-t[0])*i,t[1]+(s[1]-t[1])*i]});this.drawQuadrilateral(s),i<1&&(i+=.2,this.animation=requestAnimationFrame(n))};n()}startCaptureAnimation(){var t,e;this.cameraContext&&null!==(t=this.cameraContext)&&void 0!==t&&t.videoEl&&null!==(e=this.cameraContext)&&void 0!==e&&e.canvasEl&&(this.cameraContext.videoEl.style.filter="brightness(0%)",this.cameraContext.canvasEl.style.visibility="hidden")}closeCaptureAnimation(){var t,e;this.cameraContext&&null!==(t=this.cameraContext)&&void 0!==t&&t.videoEl&&null!==(e=this.cameraContext)&&void 0!==e&&e.canvasEl&&(this.cameraContext.videoEl.style.filter="brightness(100%)",this.cameraContext.canvasEl.style.visibility="")}}function e_(){return new Promise(t=>{setTimeout(()=>{t("")},50)})}const i_={tag:"div",id:"ddv-camera-container",className:"ddv-camera-container",children:[{tag:"video",id:"ddv-camera-video",class:"ddv-camera-camera"},{tag:"canvas",id:"ddv-camera-canvas",class:"ddv-camera-canvas"}]},n_={enableAutoCapture:!1,enableAutoDetect:!1,enableTorch:!1,maxFrameNumber:10,acceptedPolygonConfidence:65,fullscreen:!1,autoCaptureDelay:1e3};class s_{constructor(t){var e;if(Yi(this,"camera",void 0),Yi(this,"configHandler",{}),Yi(this,"isHttps",!0),Yi(this,"lastDeviceId",void 0),Yi(this,"isFirstPlayed",!0),Yi(this,"isTurningTorch",!1),Yi(this,"initializing",!1),Yi(this,"cameraContainer",void 0),Yi(this,"viewer",void 0),Yi(this,"loop",void 0),Yi(this,"videoEl",void 0),Yi(this,"canvasEl",void 0),Yi(this,"config",_s(n_)),Yi(this,"bUser",!1),Yi(this,"canFrontCamera",!1),Yi(this,"isCapturedPages",!1),Yi(this,"lastEnvironmentCameraId",void 0),Yi(this,"cameraList",[]),Yi(this,"turnOnTheTorch",!1),Yi(this,"torchSupported",!1),this.viewer=t,this.camera=new $E,this.loop=new t_(this),this.initConfigHandler(),null!==(e=navigator)&&void 0!==e&&null!==(e=e.mediaDevices)&&void 0!==e&&e.getUserMedia||(this.isHttps=!1),this.isCaptureViewer&&this.isHttps){this.initializing=!0;const t=this.getCameras().then(t=>{this.cameraList=t}),e=this.getFrontCamera().then(t=>{this.canFrontCamera=t,this.viewer.hooks.cameraInit.emit(nm.create(t))}).catch(t=>{});Promise.all([t,e]).finally(()=>{this.initializing=!1})}this.camera.setResolution(1280,720),this.bindCameraEvents(),this.initHooks(),this.handleViewerModeChanged(),this.bindNativeEvents(),this.handleExternalEvents()}initHooks(){this.bindViewerHooks(),this.bindGlobalHooks()}handleViewerModeChanged(){const{defaultDom:t,mainAndThbContainer:e}=this.viewer.context.viewService;if(this.isCaptureViewer){if(!this.cameraContainer){const e=ty(i_,this.viewer.postfix);this.cameraContainer=e,Object.assign(e.style,this.viewer.context.viewerConfig.canvasStyle),t.appendChild(e);const i=e.getElementsByTagName("video")[0],n=e.getElementsByTagName("canvas")[0];i.setAttribute("playsinline","true"),i.setAttribute("muted","true"),i.setAttribute("disablePictureInPicture","true"),i.setAttribute("autoplay","autoplay"),i.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),i.style.transition="opacity 300ms, filter 100ms ease",this.bindCameraVideo(i),this.bindCameraCanvas(n),this.updateCameraConfig(n_)}iy(this.cameraContainer,"flex"),ey(e)}else ey(this.cameraContainer),iy(e,"flex")}initConfigHandler(){const t={maxFrameNumber:XE,enableAutoCapture:JE,enableAutoDetect:ZE,acceptedPolygonConfidence:KE,fullscreen:QE,autoCaptureDelay:qE};this.configHandler=t}bindViewerHooks(){this.viewer.hooks.visibleChanged.on(t=>{this.loop.closeLoop(),"visible"===t.newVisibility&&this.loop.startLoop()},this)}bindGlobalHooks(){this.viewer.context.core.documentService.onAddPagesToDoc.on(t=>{if(!this.isCapturedPages)return;const e=Kf.create(t.pageUids[0]);this.viewer.hooks.cameraCaptured.emit(e),this.isCapturedPages=!1},this.viewer)}bindCameraEvents(){const{camera:t}=this;t.on("paused",()=>{this.loop.closeLoop()}),t.on("resumed",()=>{this.loop.closeLoop(),this.loop.startLoop()}),t.on("before:open",()=>{this.videoEl&&(this.videoEl.style.opacity="0")}),t.on("before:resolution:change",()=>{this.videoEl&&(this.videoEl.style.opacity="0"),this.loop.closeLoop()}),t.on("before:camera:change",()=>{this.videoEl&&(this.videoEl.style.opacity="0"),this.loop.closeLoop(),this.lastDeviceId=this.camera.getCamera().deviceId}),t.on("camera:changed",()=>{const t=Qf.create(this.lastDeviceId,this.camera.getCamera().deviceId);this.viewer.hooks.cameraChanged.emit(t)}),t.on("played",()=>{if(!this.videoEl||!this.isVideoPlaying)return;this.videoEl.style.opacity="1";const{enableTorch:t}=this.config,e=this.camera.getResolution();let i="unsupported";try{const t=this.camera.getCameraCapabilities();i=null!=t&&t.torch?"supported":"unsupported"}catch(t){}this.torchSupported="supported"===i,this.emitTorchChanged(i),"supported"===i&&t&&this.turnOnTorch().catch(()=>{this.config.enableTorch=!0}),this.viewer.hooks.cameraPlayed.emit(im.create(e)),this.loop.updateVideoLayout(),this.loop.closeLoop(),this.loop.startLoop()}),t.on("closed",()=>{this.isVideoPlaying||(this.loop.closeLoop(),this.viewer.hooks.cameraClosed.emit(),this.emitTorchChanged("unsupported"))})}emitTorchChanged(t){this.viewer.hooks.torchChanged.emit(sm.create(t))}getPointerEvent(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=0,s=0,o=0,r=0;if(e){const{left:t,top:i}=e.getBoundingClientRect();o=t,r=i}return t instanceof PointerEvent||t instanceof MouseEvent?(n=t.offsetX,s=t.offsetY):i?(n=t.changedTouches[0].clientX-o,s=t.changedTouches[0].clientY-r):(n=t.touches[0].clientX-o,s=t.touches[0].clientY-r),{index:-1,pageUid:"",imageX:-1,imageY:-1,canvasX:Math.floor(n),canvasY:Math.floor(s),nativeEvent:t}}handleExternalEvents(){this.viewer.hooks.cameraPlayed.on(t=>{const e={deviceId:this.camera.getCamera().deviceId,resolution:[t.resolution.width,t.resolution.height]};this.viewer.emit("played",e)},this),this.viewer.hooks.cameraClosed.on(()=>{this.viewer.emit("stopped",{deviceId:this.lastDeviceId})},this),this.viewer.hooks.cameraCaptured.on(t=>{this.viewer.emit("captured",{pageUid:t.pageUid})},this),this.viewer.hooks.cameraChanged.on(t=>{this.viewer.emit("cameraChanged",{oldDeviceId:t.oldDeviceId,newDeviceId:t.newDeviceId})},this)}bindNativeEvents(){const t=this.canvasEl;if(!t)return;const e=t=>{this.viewer.emitter.hasCallback("click")&&this.viewer.emit("click",this.getPointerEvent(t))},i=t=>{this.viewer.emitter.hasCallback("dblclick")&&this.viewer.emit("dblclick",this.getPointerEvent(t))},n=t=>{t.preventDefault(),this.viewer.emitter.hasCallback("rightclick")&&this.viewer.emit("rightclick",this.getPointerEvent(t))},s=()=>{setTimeout(()=>{this.resize()},500)},o=()=>{this.isVideoPlaying&&(this.loop.closeLoop(),"visible"===document.visibilityState&&this.loop.startLoop())};t.addEventListener("click",e),t.addEventListener("dblclick",i),t.addEventListener("contextmenu",n),document.addEventListener("visibilitychange",o),window.addEventListener("orientationchange",s),this.viewer.hooks.destroy.on(()=>{t.removeEventListener("click",e),t.removeEventListener("dblclick",i),t.removeEventListener("contextmenu",n),document.removeEventListener("visibilitychange",o),window.removeEventListener("orientationchange",s)})}get isCaptureViewer(){return this.viewer.context.viewerConfig.viewerMode===jg.CAPTURE}get isVideoPlaying(){return!!this.camera&&this.camera.isVideoPlaying}async getFrontCamera(){if(!this.isHttps)return pp.reject(pp.CAMERA_NEED_HTTPS);const t=await $E.testCameraAccess({video:{facingMode:{exact:"user"}}});return Promise.resolve(t.ok)}convertCamera(){if(!this.canFrontCamera)return Promise.reject();if("opening"===this.camera.state)return Promise.resolve();if(!this.bUser){const t=this.getCamera().deviceId;return this.camera.switchToFrontCamera().then(()=>(this.bUser=!0,this.lastEnvironmentCameraId=t,this.torchSupported&&this.emitTorchChanged("unsupported"),Promise.resolve()))}return this.setCamera(this.lastEnvironmentCameraId).then(()=>(this.bUser=!1,this.torchSupported&&this.emitTorchChanged("supported"),Promise.resolve()))}getFrameData(){if(!this.config.fullscreen)return this.camera.getFrameData();const{width:t,height:e}=this.videoEl.getBoundingClientRect(),i=this.videoEl.videoWidth,n=this.videoEl.videoHeight,s=Math.max(t/i,e/n),o=t/(i*s),r=e/(n*s),a=Math.floor((1-o)/2*i),l=Math.floor((1-r)/2*n),h=Math.floor(i*o),c=Math.floor(n*r);return this.camera.getFrameData({position:{sx:a,sy:l,sWidth:h,sHeight:c,dWidth:h,dHeight:c}})}updateCameraConfig(t){for(const[e,i]of Object.entries(t)){const t=this.configHandler[e];t&&!Ps(i)&&t(this,i)}}bindCameraVideo(t){t instanceof HTMLVideoElement&&(this.camera.setVideoEl(t),this.videoEl=t)}bindCameraCanvas(t){t instanceof HTMLCanvasElement&&(this.canvasEl=t)}async capture(){this.loop.startCaptureAnimation(),await e_(),this.loop.closeCaptureAnimation(),pp.verbose(`[${Date.now()}][cv] start capture`);const t=this.getFrameData();if(pp.verbose(`[${Date.now()}][cv] get frame done`),!t)return null;const e={type:1,data:t.data.buffer,width:t.width,height:t.height},i=await this.loop.getDetectResult(e);pp.verbose(`[${Date.now()}][cv] get detect result done`),0===t.data.length&&(t.data=new Uint8Array(e.data));const n=await this.viewer.context.core.processService.resize(t.data.buffer,1,t.width,t.height,-1);return pp.verbose(`[${Date.now()}][cv] create image done`),this.isCapturedPages=!0,await this.viewer.context.loadSource({fileData:n.data,extraPageData:[{index:0,perspectiveQuad:i.success?i.location:void 0}]}),pp.verbose(`[${Date.now()}][cv] capture done`),n.data}async play(t){if(!this.isHttps)return Promise.reject(pp.CAMERA_NEED_HTTPS);if(!t&&this.isVideoPlaying)return Promise.resolve();const{fill:e,resolution:i}=t||{},n=this.camera.getResolution();if(Rs(e)&&this.updateCameraConfig({fullscreen:e}),this.isVideoPlaying&&o_(i)&&i[0]===n.width&&i[1]===n.height)return Promise.resolve();if(n.width,n.height,o_(i)){if(this.isVideoPlaying)return this.camera.setResolution(i[0],i[1]).then(t=>(this.resize(),Promise.resolve())).catch();this.camera.setResolution(i[0],i[1])}return!this.isFirstPlayed||this.isVideoPlaying||i||"opening"===this.camera.state||this.camera.setResolution(1280,720),this.initializing&&await new Promise(t=>{const e=setInterval(()=>{this.initializing||(clearInterval(e),t(""))},100)}),this.isFirstPlayed&&(this.isFirstPlayed=!1),this.camera.open().then(async()=>(this.resize(),Promise.resolve())).catch(t=>{let e=pp.CAMERA_OCCUPIED;return"Permission denied"===t.message&&(e=pp.CAMERA_DENIED),8===t.code&&(e=pp.CAMERA_NO_CAMERA),Promise.reject(e)})}stop(){var t;this.loop.closeLoop(),this.lastDeviceId=this.getCamera().deviceId,null===(t=this.camera)||void 0===t||t.close()}async setCamera(t){let e="";Es(t)?e=t.deviceId||"":Os(t)&&(e=t);let i=!1;const n=this.cameraList.length?this.cameraList:await this.getCameras();for(let t=0;t<n.length;t++)n[t].deviceId===e&&(i=!0);if(!i)return Promise.reject(pp.CAMERA_NOT_EXIST);await this.camera.setCamera(e).catch(t=>{let e=pp.CAMERA_OCCUPIED;"Permission denied"===t.message&&(e=pp.CAMERA_DENIED),8===t.code&&(e=pp.CAMERA_NO_CAMERA),Promise.reject(e)});const s=this.camera.getResolution(),o={deviceId:e,width:s.width,height:s.height};return Promise.resolve(o)}getCamera(){const t=this.camera.getCamera();return{deviceId:t.deviceId,label:t.label}}async getCameras(){const t=(await this.camera.getAllCameras()).map(t=>({deviceId:t.deviceId,label:t.label}));return Promise.resolve(t)}async setResolution(t,e){const i=this.camera.getCamera();if(!i||""===i.deviceId)return Promise.reject(pp.CAMERA_NOT_EXIST);let n;if(Ls(t))n=t;else if(Ts(t)){const[i,s]=t;n=i,e=s}let s=this.camera.getResolution();return Ls(n)&&Ls(e)&&(this.loop.closeLoop(),s=await this.camera.setResolution(n,e).catch(t=>{})),Promise.resolve({deviceId:i.deviceId,...s})}getResolution(){const t=this.camera.getCamera();if(!t||""===t.deviceId)return[0,0];const e=this.camera.getResolution();return[e.width,e.height]}async getResolutions(){const t=(await this.camera.getResolutions()).map(t=>[t.width,t.height]);return Promise.resolve(t)}turnOnTorch(){const t=this.camera.getCamera();return t&&""!==t.deviceId?this.isTurningTorch?Promise.resolve():(this.isTurningTorch=!0,this.camera.turnOnTorch().then(()=>(this.isTurningTorch=!1,this.turnOnTheTorch=!0,this.config.enableTorch=!0,this.emitTorchChanged("on"),Promise.resolve())).catch(t=>(this.isTurningTorch=!1,this.turnOnTheTorch=!1,this.config.enableTorch=!1,this.emitTorchChanged("off"),pp.reject(pp.CAMERA_NOT_SUPPORT_TORCH)))):Promise.reject(pp.CAMERA_NO_VIDEO)}turnOffTorch(){const t=this.camera.getCamera();return t&&""!==t.deviceId?this.camera.turnOffTorch().then(()=>(this.turnOnTheTorch=!1,this.config.enableTorch=!1,this.emitTorchChanged("off"),Promise.resolve())).catch(t=>pp.reject(pp.CAMERA_NOT_SUPPORT_TORCH)):Promise.reject(pp.CAMERA_NO_VIDEO)}resize(){const{canvasEl:t}=this,{width:e,height:i}=t.getBoundingClientRect();t.width=Math.floor(e),t.height=Math.floor(i),this.loop.updateVideoLayout()}dispose(){var t,e;this.stop(),null===(t=this.loop)||void 0===t||t.closeLoop(),null===(e=this.camera)||void 0===e||e.dispose(),this.camera=null,this.loop=null,this.videoEl=null,this.canvasEl=null}}function o_(t){return!!(Ts(t)&&Ls(t[0])&&Ls(t[1]))}const r_={install(t){const e=t.getClass("Viewer"),i=(n=e,class extends n{constructor(t){if(super(t),Yi(this,"cameraContext",void 0),this.context.viewerConfig.viewerMode===jg.CAPTURE){this.cameraContext=new s_(this);const e=n_;Es(t.viewerConfig)&&["enableTorch","enableAutoCapture","enableAutoDetect","acceptedPolygonConfidence","maxFrameNumber","autoCaptureDelay"].forEach(i=>{i in t.viewerConfig&&(e[i]=t.viewerConfig[i])}),this.cameraContext.config={...e,defaultCameraConfig:n_},this.on("resized",()=>{this.cameraContext.resize()})}}isVideoPlaying(){return this.cameraContext.isVideoPlaying}convertCamera(){return this.cameraContext.convertCamera()}getCameraConfig(){return _s(this.cameraContext.config)}updateCameraConfig(t){Es(t)&&this.cameraContext.updateCameraConfig(t)}capture(){return this.cameraContext.capture()}play(t){return this.cameraContext.play(t)}stop(){this.isVideoPlaying()?this.cameraContext.stop():pp.warning(pp.CAMERA_NO_VIDEO)}getCurrentCamera(){return this.cameraContext.getCamera()}getAllCameras(){return this.cameraContext.getCameras()}selectCamera(t){return this.cameraContext.setCamera(t)}getCurrentResolution(){return this.cameraContext.getResolution()}getResolutions(){return this.cameraContext.getResolutions()}setResolution(t,e){return this.cameraContext.setResolution(t,e)}turnOnTorch(){return this.cameraContext.turnOnTorch()}turnOffTorch(){return this.cameraContext.turnOffTorch()}dispose(){var t;this.cameraContext&&(null===(t=this.cameraContext)||void 0===t||t.dispose()),this.cameraContext=null,super.dispose()}});var n;t.setClass("Viewer",i)}};class a_{constructor(t){Yi(this,"uid",void 0),Yi(this,"areaUid",void 0),Yi(this,"isRect",!0),Yi(this,"vertexes",[]),Yi(this,"midpoints",[]),Yi(this,"points",[]),Yi(this,"keepAspectRatio",!1),Yi(this,"isConvex",!0),Yi(this,"renderer",void 0),Yi(this,"area",void 0),Yi(this,"slopeRatio",[]),Yi(this,"selectedPart",-1),Yi(this,"startX",null),Yi(this,"startY",null),Yi(this,"lastX",null),Yi(this,"lastY",null),Yi(this,"lastAspectRatio",1),Yi(this,"b1",void 0),Yi(this,"b2",void 0),Yi(this,"k1",void 0),Yi(this,"k2",void 0),this.uid=Us(),Object.assign(this,t),this.initBox(t.vertexes)}initBox(t){this.vertexes=t,this.midpoints=l_(this.vertexes),this.points=this.vertexes.slice().concat(this.midpoints.slice()),this.slopeRatio=Mo(this.vertexes)}getRect(){if(!this.isRect)return null;const{minX:t,maxX:e,minY:i,maxY:n}=this.getBounds();return{left:t,top:i,width:e-t||1,height:n-i||1}}getQuad(){if(this.isRect)return null;const{points:t}=this,e=[];for(let i=0;i<4;i++)e.push([t[2*i],t[2*i+1]]);return e}getActivePartNum(t,e,i){const n=this.getSelectedCtrlPointNum(t,e,i);return n>-1?n:this.isPointOnBox(t,e)?8:-1}getSelectedCtrlPointNum(t,e,i){const{points:n}=this,{width:s,height:o,zoom:r}=this.area,{ctrlWidth:a,ctrlHeight:l,ctrlRadiusMultipleMobile:h}=this.renderer.config.boxStyle;let c=l/2/r,d=a/2/r;i&&(d*=h,c*=h);const u=Bs(d,0,3*d),p=Bs(c,0,3*c);for(let i=0;i<8;i++){const r=n[2*i],a=n[2*i+1];if(t<=r+u&&t>=r-u&&e<=a+p&&e>=a-p&&t>=0-u&&t<=s+u&&e>=0-p&&e<=o+p&&(i<4&&this.renderer.config.enableEditCropBoxVertices||this.renderer.config.enableEditCropBoxMidpoints))return i}return-1}checkOrientation(t){if(t<0||t>7)return null;const{minX:e,maxX:i,minY:n,maxY:s}=this.getBounds(),{points:o}=this,r=o[2*t],a=o[2*t+1];let l="",h="";return r===i?l="e":r===e&&(l="w"),a===s?h="s":a===n&&(h="n"),t<4?h+l:h||l}onStartHandler(t,e,i,n){var s;if(null!==(s=i)&&void 0!==s||(i=this.getActivePartNum(t,e,n)),!(i<0)&&(this.startX=t,this.startY=e,this.lastX=t,this.lastY=e,this.selectedPart=i,!this.isRect&&i>3&&i<8)){const{points:t,slopeRatio:e}=this,n=i-4;this.k1=e[(n+1)%4],this.b1=t[(2*n+3)%8]-this.k1*t[(2*n+2)%8],this.k2=e[(n+3)%4],this.b2=t[(2*n+1)%8]-this.k2*t[(2*n+0)%8]}}onMoveHandler(t,e,i){const{selectedPart:n}=this;if(n<0)return;const s=t-this.lastX,o=e-this.lastY;if(0===s&&0===o)return;const{points:r}=this;let a=r.slice();var l;n<8?(null!==(l=i)&&void 0!==l||(i=n),this.isRect?a=this.moveRectPoint(a,i,t,e):(a=this.moveQuadPoint(a,i,t,e),this.slopeRatio=Mo(r).slice(0,4),this.isConvex=Oo(a))):8===n&&(a=this.moveBox(a,s,o));const h=l_(a);this.points=a.slice(0,8).concat(h),this.midpoints=h,this.lastX=t,this.lastY=e}onEndHandler(){const{startX:t,startY:e,vertexes:i,midpoints:n,lastX:s,lastY:o,selectedPart:r}=this;if(r<0)return;this.startX=0,this.startY=0,this.selectedPart=-1;let a=this.points.slice();const l=Oo(a);(t===s&&e===o||!l)&&(a=i.slice().concat(n)),this.isConvex=!0,this.vertexes=a.slice(0,8),this.midpoints=l_(a),this.points=a.slice(0,8).concat(this.midpoints),this.slopeRatio=Mo(a).slice(0,4)}getBounds(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.points;return{minX:Math.min(t[0],t[2],t[4],t[6]),maxX:Math.max(t[0],t[2],t[4],t[6]),minY:Math.min(t[1],t[3],t[5],t[7]),maxY:Math.max(t[1],t[3],t[5],t[7])}}moveRectPoint(t,e,i,n){let s=0,o=0;const{enableEditCropBoxMidpoints:r,enableEditCropBoxVertices:a}=this.renderer.config;if(this.keepAspectRatio){const{minX:l,maxX:h,minY:c,maxY:d}=this.getBounds(),u=this.checkOrientation(e);let p=(h-l)/(d-c);0===p||p===1/0||p===-1/0||Number.isNaN(p)?p=this.lastAspectRatio:this.lastAspectRatio=p,s=0,o=0;let g="w",f=!1;if(e<4){if(a){if(f=!0,s=i-t[2*e],o=n-t[2*e+1],0===s||0===o)return t;g="w"}}else{const a=e-4;if(r){f=!0;const r={e:[(a+1)%4,"w"],s:[a,"h"],w:[a,"w"],n:[(a+1)%4,"h"]};if(["e","s","w","n"].includes(u)&&([e,g]=r[u]),s=i-t[2*a],o=n-t[2*a+1],0===s||0===o)return t}}if(f){const i=["ne","sw","n","w"];"h"===g?(s=o*p,i.includes(u)&&(s=-s)):(o=s/p,i.includes(u)&&(o=-o));const n=t[2*e]+s,r=t[2*e+1]+o,{width:a,height:l}=this.area;n<0?(s=0-t[2*e],o=0):n>a?(s=a-t[2*e],o=0):r<0?(o=0-t[2*e+1],s=0):r>l&&(o=l-t[2*e+1],s=0),t[2*e]+=s,t[2*e+1]+=o;const h=(e+1)%4,c=(e+3)%4;e%2?(t[2*h]+=s,t[2*c+1]+=o):(t[2*h+1]+=o,t[2*c]+=s)}}else if(e<4){if(a){if(s=i-t[2*e],o=n-t[2*e+1],0===s&&0===o)return t;t[2*e]=i,t[2*e+1]=n;const r=(e+1)%4,a=(e+3)%4;e%2?(t[2*r]=i,t[2*a+1]=n):(t[2*r+1]=n,t[2*a]=i)}}else{const s=e-4;if(r){const e=this.slopeRatio[s%4];0===e?(t[(2*s+3)%8]=n,t[(2*s+1)%8]=n):e!==1/0&&e!==-1/0||(t[(2*s+2)%8]=i,t[(2*s+0)%8]=i)}}return t}moveQuadPoint(t,e,i,n){const s=t.slice();if(e<4){const s=i-t[2*e],o=n-t[2*e+1];if(0===s&&0===o)return t;t[2*e]=i,t[2*e+1]=n}else{const o=e-4,r=this.slopeRatio[o%4],a=n-r*i,l=-a/r,h=a,c=t[(2*o+9)%8]-r*t[(2*o+8)%8],d=-c/r,{k1:u,b1:p,k2:g,b2:f}=this;0===r?(t[(2*o+3)%8]=n,u!==1/0&&u!==-1/0&&(t[(2*o+2)%8]=(n-p)/u),t[(2*o+1)%8]=n,g!==1/0&&g!==-1/0&&(t[(2*o+0)%8]=(n-f)/g)):r===1/0||r===-1/0?(t[(2*o+2)%8]=i,t[(2*o+3)%8]=u*i+p,t[(2*o+0)%8]=i,t[(2*o+1)%8]=g*i+f):(0===u?t[(2*o+2)%8]+=l-d:u===1/0||u===-1/0?t[(2*o+3)%8]+=h-c:(t[(2*o+2)%8]=(p-a)/(r-u),t[(2*o+3)%8]=(r*p-u*a)/(r-u)),0===g?t[(2*o+0)%8]+=l-d:g===1/0||g===-1/0?t[(2*o+1)%8]+=h-c:(t[(2*o+0)%8]=(f-a)/(r-g),t[(2*o+1)%8]=(r*f-g*a)/(r-g)));for(let e=0;e<4;e++){const i=t[2*e],n=t[2*e+1];if(i<0||i>this.area.width||n<0||n>this.area.height)return s}}return t}moveBox(t,e,i){const{minX:n,maxX:s,minY:o,maxY:r}=this.getBounds(t);e=Bs(e,-n,this.area.width-s),i=Bs(i,-o,this.area.height-r);for(let n=0;n<4;n++)t[2*n]+=e,t[2*n+1]+=i;return t}isPointOnBox(t,e){if(this.isRect){const{minX:i,maxX:n,minY:s,maxY:o}=this.getBounds();return t>=i&&t<=n&&e>=s&&e<=o}const i=[...this.vertexes],n=[...this.midpoints],s=[];for(let t=0;t<4;t++)s.push([i[2*t],i[2*t+1]]),s.push([n[2*t],n[2*t+1]]);return function(t,e){let i,n,s,o,r=0;const a=e.length;for([s]=e,i=1;i<=a;i++)o=e[i%a],t[0]>Math.min(s[0],o[0])&&t[0]<=Math.max(s[0],o[0])&&t[1]<=Math.max(s[1],o[1])&&s[0]!==o[0]&&(n=(t[0]-s[0])*(o[1]-s[1])/(o[0]-s[0])+s[1],(s[1]===o[1]||t[1]<=n)&&(r+=1)),s=o;return r%2!=0}([t,e],s)}}function l_(t){const e=t.slice(0,8).concat(t[0],t[1]),i=[];for(let t=0;t<4;t++){const n=(e[2*t]+e[2*(t+1)])/2,s=(e[2*t+1]+e[2*(t+1)+1])/2;i.push(n,s)}return i}class h_{constructor(t,e,i){Yi(this,"areaUid",void 0),Yi(this,"left",void 0),Yi(this,"top",void 0),Yi(this,"width",void 0),Yi(this,"height",void 0),Yi(this,"boxes",void 0),Yi(this,"isVisible",!0),Yi(this,"zoom",1),Yi(this,"oldRect",void 0),Yi(this,"oldQuad",void 0),Yi(this,"isModified",!1),Yi(this,"isDrawNewBox",!1),Yi(this,"activeBoxUid",void 0),Yi(this,"activePartNum",-1),Yi(this,"startX",void 0),Yi(this,"startY",void 0),Yi(this,"isMouseDown",!1),Yi(this,"isDrawing",!1),Yi(this,"renderer",void 0),this.renderer=t,this.areaUid=e,this.boxes=[],this.updateAreaRect(i)}hasActiveBox(){return!!this.activeBoxUid}getFullVertexes(){return[0,0,this.width,0,this.width,this.height,0,this.height]}isContainRect(t){return t.left>=0&&t.left<=this.width&&t.left+t.width<=this.width&&t.top>=0&&t.top<=this.height&&t.top+t.height<=this.height}isContainBox(t){const e=t.getRect();return this.isContainRect(e)}isFullBox(t){const{vertexes:e}=t;return 0===e[0]&&0===e[1]&&e[2].toFixed(2)===this.width.toFixed(2)&&0===e[3]&&e[4].toFixed(2)===this.width.toFixed(2)&&e[5].toFixed(2)===this.height.toFixed(2)&&0===e[6]&&e[7].toFixed(2)===this.height.toFixed(2)}addRectBox(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=this.handleBoundary(t),this.addBox(t,!0,e,i)}updateRectBox(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const n=t.getRect(),s=t.getQuad();if(e=this.handleBoundary(e),t.initBox(e),i){const e={box:t};t.isRect?(e.oldRect=n,e.newRect=t.getRect()):(e.oldQuad=s,e.newQuad=t.getQuad()),this.renderer.hooks.boxModified.emit(e)}}handleBoundary(t){t=[...t];for(let e=0;e<4;e++){const i=[t[2*e],t[2*e+1]];i[0]=Bs(i[0],0,this.width),i[1]=Bs(i[1],0,this.height),[t[2*e],t[2*e+1]]=i}return t}addQuadBox(t){return this.addBox(t,!1)}addBox(t){let e=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const n=new a_({isRect:!(arguments.length>1&&void 0!==arguments[1])||arguments[1],area:this,renderer:this.renderer,vertexes:[...t],keepAspectRatio:this.renderer.config.keepAspectRatio});return this.boxes.push(n),e&&this.renderer.hooks.boxCreated.emit({box:n,fromEvent:i}),n}getBoxRects(){return this.boxes.map((t,e)=>({index:e,...t.getRect()}))}getBoxByUid(t){return this.boxes.find(e=>e.uid===t)}deleteBoxByUid(t){const e=this.boxes.findIndex(e=>e.uid===t);e>-1&&this.boxes.splice(e,1)}clearBoxes(){this.boxes.length=0}updateAreaRect(t){this.left=t.left,this.top=t.top,this.width=t.width,this.height=t.height}setKeepAspectRatio(t){this.isDrawing||this.boxes.forEach(e=>{e.keepAspectRatio=t})}isTouchedPoint(t,e,i){return t=Bs(t,0,this.width),e=Bs(e,0,this.height),this.boxes.some(n=>{const s=n.getActivePartNum(t,e,i);return s>-1&&s<8})}isTouchedBox(t,e,i){return t=Bs(t,0,this.width),e=Bs(e,0,this.height),this.boxes.some(n=>n.getActivePartNum(t,e,i)>-1)}onStartHandler(t,e,i){this.isMouseDown=!0,t=Bs(t,0,this.width),e=Bs(e,0,this.height),this.startX=t,this.startY=e;const n=this.boxes.find(n=>{const s=n.getActivePartNum(t,e,i);return s>-1&&(this.activePartNum=s),s>-1});n&&(this.oldRect=n.getRect(),this.oldQuad=n.getQuad(),this.activeBoxUid=n.uid,n.keepAspectRatio=this.renderer.config.keepAspectRatio,n.onStartHandler(t,e,void 0,i))}onMoveHandler(t,e,i,n){if(!this.isMouseDown)return;let s;if(t=Bs(t,0,this.width),e=Bs(e,0,this.height),this.activeBoxUid){if(s=this.getBoxByUid(this.activeBoxUid),!s)return;const{keepAspectRatioWithShift:n,keepAspectRatio:o,enableMoveQuad:r}=this.renderer.config;if(s.isRect)s.keepAspectRatio=!(!i||!n)||o;else if(!r&&8===this.activePartNum)return;return s.onMoveHandler(t,e),void(this.isModified=!0)}const{enableCreateBoxByPointer:o,enableMultiple:r}=this.renderer.config;if((r||!this.boxes.length)&&o){const{startX:i,startY:o}=this;let r=e-o;const a=t-i;let l=-1;const h=2/this.zoom;if(a<-h&&r<-h?l=0:a>h&&r<-h?l=1:a>h&&r>h?l=2:a<-h&&r>h&&(l=3),l>-1){const{aspectRatio:h}=this.renderer.config;h>0&&(r=a/h,l%2&&(r=-a/h));const c=[],d=l%2?[i,o,i,o+r,t,o+r,t,o]:[t,o+r,i,o+r,i,o,t,o];for(let t=0;t<4;t++)c.push(d[2*(l+t)%8]),c.push(d[(2*(l+t)+1)%8]);s=this.addRectBox(c,!1),this.isDrawNewBox=!0,s.keepAspectRatio=h>0,this.isDrawing=!0,this.activeBoxUid=s.uid,s.onStartHandler(this.startX,this.startY,l,n),s.onMoveHandler(t,e,l)}}}onEndHandler(){if(!this.isMouseDown||!this.activeBoxUid)return;this.isMouseDown=!1;const t=this.getBoxByUid(this.activeBoxUid);if(t){if(t.keepAspectRatio=this.renderer.config.keepAspectRatio,t.onEndHandler(),this.isDrawNewBox)this.isDrawNewBox=!1,this.renderer.hooks.boxCreated.emit({box:t,fromEvent:!1});else if(this.isModified){const e={box:t};t.isRect?(e.oldRect=this.oldRect,e.newRect=t.getRect()):(e.oldQuad=this.oldQuad,e.newQuad=t.getQuad()),this.renderer.hooks.boxModified.emit(e)}this.oldRect=null,this.oldQuad=null,this.isModified=!1,this.isDrawing=!1,this.activeBoxUid=null,this.activePartNum=-1}}isPointHover(t){let[e,i]=t;return e>=0&&e<=this.width&&i>=0&&i<=this.height}getCursorInfo(t,e,i){for(let n=this.boxes.length-1;n>=0;n--){const s=this.boxes[n],o=s.getActivePartNum(t,e,i);if(o>-1){let t="move";return o<8&&(t=s.checkOrientation(o)),{part:o,position:t,isRect:s.isRect}}}return null}}const c_={aspectRatio:0,keepAspectRatio:!1,keepAspectRatioWithShift:!0,enableMultiple:!1,enableCreateBoxByPointer:!0,enableCursor:!0,enableMask:!0,enableMagnifier:!0,moveThreshold:2,enableMoveQuad:!1,boxStyle:{borderColor:"orange",borderWidth:2,borderStyle:[5,2],background:"rgba(255,255,255,0)",ctrlBorderWidth:2,ctrlBorderRadius:4,ctrlBorderColor:"orange",ctrlWidth:16,ctrlHeight:16,ctrlBackground:"rgba(255,0,0,0)",invalidCtrlBorderColor:"red",invalidBorderColor:"red",ctrlRadiusMultipleMobile:2},enableEditCropBoxVertices:!0,enableEditCropBoxMidpoints:!0,enableHideEditingCropBoxVertex:!0,enableHideEditingCropBoxMidpoint:!0};class d_{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Yi(this,"areas",void 0),Yi(this,"scrollTop",0),Yi(this,"scrollLeft",0),Yi(this,"zoom",1),Yi(this,"config",void 0),Yi(this,"canvasDom",void 0),Yi(this,"isMousedown",!1),Yi(this,"isEditing",!1),Yi(this,"editingCursor",18),Yi(this,"hoveredArea",void 0),Yi(this,"hooks",{boxCreated:zs(),boxModified:zs(),boxDeleted:zs()}),this.areas=new Map,this.zoom=1,this.config=_s(c_),_o(t,this.config),this.setCanvasDom(t.canvas)}setCanvasDom(t){t&&(this.canvasDom=t)}updateConfig(t){_o(t,this.config)}addArea(t,e){if(this.areas.has(t)){const i=this.areas.get(t);return i.updateAreaRect(e),i}const i=new h_(this,t,e);return this.areas.set(t,i),i}deleteArea(t){this.areas.has(t)&&(this.areas.get(t).boxes.forEach(t=>{this.hooks.boxDeleted.emit(t)}),this.areas.delete(t))}clearArea(){this.areas.forEach(t=>{t.boxes.forEach(t=>{this.hooks.boxDeleted.emit(t)})}),this.areas.clear()}clearAreaBoxes(t){if(this.areas.has(t)){const e=this.areas.get(t);e.boxes.forEach(t=>{this.hooks.boxDeleted.emit(t)}),e.clearBoxes()}}addRectBox(t,e){return this.areas.get(e).addRectBox(t)}addQuadBox(t,e){return this.areas.get(e).addQuadBox(t)}updateOptions(t){Object.assign(this,t),Ls(t.zoom)&&this.areas.forEach(e=>{e.zoom=t.zoom})}getAreaByUid(t){return this.areas.get(t)}deleteAreaByUid(t){this.areas.delete(t)}getHoveredArea(t){const e=this.nativeToCanvas(t);for(const t of this.areas.values()){const i=this.canvasToArea(e,t);if(t.isPointHover(i)&&t.isVisible)return t}return null}getHoveredAreaForCursor(t){const e=ho(t),i=this.nativeToCanvas(t);for(const t of this.areas.values()){const n=this.canvasToArea(i,t),[s,o]=n,r=t.isVisible&&t.boxes.find(t=>t.getActivePartNum(s,o,e)>-1);if(t.isPointHover(n)||r)return t}return null}isControlPointTouched(t){const e=this.getHoveredArea(t);if(!e||!e.isVisible)return!1;const i=this.nativeToCanvas(t),[n,s]=this.canvasToArea(i,e),o=ho(t);return e.isTouchedPoint(n,s,o)}isBoxTouched(t){const e=this.getHoveredArea(t);if(!e||!e.isVisible)return!1;const i=this.nativeToCanvas(t),[n,s]=this.canvasToArea(i,e),o=ho(t);return e.isTouchedBox(n,s,o)}onStartHandler(t){const e=this.getHoveredArea(t);if(!e||!e.isVisible)return;this.hoveredArea=e,this.isMousedown=!0;const i=this.nativeToCanvas(t),[n,s]=this.canvasToArea(i,e),o=ho(t);e.onStartHandler(n,s,o)}onMoveHandler(t){if(!this.canvasDom)return null;let e=null;const i=this.getHoveredArea(t),n=ho(t),s=this.nativeToCanvas(t);if(this.isMousedown){const[e,i]=this.canvasToArea(s,this.hoveredArea);this.hoveredArea.onMoveHandler(e,i,fo(t),n)}if(this.config.enableCursor&&i&&"mouse"===t.pointerType)if(this.hasBox()){const[t,o]=this.canvasToArea(s,i),r=i.getCursorInfo(t,o,n);if(null===r)this.config.enableMultiple&&(e=18);else if(r.isRect)switch(r.position){case"n":case"s":e=20;break;case"w":case"e":e=21;break;case"nw":e=22;break;case"ne":e=23;break;case"sw":e=24;break;case"se":e=25;break;case"move":e=19}else r.part>-1&&r.part<8&&(e=18)}else e=18;return e}hasBox(){for(const t of this.areas.values())if(t.isVisible&&t.boxes.length)return!0;return!1}onEndHandler(t){this.isMousedown&&(this.isMousedown=!1,this.isEditing=!1,this.hoveredArea.onEndHandler(),this.hoveredArea=null)}render(){if(!this.canvasDom||!this.areas.size)return;const t=this.canvasDom.getContext("2d");t.setTransform(1,0,0,1,0,0),this.areas.forEach(e=>{e.isVisible&&e.boxes.length&&this.renderArea(t,e)})}renderArea(t,e){const{borderStyle:i,borderColor:n,borderWidth:s,ctrlBorderColor:o,ctrlBackground:r,ctrlBorderWidth:a,ctrlBorderStyle:l,background:h,maskColor:c,invalidBorderColor:d,invalidCtrlBorderColor:u,ctrlBorderRadius:p,ctrlWidth:g,ctrlHeight:f}=this.config.boxStyle,m=devicePixelRatio,v=g*m,y=f*m,x=Math.min(p*m,v/2,y/2),w=[i[0]*m,i[1]*m],C=s*m,b=a*m,S=[l[0]*m,l[1]*m];t.save(),t.beginPath(),t.rect(e.left*m,e.top*m,e.width*e.zoom*m,e.height*e.zoom*m),t.closePath(),t.clip(),this.config.enableMask&&c&&(t.save(),t.beginPath(),t.rect(e.left*m,e.top*m,e.width*e.zoom*m,e.height*e.zoom*m),e.boxes.forEach(i=>{let n=this.areaPointsToCanvas(i.points.slice(0,8),e),s=this.areaPointsToCanvas(i.midpoints.slice(0,8),e);1!==m&&(n=n.map(t=>t*m),s=s.map(t=>t*m)),t.moveTo(n[0],n[1]);for(let e=1;e<4;e++)t.lineTo(n[2*e],n[2*e+1])}),t.closePath(),t.clip("evenodd"),t.fillStyle=c,t.fill(),t.restore()),e.boxes.forEach(i=>{let s=this.areaPointsToCanvas(i.points.slice(0,8),e),a=this.areaPointsToCanvas(i.midpoints.slice(0,8),e);1!==m&&(s=s.map(t=>t*m),a=a.map(t=>t*m)),t.save(),t.setLineDash(w),t.strokeStyle=i.isConvex?n:d,t.fillStyle=""===h?"transparent":h,t.lineWidth=C,t.beginPath(),t.moveTo(s[0],s[1]);for(let e=1;e<4;e++)t.lineTo(s[2*e],s[2*e+1]);t.closePath(),t.fill(),t.stroke(),t.setLineDash(S),t.strokeStyle=i.isConvex?o:u,t.fillStyle=""===r?"transparent":r,t.lineWidth=b,this.config.enableEditCropBoxVertices&&this.drawCtrlPoints(t,s,v,y,x,this.config.enableHideEditingCropBoxVertex?i.selectedPart:-1),this.config.enableEditCropBoxMidpoints&&this.drawCtrlPoints(t,a,v,y,x,this.config.enableHideEditingCropBoxMidpoint?i.selectedPart-4:-1),t.restore()}),t.restore()}drawCtrlPoints(t,e,i,n,s,o){const r=i/2,a=n/2;for(let l=0;l<4;l++){if(l===o)continue;t.beginPath();const h=e[2*l],c=e[2*l+1];if(0===s)t.rect(h-r,c-a,i,n);else{const{PI:e}=Math;t.arc(h-r+s,c-a+s,s,e,3*e/2),t.arc(h+r-s,c-a+s,s,3*e/2,2*e),t.arc(h+r-s,c+a-s,s,0,e/2),t.arc(h-r+s,c+a-s,s,e/2,e)}t.closePath(),t.fill(),t.stroke()}}areaPointsToCanvas(t,e){const i=[];for(let n=0;n<4;n++){const[s,o]=this.areaToCanvas([t[2*n],t[2*n+1]],e);i.push(s,o)}return i}canvasToArea(t,e){let[i,n]=t;const{scrollLeft:s,scrollTop:o,zoom:r}=this;return i=(i-e.left+s)/r,n=(n-e.top+o)/r,[i,n]}areaToCanvas(t,e){let[i,n]=t;const{scrollLeft:s,scrollTop:o,zoom:r}=this;return i=i*r+e.left-s,n=n*r+e.top-o,[i,n]}nativeToCanvas(t){const e=function(t){return["touchstart","touchend","touchmove"].includes(t.type)}(t)?t.targetTouches[0]:t,i=this.canvasDom.getBoundingClientRect(),{scrollX:n,scrollY:s}=window;return[e.pageX-n-i.left,e.pageY-s-i.top]}}class u_{constructor(t,e){Yi(this,"context",void 0),Yi(this,"core",void 0),Yi(this,"boxRenderer",void 0),Yi(this,"viewer",void 0),Yi(this,"isMousedown",!1),Yi(this,"canvas",void 0),Yi(this,"isRenderMagnifier",!1),Yi(this,"needRenderMagnifier",!1),Yi(this,"magnifierPoint",void 0),this.viewer=t,this.context=t.context,this.core=t.context.core,this.boxRenderer=e,this.canvas=this.context.rendererService.getCanvasDom()}afterRenderForMagnifier(){this.needRenderMagnifier&&(this.magnifierPoint,this.context.magnifierService.render("crop",this.canvas,this.magnifierPoint))}isEditCropBox(t){const e=this.boxRenderer.getHoveredArea(t);return!(!e||!e.isVisible||e.boxes.length&&!this.boxRenderer.isBoxTouched(t))}isNotOverCropBox(t){return this.boxRenderer.hasBox()&&!this.boxRenderer.isBoxTouched(t)}mousedown(t){const{context:e}=this,i=this.context.getActiveTab();if(null==i||!i.total)return;if("crop"!==this.context.viewerConfig.toolMode)return;const[n]=this.context.toCanvas(t),{page:s}=this.context.getPointerOverPageInfo(n.pageX,n.pageY).pageInfo;if(i&&s&&s.uid!==i.currentUid){const t=i.getPageIndex(s);i.gotoPage(t),this.context.emitPageChangedEvent(i),this.context.core.viewerService.onCurrentChangedByScroll.emit(Mf.create(i.uid,e.groupUid,e.uid,t)),this.context.emitPageChangedAfterRenderEvent(i)}this.isMousedown=!0,this.boxRenderer.onStartHandler(t);const o=!this.boxRenderer.hasBox()||this.boxRenderer.isControlPointTouched(t);this.isRenderMagnifier=o,o&&e.viewerConfig.enableMagnifier&&!oy(t)&&(this.needRenderMagnifier=!0,this.magnifierPoint={x:n.pageX,y:n.pageY},this.afterRenderForMagnifier())}mousemove(t){const e=this.context.getActiveTab();if(null==e||!e.total)return;if("crop"!==this.context.viewerConfig.toolMode)return;window.TouchEvent&&t instanceof TouchEvent&&t.cancelable&&t.preventDefault();const i=this.boxRenderer.onMoveHandler(t);if(oy(t)&&this.context.applyCursorState(i),this.isMousedown&&this.context.render(79),this.isRenderMagnifier&&this.context.viewerConfig.enableMagnifier&&!oy(t)){this.needRenderMagnifier=!0;const[e]=this.context.toCanvas(t);this.magnifierPoint={x:e.pageX,y:e.pageY}}}mouseup(t){this.isMousedown&&(this.boxRenderer.onEndHandler(t),this.needRenderMagnifier&&this.context.magnifierService.hide(),this.isRenderMagnifier=!1,this.isMousedown=!1,this.needRenderMagnifier=!1,this.magnifierPoint=null,this.context.render(80))}afterPerspective(t){let{pageUid:e,docUid:i,width:n,height:s}=t;const{context:o}=this,r=o.tabService.getTab(i);if(!r)return;const a=r.getPageByUid(e);if(a&&(a.rWidth=n,a.rHeight=s,o.clearOptimization([a.uid])),r.isActive){if("crop"===o.viewerConfig.toolMode){this.boxRenderer.areas.forEach(t=>{t.clearBoxes()});const t=this.boxRenderer.getAreaByUid(e),i=r.getPageByUid(e).getRect();null==t||t.updateAreaRect(i)}a&&(a.isLoaded=!1),o.scrollByCurrentChanged=!0;let t=!0;this.context.isDefaultViewer?"none"===r.context.fitMode&&(t=!1):this.context.isThumbnailViewer&&(t=!1),this.context.showTab(r,{isClearOptimization:t,renderReason:0})}}afterRotatePages(t){const{context:e}=this;if("crop"!==e.viewerConfig.toolMode)return;const i=this.context.getActiveTab();null!=i&&i.total&&i.uid===t.docUid&&(this.boxRenderer.areas.forEach(t=>{t.clearBoxes()}),t.pageUids.forEach(t=>{const e=this.boxRenderer.getAreaByUid(t),n=i.getPageByUid(t).getRect();null==e||e.updateAreaRect(n)}),this.context.render(81))}afterRender(t){const{context:e}=this;"crop"===e.viewerConfig.toolMode&&(t.allPages.forEach(e=>{const i=this.boxRenderer.getAreaByUid(e.uid);if(i){if(e.isVisible){const t=e.getRect();i.updateAreaRect(t)}"current"===this.viewer.cropMode?i.isVisible=e.uid===t.currentUid:i.isVisible=e.isVisible}}),this.boxRenderer.updateOptions({zoom:t.context.zoom}),this.boxRenderer.render())}toolModeChanged(t){if("crop"!==t.oldToolMode&&"crop"===t.newToolMode){const t=this.context.getActiveTab();if(!t)return;t.allPages.forEach(e=>{const i=e.getRect(),n=this.boxRenderer.addArea(e.uid,i);"current"===this.viewer.cropMode?n.isVisible=e.uid===t.currentUid:n.isVisible=e.isVisible}),this.boxRenderer.updateOptions({zoom:t.context.zoom})}else"crop"!==t.newToolMode&&"crop"===t.oldToolMode&&(this.boxRenderer.clearArea(),this.context.render(82))}pageChanged(t){if("crop"===this.context.viewerConfig.toolMode)return this.context.getActiveTab()?0===t.total?(this.clearRedundantBoxes(),this.boxRenderer.clearArea(),void this.context.render(83)):void("current"===this.viewer.cropMode&&this.resetPageCropArea()):void 0}deletePages(t){t.pageUids.forEach(t=>{this.boxRenderer.deleteArea(t)})}updatePage(t){const{context:e}=this;if("crop"!==e.viewerConfig.toolMode)return;const i=e.getActiveTab();if(i&&i.uid===t.docUid)if("current"===this.viewer.cropMode&&t.pageUid===i.currentUid)this.resetPageCropArea();else if("all"===this.viewer.cropMode){const n=this.boxRenderer.getAreaByUid(t.pageUid),s=i.getPageByUid(t.pageUid).getRect();n.updateAreaRect(s),this.boxRenderer.areas.forEach(t=>{t.clearBoxes()}),e.render(84)}}addPages(t){const e=this.context.getActiveTab();null!=e&&e.total&&e.uid===t.docUid&&(t.pageUids.forEach(t=>{const i=e.getPageByUid(t),n=i.getRect();this.boxRenderer.addArea(i.uid,n),this.boxRenderer.updateOptions({zoom:e.context.zoom})}),this.boxRenderer.areas.forEach(t=>{t.clearBoxes()}))}resetPageCropArea(){const t=this.context.getActiveTab();this.clearRedundantBoxes();const e=t.getCurrentPage(),i=e.getRect();this.boxRenderer.addArea(e.uid,i),this.boxRenderer.updateOptions({zoom:t.context.zoom}),this.context.render(85)}clearRedundantBoxes(){const t=this.context.getActiveTab();t&&"current"===this.viewer.cropMode&&this.boxRenderer.areas.forEach(e=>{e.areaUid!==t.currentUid&&this.boxRenderer.clearAreaBoxes(e.areaUid)})}}class p_{constructor(t,e){Yi(this,"context",void 0),Yi(this,"core",void 0),Yi(this,"boxRenderer",void 0),Yi(this,"viewer",void 0),Yi(this,"isMousedown",!1),Yi(this,"canSlide",!1),Yi(this,"isStart",!1),Yi(this,"startX",void 0),Yi(this,"isSliding",void 0),Yi(this,"slideDistance",void 0),Yi(this,"slideDirection",void 0),Yi(this,"slideRAF",void 0),Yi(this,"tabX",void 0),Yi(this,"tabY",void 0),Yi(this,"canvas",void 0),Yi(this,"isRenderMagnifier",!1),Yi(this,"needRenderMagnifier",!1),Yi(this,"magnifierPoint",void 0),this.viewer=t,this.context=t.context,this.core=t.context.core,this.boxRenderer=e,this.canvas=this.context.rendererService.getCanvasDom()}afterRenderForMagnifier(){this.needRenderMagnifier&&this.context.magnifierService.render("crop",this.canvas,this.magnifierPoint)}isNotOverQuadCtrl(t){return this.boxRenderer.hasBox()&&!this.boxRenderer.isControlPointTouched(t)}mousedown(t){const e=this.context.getActiveTab();if(null!=e&&e.total)if(this.isMousedown=!0,!this.boxRenderer.isControlPointTouched(t)&&this.context.viewerConfig.enableSlide)this.canSlide=!0,this.slideStart(t);else{this.boxRenderer.onStartHandler(t);const e=this.boxRenderer.isControlPointTouched(t);if(this.isRenderMagnifier=e,e&&this.context.viewerConfig.enableMagnifier&&!oy(t)){const[e]=this.context.toCanvas(t);this.needRenderMagnifier=!0,this.magnifierPoint={x:e.pageX,y:e.pageY},this.afterRenderForMagnifier()}}}mousemove(t){const e=this.context.getActiveTab();if(null!=e&&e.total)if(ho(t)&&t.cancelable&&t.preventDefault(),this.canSlide)this.slideMove(t);else{const e=this.boxRenderer.onMoveHandler(t);if(oy(t)&&this.context.applyCursorState(e),this.isMousedown&&this.context.render(86),this.isRenderMagnifier&&this.context.viewerConfig.enableMagnifier&&!oy(t)){const[e]=this.context.toCanvas(t);this.needRenderMagnifier=!0,this.magnifierPoint={x:e.pageX,y:e.pageY}}}}mouseup(t){this.isMousedown&&(this.canSlide?this.slideEnd(t):this.boxRenderer.onEndHandler(t),this.isRenderMagnifier=!1,this.canSlide=!1,this.isMousedown=!1,this.needRenderMagnifier&&this.context.magnifierService.hide(),this.needRenderMagnifier=!1,this.magnifierPoint=null,this.context.render(87))}reRender(){const{context:t}=this,e=t.getActiveTab();null!=e&&e.total&&"visible"===t.viewerConfig.visibility&&(this.updatePageQuad(e),t.render(88))}updatePage(t){const{context:e}=this,i=e.getActiveTab();null!=i&&i.total&&"visible"===e.viewerConfig.visibility&&i.currentUid===t.pageUid&&(this.updatePageQuad(i),e.render(89))}afterRender(t){if(null==t||!t.total)return;const{boxRenderer:e}=this;let i=!1;t.visibleChildren.forEach(t=>{const n=e.getAreaByUid(t.uid);if(n&&t.isVisible){i=!0;const e=t.getRect();n.updateAreaRect(e)}}),e.updateOptions({zoom:t.context.zoom}),i&&e.render()}pageChanged(t){if(-1===t.current&&0===t.total)return void this.boxRenderer.clearArea();const e=this.context.getActiveTab();e&&this.updatePageQuad(e)}updatePageQuad(t){const{context:e}=this,i=t.getCurrentPage();if(!i)return!1;let n=null;const s=this.boxRenderer.getAreaByUid(i.uid);s&&s.boxes[0]&&(n=s.boxes[0].getQuad());const o=e.core.pageService.getPage(t.currentUid);this.boxRenderer.clearArea();const r=i.getRect(),a=this.boxRenderer.addArea(i.uid,r);this.boxRenderer.updateOptions({zoom:t.context.zoom});const l=o.getQuadVertices(),h=a.addQuadBox(l);let c=h.getQuad();return n&&(n=o.quadToPixelPPI(n)),c&&(c=o.quadToPixelPPI(c)),Ym(n),Ym(c),e.hooks.perspectiveQuadChanged.emit(Lf.create(c,n,o.isFull)),h}afterRotatePages(t){const e=this.context.getActiveTab();null!=e&&e.total&&t.pageUids.includes(e.currentUid)&&(this.updatePageQuad(e),this.context.render(90))}afterPerspective(t){let{pageUid:e,docUid:i}=t;const{context:n}=this,s=this.context.getActiveTab();if(null==s||!s.total)return;if(s.uid!==i||s.currentUid!==e)return;const o=s.getCurrentPage();o&&(o.isLoaded=!1),this.updatePageQuad(s),n.scrollByCurrentChanged=!0,n.showTab(s,{isClearOptimization:!0,renderReason:1})}slideStart(t){if(!this.context.viewerConfig.enableSlide)return;if(this.isSliding)return;const e=this.context.getActiveTab();if(null==e||!e.total)return;const{scrollLeft:i,scrollTop:n}=this.context.viewService.getMaxScrollValue();if(i>0||n>0)return;const s=this.context.toCanvas(t);if(s.length>1)return;const o=e.getPosition();this.tabX=o.x,this.tabY=o.y,this.startX=s[0].pageX,this.isStart=!0}slideMove(t){if(!this.isStart)return;const{context:e}=this,{viewerConfig:i}=e,n=e.getActiveTab(),s=e.toCanvas(t)[0].pageX-this.startX;if(s>0?this.slideDirection="right":s<0&&(this.slideDirection="left"),this.slideDistance=Math.min(n.context.viewportWidth,Math.abs(s)),this.isSliding)"right"===this.slideDirection?n.setPosition({x:this.slideDistance+this.tabX,y:this.tabY,z:0}):"left"===this.slideDirection&&n.setPosition({x:-this.slideDistance+this.tabX,y:this.tabY,z:0}),e.render(91);else if(n&&"single"===n.context.displayMode&&"crop"===i.toolMode&&i.enableSlide){const{scrollLeft:t,scrollTop:n}=this.context.viewService.getMaxScrollValue();Math.abs(s)>i.startSlideThresholdForPerspective&&t<=0&&n<=0&&(this.isSliding=!0,e.configService.updateConfig({displayMode:"slide"}))}}slideEnd(t){if(!this.isStart)return;const{context:e}=this,i=e.getActiveTab(),{displayMode:n}=i.context;"slide"===n&&this.slide(i),this.isStart=!1}slide(t){let e,i=0,n=0,s=0,o=!1;const{viewerConfig:r}=this.context,a=t.context.viewportWidth*r.slideThresholdForPerspective;this.slideDistance>=Math.max(a,r.startSlideThresholdForPerspective)?(n=t.context.viewportWidth,e=n-this.slideDistance,"left"===this.slideDirection?t.current!==t.total-1?(s=-this.slideDistance,i=-e/6):(n=0,e=this.slideDistance,o=!0,s=-this.slideDistance,i=e/6):0!==t.current?(s=this.slideDistance,i=e/6):(n=0,e=this.slideDistance,o=!0,s=this.slideDistance,i=-e/6)):(o=!0,n=0,e=this.slideDistance,"left"===this.slideDirection?(s=-this.slideDistance,i=e/6):(s=this.slideDistance,i=-e/6));const l=()=>{s+=i;const e=s>=0;if(Math.abs(s)>=n&&(s=n,e||(s*=-1)),t.setPosition({x:s+this.tabX,y:this.tabY,z:0}),Math.abs(s)===n)return o||("right"===this.slideDirection?this.context.viewer.gotoPage(t.current-1):this.context.viewer.gotoPage(t.current+1),this.context.configService.updateConfig({fitMode:"window"})),this.isSliding=!1,this.context.configService.updateConfig({displayMode:"single"}),void cancelAnimationFrame(this.slideRAF);this.slideRAF=requestAnimationFrame(l),this.context.render(92)};this.slideRAF=requestAnimationFrame(l)}}class g_{constructor(t){Yi(this,"service",void 0),this.service=t}startHandler(t){this.service.mousedown(t)}moveHandler(t){this.service.mousemove(t)}endHandler(t){this.service.mouseup(t)}isEditCropBox(t){return this.service.isEditCropBox(t)}isNotOverCropBox(t){return this.service.isNotOverCropBox(t)}}class f_{constructor(t){Yi(this,"service",void 0),this.service=t}startHandler(t){this.service.mousedown(t)}moveHandler(t){this.service.mousemove(t)}endHandler(t){this.service.mouseup(t)}isNotOverQuadCtrl(t){return this.service.isNotOverQuadCtrl(t)}}function m_(t,e){return{left:Uo(t.left,e),top:Uo(t.top,e),width:Uo(t.width,e),height:Uo(t.height,e)}}const v_={install(t){const e=function(t){return class extends t{constructor(t){super(t),Yi(this,"boxRenderer",void 0),Yi(this,"iCropMode","current"),Yi(this,"cropRectService",void 0),Yi(this,"perspectiveQuadService",void 0);const{isDefaultViewer:e,isPerspectiveViewer:i}=this.context;(e||i)&&(this.initBoxRenderer(),this.bindExternalEvents()),this.cropRectService=new u_(this,this.boxRenderer),this.perspectiveQuadService=new p_(this,this.boxRenderer),this.listenDefaultViewerEventsForBox(),this.listenDefaultGlobalEventsForBox(),this.listenPerspectiveViewerEventsForBox(),this.listenPerspectiveGlobalEventsForBox(),this.context.hasBoxRendererModule=!0,this.context.cropBoxEditService=new g_(this.cropRectService),this.context.perspectiveQuadEditService=new f_(this.perspectiveQuadService)}initBoxRenderer(){if(!this.context.isDefaultViewer&&!this.context.isPerspectiveViewer)return;const{enableEditCropBoxMidpoints:t,enableEditCropBoxVertices:e,enableHideEditingCropBoxMidpoint:i,enableHideEditingCropBoxVertex:n}=this.context.viewerConfig;this.boxRenderer=new d_({enableEditCropBoxMidpoints:t,enableEditCropBoxVertices:e,enableHideEditingCropBoxMidpoint:i,enableHideEditingCropBoxVertex:n}),this.boxRenderer.setCanvasDom(this.context.rendererService.getCanvasDom()),this.updateQuadStyle(),this.context.hooks.quadSelectionStyleChanged.on(()=>{this.updateQuadStyle()},this),this.hooks.resize.on(()=>{this.context.render(3)},this);const{hooks:s}=this.boxRenderer;s.boxCreated.on(t=>{let{box:e,fromEvent:i}=t;const n=this.context.getActiveTab();if(null!=n&&n.total&&(this.context.isDefaultViewer&&e.isRect&&!i&&"all"===this.cropMode&&this.boxRenderer.areas.forEach(t=>{t.boxes.length?t.boxes.forEach(i=>{t.isContainBox(e)?t.updateRectBox(i,[...e.vertexes]):t.clearBoxes()}):t.isContainBox(e)&&t.addRectBox([...e.vertexes],!0,!0)}),e.isRect)){let t=e.getRect();t=Bo(t,Cr.displayResolution,72),t=m_(t,2);const i=Hf.create(t);this.hooks.cropRectDrawn.emit(i)}}),s.boxDeleted.on(t=>{const e=this.context.getActiveTab();if(null!=e&&e.total&&t.isRect){let e=t.getRect();e=Bo(e,Cr.displayResolution,72),e=m_(e,2);const i=Wf.create(e);this.hooks.cropRectDeleted.emit(i)}}),s.boxModified.on(t=>{const e=this.context.getActiveTab();if(null==e||!e.total)return;const{box:i}=t;if(this.context.isDefaultViewer&&i.isRect){let{oldRect:e,newRect:n}=t,s=0;if("all"===this.cropMode&&this.boxRenderer.areas.forEach(t=>{t.boxes.length?t.boxes.forEach(e=>{t.isContainBox(i)?(s+=1,t.updateRectBox(e,[...i.vertexes])):t.clearBoxes()}):t.isContainBox(i)&&t.addRectBox([...i.vertexes])}),e&&(e=Bo(e,Cr.displayResolution,72),e=m_(e,2)),n&&(n=Bo(n,Cr.displayResolution,72),n=m_(n,2)),!e||!n||e.left!==n.left||e.top!==n.top||e.width!==n.width||e.height!==n.height){s=Math.max(1,s);for(let t=0;t<s;t++){const t=jf.create(e,n);this.hooks.cropRectModified.emit(t)}}}if(this.context.isPerspectiveViewer&&!i.isRect){const e=this.context.core.pageService.getPage(i.area.areaUid),n=this.boxRenderer.getAreaByUid(i.area.areaUid);if(!n)return;const s=n.isFullBox(i);e.isFull=s,e.setActiveQuad(i.getQuad());let{oldQuad:o,newQuad:r}=t;o&&(o=e.quadToPixelPPI(o)),r&&(r=e.quadToPixelPPI(r)),Ym(o),Ym(r),this.hooks.perspectiveQuadChanged.emit(Lf.create(r,o,e.isFull))}})}updateQuadStyle(){const t=this.context.styleService.getParsedQuadSelectionStyle();this.boxRenderer.updateConfig({boxStyle:t})}bindExternalEvents(){this.hooks.cropRectDrawn.on(t=>{this.emit("cropRectDrawn",{rect:t.rect})},this),this.hooks.cropRectDeleted.on(t=>{this.emit("cropRectDeleted",{rect:t.rect})},this),this.hooks.cropRectModified.on(t=>{this.emit("cropRectModified",{oldRect:t.oldRect,newRect:t.newRect})},this),this.hooks.perspectiveQuadChanged.on(t=>{const{newQuad:e,oldQuad:i}=t;let n=!1;i&&e&&(n=No(i,e)),n||this.emit("quadModified",{oldQuad:i,newQuad:e})},this)}get cropMode(){return this.iCropMode}set cropMode(t){if(this.iCropMode===t)return;const e=this.iCropMode;this.iCropMode=t,this.hooks.cropModeChanged.emit(new Jf(e,t));const i=this.context.getActiveTab();if(null!=i&&i.total){if("current"===e&&"all"===t){const t=this.boxRenderer.getAreaByUid(i.currentUid);if(t){const e=t.boxes[0];e&&this.boxRenderer.areas.forEach(t=>{t.isContainBox(e)?t.boxes.length?t.updateRectBox(t.boxes[0],[...e.vertexes]):t.addRectBox([...e.vertexes]):t.clearBoxes()})}}this.cropRectService.clearRedundantBoxes(),this.context.render(74)}}toggleFullPerspective(){const{context:t}=this;if(!t.isPerspectiveViewer)return;const e=t.getActiveTab();null!=e&&e.total&&t.core.pageService.getPage(e.currentUid).toggleFull()&&(this.perspectiveQuadService.updatePageQuad(e),t.render(75))}listenDefaultGlobalEventsForBox(){this.context.isPerspectiveViewer||(this.context.core.editService.onAfterRotatePages.on(t=>{this.cropRectService.afterRotatePages(t)},this),this.context.core.onAfterPerspective.on(t=>{this.cropRectService.afterPerspective(t)},this))}listenPerspectiveGlobalEventsForBox(){this.context.isPerspectiveViewer&&(this.context.core.editService.onAfterRotatePages.on(t=>{this.perspectiveQuadService.afterRotatePages(t)},this),this.context.core.onAfterPerspective.on(t=>{this.perspectiveQuadService.afterPerspective(t)},this))}listenPerspectiveViewerEventsForBox(){if(!this.context.isPerspectiveViewer)return;const{perspectiveQuadService:t}=this;this.hooks.resize.on(()=>{t.reRender()},this),this.hooks.visibleChanged.on(()=>{t.reRender()},this),this.hooks.updatePage.on(e=>{t.updatePage(e)},this),this.hooks.afterRender.on(e=>{t.afterRender(e),t.afterRenderForMagnifier()},this),this.hooks.pageChanged.on(e=>{t.pageChanged(e)},this)}listenDefaultViewerEventsForBox(){if(!this.context.isDefaultViewer)return;const{cropRectService:t}=this;this.hooks.updatePage.on(e=>{t.updatePage(e)},this),this.hooks.addPagesToDoc.on(e=>{t.addPages(e)},this),this.hooks.afterRender.on(e=>{t.afterRender(e),t.afterRenderForMagnifier()},this),this.hooks.toolModeChanged.on(e=>{t.toolModeChanged(e)},this),this.hooks.pageChanged.on(e=>{t.pageChanged(e)},this),this.hooks.deletePages.on(e=>{t.deletePages(e)},this),this.hooks.beforeCropPages.on(()=>{this.clearRectBox()},this),this.hooks.closeDocument.on(t=>{t.pages.forEach(t=>{this.boxRenderer.deleteArea(t)})},this)}setRectBox(t,e){const i=this.context.getActiveTab();return!(!i||!i.total||(Ps(e)&&(e=[i.current]),i.indicesToUids(e).forEach(e=>{let i=t;i=Bo(t,Cr.dataResolution,Cr.displayResolution);const n=(t=>{const{left:e,top:i,width:n,height:s}=t;return[e,i,e+n,i,e+n,i+s,e,i+s]})(i),s=this.boxRenderer.areas.get(e);s.boxes.length?s.updateRectBox(s.boxes[0],n,!0):s.addRectBox(n)}),this.context.render(76),0))}getRectBox(){const t=this.context.getActiveTab();if(t&&t.total){let e=null;if(t.allPages.find(t=>{const i=this.boxRenderer.getAreaByUid(t.uid);return!(null==i||!i.boxes.length||(e=i,0))}),e){const t=e.boxes[0];if(null!=t&&t.isRect){let e=t.getRect();return e=Bo(e,Cr.displayResolution,Cr.dataResolution),e=m_(e,2),e.width=e.width||1,e.height=e.height||1,e}}}return null}getRenderedRectBoxCount(){const t=this.context.getActiveTab();let e=0;return t&&t.total&&this.boxRenderer.areas.forEach(t=>{e+=t.boxes.length}),e}getMatchedCropBoxIndices(t){const e=this.context.getActiveTab();if(!e)return[];const i=[];return e.allPages.forEach((e,n)=>{const{width:s,height:o}=this.context.viewer.getRealPtPageSize(n);(function(t,e,i){const{left:n,top:s,width:o,height:r}=t,a=1e-4;return!(Math.abs(n-e)>a&&n>e||Math.abs(n+o-e)>a&&n+o>e||Math.abs(s-i)>a&&s>i||Math.abs(s+r-i)>a&&s+r>i)})(t,s,o)&&i.push(n)}),i}getCropIndices(){const t=this.context.getActiveTab();let e=[];if(t&&t.total)if("all"===this.iCropMode){const i=[];this.boxRenderer.areas.forEach(t=>{t.boxes.length&&i.push(t.areaUid)}),e=t.uidsToIndices(i)}else e=[t.current];return e}clearRectBox(){return this.boxRenderer.areas.forEach(t=>{t.clearBoxes()}),!0}setQuadBox(t){const e=this.context.getActiveTab();if(!e||!e.total)return!1;const i=this.context.core.pageService.getPage(e.currentUid);let n=t;n=t.map(t=>Bo(t,i.resource.resolutionX,Cr.displayResolution));const s=this.boxRenderer.getAreaByUid(e.currentUid),{width:o,height:r}=s,a=Wm(n,o,r);return i.isFull=a,i.setActiveQuad(n),this.perspectiveQuadService.updatePageQuad(e),this.context.render(77),!0}getQuadBox(){const t=this.context.getActiveTab();if(t&&t.total){const e=this.boxRenderer.getAreaByUid(t.currentUid).boxes[0];if(!e.isRect){let i=e.getQuad();const n=this.context.core.pageService.getPage(t.currentUid);return i=i.map(t=>Bo(t,Cr.displayResolution,n.resource.resolutionX)),Ym(i),i}}return null}resetQuadBox(t){const e=this.context.getActiveTab();if(null==e||!e.total)return!1;let i=[];return i=Ps(t)?[e.currentUid]:e.indicesToUids(t),i.forEach(t=>{const i=this.context.core.pageService.getPage(t),{quad:n}=i;n?(i.isFull&&(i.isFull=!1),i.setActiveQuad(n),this.perspectiveQuadService.updatePageQuad(e)):i.isFull||(i.isFull=!0,this.perspectiveQuadService.updatePageQuad(e))}),this.context.render(78),!0}clearQuadBox(){return this.boxRenderer.areas.forEach(t=>{t.clearBoxes()}),!0}isConvexQuad(t){return Oo(t.flat())}}}(t.getClass("Viewer"));t.setClass("Viewer",e)}};class y_ extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="rotate",this.isValid=!0,this.core.commandService.onBeforeRefreshCommands.on(t=>{const{pageUids:e}=this.action;e.slice().forEach(i=>{if(t.pageUids.includes(i)){const t=e.indexOf(i);e.splice(t,1)}}),this.isValid=e.length>0},this)}execute(){const{core:t,action:e}=this;e.pageUids.forEach(i=>{t.pageService.getPage(i).addAction(e)});const i=fm.create(e.docUid,e.angle,e.pageUids);return t.editService.onRotatePages.emit(i),t.editService.onAfterRotatePages.emit(i),!0}undo(){const{core:t,action:e}=this;e.pageUids.forEach(i=>{t.pageService.getPage(i).deleteAction(e.actionUid)});const i=fm.create(e.docUid,e.angle,e.pageUids);t.editService.onRotatePages.emit(i),t.editService.onAfterRotatePages.emit(i)}}class x_ extends ry{constructor(t,e){super(),Yi(this,"action",void 0),Yi(this,"core",void 0),this.action=t,this.core=e,this.type="crop",this.isValid=!0,this.core.commandService.onBeforeRefreshCommands.on(t=>{const{pageUids:e}=this.action;e.slice().forEach(i=>{if(t.pageUids.includes(i)){const t=e.indexOf(i);e.splice(t,1)}}),this.isValid=e.length>0},this)}execute(){const{core:t,action:e}=this;e.pageUids.forEach(e=>{t.pageService.getPage(e).addAction(this.action)});const i=cm.create(e.docUid,e.rect,e.pageUids);return t.editService.onCropPages.emit(i),t.editService.onAfterCropPages.emit(i),!0}undo(){const{core:t,action:e}=this;e.pageUids.forEach(i=>{t.pageService.getPage(i).deleteAction(e.actionUid)});const i=cm.create(e.docUid,e.rect,e.pageUids);t.editService.onCropPages.emit(i),t.editService.onAfterCropPages.emit(i)}}class w_ extends Wo{constructor(t){super(),Yi(this,"core",void 0),Yi(this,"onRotatePages",void 0),Yi(this,"onAfterRotatePages",void 0),Yi(this,"onCropPages",void 0),Yi(this,"onAfterCropPages",void 0),this.core=t,this.initEventEmitter()}initEventEmitter(){this.onRotatePages=jo(this),this.onAfterRotatePages=jo(this),this.onCropPages=jo(this),this.onAfterCropPages=jo(this)}rotatePages(t,e,i,n){const s={actionUid:Us(),type:"rotate",docUid:t,pageUids:[...e],angle:i,rotationType:n},{core:o}=this,r=new y_(s,o);return o.commandService.execute(r,t),!0}cropPages(t,e,i){const n={actionUid:Us(),type:"crop",docUid:t,pageUids:[...e],rect:{...i}},{core:s}=this,o=new x_(n,s);return s.commandService.execute(o,t),!0}}const C_={apply(t){t.editService=new w_(t)},install(t){const e=t.getClass("Viewer"),i=(n=e,class extends n{constructor(t){super(t),this.listenGlobalEventsForEdit(),this.listenViewerEventsForEdit()}listenGlobalEventsForEdit(){const{context:t}=this,e=e=>{let{docUid:i,pageUids:n}=e;const s=t.tabService.getTab(i);if(null!=s&&s.isActive){t.scrollByCurrentChanged=!0,t.clearOptimization(n);let e=!0;t.isDefaultViewer?"none"===s.context.fitMode&&(e=!1):t.isThumbnailViewer&&(e=!1),t.showTab(s,{isClearOptimization:e,renderReason:81})}};t.core.editService.onRotatePages.on(e,this),t.core.editService.onCropPages.on(e,this)}listenViewerEventsForEdit(){this.hooks.beforeLayout.on(t=>{const{core:{pageService:e},isDefaultViewer:i,isThumbnailViewer:n,isPerspectiveViewer:s}=this.context;(i||n||s)&&t.allPages.forEach(t=>{let s=null;const o=e.getPage(t.uid);s=i||n?o.getEditResult():o.getEditResultForPerspective(),s&&(t.rWidth=s.rWidth,t.rHeight=s.rHeight,t.cropLeft=s.cropLeft,t.cropTop=s.cropTop,t.cropWidth=s.cropWidth,t.cropHeight=s.cropHeight,t.rotation=s.rotation,t.mediaBoxRect=s.mediaBox,t.cropBoxRect=s.cropBox)})},this)}rotatePages(t,e){var i;if(t%360==0)return!0;const n=this.context.getActiveTab();if(!n)return!1;null!==(i=e)&&void 0!==i||(e=[n.current]);const s=n.indicesToUids(e);return this.context.core.editService.rotatePages(n.uid,s,t,"contain")}cropPages(t,e){var i;const n=this.context.getActiveTab();if(!n)return!1;null!==(i=e)&&void 0!==i||(e=[n.current]);const s=n.indicesToUids(e);t=Bo(t,Cr.dataResolution,Cr.displayResolution),this.hooks.beforeCropPages.emit();const o=this.context.core.editService.cropPages(n.uid,s,t);return this.context.clearSelectedTexts(),this.hooks.afterCropPages.emit(s),o}});var n;t.setClass("Viewer",i)}};class b_{async perspective(t,e,i,n,s){var o;const r=new lr,a=await r.initImage({source:e.data,isRGBA:e.type===tr.RGBA,width:e.width,height:e.height,isBGRA:e.type===tr.BGRA});if(t.taskInfo.canceled)return r.terminate(),null;if(a.srcBuffer&&(e.data=a.srcBuffer),null!=n&&n.angle&&(await r.rotate({angle:n.angle}),t.taskInfo.canceled))return r.terminate(),null;if(await r.perspective(i),t.taskInfo.canceled)return r.terminate(),null;const l=await r.getImage({jpegQuality:null==s?void 0:s.jpegQuality,ifDeleteObject:!0,isRGBA:e.type===tr.RGBA,bitDepth:null==s?void 0:s.bitDepth,xDpi:null==s?void 0:s.xdpi,yDpi:null==s?void 0:s.ydpi,returnType:ir.RT_BINARY,outputType:null!==(o=null==s?void 0:s.outputType)&&void 0!==o?o:xr[e.type]});await r.freeReservedData();const h={data:new Blob([l.imageData],{type:l.blobType}),width:l.imageWidth,height:l.imageHeight,resolutionX:l.imageXResolution,resolutionY:l.imageYResolution};return r.terminate(),h}}Kv.registerPlugin(EC),Kv.registerPlugin(r_),Kv.registerPlugin(v_),Kv.registerPlugin(C_),Kv.registerPlugin(tw),Kv.registerPlugin(LT);const S_=new class{constructor(){Yi(this,"tasks",[]),Yi(this,"isRunning",!1),this.registerParser("image/jpeg",vd),this.registerParser("image/bmp",vd),this.registerParser("image/png",vd),this.registerParser("image/tiff",yd),this.registerParser("image/jp2",vd),this.registerParser("application/pdf",pu),this.registerParser("image/rgba",fu),this.registerParser("application/ddv-blank-image",Uu)}dispose(){this.reset()}reset(){vu.getAllParsers().forEach(t=>t.destroy()),vu.clear(),wu.clear()}freeParserByFileUid(t){bu.execute(t)}registerParser(t,e){Du.execute({mime:t,parser:e})}unregisterParser(t){Ru.execute(t)}registerCustomParser(t,e){ku.execute({mime:t,parser:e})}unregisterCustomParser(t){Mu.execute(t)}getDefaultParserOptions(t){return Lu.execute(t)}setDefaultParserOptions(t,e){return Ou.execute({mime:t,options:e})}getCustomParserClasses(t){return Bu.execute(t)}async parse(t,e,i,n,s){return Au.execute({fileData:t,mime:e,fileUid:i,indices:n,parseOptions:s})}async parseAnnotation(t,e,i,n,s,o){return Iu.execute({fileData:t,mime:e,fileUid:i,indices:s,parseOptions:o,parsedPages:n})}async getPage(t,e,i,n){return Tu.execute({fileData:t,mime:e,fileUid:i,fileIndex:n})}cancelGetPage(t,e){Eu.execute({fileUid:t,fileIndex:e})}async renderPage(t,e,i,n,s,o){const r={taskInfo:o,params:[t,e,i,n,s,o],resolve:void 0,reject:void 0},a=new Promise((t,e)=>{r.resolve=t,r.reject=e});return this.isRunning?(this.tasks.push(r),this.freshTasks(),a):(this.executeRenderPageTask(r),a)}async executeRenderPageTask(t){this.isRunning=!0;try{const e=await _u.execute({fileData:t.params[0],mime:t.params[1],fileUid:t.params[2],fileIndex:t.params[3],config:t.params[4],task:t.taskInfo});t.resolve(e)}catch(e){t.reject(e)}if(this.freshTasks(),this.tasks.length>0){const t=this.tasks.pop();this.executeRenderPageTask(t)}else this.isRunning=!1}freshTasks(){this.tasks.slice().forEach(t=>{if(t.taskInfo.canceled){t.resolve(null);const e=this.tasks.indexOf(t);this.tasks.splice(e,1)}})}cancelRenderPage(t,e){Pu.execute({fileUid:t,task:e})}async getParseInfo(t,e,i,n){return Nu.execute({fileData:t,mime:e,fileUid:i,options:n})}async getPageTexts(t,e,i,n){return Su.execute({fileData:t,mime:e,fileUid:i,indices:n})}},T_=new Kv(S_,new class{constructor(){this.registerSaver("application/pdf",Ur),this.registerSaver("image/png",Fr),this.registerSaver("image/jpeg",Fr),this.registerSaver("image/tiff",Vr)}registerSaver(t,e){_r.execute({mime:t,saverConstructor:e})}unregisterSaver(t){Pr.execute(t)}getSaver(t){return Er.execute(t)}},new class extends vr{async handler(t){const[e,i,n,s]=t.params;return(new b_).perspective(t,e,i,n,s)}dispose(){}perspective(t,e,i,n){const s={taskUid:Us(),canceled:!1};return this.createTask("perspective",[t,e,i,n],s)}},new class extends vr{constructor(){super(...arguments),Yi(this,"filter",void 0)}async handler(t){var e;const[i,n,s,o]=t.params;return await(null===(e=this.filter)||void 0===e?void 0:e.applyFilter(i,n))}get enableFilter(){return!!this.filter}async applyFilter(t,e,i,n){const s={taskUid:Us(),canceled:!1};return this.createTask("filter",[t,e,i,n],s)}cancelFilter(t,e){}setImageFilter(t){t?this.filter=t:this.filter&&(this.filter.destroy(),this.filter=null)}getDefaultFilterType(){var t;return null===(t=this.filter)||void 0===t?void 0:t.defaultFilterType}getSupportedFilters(){var t;return(null===(t=this.filter)||void 0===t?void 0:t.querySupported())||[]}},new class{constructor(){Yi(this,"detector",void 0)}get enableDetect(){return this.detector&&this.detector instanceof Ju}detect(t,e){var i;return null===(i=this.detector)||void 0===i?void 0:i.detect(t,e)}setDetector(t){t?this.detector=t:this.detector&&(this.detector.destroy(),this.detector=null)}resetDetector(){this.detector&&this.detector.reset()}reset(){var t;null===(t=this.detector)||void 0===t||t.destroy(),this.detector=null}});function E_(t,e,i,n){return!!Ps(t)&&fp.output(e,i,n,void 0,pp.PARAM_MISS,!0)}function __(t,e,i,n){return!!Es(t)||fp.output(e,i,n,void 0,pp.PARAM_INVALID)}class P_{static getTooltip(){return MT.getTooltip()}static setTooltip(t){const e="Elements.setTooltip",i="tooltip";return!(E_(t,1,e,i)||!__(t,1,e,i)||(MT.setTooltip(t),0))}static getDisplayTextConfig(){return MT.getDisplayTextConfig()}static setDisplayTextConfig(t){const e="Elements.displayTextConfig",i="displayTextConfig";return!(E_(t,1,e,i)||!__(t,1,e,i)||(MT.setDisplayTextConfig(t),0))}static get Layout(){return"Layout"}static get Button(){return"Button"}static get Capture(){return"Capture"}static get Flashlight(){return"Flashlight"}static get CameraConvert(){return"CameraConvert"}static get CameraResolution(){return"CameraResolution"}static get AutoDetect(){return"AutoDetect"}static get AutoCapture(){return"AutoCapture"}static get ImagePreview(){return"ImagePreview"}static get Rotate(){return"Rotate"}static get RotateLeft(){return"RotateLeft"}static get RotateRight(){return"RotateRight"}static get Delete(){return"Delete"}static get DeleteCurrent(){return"DeleteCurrent"}static get DeleteAll(){return"DeleteAll"}static get Zoom(){return"Zoom"}static get ZoomIn(){return"ZoomIn"}static get ZoomOut(){return"ZoomOut"}static get ZoomByPercentage(){return"ZoomByPercentage"}static get Crop(){return"Crop"}static get CropCurrent(){return"CropCurrent"}static get CropAll(){return"CropAll"}static get FullQuad(){return"FullQuad"}static get PerspectiveAll(){return"PerspectiveAll"}static get Undo(){return"Undo"}static get Redo(){return"Redo"}static get Pan(){return"Pan"}static get CropMode(){return"CropMode"}static get Load(){return"Load"}static get Download(){return"Download"}static get Print(){return"Print"}static get Filter(){return"Filter"}static get Restore(){return"Restore"}static get ThumbnailSwitch(){return"ThumbnailSwitch"}static get Pagination(){return"Pagination"}static get FitMode(){return"FitMode"}static get FitWindow(){return"FitWindow"}static get FitHeight(){return"FitHeight"}static get FitWidth(){return"FitWidth"}static get ActualSize(){return"ActualSize"}static get DisplayMode(){return"DisplayMode"}static get SinglePage(){return"SinglePage"}static get ContinuousPage(){return"ContinuousPage"}static get MainView(){return"MainView"}static get SeparatorLine(){return"SeparatorLine"}static get Done(){return"Done"}static get Back(){return"Back"}static get Blank(){return"Blank"}static get Close(){return"Close"}static get AnnotationSet(){return"AnnotationSet"}static get EllipseAnnotation(){return"EllipseAnnotation"}static get EraseAnnotation(){return"EraseAnnotation"}static get InkAnnotation(){return"InkAnnotation"}static get LineAnnotation(){return"LineAnnotation"}static get PolygonAnnotation(){return"PolygonAnnotation"}static get PolylineAnnotation(){return"PolylineAnnotation"}static get RectAnnotation(){return"RectAnnotation"}static get SelectAnnotation(){return"SelectAnnotation"}static get StampIconAnnotation(){return"StampIconAnnotation"}static get StampImageAnnotation(){return"StampImageAnnotation"}static get TextBoxAnnotation(){return"TextBoxAnnotation"}static get TextTypewriterAnnotation(){return"TextTypewriterAnnotation"}static get BringForward(){return"BringForward"}static get BringToFront(){return"BringToFront"}static get SendBackward(){return"SendBackward"}static get SendToBack(){return"SendToBack"}static get HighlightAnnotation(){return"HighlightAnnotation"}static get UnderlineAnnotation(){return"UnderlineAnnotation"}static get StrikeoutAnnotation(){return"StrikeoutAnnotation"}static get TextSelectionMode(){return"TextSelectionMode"}static get TextSearchPanel(){return"TextSearchPanel"}static get TextSearchPanelSwitch(){return"TextSearchPanelSwitch"}}const A_={type:"Layout",flexDirection:"column",children:[{type:"Layout",className:"ddv-capture-viewer-header-mobile",children:[{type:"CameraResolution",className:"ddv-capture-viewer-resolution"},P_.Flashlight]},P_.MainView,{type:"Layout",className:"ddv-capture-viewer-footer-mobile",children:[P_.AutoDetect,P_.AutoCapture,{type:"Capture",className:"ddv-capture-viewer-captureButton"},P_.ImagePreview,P_.CameraConvert]}]},I_={type:"Layout",flexDirection:"column",className:"ddv-edit-viewer-mobile",children:[{type:"Layout",className:"ddv-edit-viewer-header-mobile",children:[P_.Blank,P_.AnnotationSet,P_.Pagination,P_.Download,P_.TextSearchPanelSwitch]},P_.MainView,{type:"Layout",className:"ddv-edit-viewer-footer-mobile",children:[P_.DisplayMode,P_.RotateLeft,P_.Crop,P_.Undo,P_.Delete,P_.Load]},{type:P_.TextSearchPanel,className:"ddv-edit-viewer-search-mobile"}]},D_={type:"Layout",flexDirection:"column",children:[{type:"Layout",className:"ddv-perspective-viewer-header-mobile",children:[P_.Blank,P_.Pagination,P_.PerspectiveAll]},P_.MainView,{type:"Layout",className:"ddv-perspective-viewer-footer-mobile",children:[P_.FullQuad,P_.RotateLeft,P_.RotateRight,P_.DeleteCurrent,P_.DeleteAll]}]},R_={type:"Layout",flexDirection:"column",className:"ddv-capture-viewer-desktop",children:[{type:"Layout",className:"ddv-capture-viewer-header-desktop",children:[{type:P_.CameraResolution,className:"ddv-capture-viewer-resolution-desktop"},P_.AutoDetect,{type:P_.Capture,className:"ddv-capture-viewer-capture-desktop"},P_.AutoCapture]},P_.MainView,{type:P_.ImagePreview,className:"ddv-capture-viewer-image-preview-desktop"}]},k_={type:"Layout",flexDirection:"column",children:[{type:"Layout",className:"ddv-perspective-viewer-header-desktop",children:[P_.FullQuad,P_.RotateLeft,P_.RotateRight,P_.DeleteCurrent,P_.DeleteAll,{type:P_.Pagination,className:"ddv-perspective-viewer-pagination-desktop"},{type:P_.PerspectiveAll,className:"ddv-perspective-viewer-perspective-desktop"}]},P_.MainView]},M_={type:P_.Layout,flexDirection:"column",className:"ddv-edit-viewer-desktop",children:[{type:P_.Layout,className:"ddv-edit-viewer-header-desktop",children:[{type:P_.Layout,enableScroll:!0,children:[P_.ThumbnailSwitch,P_.Zoom,P_.FitMode,P_.DisplayMode,P_.RotateLeft,P_.RotateRight,P_.Crop,P_.Undo,P_.Redo,P_.DeleteCurrent,P_.DeleteAll,P_.Pan,P_.TextSelectionMode,P_.SeparatorLine,P_.AnnotationSet]},{type:P_.Layout,children:[{type:P_.Pagination,className:"ddv-edit-viewer-pagination-desktop"},P_.Load,P_.Download,P_.Print,P_.TextSearchPanelSwitch]}]},{type:P_.Layout,flexDirection:"row",children:[P_.MainView,P_.TextSearchPanel]}]},L_={type:P_.Layout,children:[P_.MainView]};_s(I_).children[0].children=[P_.Blank,P_.Blank,P_.Pagination,P_.AnnotationSet,P_.Download];const O_=_s(M_);var B_,N_;O_.children[0].children[0].enableScroll=!0,O_.children[0].children[0].children.push(P_.SeparatorLine,P_.AnnotationSet),function(t){t.REJECTED="rejected",t.ACCEPTED="accepted",t.INITIAL_HERE="initialHere",t.SIGN_HERE="signHere",t.WITNESS="witness",t.APPROVED="approved",t.NOT_APPROVED="notApproved",t.DRAFT="draft",t.FINAL="final",t.COMPLETED="completed",t.CONFIDENTIAL="confidential",t.VOID="void"}(B_||(B_={})),function(t){t.NONE="none",t.OPEN="open",t.OPEN_REVERSE="openReverse",t.CLOSED="closed",t.CLOSED_REVERSE="closedReverse",t.BUTT="butt",t.SLASH="slash",t.SQUARE="square",t.DIAMOND="diamond",t.CIRCLE="circle"}(N_||(N_={}));const U_={background:"#e2e1de"},F_={border:"1px solid #707070",background:"#fff"},V_={border:"2px solid #fe8e14",background:"rgba(255,255,255,0)",maskColor:"rgba(128,128,128,0.6)",ctrlBorderRadius:"50%",ctrlBackground:"#fe8e14",ctrlBorder:"2px solid #fe8e14",ctrlWidth:"15px",ctrlHeight:"15px",invalidCtrlBorderColor:"red",invalidBorderColor:"red"},W_={opacity:1,borderWidth:1,borderColor:"rgb(0,0,0)",background:"",lineDash:[0,0]},H_={content:"",color:"rgb(0,0,0)",fontSize:16,fontFamily:"Helvetica",fontStyle:"normal",fontWeight:"normal",lineThrough:!1,underline:!1},j_={content:"",color:"rgb(0,0,0)",fontSize:1536/72,fontFamily:"Helvetica",fontStyle:"normal",fontWeight:"normal",lineThrough:!1,underline:!1};Ms()&&(W_.borderWidth=3,H_.fontSize=72);const z_={...W_,lineEnding:{start:N_.NONE,end:N_.NONE}},G_={paletteConfig:{maxFontSize:256,maxBorderWidth:40,colorList:["#F01314","#FD7C10","#FFEE5F","#07C37F","#0E68F5","#9D3BFE","#000000","#FF9494","#87440C","#B7A514","#046743","#50C9FF","#EBA3ED","#ffffff","#CECECE"],labels:{text:"Text",stroke:"Stroke",fill:"Fill",opacity:"Opacity",style:"Style",standardBusiness:"StandardBusiness"}},toolbarConfig:{},annotationSelectionStyle:{border:"1px solid #59626A",background:"",ctrlBorderRadius:"6px",ctrlWidth:"12px",ctrlHeight:"12px",ctrlBorder:"1px solid #59626A",ctrlBackground:"white"},inkCreateDelay:1e3,showOnTopWhenSelected:!1,enableContinuousDrawing:!1,defaultStyleConfig:{rectangle:{...W_},ellipse:{...W_},polygon:{...W_},polyline:{...z_},line:{...z_},ink:{opacity:1,borderWidth:Ms()?3:1,borderColor:"rgb(0,0,0)"},textBox:{...W_,textAlign:"left",textContent:{...H_}},textTypewriter:{opacity:1,textContent:{...H_}},stamp:{opacity:1,stamp:B_.DRAFT},highlight:{background:"#FD7C10",opacity:1},underline:{borderColor:"#0E68F5",opacity:1},strikeout:{borderColor:"#F01314",opacity:1}}},Y_={canvasStyle:{...U_},quadSelectionStyle:{...V_},enableAutoCapture:!1,enableAutoDetect:!1,enableTorch:!1,maxFrameNumber:10,acceptedPolygonConfidence:80};function $_(t,e){return!!t.getActiveTab()||fp.output(e,void 0,void 0,void 0,pp.DOC_NOT_OPEN)}function X_(t,e,i,n){return!i.getActiveTab().doc.pages.length&&fp.output(n,t,e,void 0,pp.DOC_NO_IMAGE,!0)}function q_(t,e,i,n){return!!function(t){return!(!Ls(t)||Ls(t)&&!Number.isInteger(t))}(t)||fp.output(n,e,i,void 0,pp.PARAM_INVALID)}function Z_(t,e,i,n,s){const o=TI.isUiConfigValid(t,n);if(o.length>0)return fp.output(s,i,n,o);const r=dI(t,e);return!r||fp.output(s,e.charAt(0).toUpperCase()+e.slice(1),r,void 0,pp.ELEMENT_UNSUPPORTED)}function J_(t,e,i,n,s,o){return(t<e||t>i)&&fp.output(n,s,o,void 0,pp.PARAM_OUT_OF_RANGE,!0)}function K_(t,e,i,n){return!!t.includes(e)||fp.output(i,n,void 0,void 0,pp.PAGE_NOT_EXIST)}function Q_(t,e,i,n){return!!ks(t)||fp.output(n,e,i,void 0,pp.PARAM_INVALID)}function tP(t,e,i,n,s){const o=fp.formatError(fp.isStringAndNotEmpty(t,s));return!o||fp.output(e,i,n,void 0,o)}function eP(t,e,i,n,s,o,r){const a=TI.isNumberArrayValid(t,s,o,r);return!a.length||fp.output(e,i,n,a,pp.PARAM_INVALID)}class iP{getIsBoundContainer(t){return t.context.viewService.isBindContainer}bindContainer(t,e,i){E_(e,0,i,"container");const n=TI.isContainerParamValid(e);n&&fp.error(i,"container",void 0,n),t.bindContainer(e)}unbindContainer(t){t.unbindContainer()}getIsVisible(t){return"visible"===t.getViewerConfig().visibility}show(t){t.show()}hide(t){t.hide()}getCurrentDocument(t){var e;const i=null===(e=t.getActiveTab())||void 0===e?void 0:e.uid;return i?NI.getDocument(i):null}openDocument(t,e,i){const n="docUid or doc";E_(t,0,i,n),function(t){return!!Os(t)&&0!==t.trim().length}(t)||Es(t)||fp.error(i,n,void 0,pp.PARAM_INVALID);const s=Es(t)?t.uid:t;!function(t,e,i,n,s){t.getDocument(e)||fp.output(0,n,s,void 0,pp.DOC_NOT_EXIST)}(T_.documentService,s,0,i,n),T_.getViewer(e)||fp.error(i,"viewerUid",void 0,pp.PARAM_INVALID),T_.openDocument(s,e)}closeDocument(t,e){return!!$_(t,1)&&(t.closeDocument(),!0)}getStyle(t,e,i,n,s){const o="styleName";if(E_(i,1,s,o)||!tP(i,1,s,o))return null;if(!n.includes(i))return fp.warning(s,o,void 0,pp.PARAM_NOT_SUPPORT),null;if("annotationSelectionStyle"===i)return t.getAnnotationConfig().controlsStyle;const r=t.getViewerConfig();if(i in r){const t=function(t,e){const i=["border","background"],n=["left","top","right","bottom","width","height","background","border","borderRadius","translateX","translateY","opacity","visibility"],s={pageStyle:i,selectedPageStyle:i,hoveredPageStyle:i,canvasStyle:[...i,"cursor"],checkboxStyle:[...n,"checkMarkColor","checkMarkLineWidth"],pageNumberStyle:[...n,"color","fontSize","fontFamily","onPage"],quadSelectionStyle:["border","background","ctrlBorderRadius","ctrlBorder","ctrlWidth","ctrlHeight","ctrlBackground","invalidCtrlBorderColor","invalidBorderColor"]};if(t in s){const i=s[t];return Object.fromEntries(Object.entries(e).filter(t=>{let[e,n]=t;return i.includes(e)}))}return _s(e)}(i,r[i]);return"capture"===e&&"quadSelectionStyle"===i?{border:t.border,background:t.background}:t}return null}updateStyle(t,e,i,n,s){return!(E_(e,1,s,"styleName")||E_(i,1,s,"style")||!tP(e,1,s,"styleName")||!__(i,1,s,"style")||!function(t,e,i,n,s){if(!tP(t,1,n,s))return!1;if(!i.includes(t))return fp.output(1,n,s,void 0,pp.PARAM_NOT_SUPPORT);const o=yI(t,e);return!o.length||fp.output(1,n,"style",o)}(e,i,n,s,"styleName")||("annotationSelectionStyle"===e?(t.updateAnnotationConfig({controlsStyle:i}),0):(t.updateViewerConfig({[e]:i}),0)))}getUiConfig(t){return t.getUiConfig()}updateUiConfig(t,e,i,n){const s="uiConfig";return!(E_(e,1,n,s)||!Z_(e,i,n,s,1))&&t.updateUiConfig(e)}indexToUid(t,e,i){const n="index";return E_(e,1,i,n)||!q_(e,i,n,1)||!$_(t,1)||X_(void 0,void 0,t,1)||J_(e,0,t.getPageCounts()-1,1,i,n)?"":t.indexToUid(e)}uidToIndex(t,e,i){return E_(e,1,i,"uid")||!tP(e,1,i,"uid",!1)||!$_(t,1)||X_(void 0,void 0,t,1)?-1:K_(this.getCurrentDocument(t).pages,e,1,i)?t.uidToIndex(e):-1}getCurrentPageUid(t){return $_(t,1)?X_(void 0,void 0,t,1)?"":t.getCurrentPageUid():""}getCurrentPageIndex(t){return $_(t,1)?X_(void 0,void 0,t,1)?-1:t.getCurrentPageIndex():-1}getPageCount(t){return $_(t,1)?t.getPageCounts():-1}gotoPage(t,e,i){const n="index";return E_(e,1,i,n)||!q_(e,i,n,1)||!$_(t,1)||X_(void 0,void 0,t,1)||J_(e,0,t.getPageCounts()-1,1,i,n)?-1:t.gotoPage(e)}rotate(t,e,i,n){return!(E_(e,1,n,"angle")||!q_(e,n,"angle",1)||!function(t,e){return t%90==0||fp.output(1,e,"angle",void 0,pp.PARAM_NOT_SUPPORT)}(e,n)||!$_(t,1)||X_(void 0,void 0,t,1))&&(!(!Ps(i)&&!eP(i,1,n,"indices",0,this.getPageCount(t)-1))&&t.rotatePages(e,i))}saveOperation(t){return!!$_(t,1)&&t.saveOperations()}on(t,e,i,n){!E_(i,1,e,"eventName")&&!E_(n,1,e,"listener")&&tP(i,1,e,"eventName",!1)&&Q_(n,e,"listener",1)&&t.on(i,n)}off(t,e,i,n){!E_(i,1,e,"eventName")&&tP(i,1,e,"eventName",!1)&&(Ps(n)||Q_(n,e,"listener",1))&&t.off(i,n)}destroy(t){t&&t.dispose()}}function nP(t,e,i,n){return!!Rs(t)||fp.output(n,e,i,void 0,pp.PARAM_INVALID)}function sP(t,e,i,n,s,o){const r=fp.formatError(fp.isNumberAndIsInRange(t,s,o));return!r||fp.output(e,i,n,void 0,r)}function oP(t,e,i,n,s){if(!Es(t))return fp.output(i,n,s,void 0,pp.PARAM_INVALID);const o=[],r=["pageStyle","hoveredPageStyle","selectedPageStyle","currentPageStyle","placeholderStyle","canvasStyle","pageNumberStyle","checkboxStyle","quadSelectionStyle"];return Object.keys(t).forEach(i=>{const n=t[i];if("container"===i)o.push(...TI.isContainerKeyValid(n,s));else if("uiConfig"===i){const t=TI.isUiConfigValid(n,"option.uiConfig");if(t.length>0)o.push(...t);else{const t=dI(n,e);if(t){const i=pp.buildError(pp.ELEMENT_UNSUPPORTED,e.charAt(0).toUpperCase()+e.slice(1),t);o.push(`option.uiConfig: ${i.message}`)}}}else"viewerConfig"!==i&&"thumbnailConfig"!==i||Object.keys(n).forEach(t=>{const e=n[t];if(r.includes(t)){const n=yI(t,e);o.push(...n.map(t=>`${i}.${t}`))}})}),!(o.length>0)||fp.output(i,n,s,o)}const rP=["canvasStyle","quadSelectionStyle"],aP="CaptureViewer";var lP=new WeakMap,hP=new WeakMap,cP=new WeakSet;class dP{constructor(t){var e;an(this,cP),rn(this,lP,{writable:!0,value:void 0}),rn(this,hP,{writable:!0,value:new iP}),Yi(this,"uid",void 0),Yi(this,"groupUid",void 0),Yi(this,"postfix",void 0);const i=`new ${aP}`;lg.makeSureCoreLicenseExist(),lg.makeSureCameraLicenseExist(),Ps(t)||oP(t,"captureViewer",0,i,"option");const n=_o((null==t?void 0:t.viewerConfig)||{},_s({...Y_,viewerMode:jg.CAPTURE})),s=Ms()?A_:R_;Xi(this,lP,T_.createViewer({uiConfig:_s(s),...t,viewerConfig:n})),null!=t&&null!==(e=t.viewerConfig)&&void 0!==e&&e.enableAutoDetect&&!$i(this,lP).context.core.detectorService.enableDetect&&pp.warning(pp.DOC_DETECT_MISS),this.uid=$i(this,lP).uid,this.groupUid=$i(this,lP).groupUid,this.postfix=$i(this,lP).postfix,sn(this,cP,uP).call(this)}get isVisible(){return $i(this,hP).getIsVisible($i(this,lP))}get isBoundContainer(){return $i(this,hP).getIsBoundContainer($i(this,lP))}get currentDocument(){return $i(this,hP).getCurrentDocument($i(this,lP))}get acceptedPolygonConfidence(){return $i(this,lP).getCameraConfig().acceptedPolygonConfidence}set acceptedPolygonConfidence(t){const e="acceptedPolygonConfidence";sP(t,1,`${aP}.${e}`,e,0,100)&&$i(this,lP).updateCameraConfig({acceptedPolygonConfidence:t})}get maxFrameNumber(){return $i(this,lP).getCameraConfig().maxFrameNumber}set maxFrameNumber(t){const e="maxFrameNumber";sP(t,1,`${aP}.${e}`,e,1e-6,60)&&$i(this,lP).updateCameraConfig({maxFrameNumber:t})}get enableAutoDetect(){return $i(this,lP).getCameraConfig().enableAutoDetect}set enableAutoDetect(t){const e="enableAutoDetect",i=`${aP}.${e}`;nP(t,i,e,1)&&(t&&!$i(this,lP).context.core.detectorService.enableDetect&&fp.warning(i,void 0,void 0,pp.DOC_DETECT_MISS),$i(this,lP).updateCameraConfig({enableAutoDetect:t}))}get enableAutoCapture(){return $i(this,lP).getCameraConfig().enableAutoCapture}set enableAutoCapture(t){const e="enableAutoCapture";nP(t,`${aP}.${e}`,e,1)&&$i(this,lP).updateCameraConfig({enableAutoCapture:t})}bindContainer(t){$i(this,hP).bindContainer($i(this,lP),t,`${aP}.bindContainer`)}unbindContainer(){$i(this,hP).unbindContainer($i(this,lP))}show(){$i(this,hP).show($i(this,lP))}hide(){$i(this,hP).hide($i(this,lP))}getUiConfig(){return $i(this,hP).getUiConfig($i(this,lP))}updateUiConfig(t){return $i(this,hP).updateUiConfig($i(this,lP),t,"captureViewer",`${aP}.updateUiConfig`)}openDocument(t){$i(this,hP).openDocument(t,this.uid,`${aP}.openDocument`)}closeDocument(){return $i(this,hP).closeDocument($i(this,lP),`${aP}.closeDocument`)}getStyle(t){return $i(this,hP).getStyle($i(this,lP),"capture",t,rP,`${aP}.getStyle`)}updateStyle(t,e){return $i(this,hP).updateStyle($i(this,lP),t,e,rP,`${aP}.updateStyle`)}capture(){return $i(this,lP).isVideoPlaying()?$i(this,lP).context.viewService.isBindContainer?$i(this,lP).capture():pp.reject(pp.CONTAINER_NO_BOUND):pp.reject(pp.CAMERA_NO_VIDEO)}play(t){const e=`${aP}.play`;if(!Ps(t)){const i=function(t,e,i,n){const s=TI.isVideoConfig(t,n);return!s.length||fp.output(2,i,n,s)}(t,0,e,"config");if(!0!==i)return i}return $i(this,lP).play(t).catch(t=>pp.reject(t,e))}stop(){$i(this,lP).stop()}getCurrentCamera(){return $i(this,lP).getCurrentCamera()}getAllCameras(){return $i(this,lP).getAllCameras()}selectCamera(t){const e=`${aP}.selectCamera`,i="cameraObjectOrDeviceID",n=E_(t,2,e,i);if(n)return n;if(Os(t)){const n=tP(t,2,e,i,!1);if(!0!==n)return n}else{const n=function(t,e,i,n){const s=TI.isVideoDeviceInfo(t,n);return!s.length||fp.output(2,i,n,s)}(t,0,e,i);if(!0!==n)return n}return $i(this,lP).selectCamera(t).catch(t=>pp.reject(t,e,i))}getCurrentResolution(){return $i(this,lP).getCurrentResolution()}turnOnTorch(){return $i(this,lP).turnOnTorch().catch(t=>pp.reject(t))}turnOffTorch(){return $i(this,lP).turnOffTorch().catch(t=>pp.reject(t))}on(t,e){$i(this,hP).on($i(this,lP),`${aP}.on`,t,e)}off(t,e){$i(this,hP).off($i(this,lP),`${aP}.off`,t,e)}destroy(){$i(this,hP).destroy($i(this,lP))}}function uP(){$i(this,lP).hooks.destroy.on(()=>{Xi(this,lP,null),Object.setPrototypeOf(this,null)})}const pP={canvasStyle:{...U_},currentPageStyle:{border:"4px solid #fe8e14"},pageStyle:{border:"6px solid rgba(0,0,0,0)",background:"rgba(255,255,255,0)"},selectedPageStyle:{border:"6px solid #AAAAAA",background:"#AAAAAA"},hoveredPageStyle:{border:"6px solid #AAAAAA",background:"#AAAAAA"},placeholderStyle:{border:"6px solid rgba(136,136,136,0.2)",background:"rgba(136,136,136,0.2)"},pageNumberStyle:{onPage:!1,visibility:"visible",width:"32px",height:"24px",background:"rgba(255,255,255,0)",border:"0px solid #000",borderRadius:"0px",opacity:1,color:"#323234",fontSize:"14px",fontFamily:"Open Sans",left:"50%",top:"",right:"",bottom:"3px",translateX:"-50%",translateY:"0px"},checkboxStyle:{left:"2px",top:"2px",width:"16px",height:"16px",background:"#fff",border:"2px solid #999999",borderRadius:"0px",translateX:"0px",translateY:"0px",opacity:1,visibility:"visible",checkMarkColor:"#FE8E14",checkMarkLineWidth:"2px"},rows:2,columns:2,multiselectMode:!1,scrollToLatest:!1,enableDragPage:!0,scrollDirection:"vertical",enableAutoScrollForDragPages:!0},gP={...pP,visibility:"hidden",size:"180px",position:"left",rows:4,columns:1,canvasStyle:{background:"#DDDDDD"}},fP={canvasStyle:{...U_},pageStyle:{...F_},quadSelectionStyle:{...V_},currentPageStyle:{border:"",background:""},minZoom:.01,maxZoom:64,scrollDirection:"vertical",enableSlide:!0,scrollToLatest:!1,enableMagnifier:!0,enableLoadSourceByDrag:!0,enableAutoScrollForTextSelection:!0},mP=["canvasStyle","pageStyle","selectedPageStyle","hoveredPageStyle","placeholderStyle","pageNumberStyle","checkboxStyle","currentPageStyle","cursorStyle"];var vP=new WeakSet;class yP{constructor(t){var e,i;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"BaseBrowseViewer";an(this,vP),Yi(this,"v",void 0),Yi(this,"vCommon",new iP),Yi(this,"uid",void 0),Yi(this,"groupUid",void 0),Yi(this,"postfix",void 0),Yi(this,"errorPrefix",void 0),this.errorPrefix=n;const s=`new ${this.errorPrefix}`;lg.makeSureCoreLicenseExist(),Ps(t)||oP(t,"browseViewer",0,s,"option");const o=SI(null==t?void 0:t.keyboardInteractionConfig),r=_o((null==t?void 0:t.viewerConfig)||{},_s({...pP,viewerMode:jg.THUMBNAIL,displayMode:"multiple",toolMode:"pan",enableOptimizePage:!0})),a={passwordLoaderConfig:{enabled:null!==(e=null==t||null===(i=t.viewerConfig)||void 0===i?void 0:i.enablePasswordLoader)&&void 0!==e?e:"BrowseViewer"===n}};this.v=T_.createViewer({uiConfig:_s(L_),...t,viewerConfig:{enablePopup:!0,...r,...o},popupConfig:a}),this.uid=this.v.uid,this.groupUid=this.v.groupUid,this.postfix=this.v.postfix,sn(this,vP,xP).call(this)}get isVisible(){return this.vCommon.getIsVisible(this.v)}get isBoundContainer(){return this.vCommon.getIsBoundContainer(this.v)}set multiselectMode(t){const e="multiselectMode";nP(t,`${this.errorPrefix}.${e}`,e,1)&&this.v.updateViewerConfig({multiselectMode:t})}get multiselectMode(){return this.v.getViewerConfig().multiselectMode}show(){this.vCommon.show(this.v)}hide(){this.vCommon.hide(this.v)}getUiConfig(){return this.vCommon.getUiConfig(this.v)}updateUiConfig(t){return this.vCommon.updateUiConfig(this.v,t,"browseViewer",`${this.errorPrefix}.updateUiConfig`)}getStyle(t){return this.vCommon.getStyle(this.v,"browse",t,mP,`${this.errorPrefix}.getStyle`)}updateStyle(t,e){const i=`${this.errorPrefix}.updateStyle`;return this.vCommon.updateStyle(this.v,t,e,mP,i)}getSelectedPageIndices(){return $_(this.v,1)?this.v.getSelectedPageIndices():[]}selectAllPages(){if(!$_(this.v,1))return[];if(0===this.v.getPageCounts()){const t=`${this.errorPrefix}.selectAllPages`;return fp.output(1,t,void 0,void 0,pp.DOC_NO_IMAGE),[]}return this.v.selectAllPages()}selectPages(t){const e=`${this.errorPrefix}.selectPages`,i="indices";return E_(t,1,e,i)||!$_(this.v,1)?[]:eP(t,1,e,i,0,this.v.getPageCounts()-1)?this.v.selectPagesByIndices(t):[]}setRowAndColumn(t,e){const i=`${this.errorPrefix}.setRowAndColumn`,n="row",s="column",{maxColumns:o,maxRows:r}=this.v.getViewerConfig();return!(E_(t,1,i,n)||E_(e,1,i,s)||!q_(t,i,n,1)||!q_(e,i,s,1)||J_(t,1,r,1,i,n)||J_(e,1,o,1,i,s))&&this.v.setRowAndColumn(t,e)}on(t,e){this.vCommon.on(this.v,`${this.errorPrefix}.on`,t,e)}off(t,e){this.vCommon.off(this.v,`${this.errorPrefix}.off`,t,e)}getVisiblePagesInfo(){return this.v.getVisiblePagesInfo()}}function xP(){this.v.hooks.destroy.on(()=>{this.v=null,Object.setPrototypeOf(this,null)})}function wP(t,e,i,n,s){const o=TI.isAnnotationOptionsValid(t,n,s);return!o.length||fp.output(e,i,n,o)}const CP={borderColor:"rgb(0,0,0)",background:"",borderWidth:1,opacity:1,lineDash:[0,0],flags:{print:!0,noView:!1,readOnly:!1},rotation:0};var bP=new WeakMap;class SP{constructor(t){Yi(this,"uid",null),Yi(this,"creationDate",""),Yi(this,"modificationDate",""),rn(this,bP,{writable:!0,value:void 0}),Xi(this,bP,t),this.uid=Us(),this.creationDate=Rm(),this.modificationDate=this.creationDate}get source(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.source:""}get type(){return null}get pageUid(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.pageUid:""}get flattened(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return!!t&&t.flattened}set flattened(t){const e="Annotation.flattened";E_(t,1,e,"options")||nP(t,e,"options",1)&&T_.annotationService.annotationApp.getAnnotationByUid(this.uid).flattened!==t&&(t?T_.annotationService.flattenAnnotations([this.uid]):T_.annotationService.unFlattenAnnotation(this.uid))}getOptions(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);if(t){const e=t.getConfig(),i=_P(e,this.type);Xi(this,bP,{...i}),this.modificationDate=e.comment.modificationDate}return IP(this.type,$i(this,bP))}updateOptions(t){const e="Annotation.updateOptions";if(E_(t,1,e,"options"))return!1;if(!__(t,1,e,"options"))return!1;if(!wP(t,1,e,"options",this.type))return!1;const i=this.getOptions(),n=TP(this.type,t,i);if(["rectangle","stamp","ellipse","textBox","ink"].includes(this.type)||(n.has("rotated")&&n.delete("rotated"),Ls(null==t?void 0:t.angle)&&(t.angle=void 0)),!n.size)return!0;this.getOptions(),_o(t,$i(this,bP)),t.flags={...$i(this,bP).flags,...t.flags||{}};const s=EP({...t},this.type);var o;if(["highlight","underline","strikeout"].includes(this.type)&&null!=s&&null!==(o=s.style)&&void 0!==o&&null!==(o=o.lines)&&void 0!==o&&o.length){const{lines:t}=s.style,e=16,i=t[0],n=t[t.length-1],o={left:i.left,top:i.top,width:e,height:e},r={left:n.left+n.width-e,top:n.top,width:e,height:n.height};s.startCharRect=o,s.endCharRect=r;const a=sy(t);s.style.borderWidth=a}return T_.annotationService.updateAnnotations([{annotationUid:this.uid,options:s}],void 0,[...n]),!0}}function TP(t,e,i){const n="startPoint",s="endPoint",o=new Map([[["x","y"],"moved"],[["width","height","rects"],"resized"],[["rotation"],"rotated"],[["flags"],"flagsChanged"],[["borderWidth","borderColor","background","opacity","textAlign","lineCap","lineJoin","miterLimit","lineDash","lineEnding","textContents"],"appearanceChanged"],[["textContents","stamp"],"contentChanged"]]),r=_s(e);r.flags={...i.flags,...(null==r?void 0:r.flags)||{}},["line","polyline"].includes(t)&&e.lineEnding&&(r.lineEnding={...i.lineEnding,...(null==r?void 0:r.lineEnding)||{}});const a=new Set,l=Object.keys(r);return l.forEach(e=>{if(!vI(i[e],r[e]))if("points"!==e||"ink"!==t&&"polygon"!==t&&"polyline"!==t)if(e!==n&&e!==s||"line"!==t)for(const[t,i]of o)t.includes(e)&&!a.has(i)&&a.add(i);else l.includes(n)&&l.includes(s)&&CI([i[n],i[s]],[r[n],r[s]])?a.add("moved"):a.add("resized");else CI(i[e],r[e])?a.add("moved"):a.add("resized")}),a}function EP(t,e){const i=_s(t),n={style:i,flags:[],transform:{}},{lineEnding:s,points:o,textContents:r,stamp:a,borderWidth:l,x:h,y:c,width:d,height:u,startPoint:p,endPoint:g,lineDash:f,rects:m}=i||{},v=Cr.dataResolution,y=Cr.displayResolution,x=["ink","line","polygon","polyline","highlight","underline","strikeout"].includes(e);if(m&&(n.style.lines=MP(m,v,y,"date")),o&&("ink"===e?n.style.segments=kP(o,v,y):n.style.points=RP(o,v,y)),s&&(n.style.lineEnding=PP(s,"date")),a&&(n.style.imageData=null,a instanceof Blob||Os(a)&&sI(a)?n.style.imageData=a:Os(a)?n.style.iconName=AP(a,"date"):bI(a)&&(n.style.stampConfig=a)),Ps(l)||(n.style.borderWidth=Bo(l,v,y)),Ps(h)||(x?delete n.style.x:n.style.x=Bo(h,v,y)),Ps(c)||(x?delete n.style.y:n.style.y=Bo(c,v,y)),Ps(d)||(n.style.width=Bo(d,v,y)),Ps(u)||(n.style.height=Bo(u,v,y)),Ps(f)||(n.style.lineDash=Bo(f,v,y)),Ps(p)||(n.style.startPoint=Bo(p,v,y)),Ps(g)||(n.style.endPoint=Bo(g,v,y)),r){const t=[];r.forEach(e=>{null!=e&&e.fontSize&&(e.fontSize=Bo(e.fontSize,v,y)),Os(e.fontFamily)&&""===(null==e?void 0:e.fontFamily.trim())&&(e.fontFamily="Helvetica"),t.push({...j_,...e})}),n.style.textContents=t}return Ls(t.rotation)&&(n.transform.angle=t.rotation),t.flags&&(t.flags.print&&n.flags.push("print"),t.flags.noView&&n.flags.push("noView"),t.flags.readOnly&&n.flags.push("readOnly"),t.flags.noResize&&n.flags.push("noResize"),t.flags.noRotate&&n.flags.push("noRotate"),t.flags.noMove&&n.flags.push("noMove")),n}function _P(t,e){var i,n,s,o,r,a,l,h,c,d,u;const{lineEnding:p,iconName:g,imageData:f,segments:m,textContents:v,borderWidth:y,x:x,y:w,width:C,height:b,startPoint:S,endPoint:T,lineDash:E,points:_,stampConfig:P,lines:A}=(null==t?void 0:t.style)||{},I=Cr.displayResolution,D=Cr.dataResolution;if(A&&(t.style.rects=MP(A,I,D,"user")),_&&(t.style.points=RP(_,I,D)),m&&"ink"===e&&(t.style.points=kP(m,I,D),delete t.style.segments),p&&(t.style.lineEnding=PP(p,"user")),(f||g||P)&&(t.style.stamp=f||AP(g,"user")||_s(P),delete t.style.iconName,delete t.style.imageData,delete t.style.stampConfig),Ps(y)||(t.style.borderWidth=Bo(y,I,D)),Ps(x)||(t.style.x=Bo(x,I,D)),Ps(w)||(t.style.y=Bo(w,I,D)),Ps(C)||(t.style.width=Bo(C,I,D)),Ps(b)||(t.style.height=Bo(b,I,D)),Ps(S)||(t.style.startPoint=Bo(S,I,D)),Ps(T)||(t.style.endPoint=Bo(T,I,D)),Ps(E)||(t.style.lineDash=Bo(E,I,D)),v){const e=[];v.forEach(t=>{null!=t&&t.fontSize&&(t.fontSize=Bo(t.fontSize,I,D)),Os(t.fontFamily)&&""===(null==t?void 0:t.fontFamily.trim())&&(t.fontFamily="Helvetica"),e.push({...j_,...t})}),t.style.textContents=e}return null===(i=t.style)||void 0===i||delete i.lineJoin,null===(n=t.style)||void 0===n||delete n.lineCap,null===(s=t.style)||void 0===s||delete s.miterLimit,{...t.style,rotation:null!==(o=null===(r=t.transform)||void 0===r?void 0:r.angle)&&void 0!==o?o:void 0,flags:{print:!(null===(a=t.flags)||void 0===a||!a.includes("print")),noView:!(null===(l=t.flags)||void 0===l||!l.includes("noView")),readOnly:!(null===(h=t.flags)||void 0===h||!h.includes("readOnly")),noResize:!(null===(c=t.flags)||void 0===c||!c.includes("noResize")),noRotate:!(null===(d=t.flags)||void 0===d||!d.includes("noRotate")),noMove:!(null===(u=t.flags)||void 0===u||!u.includes("noMove"))}}}function PP(t,e){const i={None:N_.NONE,OpenArrow:N_.OPEN,ROpenArrow:N_.OPEN_REVERSE,ClosedArrow:N_.CLOSED,RClosedArrow:N_.CLOSED_REVERSE,Butt:N_.BUTT,Slash:N_.SLASH,Square:N_.SQUARE,Diamond:N_.DIAMOND,Circle:N_.CIRCLE};if("user"===e){const[e,n]=t;return{start:i[e],end:i[n]}}return[mI(i,t.start)[0]||"None",mI(i,t.end)[0]||"None"]}function AP(t,e){const i={[B_.REJECTED]:Yh.REJECTED,[B_.ACCEPTED]:Yh.ACCEPTED,[B_.INITIAL_HERE]:Yh.INITIAL_HERE,[B_.SIGN_HERE]:Yh.SIGN_HERE,[B_.WITNESS]:Yh.WITNESS,[B_.APPROVED]:Yh.APPROVED,[B_.NOT_APPROVED]:Yh.NOT_APPROVED,[B_.DRAFT]:Yh.DRAFT,[B_.FINAL]:Yh.FINAL,[B_.COMPLETED]:Yh.COMPLETED,[B_.CONFIDENTIAL]:Yh.CONFIDENTIAL,[B_.VOID]:Yh.VOID};return"user"===e?mI(i,t)[0]||t:i[t]||Yh.DRAFT}function IP(t,e){const i=["opacity","flags"],n=["x","y","width","height"],s=["borderColor","borderWidth","lineDash"],o=[...i,...s,...n,"background","rotation"],r=["points","background",...s,...i],a=["rects","opacity"],l={rectangle:o,ellipse:o,polygon:r,polyline:["lineEnding",...r],stamp:["stamp",...n,...i,"rotation"],ink:["points","borderWidth","borderColor","rotation",...i],line:["startPoint","endPoint","lineEnding","background",...s,...i],textBox:["textContents","textAlign","background","rotation",...i,...s,...n],textTypewriter:["x","y","textContents",...i],highlight:[...a,...i,"background"],underline:[...a,...i,"borderColor"],strikeout:[...a,...i,"borderColor"]}[t];if(!l)return e;const h={};for(const i in e)if(l.includes(i)){let n=e[i];"rects"===i?h[i]=n.map(t=>({x:Lo(t.x,2),y:Lo(t.y,2),width:Lo(t.width,2),height:Lo(t.height,2)})):"points"!==i||"ink"!==t&&"polygon"!==t&&"polyline"!==t?"startPoint"!==i&&"endPoint"!==i||"line"!==t?"borderColor"===i||"background"===i?h[i]=DP(n,2):"opacity"===i?(n>1&&(n=1),n<0&&(n=0),h[i]=Lo(n,2)):"textContents"===i?h[i]=n.map(t=>(void 0!==t.color&&(t.color=DP(t.color,2)),void 0!==t.fontSize&&(t.fontSize=Lo(t.fontSize,2)),t)):"lineDash"===i?h[i]=n.map(t=>Lo(t,2)):Ls(e[i])?h[i]=Lo(n,2):h[i]=n:h[i]={x:Lo(n.x,2),y:Lo(n.y,2)}:Ts(n[0])?h[i]=n.map(t=>t.map(t=>({x:Lo(t.x,2),y:Lo(t.y,2)}))):h[i]=n.map(t=>({x:Lo(t.x,2),y:Lo(t.y,2)}))}return h}function DP(t,e){if(t&&t.startsWith("rgb")){const i=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)/,n=t.match(i);if(n){const t=parseInt(n[1],10),i=parseInt(n[2],10),s=parseInt(n[3],10);let o=void 0!==n[4]?parseFloat(n[4]):void 0;if(void 0!==o){o<0&&(o=0),o>1&&(o=1);const n=function(t,e){const i=t.toString();return/^\d+\.\d{3,}$/.test(i)?parseFloat(t.toFixed(e)):t}(o,e);return`rgba(${t},${i},${s},${n})`}return`rgb(${t},${i},${s})`}}return t}function RP(t,e,i){return t.map(t=>({x:Bo(t.x,e,i),y:Bo(t.y,e,i)}))}function kP(t,e,i){return t.map(t=>t.map(t=>({x:Bo(t.x,e,i),y:Bo(t.y,e,i)})))}function MP(t,e,i,n){return"date"===n?t.map(t=>({left:Bo(t.x,e,i),top:Bo(t.y,e,i),width:Bo(t.width,e,i),height:Bo(t.height,e,i)})):t.map(t=>({x:Bo(t.left,e,i),y:Bo(t.top,e,i),width:Bo(t.width,e,i),height:Bo(t.height,e,i)}))}const LP={...CP,x:10,y:10,width:100,height:100};class OP extends SP{constructor(t){super(t=_o(t||{},_s(LP)))}get type(){return"rectangle"}}const BP={...CP,x:10,y:10,width:100,height:80};class NP extends SP{constructor(t){super(t=_o(t||{},_s(BP)))}get type(){return"ellipse"}}const UP={...CP,points:[[{x:10,y:10},{x:110,y:80}],[{x:110,y:10},{x:10,y:80}]]};class FP extends SP{constructor(t){super(t=_o(t||{},_s(UP)))}get type(){return"ink"}}const VP={...CP,startPoint:{x:10,y:10},endPoint:{x:110,y:80},lineEnding:{start:N_.NONE,end:N_.NONE},flags:{print:!0,noView:!1,readOnly:!1,noRotate:!0}};class WP extends SP{constructor(t){var e;let i=t;!1===(null===(e=t)||void 0===e||null===(e=e.flags)||void 0===e?void 0:e.noRotate)&&(i=_s(t),i.flags.noRotate=!0),super(t=_o(i||{},_s(VP)))}get type(){return"line"}updateOptions(t){var e;let i=t;return!1===(null==t||null===(e=t.flags)||void 0===e?void 0:e.noRotate)&&(i=_s(t),i.flags.noRotate=!0),super.updateOptions(i)}}const HP={...CP,points:[{x:60,y:10},{x:10,y:55},{x:30,y:110},{x:90,y:110},{x:110,y:55}],flags:{print:!0,noView:!1,readOnly:!1,noRotate:!0}};class jP extends SP{constructor(t){var e;let i=t;!1===(null===(e=t)||void 0===e||null===(e=e.flags)||void 0===e?void 0:e.noRotate)&&(i=_s(t),i.flags.noRotate=!0),super(t=_o(i||{},_s(HP)))}get type(){return"polygon"}updateOptions(t){var e;let i=t;return!1===(null==t||null===(e=t.flags)||void 0===e?void 0:e.noRotate)&&(i=_s(t),i.flags.noRotate=!0),super.updateOptions(i)}}const zP={...CP,points:[{x:10,y:40},{x:50,y:80},{x:110,y:10}],lineEnding:{start:N_.NONE,end:N_.NONE},flags:{print:!0,noView:!1,readOnly:!1,noRotate:!0}};class GP extends SP{constructor(t){var e;let i=t;!1===(null===(e=t)||void 0===e||null===(e=e.flags)||void 0===e?void 0:e.noRotate)&&(i=_s(t),i.flags.noRotate=!0),super(t=_o(i||{},_s(zP)))}get type(){return"polyline"}updateOptions(t){var e;let i=t;return!1===(null==t||null===(e=t.flags)||void 0===e?void 0:e.noRotate)&&(i=_s(t),i.flags.noRotate=!0),super.updateOptions(i)}}async function YP(t,e,i,n,s){const o=[`${s}.${n} is invalid`];let r=!1;if(Ds(t)){const e=await Io(t);["image/bmp","image/jpeg","image/png"].includes(e)||(r=!0)}else r=!0;return!r||fp.output(e,i,s,o)}const $P={x:10,y:10,stamp:B_.DRAFT,width:void 0,height:void 0,opacity:1,flags:{print:!0,noView:!1,readOnly:!1},rotation:0},XP={[B_.REJECTED]:[23.58,23.54],[B_.ACCEPTED]:[28.39,24.6],[B_.INITIAL_HERE]:[126.26,33.78],[B_.SIGN_HERE]:[126.26,33.78],[B_.WITNESS]:[126.26,33.78],[B_.APPROVED]:[211.33,59.33],[B_.NOT_APPROVED]:[284.83,59.33],[B_.DRAFT]:[144.19,59.66],[B_.FINAL]:[123.73,59.66],[B_.COMPLETED]:[227.83,59.33],[B_.CONFIDENTIAL]:[272.83,59.33],[B_.VOID]:[114.71,59.66]};var qP=new WeakMap;class ZP{constructor(t){Yi(this,"uid",null),Yi(this,"creationDate",""),Yi(this,"modificationDate",""),rn(this,qP,{writable:!0,value:void 0}),t=_o(t||{},_s($P)),!Os(t.stamp)||!XP[t.stamp]||Ls(t.width)&&Ls(t.height)||(t.width=t.width||XP[t.stamp][0],t.height=t.height||XP[t.stamp][1]),Xi(this,qP,t),this.uid=Us(),this.creationDate=Rm(),this.modificationDate=this.creationDate}get source(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.source:""}get type(){return"stamp"}get pageUid(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.pageUid:""}get flattened(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return!!t&&t.flattened}set flattened(t){const e="Annotation.flattened";E_(t,1,e,"options")||nP(t,e,"options",1)&&T_.annotationService.annotationApp.getAnnotationByUid(this.uid).flattened!==t&&(t?T_.annotationService.flattenAnnotations([this.uid]):T_.annotationService.unFlattenAnnotation(this.uid))}getOptions(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);if(t){const e=t.getConfig(),i=_P(e,this.type);Xi(this,qP,{...i}),this.modificationDate=e.comment.modificationDate}return IP(this.type,$i(this,qP))}async updateOptions(t){const e="Annotation.updateOptions";if(E_(t,0,e,"options"))return;if(!__(t,0,e,"options"))return;if(!wP(t,0,e,"options",this.type))return;if(Ds(t.stamp)&&!await YP(t.stamp,0,e,"stamp","options"))return;const i=this.getOptions(),n=TP(this.type,t,i);if(!n.size)return;this.getOptions(),_o(t,$i(this,qP)),t.flags={...$i(this,qP).flags,...t.flags||{}};let s=t;s={x:$i(this,qP).x,y:$i(this,qP).y,width:$i(this,qP).width,height:$i(this,qP).height,...s},null!=t&&t.stamp||(s={...s,stamp:null});const o=EP(s,this.type);o.style={...i,...o.style},T_.annotationService.updateAnnotations([{annotationUid:this.uid,options:o}],void 0,[...n])}}const JP={...CP,x:10,y:10,width:150,height:80,textAlign:"left",textContents:[{content:"Insert text here"}]};class KP extends SP{constructor(t){super(t=_o(t||{},_s(JP)))}get type(){return"textBox"}}const QP={x:10,y:10,textContents:[{content:"Insert text here"}],opacity:1,author:"",subject:"",flags:{print:!0,noView:!1,readOnly:!1,noResize:!0,noRotate:!0}};class tA extends SP{constructor(t){var e,i;const n=_s(t);!1===(null===(e=t)||void 0===e||null===(e=e.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null===(i=t)||void 0===i||null===(i=i.flags)||void 0===i?void 0:i.noResize)&&(n.flags.noResize=!0),super(t=_o(n||{},_s(QP)))}get type(){return"textTypewriter"}updateOptions(t){var e,i;const n=_s(t);return!1===(null==t||null===(e=t.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null==t||null===(i=t.flags)||void 0===i?void 0:i.noResize)&&(n.flags.noResize=!0),super.updateOptions(n)}}function eA(t,e,i,n,s,o){const r=fp.formatError({isValid:Ts(t)});if(r)return fp.output(e,i,n,void 0,r);const a=[];return t.forEach((t,e)=>{const i=fp.formatDetails(gp("Array",s,`[${e}]`,!0),fp.isStringAndNotEmpty(t,o));a.push(...i)}),!a.length||fp.output(e,i,n,a)}function iA(t,e,i,n,s){const o=[];return e.forEach((e,i)=>{t.has(e)||o.push(`annotationUids[${i}]: The specified annotation(s) do not exist.`)}),!o.length||fp.output(i,n,s,o,pp.ANNOTATION_NOT_EXIST)}function nA(t,e,i,n,s){return!!t.has(e)||fp.output(i,n,s,void 0,pp.ANNOTATION_NOT_EXIST)}class sA{constructor(){Yi(this,"uid",null),Yi(this,"creationDate",""),Yi(this,"modificationDate",""),this.uid=Us(),this.creationDate=Rm(),this.modificationDate=Rm()}get source(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.source:""}get type(){return"unknown"}get pageUid(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.pageUid:""}get flattened(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return!!t&&t.flattened}set flattened(t){const e="Annotation.flattened";E_(t,1,e,"options")||nP(t,e,"options",1)&&T_.annotationService.annotationApp.getAnnotationByUid(this.uid).flattened!==t&&(t?T_.annotationService.flattenAnnotations([this.uid]):T_.annotationService.unFlattenAnnotation(this.uid))}}var oA=new WeakMap;class rA{constructor(t){rn(this,oA,{writable:!0,value:void 0}),Yi(this,"uid",null),Yi(this,"creationDate",""),Yi(this,"modificationDate",""),this.uid=Us(),this.creationDate=Rm(),this.modificationDate=Rm(),Xi(this,oA,t)}get source(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.source:""}get type(){return"incomplete"}get pageUid(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return t?t.pageUid:""}get raw(){return $i(this,oA)}get flattened(){const t=T_.annotationService.annotationApp.getAnnotationByUid(this.uid);return!!t&&t.flattened}set flattened(t){const e="Annotation.flattened";E_(t,1,e,"options")||nP(t,e,"options",1)&&T_.annotationService.annotationApp.getAnnotationByUid(this.uid).flattened!==t&&(t?T_.annotationService.flattenAnnotations([this.uid]):T_.annotationService.unFlattenAnnotation(this.uid))}}const aA={flags:{print:!0,noView:!1,readOnly:!1,noMove:!0,noRotate:!0},rects:[{x:10,y:10,width:100,height:100}],background:"#FD7C10",opacity:1};class lA extends SP{constructor(t){var e,i;const n=_s(t);!1===(null===(e=t)||void 0===e||null===(e=e.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null===(i=t)||void 0===i||null===(i=i.flags)||void 0===i?void 0:i.noMove)&&(n.flags.noMove=!0),super(t=_o(n||{},_s(aA)))}get type(){return"highlight"}updateOptions(t){var e,i;const n=_s(t);return!1===(null==t||null===(e=t.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null==t||null===(i=t.flags)||void 0===i?void 0:i.noMove)&&(n.flags.noMove=!0),super.updateOptions(n)}}const hA={flags:{print:!0,noView:!1,readOnly:!1,noMove:!0,noRotate:!0},rects:[{x:10,y:10,width:100,height:100}],borderColor:"#0E68F5",opacity:1};class cA extends SP{constructor(t){var e,i;const n=_s(t);!1===(null===(e=t)||void 0===e||null===(e=e.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null===(i=t)||void 0===i||null===(i=i.flags)||void 0===i?void 0:i.noMove)&&(n.flags.noMove=!0),super(t=_o(n||{},_s(hA)))}get type(){return"underline"}updateOptions(t){var e,i;const n=_s(t);return!1===(null==t||null===(e=t.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null==t||null===(i=t.flags)||void 0===i?void 0:i.noMove)&&(n.flags.noMove=!0),super.updateOptions(n)}}const dA={flags:{print:!0,noView:!1,readOnly:!1,noMove:!0,noRotate:!0},rects:[{x:10,y:10,width:100,height:100}],borderColor:"#F01314",opacity:1};class uA extends SP{constructor(t){var e,i;const n=_s(t);!1===(null===(e=t)||void 0===e||null===(e=e.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null===(i=t)||void 0===i||null===(i=i.flags)||void 0===i?void 0:i.noMove)&&(n.flags.noMove=!0),super(t=_o(n||{},_s(dA)))}get type(){return"strikeout"}updateOptions(t){var e,i;const n=_s(t);return!1===(null==t||null===(e=t.flags)||void 0===e?void 0:e.noRotate)&&(n.flags.noRotate=!0),!1===(null==t||null===(i=t.flags)||void 0===i?void 0:i.noMove)&&(n.flags.noMove=!0),super.updateOptions(n)}}const pA=["annotationsAdded","annotationsDeleted","annotationsModified","annotationLayerChanged"],gA="AnnotationManager",fA=new Map;var mA=new WeakMap,vA=new WeakMap,yA=new WeakMap,xA=new WeakSet,wA=new WeakSet;function CA(t,e){switch(t){case"rectangle":return new OP(e);case"ellipse":return new NP(e);case"polygon":return new jP(e);case"polyline":return new GP(e);case"line":return new WP(e);case"stamp":return new ZP(e);case"ink":return new FP(e);case"textBox":return new KP(e);case"textTypewriter":return new tA(e);case"unknown":return new sA;case"highlight":return new lA(e);case"underline":return new cA(e);case"strikeout":return new uA(e);case"incomplete":return new rA((null==e?void 0:e.annotationRaw)||{});default:return null}}function bA(t,e){$i(this,yA).emit(t,e)}const SA=new class{constructor(){an(this,wA),an(this,xA),rn(this,mA,{writable:!0,value:void 0}),rn(this,vA,{writable:!0,value:void 0}),rn(this,yA,{writable:!0,value:void 0}),Xi(this,mA,T_),Xi(this,vA,fA),Xi(this,yA,new Ws);const t=$i(this,mA).annotationService.annotationApp.hooks;t.annotationCreated.on(t=>{const e=t.annotations.reduce((t,e)=>{if(!$i(this,vA).has(e.uid)){const t=e.getConfig(),i=_P(t),n=sn(this,xA,CA).call(this,t.type,i);n&&(n.uid=t.uid,n.creationDate=t.comment.creationDate,n.modificationDate=t.comment.modificationDate,$i(this,vA).set(t.uid,n))}return t.push(e.uid),t},[]);sn(this,wA,bA).call(this,"annotationsAdded",{annotationUids:e})}),t.annotationDeleted.on(t=>{t.annotations.forEach(t=>{$i(this,vA).has(t.uid)&&(this.getAnnotationsByUids([t.uid])[0].modificationDate="",$i(this,vA).delete(t.uid))});const e=t.annotations.map(t=>t.uid);t.emitEvent&&sn(this,wA,bA).call(this,"annotationsDeleted",{annotationUids:e})}),t.annotationUpdated.on(t=>{const e={modifiedAnnotations:t.updateDetails.map(t=>{const e=this.getAnnotationsByUids([t.annotationUid])[0],i=e.type,n=T_.annotationService.annotationApp.getAnnotationByUid(e.uid);return e.modificationDate=n.comment.modificationDate,{uid:t.annotationUid,oldOptions:IP(i,_P(_s(t.from.all),i)),newOptions:IP(i,_P(_s(t.to.all),i))}}),actions:[...t.updateActions]};$i(this,yA).hasCallback("annotationsModified")&&(e.actions.includes("flattenedChanged")||sn(this,wA,bA).call(this,"annotationsModified",e))});const e=(t,e)=>{$i(this,mA).annotationService.enableEmitLayerChanged&&sn(this,wA,bA).call(this,"annotationLayerChanged",{oldAnnotationUidList:[...t.from],newAnnotationUidList:[...t.to]})};t.bringFroward.on(t=>{e(t)}),t.bringToFront.on(t=>{e(t)}),t.sendBackward.on(t=>{e(t)}),t.sendToBack.on(t=>{e(t)})}createAnnotation(t,e,i){const n="AnnotationManager.createAnnotation",s="pageUid",o="type",r="annotationOptions";let a=null;try{lg.makeSureCoreLicenseExist(),lg.makeSureAnnotationLicenseExist(),E_(t,0,n,s),E_(e,0,n,o),tP(t,0,n,s,!1),function(t,e,i,n){Os(t)?["rectangle","ellipse","polygon","polyline","line","stamp","ink","textBox","textTypewriter","highlight","underline","strikeout"].includes(t)||fp.output(0,i,n,void 0,pp.PARAM_NOT_SUPPORT):fp.output(0,i,n,void 0,pp.PARAM_INVALID)}(e,0,n,o),a=$i(this,mA).pageService.getPage(t),a||fp.error(n,s,void 0,pp.PAGE_NOT_EXIST),Ps(i)||(__(i,0,n,r),wP(i,0,n,r,e))}catch(t){if("stamp"===e)return Promise.reject(t);throw t}const l=_s(i||{}),h=()=>{var i,n,s;const o=sn(this,xA,CA).call(this,e,l);$i(this,vA).set(o.uid,o);const r=$i(this,mA).pageService.getPage(t).doc.uid,h=EP(o.getOptions(),e);if("textTypewriter"===e){const t=a.mediaBox.width,e=a.mediaBox.width-h.style.x;h.style.width=e<0?t:e}if("underline"===e||"strikeout"===e){var c;const t=sy(null==h||null===(c=h.style)||void 0===c?void 0:c.lines)||1;h.style.borderWidth=t}const d={uid:o.uid,docUid:r,pageUid:t,type:e,style:h.style,transform:h.transform,flags:h.flags,source:"api",comment:{annotationUid:o.uid,author:(null===(i=h.comment)||void 0===i?void 0:i.author)||"",subject:(null===(n=h.comment)||void 0===n?void 0:n.subject)||"",contents:(null===(s=h.comment)||void 0===s?void 0:s.contents)||"",creationDate:o.creationDate,modificationDate:o.creationDate,markedStates:[],reviewStates:[],replies:[]}};return $i(this,mA).annotationService.createAnnotation(r,d),o};if("stamp"===e&&Ds(null==l?void 0:l.stamp)){const t=l;return new Promise(async(e,i)=>{try{await YP(t.stamp,0,n,"stamp",r)}catch(t){return void i(t)}if(!Ls(t.width)||!Ls(t.height)){const e=new hr,n=await e.readImageInfo({fileSource:t.stamp}).catch(t=>{i(t)});let s=n.imageWidth,o=n.imageHeight;if(s>400||o>400){const t=Math.max(s/400,o/400);s/=t,o/=t}t.width=s,t.height=o}e(h())})}return h()}deleteAnnotations(t){const e=`${gA}.deleteAnnotations`,i="annotationUids";return!(E_(t,1,e,i)||!eA(t,1,e,i,void 0,!1)||!iA($i(this,vA),t,1,e,i)||($i(this,mA).annotationService.deleteAnnotations(t),0))}getAnnotationsByUids(t){const e=`${gA}.getAnnotationsByUids`,i="annotationUids";return!E_(t,1,e,i)&&eA(t,1,e,i,void 0,!1)&&iA($i(this,vA),t,1,e,i)?t.map(t=>$i(this,vA).get(t)):[]}getAnnotationsByPage(t){const e=`${gA}.getAnnotationsByPage`,i="pageUid";if(E_(t,1,e,i)||!tP(t,1,e,i,!1))return[];if(!$i(this,mA).pageService.getPage(t))return fp.warning(e,i,void 0,pp.PAGE_NOT_EXIST),[];const n=$i(this,mA).annotationService.getAnnotationUidsByLayer(t),s=[];return n.forEach(t=>{const e=$i(this,vA).get(t);e&&s.push(e)}),s}getAnnotationsByDoc(t){const e=`${gA}.getAnnotationsByDoc`,i="docUid";if(E_(t,1,e,i)||!tP(t,1,e,i,!1))return[];const n=$i(this,mA).documentService.getDocument(t);return n?n.pages.reduce((t,e)=>($i(this,mA).annotationService.getAnnotationUidsByLayer(e).forEach(e=>{const i=$i(this,vA).get(e);i&&t.push(i)}),t),[]):(fp.warning(e,i,void 0,pp.DOC_NOT_EXIST),[])}bringAnnotationForward(t){const e=`${gA}.bringAnnotationForward`,i="annotationUid";return!(E_(t,1,e,i)||!tP(t,1,e,i,!1)||!nA($i(this,vA),t,1,e,i))&&(!!this.getAnnotationsByUids([t])[0].flattened||$i(this,mA).annotationService.bringForward(t))}sendAnnotationBackward(t){const e=`${gA}.sendAnnotationBackward`,i="annotationUid";return!(E_(t,1,e,i)||!tP(t,1,e,i,!1)||!nA($i(this,vA),t,1,e,i))&&(!!this.getAnnotationsByUids([t])[0].flattened||$i(this,mA).annotationService.sendBackward(t))}bringAnnotationToFront(t){const e=`${gA}.bringAnnotationToFront`,i="annotationUid";return!(E_(t,1,e,i)||!tP(t,1,e,i,!1)||!nA($i(this,vA),t,1,e,i))&&(!!this.getAnnotationsByUids([t])[0].flattened||$i(this,mA).annotationService.bringToFront(t))}sendAnnotationToBack(t){const e=`${gA}.sendAnnotationToBack`,i="annotationUid";return!(E_(t,1,e,i)||!tP(t,1,e,i,!1)||!nA($i(this,vA),t,1,e,i))&&(!!this.getAnnotationsByUids([t])[0].flattened||$i(this,mA).annotationService.sendToBack(t))}on(t,e){const i="AnnotationManager.on",n="eventName",s="listener";!E_(t,1,i,n)&&!E_(e,1,i,s)&&tP(t,1,i,n,!1)&&Q_(e,i,s,1)&&(pA.includes(t)?$i(this,yA).on(t,e):pp.warning(pp.PARAM_NOT_SUPPORT,i,n))}off(t,e){const i="AnnotationManager.off",n="eventName";!E_(t,1,i,n)&&tP(t,1,i,n,!1)&&(Ps(e)||Q_(e,i,"listener",1))&&(pA.includes(t)?$i(this,yA).off(t,e):pp.warning(pp.PARAM_NOT_SUPPORT,i,n))}};function TA(t,e,i,n,s,o){const r=[];let a=!1;if(s.length)s.forEach((t,e)=>{const{width:s,height:o}=i.getRealPtPageSize(t);fI(n,s,o)||r.push(`indices[${t}]: ${pp.RECT_EXCEED_PAGE_BOUND.message}`)}),r.length>0&&(a=!0);else{const{width:t,height:e}=i.getRealPtPageSize();fI(n,t,e)||(a=!0)}return!!a&&fp.output(o,t,e,r.length?r:void 0,pp.RECT_EXCEED_PAGE_BOUND,!0)}function EA(t,e,i,n){const s=TI.isRectValid(t);return!!s.length&&fp.output(n,e,i,s,void 0,!0)}const _A=["canvasStyle","pageStyle","quadSelectionStyle","currentPageStyle","annotationSelectionStyle","cursorStyle"],PA="EditViewer";var AA=new WeakMap,IA=new WeakMap,DA=new WeakMap,RA=new WeakSet,kA=new WeakSet,MA=new WeakSet,LA=new WeakSet;class OA{constructor(t){var e,i,n,s,o,r;an(this,LA),an(this,MA),an(this,kA),an(this,RA),rn(this,AA,{writable:!0,value:void 0}),rn(this,IA,{writable:!0,value:!0}),rn(this,DA,{writable:!0,value:new iP}),Yi(this,"uid",void 0),Yi(this,"groupUid",void 0),Yi(this,"postfix",void 0),Yi(this,"thumbnail",void 0),lg.makeSureCoreLicenseExist(),Ps(t)||oP(t,"editViewer",0,"new EditViewer","option");const a=SI(null==t?void 0:t.keyboardInteractionConfig);!1===(null==t||null===(e=t.viewerConfig)||void 0===e?void 0:e.enableMagnifier)&&(t.viewerConfig.enableTextMagnifier=!1);const l=_o((null==t?void 0:t.viewerConfig)||{},_s({...fP,viewerMode:jg.DEFAULT,displayMode:"continuous",enablePopup:!0,enableOptimizePage:!0}));if(l.minZoom>l.maxZoom){pp.warning(pp.MIN_ZOOM_INVALID);const t=l.maxZoom;l.maxZoom=l.minZoom,l.minZoom=t}const{maxZoom:h,minZoom:c}=l;l.maxZoom=h>64||h<.01?64:h,l.minZoom=c>64||c<.01?.01:c,Ms()&&(G_.toolbarConfig.style={scale:"0.9"}),Xi(this,AA,T_.createViewer({uiConfig:_s(Ms()?I_:M_),...t,viewerConfig:{...l,...a},popupConfig:{annotationToolBarConfig:{...null==G_?void 0:G_.toolbarConfig,...null==t||null===(i=t.annotationConfig)||void 0===i?void 0:i.toolbarConfig},annotationPaletteConfig:{...G_.paletteConfig,...null==t||null===(n=t.annotationConfig)||void 0===n?void 0:n.paletteConfig},annotationCustomStampPanelConfig:{...null==t||null===(s=t.annotationConfig)||void 0===s?void 0:s.customStampPanelConfig},passwordLoaderConfig:{enabled:null===(o=null==t||null===(r=t.viewerConfig)||void 0===r?void 0:r.enablePasswordLoader)||void 0===o||o}}})),this.uid=$i(this,AA).uid,this.groupUid=$i(this,AA).groupUid,this.postfix=$i(this,AA).postfix;const d=_o(_s(null==t?void 0:t.annotationConfig)||{},_s(G_));$i(this,AA).updateAnnotationConfig(uI(d)),cI($i(this,AA).getUiConfig()).includes(P_.Filter)&&!$i(this,AA).context.core.filterService.enableFilter&&pp.warning(pp.IMG_FILTER_MISS),t&&!1===t.createThumbnail||sn(this,MA,UA).call(this,null==t?void 0:t.thumbnailConfig,a),t&&!Ps(null==t?void 0:t.adaptiveIconSize)&&Xi(this,IA,t.adaptiveIconSize),$i(this,AA).rootDom&&($i(this,AA).rootDom.style.fontSize="20px",nI(this,$i(this,AA).rootDom,$i(this,IA))),YI.forEach(t=>{$i(this,AA).addFontToUi(t)}),sn(this,LA,FA).call(this),sn(this,kA,NA).call(this),sn(this,RA,BA).call(this)}get isVisible(){return $i(this,DA).getIsVisible($i(this,AA))}get isBoundContainer(){return $i(this,DA).getIsBoundContainer($i(this,AA))}get currentDocument(){return $i(this,DA).getCurrentDocument($i(this,AA))}get zoom(){return parseFloat($i(this,AA).getViewerConfig().zoom.toFixed(4))}set zoom(t){const{maxZoom:e,minZoom:i}=$i(this,AA).getViewerConfig();(function(t,e,i,n,s,o){const r=fp.formatError(fp.isNumberAndIsInRange(t));return r?fp.output(1,i,n,void 0,r):(t<s&&fp.output(1,i,n,void 0,pp.ZOOM_TOO_SMALL),t>o&&fp.output(1,i,n,void 0,pp.ZOOM_TOO_LARGE),!0)})(t,0,`${PA}.zoom`,"zoom",i,e)&&$i(this,AA).updateViewerConfig({zoom:t})}get zoomOrigin(){return $i(this,AA).getViewerConfig().zoomOrigin}set zoomOrigin(t){(function(t,e){const i=TI.isZoomOriginValid(t);return!i.length||fp.output(1,e,"zoomOrigin",i)})(t,`${PA}.zoomOrigin`)&&$i(this,AA).updateViewerConfig({zoomOrigin:{x:t.x,y:t.y}})}get displayMode(){const{displayMode:t}=$i(this,AA).getViewerConfig(),e=$i(this,AA).getActiveTab();return e?e.context.displayMode:t}set displayMode(t){const e="displayMode",i=`${PA}.${e}`;tP(t,1,i,e)&&(["single","continuous"].includes(t)?$i(this,AA).updateViewerConfig({displayMode:t}):pp.warning(pp.PARAM_NOT_SUPPORT,i,e))}get toolMode(){const{toolMode:t}=$i(this,AA).getViewerConfig();return t}set toolMode(t){const e="toolMode",i=`${PA}.${e}`;tP(t,1,i,e)&&function(t,e,i,n){return!!["crop","pan","annotation","textSelection"].includes(t)||fp.output(1,i,n,void 0,pp.PARAM_NOT_SUPPORT)}(t,0,i,e)&&$i(this,AA).updateViewerConfig({toolMode:t})}get annotationMode(){const{annotationMode:t}=$i(this,AA).getViewerConfig();return t}set annotationMode(t){const e="annotationMode",i=`${PA}.${e}`;tP(t,1,i,e)&&function(t,e,i,n){return!!["rectangle","ellipse","line","polygon","polyline","ink","textBox","textTypewriter","stamp","erase","select","highlight","underline","strikeout"].includes(t)||fp.output(1,i,n,void 0,pp.PARAM_NOT_SUPPORT)}(t,0,i,e)&&$i(this,AA).updateViewerConfig({annotationMode:t})}get fitMode(){const{fitMode:t}=$i(this,AA).getViewerConfig(),e=$i(this,AA).getActiveTab();return e?e.context.fitMode:t}set fitMode(t){const e=`${PA}.fitMode`,i="fitMode";tP(t,1,e,i)&&function(t,e,i,n){return!!["width","height","window","actualSize"].includes(t)||fp.output(1,i,n,void 0,pp.PARAM_NOT_SUPPORT)}(t,0,e,i)&&$i(this,AA).updateViewerConfig({fitMode:t})}get cropMode(){return $i(this,AA).cropMode}set cropMode(t){const e=`${PA}.cropMode`,i="cropMode";tP(t,1,e,i)&&function(t,e,i,n){return!!["all","current"].includes(t)||fp.output(1,i,n,void 0,pp.PARAM_NOT_SUPPORT)}(t,0,e,i)&&($i(this,AA).cropMode=t)}bindContainer(t){$i(this,DA).bindContainer($i(this,AA),t,`${PA}.bindContainer`)}unbindContainer(){$i(this,DA).unbindContainer($i(this,AA))}show(){$i(this,DA).show($i(this,AA)),nI(this,$i(this,AA).rootDom,$i(this,IA))}hide(){$i(this,DA).hide($i(this,AA))}getUiConfig(){return $i(this,DA).getUiConfig($i(this,AA))}updateUiConfig(t){return $i(this,AA).selectAnnotations([]),!!$i(this,DA).updateUiConfig($i(this,AA),t,"editViewer",`${PA}.updateUiConfig`)&&($i(this,AA).emit("thumbnailBind",this.thumbnail.uid),nI(this,$i(this,AA).rootDom,$i(this,IA)),!0)}openDocument(t){$i(this,DA).openDocument(t,this.uid,`${PA}.openDocument`)}closeDocument(){return $i(this,DA).closeDocument($i(this,AA),`${PA}.closeDocument`)}getStyle(t){return $i(this,DA).getStyle($i(this,AA),"edit",t,_A,`${PA}.getStyle`)}updateStyle(t,e){const i=`${PA}.updateStyle`;return $i(this,DA).updateStyle($i(this,AA),t,e,_A,i)}setParallelScrollCount(t){const e=`${PA}.setParallelScrollCount`,i="count",{maxColumns:n,maxRows:s}=$i(this,AA).getViewerConfig();return!(E_(t,1,e,i)||!q_(t,e,i,1)||J_(t,1,s,1,e,i)||J_(t,1,n,1,e,i))&&("continuous"!==this.displayMode?(pp.warning(pp.ROW_COLUMN_CAN_NOT_CHANGE,e),!1):$i(this,AA).setRowAndColumn(t,t))}setCropRect(t){const e=`${PA}.setCropRect`,i="rect";if(E_(t,1,e,i)||EA(t,e,i,1)||!$_($i(this,AA),1)||X_(void 0,void 0,$i(this,AA),1))return!1;const n="current"===this.cropMode?[$i(this,AA).getCurrentPageIndex()]:$i(this,AA).getMatchedCropBoxIndices(t);return!TA(e,i,$i(this,AA),t,n,1)&&("crop"!==this.toolMode?(pp.warning(pp.TOOL_MODE_NOT_AVAILABLE,e),!1):$i(this,AA).setRectBox(t))}getCropRect(){return $_($i(this,AA),1)?$i(this,AA).getRectBox():null}crop(t,e){const i=`${PA}.crop`,n=$i(this,AA).getPageCounts(),s="rect";if(E_(t,1,i,s)||EA(t,i,s,1)||!$_($i(this,AA),1)||X_(void 0,void 0,$i(this,AA),1))return!1;let o;if(e&&e.length>0){if(!eP(e,1,i,"indices",0,n-1))return!1;o=e}else o="current"===this.cropMode?[$i(this,AA).getCurrentPageIndex()]:$i(this,AA).getMatchedCropBoxIndices(t);return!TA(i,s,$i(this,AA),t,o,1)&&$i(this,AA).cropPages(t,o)}rotate(t,e){const i=`${PA}.rotate`;return $i(this,DA).rotate($i(this,AA),t,e,i)}undo(){if(!$_($i(this,AA),1))return!1;const t=$i(this,AA).undo();return t||pp.warning(pp.UNDO_NOOP),t}redo(){if(!$_($i(this,AA),1))return!1;const t=$i(this,AA).redo();return t||pp.warning(pp.REDO_NOOP),t}saveOperations(){return $i(this,DA).saveOperation($i(this,AA))}indexToUid(t){const e=`${PA}.indexToUid`;return $i(this,DA).indexToUid($i(this,AA),t,e)}uidToIndex(t){const e=`${PA}.uidToIndex`;return $i(this,DA).uidToIndex($i(this,AA),t,e)}getCurrentPageUid(){return $i(this,DA).getCurrentPageUid($i(this,AA))}getCurrentPageIndex(){return $i(this,DA).getCurrentPageIndex($i(this,AA))}getPageCount(){return $i(this,DA).getPageCount($i(this,AA))}goToPage(t){const e=`${PA}.goToPage`;return $i(this,DA).gotoPage($i(this,AA),t,e)}selectAnnotations(t){const e=`${PA}.selectAnnotations`,i="annotationUids";if(!$_($i(this,AA),1)||X_(void 0,void 0,$i(this,AA),1)||E_(t,1,e,i)||!eA(t,1,e,i,void 0,!1))return!1;if(["textSelection","crop"].includes(this.toolMode))return pp.warning(pp.TOOL_MODE_NOT_AVAILABLE,e),!1;t=[...new Set(t)];const n=[],s=[],o=[],r=[],a=this.getCurrentPageUid(),l=t.reduce((t,e,l)=>{const h=T_.annotationService.getAnnotationByUid(e);return h?h.pageUid!==a?n.push(`${i}[${l}]: The specified annotation is not on the current page.`):"incomplete"===h.type||"unknown"===h.type?s.push(`${i}[${l}]: ${pp.UNSELECTED_UNKNOWN.message}`):h.flags.includes("readOnly")||h.flags.includes("noView")?o.push(`${i}[${l}]: ${pp.UNSELECTED_READONLY.message}`):h.flattened?r.push(`${i}[${l}]: ${pp.UNSELECTED_FLATTENED.message}`):t.push(e):n.push(`${i}[${l}]: The specified annotation does not exist.`),t},[]),h=[{result:n,exceptionType:pp.ANNOTATION_SELECT},{result:s,exceptionType:pp.UNSELECTED_UNKNOWN},{result:o,exceptionType:pp.UNSELECTED_READONLY},{result:r,exceptionType:pp.UNSELECTED_FLATTENED}];for(const{result:t,exceptionType:n}of h)if(t.length){const s=n;return s.details=t,pp.warning(s,e,i),!1}const c=$i(this,AA).getSelectedAnnotations().map(t=>t.uid);return c.length===l.length&&function(t,e){if(t.length!==e.length)return!1;const i=t.slice().sort(),n=e.slice().sort();for(let t=0;t<i.length;t++)if(i[t]!==n[t])return!1;return!0}(c,l)||$i(this,AA).selectAnnotations(l),!0}getSelectedAnnotations(){return!$_($i(this,AA),1)||X_(void 0,void 0,$i(this,AA),1)?[]:$i(this,AA).getSelectedAnnotations().length?SA.getAnnotationsByUids($i(this,AA).getSelectedAnnotations().map(t=>t.uid)):[]}async copySelectedTexts(){await $i(this,AA).copySelectedTexts()}on(t,e){$i(this,DA).on($i(this,AA),`${PA}.on`,t,e)}off(t,e){$i(this,DA).off($i(this,AA),`${PA}.off`,t,e)}destroy(){$i(this,DA).destroy($i(this,AA))}setAnnotationDrawingStyle(t){var e,i;const n=`${PA}.setAnnotationDrawingStyle`,s="config";if(E_(t,1,n,s)||!__(t,1,n,s))return!1;const o=TI.isAnnotationDrawingStyleValid(t,s);if(o.length){const t=pp.PARAM_INVALID;return t.details=o,pp.warning(t,n,s),!1}(null==t||null===(e=t.textBox)||void 0===e||null===(e=e.textContent)||void 0===e?void 0:e.fontSize)<=0&&(t.textBox.textContent.fontSize=1),(null==t||null===(i=t.textTypewriter)||void 0===i||null===(i=i.textContent)||void 0===i?void 0:i.fontSize)<=0&&(t.textTypewriter.textContent.fontSize=1);const r=$i(this,AA).getAnnotationConfig().defaultStyleConfig;if(null!=t&&t.line){const e=PP(r.line.lineEnding,"user");t.line.lineEnding={...e,...t.line.lineEnding}}if(null!=t&&t.polyline){const e=PP(r.polyline.lineEnding,"user");t.polyline.lineEnding={...e,...t.polyline.lineEnding}}const a=uI({defaultStyleConfig:t});return $i(this,AA).updateAnnotationConfig(a),!0}getTextSelection(){const t=$i(this,AA).context.getTextSelection();return t.forEach(t=>{t.rects=t.rects.map(t=>({x:Lo(t.x,2),y:Lo(t.y,2),width:Lo(t.width,2),height:Lo(t.height,2)}))}),t}async searchNextText(t,e){const i=`${PA}.searchNextText`;if(E_(t,1,i,"text")||!tP(t,1,i,"text")||!$_($i(this,AA),1)||X_(void 0,void 0,$i(this,AA),1))return!1;if(e){const t=TI.isSearchTextOptionsValid(e,"options");if(t.length){const e=pp.PARAM_INVALID;return e.details=t,pp.warning(e,i,"options"),!1}}return $i(this,AA).searchNextText(t,e).then(t=>(t||pp.warning(pp.NO_RESULTS_FOUND),t))}async searchPrevText(t,e){const i=`${PA}.searchPrevText`;if(E_(t,1,i,"text")||!tP(t,1,i,"text")||!$_($i(this,AA),1)||X_(void 0,void 0,$i(this,AA),1))return!1;if(e){const t=TI.isSearchTextOptionsValid(e,"options");if(t.length){const e=pp.PARAM_INVALID;return e.details=t,pp.warning(e,i,"options"),!1}}return $i(this,AA).searchPrevText(t,e).then(t=>(t||pp.warning(pp.NO_RESULTS_FOUND),t))}async searchFullText(t,e){const i=`${PA}.searchFullText`;if(E_(t,1,i,"text")||!tP(t,1,i,"text")||!$_($i(this,AA),1)||X_(void 0,void 0,$i(this,AA),1))return!1;if(e){const t=TI.isSearchTextOptionsValid(e,"options");if(t.length){const e=pp.PARAM_INVALID;return e.details=t,pp.warning(e,i,"options"),!1}}return $i(this,AA).searchFullText(t,e).then(t=>(t||pp.warning(pp.NO_RESULTS_FOUND),t))}getVisiblePagesInfo(){return $i(this,AA).getVisiblePagesInfo()}getAnnotationDrawingStyle(){return pI($i(this,AA).getAnnotationConfig().defaultStyleConfig)}}function BA(){$i(this,AA).hooks.annotationDefaultStyleChanged.on(t=>{$i(this,AA).emitter.hasCallback("annotationDrawingStyleChanged")&&$i(this,AA).emit("annotationDrawingStyleChanged",{newDrawingStyle:pI(_s(t.newStyle)),oldDrawingStyle:pI(_s(t.oldStyle))})})}function NA(){$i(this,AA).hooks.destroy.on(()=>{var t;null===(t=this.thumbnail)||void 0===t||t.vCommon.destroy(this.thumbnail.v),this.thumbnail=null,Xi(this,AA,null),Object.setPrototypeOf(this,null)})}function UA(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=t||{},n=_s(gP);Ms()&&(n.size="100%",n.rows=3,n.columns=2,n.canvasStyle.background="#4B4B4B",n.pageNumberStyle.color="white",n.enableOptimizePage=!0),_o(i,n);const{mainAndThbContainer:s,mainContainer:o,thumbnailContainer:r}=$i(this,AA).context.viewService,{size:a,position:l,visibility:h}=n,c=_s(L_);let d="row",u=a,p="100%",g="left"===l?"-1":"1";"top"!==l&&"bottom"!==l||(d="column",u="100%",p=a,g="top"===l?"-1":"1");const f=`ddv-edit-viewer-thumb-${l}`;c.className=f,Object.assign(r.style,{width:u,height:p,order:g,display:"visible"===h?"block":"none"}),s.style.flexDirection=d,s.insertBefore(r,o),$i(this,AA).context.resize(),$i(this,AA).context.viewerConfig.hasThb=!0;const m=new yP({container:r,viewerConfig:{...n,...e},groupUid:this.groupUid,uiConfig:c},`${PA}.thumbnail`);this.thumbnail=m,$i(this,AA).emit("thumbnailBind",m.uid),m.v.emit("thumbnailBind",$i(this,AA).uid),m.on("click",()=>{$i(this,AA).emit("ui_hidePopup",null)})}function FA(){this.on("resized",t=>{nI(this,$i(this,AA).rootDom,$i(this,IA))})}const VA={canvasStyle:{...U_},pageStyle:{...F_},quadSelectionStyle:{...V_},enableSlide:!0,enableMagnifier:!0};function WA(t,e,i,n){const s=TI.isQuadValid(t);return s.length?fp.output(e,i,n,s):!!Oo(t.flat())||fp.output(e,i,n,void 0,pp.PARAM_INVALID)}function HA(t,e,i,n){return!!function(t,e,i){for(let n=0;n<t.length;n++)if(t[n][0]>e||t[n][1]>i)return!0;return!1}(t,i,n)&&(fp.output(e,void 0,void 0,void 0,pp.QUAD_EXCEED_PAGE_BOUND),!0)}const jA=["canvasStyle","pageStyle","quadSelectionStyle","cursorStyle"],zA="PerspectiveViewer";var GA=new WeakMap,YA=new WeakMap,$A=new WeakSet;class XA{constructor(t){var e,i;an(this,$A),rn(this,GA,{writable:!0,value:void 0}),rn(this,YA,{writable:!0,value:new iP}),Yi(this,"uid",void 0),Yi(this,"groupUid",void 0),Yi(this,"postfix",void 0),lg.makeSureCoreLicenseExist(),Ps(t)||oP(t,"perspectiveViewer",0,`new ${zA}`,"option");const n=_o((null==t?void 0:t.viewerConfig)||{},_s({...VA,viewerMode:jg.PERSPECTIVE,toolMode:"crop"})),s=Ms()?D_:k_;Xi(this,GA,T_.createViewer({uiConfig:_s(s),...t,viewerConfig:{enablePopup:!0,...n},popupConfig:{passwordLoaderConfig:{enabled:null===(e=null==t||null===(i=t.viewerConfig)||void 0===i?void 0:i.enablePasswordLoader)||void 0===e||e}}})),this.uid=$i(this,GA).uid,this.groupUid=$i(this,GA).groupUid,this.postfix=$i(this,GA).postfix,sn(this,$A,qA).call(this)}get isVisible(){return $i(this,YA).getIsVisible($i(this,GA))}get isBoundContainer(){return $i(this,YA).getIsBoundContainer($i(this,GA))}get currentDocument(){return $i(this,YA).getCurrentDocument($i(this,GA))}bindContainer(t){$i(this,YA).bindContainer($i(this,GA),t,`${zA}.bindContainer`)}unbindContainer(){$i(this,YA).unbindContainer($i(this,GA))}show(){$i(this,YA).show($i(this,GA))}hide(){$i(this,YA).hide($i(this,GA))}getUiConfig(){return $i(this,YA).getUiConfig($i(this,GA))}updateUiConfig(t){return $i(this,YA).updateUiConfig($i(this,GA),t,"perspectiveViewer",`${zA}.updateUiConfig`)}openDocument(t){$i(this,YA).openDocument(t,this.uid,`${zA}.openDocument`)}closeDocument(){return $i(this,YA).closeDocument($i(this,GA),`${zA}.closeDocument`)}getStyle(t){return $i(this,YA).getStyle($i(this,GA),"perspective",t,jA,`${zA}.getStyle`)}updateStyle(t,e){const i=`${zA}.updateStyle`;return $i(this,YA).updateStyle($i(this,GA),t,e,jA,i)}setQuadSelection(t){const e=`${zA}.setQuadSelection`,i="quad";if(E_(t,1,e,i)||!WA(t,1,e,i)||!$_($i(this,GA),1)||X_(e,void 0,$i(this,GA),1))return!1;const{width:n,height:s}=$i(this,GA).getRealPixelSize();return!HA(t,1,n,s)&&$i(this,GA).setQuadBox(t)}getQuadSelection(){const t=`${zA}.getQuadSelection`;return!$_($i(this,GA),1)||X_(t,void 0,$i(this,GA),1)?null:$i(this,GA).getQuadBox()}resetQuadSelection(t){const e=`${zA}.resetQuadSelection`;return!(!$_($i(this,GA),1)||X_(e,void 0,$i(this,GA),1))&&(!(!Ps(t)&&!eP(t,1,e,"indices",0,$i(this,GA).getPageCounts()-1))&&$i(this,GA).resetQuadBox(t))}applyPerspective(t){const e=`${zA}.applyPerspective`,i="quad";E_(t,0,e,i),WA(t,0,e,i),$_($i(this,GA),0),X_(e,void 0,$i(this,GA),0);let{width:n,height:s}=$i(this,GA).getRealPixelSize();return n=Math.round(n),s=Math.round(s),HA(t,0,n,s),$i(this,GA).perspectivePage(t)}rotate(t,e){const i=`${zA}.rotate`;return $i(this,YA).rotate($i(this,GA),t,e,i)}saveOperations(){return $i(this,YA).saveOperation($i(this,GA))}goToPage(t){const e=`${zA}.goToPage`;return $i(this,YA).gotoPage($i(this,GA),t,e)}indexToUid(t){const e=`${zA}.indexToUid`;return $i(this,YA).indexToUid($i(this,GA),t,e)}uidToIndex(t){const e=`${zA}.uidToIndex`;return $i(this,YA).uidToIndex($i(this,GA),t,e)}getCurrentPageUid(){return $i(this,YA).getCurrentPageUid($i(this,GA))}getCurrentPageIndex(){return $i(this,YA).getCurrentPageIndex($i(this,GA))}getPageCount(){return $i(this,YA).getPageCount($i(this,GA))}on(t,e){$i(this,YA).on($i(this,GA),`${zA}.on`,t,e)}off(t,e){$i(this,YA).off($i(this,GA),`${zA}.off`,t,e)}destroy(){$i(this,YA).destroy($i(this,GA))}getVisiblePagesInfo(){return $i(this,GA).getVisiblePagesInfo()}}function qA(){$i(this,GA).hooks.destroy.on(()=>{Xi(this,GA,null),Object.setPrototypeOf(this,null)})}class ZA extends yP{constructor(t){super(t,"BrowseViewer")}get currentDocument(){return this.vCommon.getCurrentDocument(this.v)}bindContainer(t){this.vCommon.bindContainer(this.v,t,`${this.errorPrefix}.bindContainer`)}unbindContainer(){this.vCommon.unbindContainer(this.v)}openDocument(t){this.vCommon.openDocument(t,this.uid,`${this.errorPrefix}.openDocument`)}closeDocument(){return this.vCommon.closeDocument(this.v,`${this.errorPrefix}.closeDocument`)}rotate(t,e){const i=`${this.errorPrefix}.rotate`;return this.vCommon.rotate(this.v,t,e,i)}indexToUid(t){const e=`${this.errorPrefix}.indexToUid`;return this.vCommon.indexToUid(this.v,t,e)}uidToIndex(t){const e=`${this.errorPrefix}.uidToIndex`;return this.vCommon.uidToIndex(this.v,t,e)}getCurrentPageUid(){return this.vCommon.getCurrentPageUid(this.v)}getCurrentPageIndex(){return this.vCommon.getCurrentPageIndex(this.v)}getPageCount(){return this.vCommon.getPageCount(this.v)}goToPage(t){const e=`${this.errorPrefix}.goToPage`;return this.vCommon.gotoPage(this.v,t,e)}saveOperations(){return this.vCommon.saveOperation(this.v)}destroy(){this.vCommon.destroy(this.v)}}var JA=new WeakMap,KA=new WeakMap,QA=new WeakMap,tI=new WeakSet;class eI{constructor(t){an(this,tI),rn(this,JA,{writable:!0,value:void 0}),rn(this,KA,{writable:!0,value:void 0}),rn(this,QA,{writable:!0,value:!1}),Yi(this,"uid",void 0),Yi(this,"isDestroyed",!1),Yi(this,"postfix",void 0),this.uid=Us(),this.postfix=`-${this.uid}`,Xi(this,KA,new Ws),Ps(t)||oP(t,"customViewer",0,"new CustomViewer","option");let e=null==t?void 0:t.uiConfig;(!e||Es(e)&&0===Object.keys(e).length)&&(e={type:"Layout"}),sn(this,tI,iI).call(this),Xi(this,JA,new XC({container:null==t?void 0:t.container,emitter:$i(this,KA),postfix:this.uid,uiConfig:e,injection:{viewer:{postfix:this.postfix}}})),null!=t&&t.container&&e&&$i(this,JA).bindContainer(t.container)}get isBoundContainer(){return $i(this,QA)}get isVisible(){return"none"!==$i(this,JA).rootDom.style.display}bindContainer(t){const e="CustomViewer.bindContainer";E_(t,0,e,"container");const i=TI.isContainerParamValid(t);i&&fp.error(e,"container",void 0,i),$i(this,JA).bindContainer(t)&&Xi(this,QA,!0)}unbindContainer(){$i(this,JA).unbindContainer(),Xi(this,QA,!1)}hide(){$i(this,JA).rootDom.style.display="none"}show(){$i(this,JA).rootDom.style.display="flex"}getUiConfig(){return $i(this,JA).uiConfig}updateUiConfig(t){const e="CustomViewer.updateUiConfig",i="uiConfig";return!(E_(t,1,e,i)||!Z_(t,"customViewer",e,i,1))&&$i(this,JA).updateUiConfig(t)}on(t,e){const i="CustomViewer.on";!E_(t,1,i,"eventName")&&!E_(e,1,i,"listener")&&tP(t,1,i,"eventName",!1)&&Q_(e,i,"listener",1)&&$i(this,KA).on(t,e)}off(t,e){const i="CustomViewer.off";!E_(t,1,i,"eventName")&&tP(t,1,i,"eventName",!1)&&(Ps(e)||Q_(e,i,"listener",1))&&$i(this,KA).off(t,e)}destroy(){this.isDestroyed||($i(this,JA).dispose(),$i(this,KA).destroy(),Xi(this,JA,null),Xi(this,KA,null)),this.isDestroyed=!0,Object.setPrototypeOf(this,null)}}function iI(){XC.registerComponent({Root:QC,Layout:ZC,Button:qC,Blank:QS,SeparatorLine:tb,Close:tT,Done:iT,Back:eT})}function nI(t,e,i){if(!i||Ms()||!t.isVisible)return;const n=e,s=n.clientWidth;if(t instanceof OA){let t=20;s<1280&&(t=Math.max(13.5,s/1280*20)),n.style.fontSize=`${t}px`}}function sI(t){if(t instanceof Blob)return!0;if(Os(t)){const e=t=>{try{return new URL(t),!0}catch(t){return!1}};return!(!(t=>/^data:image\/([a-zA-Z]*);base64,/.test(t))(t)&&!e(t))}return!1}function oI(t){return!![B_.REJECTED,B_.ACCEPTED,B_.INITIAL_HERE,B_.SIGN_HERE,B_.WITNESS,B_.APPROVED,B_.NOT_APPROVED,B_.DRAFT,B_.FINAL,B_.COMPLETED,B_.CONFIDENTIAL,B_.VOID].includes(t)}function rI(t){return!!oI(t)||!!Ds(t)||!!bI(t)}function aI(t){return!!Es(t)&&!(null!=t&&t.content&&!Os(t.content)||null!=t&&t.color&&!Os(t.color)||null!=t&&t.fontFamily&&!Os(t.fontFamily)||null!=t&&t.fontSize&&!Ls(t.fontSize)||null!=t&&t.lineThrough&&!Rs(t.lineThrough)||null!=t&&t.underline&&!Rs(t.underline)||null!=t&&t.fontWeight&&!["normal","bold"].includes(t.fontWeight)||null!=t&&t.fontStyle&&!["normal","italic"].includes(t.fontStyle))}function lI(t){return!!Es(t)&&!!(Ls(null==t?void 0:t.x)&&Ls(null==t?void 0:t.y)&&Ls(null==t?void 0:t.width)&&Ls(null==t?void 0:t.height))&&!(t.width<=0||t.height<=0)}function hI(t,e){const i=["Load","Download","Print"],n=["Layout","Button","Blank","SeparatorLine","Close","Done","Back"],s=[...n,"MainView"],o=["Pagination","RotateLeft","RotateRight","Delete","DeleteCurrent","DeleteAll"],r=[...s,...o,...i,"PerspectiveAll","FullQuad"],a=[...s,...o,...i],l=[...s,"Capture","Flashlight","CameraConvert","CameraResolution","AutoDetect","AutoCapture","ImagePreview"],h=[...s,...o,...i,"Zoom","ZoomIn","ZoomOut","ZoomByPercentage","ThumbnailSwitch","FitMode","DisplayMode","Crop","Filter","Undo","Redo","Pan","FitWidth","FitHeight","FitWindow","ActualSize","SinglePage","ContinuousPage","AnnotationSet","EllipseAnnotation","EraseAnnotation","InkAnnotation","LineAnnotation","PolygonAnnotation","PolylineAnnotation","RectAnnotation","SelectAnnotation","StampIconAnnotation","StampImageAnnotation","TextBoxAnnotation","TextTypewriterAnnotation","BringForward","BringToFront","SendBackward","SendToBack","TextSearchPanel","TextSearchPanelSwitch","TextSelectionMode","HighlightAnnotation","UnderlineAnnotation","StrikeoutAnnotation"];let c;switch(e){case"captureViewer":c=l;break;case"editViewer":c=h;break;case"perspectiveViewer":c=r;break;case"customViewer":c=n;break;case"browseViewer":c=a}const d=[];return null!=t&&t.type&&!c.includes(null==t?void 0:t.type)&&d.push(t.type),null!=t&&t.children&&t.children.forEach(t=>{Os(t)&&!c.includes(t)&&d.push(t),Es(t)&&d.push(...hI(t,e))}),d}function cI(t){const e=[];return null!=t&&t.type&&e.push(t.type),null!=t&&t.children&&t.children.forEach(t=>{Os(t)&&e.push(t),Es(t)&&e.push(...cI(t))}),[...new Set(e)]}function dI(t,e){const i=hI(t,e);if(i.length>0){let t="";return i.forEach((e,n)=>{n===i.length-1?t+=`${e}`:t+=`${e} `}),t}return!1}function uI(t){const{defaultStyleConfig:e}=t;return Object.keys(e).forEach(t=>{const i=e[t];"object"==typeof i&&null!==i&&((t=>{if("lineEnding"in t&&"object"==typeof t.lineEnding&&null!==t.lineEnding){const e=PP(t.lineEnding,"date");delete t.lineEnding,t.lineEnding=e}})(i),(t=>{"borderWidth"in t&&(t.borderWidth=Bo(Ls(null==t?void 0:t.borderWidth)?t.borderWidth:1,Cr.dataResolution,Cr.displayResolution))})(i),(t=>{if("textContent"in t)if(Es(t.textContent)){var e,i,n,s,o,r,a;Ls(null==t||null===(e=t.textContent)||void 0===e?void 0:e.fontSize)&&(t.textContent.fontSize=Bo(null==t||null===(a=t.textContent)||void 0===a?void 0:a.fontSize,Cr.dataResolution,Cr.displayResolution)),null!=t&&null!==(i=t.textContent)&&void 0!==i&&i.fontStyle&&!["normal","italic"].includes(null==t||null===(n=t.textContent)||void 0===n?void 0:n.fontStyle)&&(t.textContent.fontStyle="normal"),null!=t&&null!==(s=t.textContent)&&void 0!==s&&s.fontWeight&&!["normal","bold"].includes(null==t||null===(o=t.textContent)||void 0===o?void 0:o.fontWeight)&&(t.textContent.fontWeight="normal"),""===(null==t||null===(r=t.textContent)||void 0===r?void 0:r.fontFamily)&&(t.textContent.fontFamily="Helvetica")}else t.textContent={}})(i),(t=>{"lineDash"in t&&t.lineDash.length&&(t.lineDash=Bo(t.lineDash,Cr.dataResolution,Cr.displayResolution))})(i),(t=>{"textAlign"in t&&!["left","right","center","justify"].includes(null==t?void 0:t.textAlign)&&(t.textAlign="left")})(i),(t=>{"opacity"in t&&(!Ls(null==t?void 0:t.opacity)||(null==t?void 0:t.opacity)<0||(null==t?void 0:t.opacity)>1)&&(t.opacity=1)})(i),"stamp"===t&&(t=>{t.stamp instanceof Blob&&(t.imageData=t.stamp),Os(t.stamp)&&(sI(t.stamp)?t.imageData=t.stamp:t.stampIcon=oI(t.stamp)?AP(t.stamp,"date"):AP(B_.DRAFT,"date")),bI(t.stamp)&&(t.stampConfig=t.stamp),delete t.stamp})(i))}),{...t,controlsStyle:t.annotationSelectionStyle}}function pI(t){return Object.keys(t).forEach(e=>{const i=t[e];"object"==typeof i&&null!==i&&((t=>{if("lineEnding"in t){const e=PP(t.lineEnding,"user");t.lineEnding=e}})(i),(t=>{"borderWidth"in t&&(t.borderWidth=Bo(t.borderWidth,Cr.displayResolution,Cr.dataResolution,!0))})(i),(t=>{var e,i;"textContent"in t&&null!=t&&null!==(e=t.textContent)&&void 0!==e&&e.fontSize&&(t.textContent.fontSize=Bo(null==t||null===(i=t.textContent)||void 0===i?void 0:i.fontSize,Cr.displayResolution,Cr.dataResolution,!0))})(i),(t=>{"lineDash"in t&&(t.lineDash=Bo(t.lineDash,Cr.displayResolution,Cr.dataResolution,!0))})(i),"stamp"===e&&(t=>{t.imageData&&(t.stamp=t.imageData),delete t.imageData,t.stampConfig&&(t.stamp||(t.stamp=t.stampConfig)),delete t.stampConfig,t.stampIcon&&(t.stamp||(t.stamp=AP(t.stampIcon,"user"))),delete t.stampIcon})(i))}),t}function gI(t){if(""===t)return!0;const e=document.createElement("div");e.style.border=t;const i=t=>""===t||"initial"===t,{borderWidth:n,borderColor:s,borderStyle:o}=e.style;return!(i(n)||i(s)||i(o))}function fI(t,e,i){const{left:n,top:s,width:o,height:r}=t,a=1e-4;return!(Math.abs(n-e)>a&&n>e||Math.abs(n+o-e)>a&&n+o>e||Math.abs(s-i)>a&&s>i||Math.abs(s+r-i)>a&&s+r>i)}function mI(t,e){return Object.keys(t).filter(i=>t[i]===e)}function vI(t,e){if(t===e)return!0;if(Es(t)&&Es(e)&&Object.keys(t).length===Object.keys(e).length)for(const i in t){if(!Object.prototype.hasOwnProperty.call(e,i))return!1;if(!vI(t[i],e[i]))return!1}else{if(!Ts(t)||!Ts(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!vI(t[i],e[i]))return!1}return!0}function yI(t,e){let i;switch(t){case"canvasStyle":i=function(t,e){const i=[];return i.push(...wI(t,{border:(null==e?void 0:e.border)||"",background:(null==e?void 0:e.background)||""})),Ps(null==e?void 0:e.cursor)||Os(e.cursor)||i.push(`${t}.cursor is invalid`),i}(t,e);break;case"pageNumberStyle":i=function(t,e){const i=[],n=["color","fontSize","fontFamily","left","top","right","bottom","width","height","background","border","borderRadius","translateX","translateY"];return Object.keys(e).forEach(s=>{-1!==n.indexOf(s)&&(Os(e[s])||i.push(`${t}.${s} is invalid.`)),"border"===s&&Os(e[s])&&!gI(e[s])&&i.push(`${t}.border is invalid.`),("onPage"===s&&!Rs(e[s])||"opacity"===s&&!Ls(e[s])||"visibility"===s&&-1===["visible","hidden"].indexOf(e[s]))&&i.push(`${t}.${s} is invalid.`)}),i}(t,e);break;case"checkBoxStyle":i=function(t,e){const i=[],n=["checkMarkColor","checkMarkLineWidth","left","top","right","bottom","width","height","background","border","borderRadius","translateX","translateY"];return Object.keys(e).forEach(s=>{-1!==n.indexOf(s)&&(Os(e[s])||i.push(`${t}.${s} is invalid.`)),"border"===s&&Os(e[s])&&!gI(e[s])&&i.push(`${t}.border is invalid.`),("opacity"===s&&!Ls(e[s])||"visibility"===s&&-1===["visible","hidden"].indexOf(e[s]))&&i.push(`${t}.${s} is invalid.`)}),i}(t,e);break;case"quadSelectionStyle":i=function(t,e){const i=[],n=["border","background","ctrlBorderRadius","ctrlBorder","ctrlWidth","ctrlHeight","ctrlBackground","invalidCtrlBorderColor","invalidBorderColor"];return Object.keys(e).forEach(s=>{-1!==n.indexOf(s)&&(Os(e[s])||i.push(`${t}.${s} is invalid`)),"border"!==s&&"ctrlBorder"!==s||!Os(e[s])||gI(e[s])||i.push(`${t}.${s} is invalid`)}),i}(t,e);break;case"annotationSelectionStyle":i=function(t,e){const i=[],n=["border","background","ctrlBorderRadius","ctrlBorder","ctrlWidth","ctrlHeight","ctrlBackground"];return Object.keys(e).forEach(s=>{-1!==n.indexOf(s)&&(Os(e[s])||i.push(`${t}.${s} is invalid.`)),"border"!==s&&"ctrlBorder"!==s||!Os(e[s])||gI(e[s])||i.push(`${t}.${s} is invalid.`)}),i}(t,e);break;default:i=wI(t,e)}return i}function xI(t){return!!Ls(t)&&t>=0}function wI(t,e){const i=[];return Object.keys(e).forEach(n=>{-1!==["background","border"].indexOf(n)&&(Os(e[n])||i.push(`${t}.${n} is invalid.`),"border"===n&&e[n]&&Os(e[n])&&!gI(e[n])&&i.push(`${t}.border is invalid.`))}),i}function CI(t,e){const i=t.flat(2),n=e.flat(2);if(i.length!==n.length)return!1;const s=n[0].x-i[0].x,o=n[1].y-i[1].y;for(let t=1;t<i.length;t++){if(n[t].x-i[t].x!==s)return!1;if(n[t].y-i[t].y!==o)return!1}return!0}function bI(t){return Array.isArray(t)&&t.every(t=>"object"==typeof t&&null!==t)}function SI(t){const e={};return!1===(null==t?void 0:t.enableZoom)&&(e.enableZoomInWithKeyboard=!1,e.enableZoomOutWithKeyboard=!1),!1===(null==t?void 0:t.enableUndoRedo)&&(e.enableUndoWithKeyboard=!1,e.enableRedoWithKeyboard=!1),!1===(null==t?void 0:t.enableAnnotationClipboard)&&(e.enableCopyCutPasteWithKeyboard=!1),!1===(null==t?void 0:t.enableMoveAnnotation)&&(e.enableMoveAnnotationWithKeyboard=!1),!1===(null==t?void 0:t.enableDeleteAnnotation)&&(e.enableDeleteWithKeyboard=!1),!1===(null==t?void 0:t.enablePageNavigation)&&(e.enableSelectPageWithKeyboard=!1),!1===(null==t?void 0:t.enableMultiplePagesSelection)&&(e.enableSelectWithShift=!1,e.enableSelectWithCtrl=!1,e.enableSelectAllWithKeyboard=!1),!1===(null==t?void 0:t.enableMultipleAnnotationsSelection)&&(e.enableMultipleSelectAnnotationWithKeyboard=!1),e}class TI{static isLicenseValid(t){if(Os(t)){const e=t.trim();return 0===e.length||e.startsWith("DLS")||(e.startsWith("f")||e.startsWith("t"))&&e.length>50}return!1}static isQuadValid(t,e){const i=[],n=gp("Quad",e);if(Ps(t))return i.push(`${n} is missing.`),i;const s=fp.isArrayAndMeetMinLength(t,4),o=fp.formatDetails(n,s);return o.length?(i.push(...o),i):(t.forEach((t,n)=>{const s=gp("Quad",e,`[${n}]`,!0),o=fp.isArrayAndMeetMinLength(t,2),r=fp.formatDetails(gp("Array",s),o);r.length?i.push(...r):t.forEach((t,e)=>{const n=fp.isNumberAndIsInRange(t),o=fp.formatDetails(gp("Array",s,`[${e}]`,!0),n);o.length&&i.push(...o)})}),i)}static isRectValid(t,e){const i=[],n=gp("Rect",e);if(Ps(t))return i.push(`${n} is missing.`),i;const s=fp.formatDetails(n,Es(t));return s.length?(i.push(...s),i):(["left","top","width","height"].forEach(n=>{const s=fp.formatDetails(gp("Rect",e,n),fp.isNumberAndIsInRange(t[n]));s.length&&i.push(...s)}),i)}static isUpdatedSourceValid(t,e,i){const n=[],s="UpdatedSource",o=fp.formatDetails(gp(s,e),Es(t));if(o.length)return n.push(...o),n;const r=TI.isSourceValid(t,"source",i);if(r.length&&n.push(...r),!Ps(t.fileIndex)){const i=fp.formatDetails(gp(s,e,"fileIndex"),fp.isNumberAndIsInRange(t.fileIndex,0));n.push(...i)}return n}static isSourceValid(t,e,i){const n=[],s="Source",o=fp.formatDetails(gp(s,e),Es(t));if(o.length)return n.push(...o),n;const r=fp.formatDetails(gp(s,e,"fileData"),Ds(t.fileData));return r.length?(n.push(...r),n):n}static isSourcesValid(t,e,i){const n=[],s="Source[]",o=fp.formatDetails(gp(s,e),fp.isArrayAndMeetMinLength(t));return o.length?(n.push(...o),n):(t.forEach((t,o)=>{n.push(...this.isSourceValid(t,gp(s,e,`[${o}]`,!0),i))}),n)}static isLoadSourceOptionsValid(t,e){const i=[],n="LoadSourceOptions",s=fp.formatDetails(gp(n,e),Es(t));if(s.length)return i.push(...s),i;if(!Ps(t.insertBeforeIndex)){const s=fp.formatDetails(gp(n,e,"insertBeforeIndex"),fp.isNumberAndIsInRange(t.insertBeforeIndex));i.push(...s)}if(!Ps(t.exception)){const s=fp.formatDetails(gp(n,e,"exception"),fp.isStringAndNotEmpty(t.exception,!1));i.push(...s)}return i}static isHandlerTypeValid(t){return{isValid:Os(t)&&["documentBoundariesDetect","imageFilter"].includes(t)}}static isContainerKeyValid(t,e){const i="container";let n;if(Vs(t)&&(n=t),Os(t)){const e=document.getElementById(t);Vs(e)&&(n=e)}const s=[];return n||s.push(`${gp(i,e,i)}: ${pp.CONTAINER_NOT_EXIST.message}`),s}static isContainerParamValid(t){return Os(t)||Vs(t)?this.isContainerKeyValid(t).length>0?pp.CONTAINER_NOT_EXIST:null:pp.PARAM_INVALID}static isUiConfigValid(t,e){const i="UiConfig",n=[],s=fp.formatDetails(gp(i,e),Es(t));if(s.length)return n.push(...s),n;const o=fp.formatDetails(gp(i,e,"type"),fp.isStringAndNotEmpty(t.type,!1));if(n.push(...o),["id","name","flexDirection","tooltip","className","label"].forEach(s=>{if(!Ps(t[s])){const o=fp.formatDetails(gp(i,e,s),fp.isStringAndNotEmpty(t[s]));n.push(...o)}}),["style","events"].forEach(s=>{if(!Ps(t[s])){const o=fp.formatDetails(gp(i,e,s),Es(t[s]));n.push(...o)}}),!Ps(t.children)){const s=fp.formatDetails(gp(i,e,"children"),fp.isArrayAndMeetMinLength(t.children));if(s.length)return n.push(...s),n;t.children.forEach((t,s)=>{if(Os(t)||Es(t)||n.push(`${i}.children[${s}] is invalid.`),Es(t)){const o=this.isUiConfigValid(t,gp(i,e,`children[${s}]`));n.push(...o)}})}return n}static isDocOptionsValid(t,e){const i=[],n=e||"CreateDocumentOptions",s=fp.formatDetails(gp(n,e),Es(t));if(s.length)return i.push(...s),i;if(!Ps(t.name)){const s=fp.formatDetails(gp(n,e,"name"),fp.isStringAndNotEmpty(t.name,!1));i.push(...s)}if(!Ps(t.author)){const s=fp.formatDetails(gp(n,e,"author"),fp.isStringAndNotEmpty(t.author,!1));i.push(...s)}if(!Ps(t.creationDate)){const s=fp.formatDetails(gp(n,e,"creationDate"),fp.isPdfDate(t.creationDate));i.push(...s)}if(!Ps(t.deleteOriginal)){const s=fp.formatDetails(gp(n,e,"deleteOriginal"),Rs(t.deleteOriginal));i.push(...s)}return i}static isTransferOptionsValid(t,e,i,n){const s=[],o="TransferOptions",r=fp.formatDetails(gp(o,n),Es(t));if(r.length)return s.push(...r),s;if(!Ps(t.sourceIndices)){const r=this.isNumberArrayValid(t.sourceIndices,e,i,gp(o,n,"sourceIndices"));s.push(...r)}if(!Ps(t.insertBeforeIndex)){const e=fp.formatDetails(gp(o,n,"insertBeforeIndex"),fp.isNumberAndIsInRange(t.insertBeforeIndex,0));s.push(...e)}return s}static isNumberArrayValid(t,e,i,n){return this.isTypeArrayValid("number",t,e,i,n)}static isStringArrayValid(t,e){return this.isTypeArrayValid("string",t,void 0,void 0,e)}static isBlobArrayValid(t,e){return this.isTypeArrayValid("blob",t,void 0,void 0,e)}static isTypeArrayValid(t,e,i,n,s){const o=[],r=fp.formatDetails(gp("Array",s),fp.isArrayAndMeetMinLength(e));return r.length?(o.push(...r),o):(e.forEach((e,r)=>{let a=null;"blob"===t?a=Ds(e):"number"===t?a=fp.isNumberAndIsInRange(e,i,n):"string"===t&&(a=fp.isStringAndNotEmpty(e));const l=fp.formatDetails(gp("Array",s,`[${r}]`,!0),a);o.push(...l)}),o)}static isRotationValid(t,e){const i=[],n=gp("",e,"rotation"),s=fp.formatDetails(n,fp.isNumberAndIsInRange(t));return s.length?(i.push(...s),i):(i.length||t%90==0||i.push(`'${n}' is not supported.`),i)}static isFilterTypeValid(t,e,i){const n=[],s=gp("",i,"filter"),o=fp.formatDetails(s,fp.isStringAndNotEmpty(t,!1));return o.length?(n.push(...o),n):(!n.length&&"none"!==t&&Ts(e)&&e.length>0&&!e.includes(t)&&n.push(`'${s}' is not supported.`),n)}static isSaveJpegSettingsValid(t,e){const i=[],n="SaveJpegSettings",s=fp.formatDetails(gp(n,e),Es(t));if(s.length)return i.push(...s),i;if(!Ps(t.quality)){const s=fp.formatDetails(gp(n,e,"quality"),fp.isNumberAndIsInRange(t.quality,0,100));i.push(...s)}if(!Ps(t.saveAnnotation)){const s=fp.formatDetails(gp(n,e,"saveAnnotation"),Rs(t.saveAnnotation));i.push(...s)}return i}static isSavePngSettingsValid(t,e){const i=[],n="SavePngSettings",s=fp.formatDetails(gp(n,e),Es(t));if(s.length)return i.push(...s),i;if(!Ps(t.saveAnnotation)){const s=fp.formatDetails(gp(n,e,"saveAnnotation"),Rs(t.saveAnnotation));i.push(...s)}return i}static isSavePdfSettingsValid(t,e){const i=[],n="SavePdfSettings",s=fp.formatDetails(gp(n,e),Es(t));if(s.length)return i.push(...s),i;if(["author","creator","keyWords","producer","subject","title"].forEach(s=>{const o=t[s];if(!Ps(o)){const t=fp.formatDetails(gp(n,e,s),fp.isStringAndNotEmpty(o,!1));i.push(...t)}}),!Ps(t.compression)){const s=fp.formatDetails(gp(n,e,"compression"),Mr.has(t.compression));i.push(...s)}if(!Ps(t.creationDate)){const s=fp.formatDetails(gp(n,e,"creationDate"),fp.isPdfDate(t.creationDate));i.push(...s)}if(!Ps(t.modifiedDate)){const s=fp.formatDetails(gp(n,e,"modifiedDate"),fp.isPdfDate(t.modifiedDate));i.push(...s)}if(!Ps(t.pageType)){const s=fp.formatDetails(gp(n,e,"pageType"),kr.has(t.pageType));i.push(...s)}if(!Ps(t.version)){const s=fp.formatDetails(gp(n,e,"version"),this.isPdfVersionValid(t.version));i.push(...s)}if(!Ps(t.mimeType)){const s=fp.formatDetails(gp(n,e,"mimeType"),fp.isStringAndNotEmpty(t.mimeType));i.push(...s)}if(!Ps(t.quality)){const s=fp.formatDetails(gp(n,e,"quality"),fp.isNumberAndIsInRange(t.quality,0,100));i.push(...s)}if(!Ps(t.password)){const s=fp.formatDetails(gp(n,e,"password"),fp.isStringAndNotEmpty(t.password));i.push(...s),!s.length&&t.password.length>32&&i.push("The specified password exceeds 32 characters.")}if(!Ps(t.saveAnnotation)){const s=fp.formatDetails(gp(n,e,"saveAnnotation"),["none","image","annotation","flatten"].includes(t.saveAnnotation));i.push(...s)}if(!Ps(t.imageScaleFactor)){const s=fp.formatDetails(gp(n,e,"imageScaleFactor"),fp.isNumberAndIsInRange(t.imageScaleFactor,Number.MIN_VALUE,1));i.push(...s)}return i}static isPdfVersionValid(t){return!!Os(t)&&["1.1","1.2","1.3","1.4","1.5","1.6","1.7"].includes(t.trim())}static isSaveTiffSettingsValid(t,e){const i=[],n="SaveTiffSettings",s=fp.formatDetails(gp(n,e),Es(t));if(s.length)return i.push(...s),i;if(!Ps(t.compression)){const s=fp.formatDetails(gp(n,e,"compression"),Lr.has(t.compression));i.push(...s)}if(!Ps(t.customTag)){const s=fp.formatDetails(gp(n,e,"customTag"),fp.isArrayAndMeetMinLength(t.customTag));i.push(...s),s.length||t.customTag.forEach((t,s)=>{const o=this.isTiffCustomTagValid(t,gp(n,e,`customTag[${s}]`));i.push(...o)})}if(!Ps(t.quality)){const s=fp.formatDetails(gp(n,e,"quality"),fp.isNumberAndIsInRange(t.quality,0,100));i.push(...s)}return i}static isTiffCustomTagValid(t,e){const i=[],n="CustomTag",s=fp.formatDetails(gp(n,e),Es(t));if(s.length)return i.push(...s),i;if(!Ps(t.content)){const s=fp.formatDetails(gp(n,e,"content"),fp.isStringAndNotEmpty(t.content,!1));i.push(...s)}if(!Ps(t.contentIsBase64)){const s=fp.formatDetails(gp(n,e,"contentIsBase64"),Rs(t.contentIsBase64));i.push(...s)}if(!Ps(t.id)){const s=fp.formatDetails(gp(n,e,"id"),fp.isNumberAndIsInRange(t.id));i.push(...s)}return i}static isVideoDeviceInfo(t,e){const i=[],n=fp.formatDetails(e,Es(t));i.push(...n);const s=fp.formatDetails(gp(e,void 0,"deviceId"),fp.isStringAndNotEmpty(t.deviceId,!1));i.push(...s);const o=fp.formatDetails(gp(e,void 0,"label"),fp.isStringAndNotEmpty(t.label,!1));return i.push(...o),i}static isVideoConfig(t,e){const i=[],n=fp.formatDetails(e,Es(t));if(n.length)return i.push(...n),i;if(!Ps(t.fill)){const n=fp.formatDetails(gp(e,void 0,"fill"),Rs(t.fill));i.push(...n)}if(!Ps(t.resolution)){const n=TI.isNumberArrayValid(t.resolution,0,void 0,gp(e,void 0,"resolution"));i.push(...n)}return i}static isZoomOriginValid(t){const e=[],i=fp.formatDetails("zoomOrigin",Es(t));return i.length?(e.push(...i),e):(["x","y"].forEach(i=>{const n=t[i];Ps(n)?e.push(`ZoomOrigin.${i} is missing.`):["start","center","end"].includes(n)||e.push(`ZoomOrigin.${i} is valid.`)}),e)}static isAnnotationOptionsValid(t,e,i){const n=[],s=["x","y","rotation"],o=["width","height","borderWidth","opacity","miterLimit","fontSize"],r=["borderColor","background","icon","lineCap","lineJoin","textAlign","content","color","fontFamily","fontWeight","fontStyle"],a=["points"],l=["textContents"],h=["startPoint","endPoint"],c=["flags"],d=["stamp"],u=["lineDash"],p=["rects"],g=t=>!!Es(t)&&!!Ls(null==t?void 0:t.x)&&!!Ls(null==t?void 0:t.y),f=function(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Ts(t))return!1;if(e&&t.length<2)return!1;for(let e=0;e<t.length;e++)if(!g(t[e]))return!1;return!0};return Object.keys(t).forEach(m=>{const v=t[m];let y=!0;(s.includes(m)&&!Ls(v)||o.includes(m)&&!xI(v)||r.includes(m)&&!Os(v)||l.includes(m)&&!((t,e)=>{if(!Ts(t))return!1;if("textTypewriter"===e&&0===t.length)return!1;for(let e=0;e<t.length;e++){const i=t[e];if(!Es(i))return!1;if(!aI(i))return!1}return!0})(v,i)||h.includes(m)&&!g(v)||c.includes(m)&&!Es(v)||d.includes(m)&&!rI(v)||u.includes(m)&&!(t=>{if(!Ts(t))return!1;for(let e=0;e<t.length;e++)if(!xI(t[e]))return!1;return!0})(v)||p.includes(m)&&!(t=>{if(!Ts(t))return!1;if(0===t.length)return!1;for(let e=0;e<t.length;e++){const i=t[e];if(!Es(i))return!1;if(!lI(i))return!1}return!0})(v))&&(y=!1),a.includes(m)&&("ink"===i?(t=>{if(!Ts(t))return!1;if(!t.length)return!1;for(let e=0;e<t.length;e++)if(!f(t[e],!1))return!1;return!0})(t[m])||(y=!1):f(t[m])||(y=!1)),y||n.push(`${e}.${m} is invalid`)}),n}static isAnnotationDrawingStyleValid(t,e){const i=["opacity","borderWidth"],n=["borderColor","background","textAlign"],s=["lineEnding","textContent"],o=[];return Object.keys(t).forEach(r=>{if(["rectangle","ellipse","polygon","polyline","line","ink","textBox","textTypewriter","stamp","highlight","underline","strikeout"].includes(r)){const a=t[r];Es(a)?Object.keys(a).forEach(t=>{const l=a[t];let h=!0;(i.includes(t)&&!Ls(l)||n.includes(t)&&!Os(l)||s.includes(t)&&!Es(l))&&(h=!1),"stamp"!==t||rI(l)||(h=!1),"textContent"===t&&h&&(null!=l&&l.content&&!Os(l.content)||null!=l&&l.color&&!Os(l.color)||null!=l&&l.fontFamily&&!Os(l.fontFamily)||null!=l&&l.fontSize&&!Ls(l.fontSize)||null!=l&&l.lineThrough&&!Rs(l.lineThrough)||null!=l&&l.underline&&!Rs(l.underline)||null!=l&&l.fontWeight&&!["normal","bold"].includes(l.fontWeight)||null!=l&&l.fontStyle&&!["normal","italic"].includes(l.fontStyle))&&(h=!1),h||o.push(`${e}[${r}].${t} is invalid`)}):o.push(`${e}[${r}] is invalid`)}}),o}static isSearchTextOptionsValid(t,e){const i=[],n=fp.formatDetails(e,Es(t));return n.length?(i.push(...n),i):(["caseSensitive","wholeWord"].forEach(n=>{if(!Ps(t[n])){const s=fp.formatDetails(gp(e,void 0,n),Rs(t[n]));i.push(...s)}}),i)}}var EI=new WeakMap,_I=new WeakMap,PI=new WeakMap;class AI{constructor(t,e){rn(this,PI,{get:II,set:void 0}),rn(this,EI,{writable:!0,value:void 0}),rn(this,_I,{writable:!0,value:void 0}),Xi(this,EI,t),Xi(this,_I,e)}get name(){return $i(this,_I).name}get uid(){return $i(this,_I).uid}get pages(){return $i(this,_I).pages.slice()}get creationDate(){return $i(this,_I).creationDate}get author(){return $i(this,_I).author}async loadSource(t,e){const i="IDocument.loadSource",n="sources";lg.makeSureLoadLicenseExist(),E_(t,0,i,n),function(t,e,i,n,s){let o=[];if(Ts(t)){for(let i=0;i<t.length;i++)if(!Ds(t[i]))if(Es(t[i])){const n=TI.isSourceValid(t[i],gp("Source",void 0,`[${i}]`,!0),e);n.length&&o.push(...n)}else{const t=fp.formatDetails(gp("Source",s,`[${i}]`,!0),!1);o.push(...t)}}else Ds(t)||(o=TI.isSourceValid(t,void 0,e));!o.length||fp.output(0,n,s,o)}(t,$i(this,EI).filterService.getSupportedFilters().map(t=>t.type),0,i,n),Es(e)?function(t,e,i){const n=TI.isLoadSourceOptionsValid(t,void 0);!n.length||fp.output(0,i,"loadSourceOptions",n)}(e,0,i):Ps(e)||sP(e,0,i,"index",0),Ts(t)||(t=[t]),t=t.map(t=>Ds(t)?{fileData:t}:(t.extraPageData=[],t));const s=pp.buildInfo("loadSource",{docUid:this.uid,current:0,total:t.length});return pp.info(s),$i(this,EI).loadSource(t,this.uid,e,s).catch(t=>(s.status="Failed",pp.info(s),pp.reject(t,i)))}getPageData(t){const e="IDocument.getPageData",i="pageUid";return E_(t,0,e,i),tP(t,0,e,i,!1),this.pages.includes(t)||fp.error(e,i,void 0,pp.PAGE_NOT_EXIST),$i(this,EI).getPageData(t)}async updatePage(t,e){const i="IDocument.updatePage",n="pageUid";return lg.makeSureLoadLicenseExist(),E_(t,0,i,n),E_(e,0,i,"data"),tP(t,0,i,n,!1),K_(this.pages,t,0,i),function(t,e,i,n){const s=TI.isUpdatedSourceValid(t,gp("UpdatedSource",void 0),e);!s.length||fp.output(0,n,"source",s)}(e,$i(this,EI).filterService.getSupportedFilters().map(t=>t.type),0,i),e.rotation=void 0,e.perspectiveQuad=void 0,e.filer=void 0,$i(this,EI).updatePage(t,e).catch(t=>-80101===t.code?pp.reject(t,i,"fileData"):pp.reject(t,i,"source"))}deletePages(t){const e="IDocument.deletePages",i="indices";if(E_(t,1,e,i)||!eP(t,1,e,i,0,$i(this,PI)-1))return!1;const n=t.map(t=>$i(this,_I).pages[t]);return $i(this,EI).deletePages(this.uid,n)}deleteAllPages(){return $i(this,_I).pages.slice(),$i(this,EI).deleteAllPages(this.uid)}movePages(t,e){const i="IDocument.movePages",n="indices";E_(t,0,i,n),eP(t,0,i,n,0,$i(this,PI)-1),Ps(e)||sP(e,0,i,"insertBeforeIndex",0),e=e>$i(this,PI)-1?void 0:e,$i(this,EI).movePages(this.uid,t,e)}switchPage(t,e){const i="IDocument.switchPage",n="oneIndex",s="anotherIndex";E_(t,0,i,n),E_(e,0,i,s),sP(t,0,i,n,0,$i(this,PI)-1),sP(e,0,i,s,0,$i(this,PI)-1),$i(this,EI).documentService.swapPages(this.uid,t,e)}rename(t){const e="IDocument.rename",i="name";return!E_(t,1,e,i)&&!!tP(t,1,e,i)&&$i(this,EI).documentService.renameDocument(this.uid,t)}setPageCustomData(t,e){const i="IDocument.setPageCustomData",n="pageUid";return E_(t,0,i,n),E_(e,0,i,"data"),tP(t,0,i,n,!1),K_(this.pages,t,0,i),$i(this,EI).setCustomData(t,e)}getPageCustomData(t){const e="IDocument.getPageCustomData",i="pageUid";return E_(t,0,e,i),tP(t,0,e,i,!1),K_(this.pages,t,0,e),$i(this,EI).getCustomData(t)}async saveToJpeg(t,e){const i="IDocument.saveToJpeg",n="index";E_(t,0,i,n),sP(t,0,i,n,0,$i(this,PI)-1),Ps(e)||function(t,e,i){const n=TI.isSaveJpegSettingsValid(t);!n.length||fp.output(0,i,"saveJpegSettings",n)}(e,0,i);const s=this.pages[t],o=pp.buildInfo("save",{docUid:this.uid,pageUids:[s],current:0,total:1});return pp.info(o),$i(this,EI).fileSaveService.saveToJpeg(s,e,o).catch(t=>{o.status="Failed",pp.info(o),pp.reject(t,i)})}saveToPng(t,e){const i="IDocument.saveToPng",n="index";E_(t,0,i,n),sP(t,0,i,n,0,$i(this,PI)-1),Ps(e)||function(t,e,i){const n=TI.isSavePngSettingsValid(t);n.length&&fp.output(0,i,"savePngSettings",n)}(e,0,i);const s=this.pages[t],o=pp.buildInfo("save",{docUid:this.uid,pageUids:[s],current:0,total:1});return pp.info(o),$i(this,EI).fileSaveService.saveToPng(s,e,o).catch(t=>(o.status="Failed",pp.info(o),pp.reject(t,i)))}saveToPdf(t,e){const i="IDocument.saveToPdf";0===this.pages.length&&pp.throw(pp.DOC_NO_IMAGE),Ts(t)?eP(t,0,i,"indices",0,$i(this,PI)-1):(e=t,t=Array.from(Array(this.pages.length).keys())),Ps(e)||function(t,e,i){const n=TI.isSavePdfSettingsValid(t);!n.length||fp.output(0,i,"savePdfSettings",n)}(e,0,i);const n=[];t.forEach(t=>{n.push(this.pages[t])});try{!e||"annotation"!==e.saveAnnotation&&"flatten"!==e.saveAnnotation||lg.makeSureAnnotationLicenseExist()}catch(t){return Promise.reject(t)}const s=pp.buildInfo("save",{docUid:this.uid,pageUids:n,current:0,total:n.length});return pp.info(s),$i(this,EI).fileSaveService.saveToPdf(n,e,s).catch(t=>(s.status="Failed",pp.info(s),pp.reject(t,i)))}saveToTiff(t,e){const i="IDocument.saveToTiff";0===this.pages.length&&pp.throw(pp.DOC_NO_IMAGE),Ts(t)?eP(t,0,i,"indices",0,$i(this,PI)-1):(e=t,t=Array.from(Array(this.pages.length).keys())),Ps(e)||function(t,e,i){const n=TI.isSaveTiffSettingsValid(t);!n.length||fp.output(0,i,"saveTiffSettings",n)}(e,0,i);const n=[];t.forEach(t=>{n.push(this.pages[t])});const s=pp.buildInfo("save",{docUid:this.uid,pageUids:n,current:0,total:n.length});return pp.info(s),$i(this,EI).fileSaveService.saveToTiff(n,e,s).catch(t=>(s.status="Failed",pp.info(s),pp.reject(t,i)))}print(t,e){const i="IDocument.print";let n,s=e;var o;Ts(t)?(eP(t,0,i,"indices",0,$i(this,PI)-1),n=t):s=t,Ps(s)||Ps(null===(o=s)||void 0===o?void 0:o.printAnnotation)||Rs(s.printAnnotation)||fp.error(i,"setting.printAnnotation",void 0,pp.PARAM_INVALID),0===this.pages.length&&pp.throw(pp.DOC_NO_IMAGE),$i(this,EI).printPages(this.uid,n,s)}insertBlankPage(t,e,i){const n="IDocument.insertBlankPage",s="pageWidth",o="pageHeight";return lg.makeSureLoadLicenseExist(),E_(t,0,n,s),E_(e,0,n,o),sP(t,0,n,s,.72,7200),sP(e,0,n,o,.72,7200),Ps(i)||sP(i,0,n,"insertBeforeIndex",0),$i(this,EI).insertBlankPage(this.uid,Math.floor(Bo(t,Cr.dataResolution,72))||1,Math.floor(Bo(e,Cr.dataResolution,72))||1,72,72,i)}isPageModified(t){const e="IDocument.isPageModified",i="index";E_(t,0,e,i),sP(t,0,e,i,0,$i(this,PI)-1);const n=this.pages[t];return $i(this,EI).isPageModified(n)}createTextSearcher(t,e){const i="IDocument.createTextSearcher";if(E_(t,0,i,"text"),tP(t,0,i,"text"),!Ps(e)){const t=TI.isSearchTextOptionsValid(e,"options");if(t.length){const e=pp.PARAM_INVALID;e.details=t,pp.error(e,i,"options")}}return""===t&&pp.error(pp.PARAM_INVALID,i,"text"),$i(this,EI).createTextSearcher(this.uid,t,e)}}function II(){return $i(this,_I).pages.length}function DI(t,e,i,n,s){if(!Ps(t)){const o="transferOptions",r=TI.isTransferOptionsValid(t,e,i,o);if(r.length)return fp.output(n,s,o,r)}return!0}function RI(t,e,i,n){if(!Ps(t)){const s=TI.isDocOptionsValid(t);if(s.length)return fp.output(e,i,n,s)}return!0}function kI(t,e,i,n,s){const o=e.reduce((e,i,n)=>(t.has(i)||e.push(`${s}[${n}]:The specified document(s) do not exist.`),e),[]);return!o.length||fp.output(i,n,s,o,pp.DOC_NOT_EXIST,!0)}const MI=["documentCreated","documentDeleted","pagesAdded","pagesDeleted"];var LI=new WeakMap,OI=new WeakMap,BI=new WeakMap;const NI=new class extends Wo{constructor(){super(),rn(this,LI,{writable:!0,value:void 0}),rn(this,OI,{writable:!0,value:void 0}),rn(this,BI,{writable:!0,value:void 0}),Xi(this,BI,new Ws),Xi(this,LI,T_),Xi(this,OI,new Map),T_.onAfterUnload.on(()=>{$i(this,OI).clear(),$i(this,BI).removeAllEventListeners()},this);const{documentService:t}=T_;t.onDocumentCreated.on(t=>{const e=$i(this,LI).getDocument(t.docUid),i=new AI($i(this,LI),e);$i(this,OI).set(i.uid,i),$i(this,BI).emit("documentCreated",t)},this),t.onDocumentDeleted.on(t=>{$i(this,OI).has(t.docUid)&&$i(this,OI).delete(t.docUid),$i(this,BI).emit("documentDeleted",t)},this),t.onPagesAddedOut.on(t=>{t.indices.length&&t.pageUids.length&&$i(this,BI).emit("pagesAdded",t)},this),t.onDeletePagesFromDoc.on(t=>{$i(this,BI).emit("pagesDeleted",t)},this),t.onDeleteAllPagesFromDoc.on(t=>{$i(this,BI).emit("pagesDeleted",t)},this)}createDocument(t){RI(t,0,"DocumentManager.createDocument","createDocumentOptions");const e=$i(this,LI).createDocument(t);return $i(this,OI).get(e.uid)}getDocument(t){const e="DocumentManager.getDocument",i="docUid";if(E_(t,1,e,i)||!tP(t,1,e,i))return null;return $i(this,OI).get(t)||(fp.warning(e,i,void 0,pp.DOC_NOT_EXIST),null)}getAllDocuments(){return Array.from($i(this,OI).values())}deleteDocuments(t){const e="DocumentManager.deleteDocuments",i="docUids";return!(E_(t,1,e,i)||!eA(t,1,e,i,void 0,!1)||!kI($i(this,OI),t,1,e,i))&&$i(this,LI).deleteDocuments([...new Set(t)])}deleteAllDocuments(){const t=$i(this,LI).documentService.getAllDocuments();return $i(this,LI).deleteDocuments(t.map(t=>t.uid))}copyPagesToDocument(t,e,i){const n="DocumentManager.copyPagesToDocument",s="sourceDocUid",o="targetDocUid";E_(t,0,n,s),E_(e,0,n,o),tP(t,0,n,s),tP(e,0,n,o);const r=$i(this,OI).get(t),a=$i(this,OI).get(e);return r&&a||pp.throw(pp.DOC_NOT_EXIST,n),DI(i,0,r.pages.length-1,0,n),$i(this,LI).transferDocument(t,e,{...i,copy:!0})}movePagesToDocument(t,e,i){const n="DocumentManager.movePagesToDocument",s="sourceDocUid",o="targetDocUid";E_(t,0,n,s),E_(e,0,n,o),tP(t,0,n,s),tP(e,0,n,o);const r=$i(this,OI).get(t),a=$i(this,OI).get(e);return r&&a||pp.throw(pp.DOC_NOT_EXIST,n),DI(i,0,r.pages.length-1,0,n),$i(this,LI).transferDocument(t,e,i)}mergeDocuments(t,e){const i="DocumentManager.mergeDocuments",n="docUids";E_(t,0,i,n),eA(t,0,i,n,void 0,!1),function(t){return new Set(t).size!==t.length}(t)&&fp.error(void 0,void 0,void 0,pp.DOC_UID_DUPLICATE),kI($i(this,OI),t,0,i,n),RI(e,0,i,"mergeDocumentOptions");const s=$i(this,LI).mergeDocuments(t,e);return $i(this,OI).get(s.uid)}on(t,e){const i="DocumentManager.on";!E_(t,1,i,"eventName")&&!E_(e,1,i,"listener")&&tP(t,1,i,"eventName",!1)&&Q_(e,i,"listener",1)&&(MI.includes(t)?$i(this,BI).on(t,e):pp.warning(pp.PARAM_NOT_SUPPORT,i,"eventName"))}off(t,e){const i="DocumentManager.off";!E_(t,1,i,"eventName")&&tP(t,1,i,"eventName",!1)&&(Ps(e)||Q_(e,i,"listener",1))&&(MI.includes(t)?$i(this,BI).off(t,e):pp.warning(pp.PARAM_NOT_SUPPORT,i,"eventName"))}},{currentScript:UI}=document;let FI="";function VI(){let t,e;var i;if(""===FI&&(M&&M.engineResourcePaths?(t=M.engineResourcePaths.ddv,e=M.engineResourcePaths.rootDirectory):null!==(i=window)&&void 0!==i&&null!==(i=i.Dynamsoft)&&void 0!==i&&null!==(i=i.Core)&&void 0!==i&&null!==(i=i.CoreModule)&&void 0!==i&&null!==(i=i.engineResourcePaths)&&void 0!==i&&i.ddv&&(t=window.Dynamsoft.Core.CoreModule.engineResourcePaths.ddv,window.Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory&&(e=window.Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory)),t))if(Os(t)&&(FI=t),Os(FI)){if(FI.startsWith("https://")||FI.startsWith("http://"));else if(FI.startsWith("@engineRootDirectory/")){let t=e;e&&Os(e)&&e.length>0?"/"===t.charAt(t.length-1)&&(t=t.substring(0,t.length-1)):t="",FI=FI.replace("@engineRootDirectory",t)}else if("@engineRootDirectory"===FI&&(FI=""),e&&Os(e)&&e.length>0){let t="";"/"!==e.charAt(e.length-1)&&(t="/"),FI=[e,t,FI].join("")}}else FI="";return FI}var WI=new WeakMap,HI=new WeakMap,jI=new WeakMap;const zI=new class{constructor(){rn(this,WI,{writable:!0,value:""}),rn(this,HI,{writable:!0,value:""}),rn(this,jI,{writable:!0,value:""})}get versionInfo(){return{viewer:mg,engine:$o.version}}set engineResourcePath(t){Os(t)?Xi(this,jI,t):pp.throw(pp.PARAM_INVALID,"Core.engineResourcePath","engineResourcePath")}get engineResourcePath(){const t=VI();return""!==t?(Xi(this,jI,t),t):(""===$i(this,jI)&&Xi(this,jI,`${(()=>{if(!Jn&&UI){let{src:t}=UI;const e=t.indexOf("?");if(-1!==e)t=t.substring(0,e);else{const e=t.indexOf("#");-1!==e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})()}engine`),$i(this,jI))}set license(t){!function(t){const e=fp.formatError({isValid:TI.isLicenseValid(t)});!e||fp.output(0,"Core.license","license",void 0,e)}(t),Xi(this,HI,t)}get license(){return $i(this,HI)}set deviceFriendlyName(t){Os(t)?Xi(this,WI,t):pp.throw(pp.PARAM_INVALID,"Core.deviceFriendlyName","deviceFriendlyName")}get deviceFriendlyName(){return $i(this,WI)}loadWasm(){return async function(t){let e=t.trim();e.endsWith("/")||(e=`${e}/`);const i=pp.buildInfo("loadWasm",{});if(pp.info(i),$o.resourceDir=e,!await $o.isResourceDirValid())return i.status="Failed",pp.info(i),pp.reject(pp.RESOURCE_NOT_FOUND,"DDV.Core.loadWasm");const n=$o.preloadModule("proc"),s=$o.preloadModule("pdf");await Promise.all([n,s]),i.status="Completed",pp.info(i)}(this.engineResourcePath)}init(){return async function(t){const e=pp.buildInfo("init",{});pp.info(e);let i=t.engineResourcePath.trim();if(i.endsWith("/")||(i=`${i}/`),$o.resourceDir=i,lg.init(),!await $o.isResourceDirValid())return lg.reset(),e.status="Failed",pp.info(e),pp.reject(pp.RESOURCE_NOT_FOUND,"DDV.Core.init");if(!await $o.isResourceVersionMatch())return lg.reset(),e.status="Failed",pp.info(e),pp.reject(pp.RESOURCE_NOT_MATCHED,"DDV.Core.init");let n=function(){var t;let e=null;var i;if(I&&I.license)e=null===(i=I.license.LicenseManager)||void 0===i?void 0:i.license;else if(null!==(t=window)&&void 0!==t&&null!==(t=t.Dynamsoft)&&void 0!==t&&null!==(t=t.Core)&&void 0!==t&&null!==(t=t.mapPackageRegister)&&void 0!==t&&t.license){var n;e=null===(n=window.Dynamsoft.Core.mapPackageRegister.license.LicenseManager)||void 0===n?void 0:n.license}return null!==e?""===e?"":(Os(e)&&(e=e.trim()),e):null}();null!==n&&""!==n||(n=t.license.trim());let s,o,r=n.startsWith("DLS")||0===n.length,a=!1,l=!1;if(r)try{var h;let e;if(null!=I&&I.license?e=await I.license.getAR():null!==(h=window)&&void 0!==h&&null!==(h=h.Dynamsoft)&&void 0!==h&&null!==(h=h.Core)&&void 0!==h&&null!==(h=h.mapPackageRegister)&&void 0!==h&&h.license&&(e=await window.Dynamsoft.Core.mapPackageRegister.license.getAR()),e)s=e.ar,o=e.u,a=e.pt,e.pk?(s=e.pk,r=!1):l=!0,Ps(s)&&e.ae&&pp.throw(fg(e.ae));else{const e=await async function(t,e,i){const n=new Mg(t);return await n.init(e,i,void 0),{authResult:n.getAuthResult(),clientUUID:n.getClientUUID(),bPublicTrial:n.isPublicTrial()}}(n,i,t.deviceFriendlyName||"");s=e.authResult,o=e.clientUUID,a=e.bPublicTrial}}catch(t){throw lg.setLicenseErr(t),e.status="Failed",pp.info(e),t}else s=n,o="";const c={licenseInfo:null};try{const t=await $o.getLicenseInfo(s,r,o);c.licenseInfo=t,lg.setLicenseInfo(t),!l&&a&&t.trial&&t.msg&&Cp({_bNeverShowDialog:!1,engineResourcePath:i,_onLog:console.log},"warn",t.msg)}catch(t){throw t&&t.code<=-8e4&&lg.setLicenseErr(t),e.status="Failed",pp.info(e),t}return r&&(c.deviceUuid=o),e.status="Completed",pp.info(e),c}({license:$i(this,HI),engineResourcePath:this.engineResourcePath,deviceFriendlyName:$i(this,WI)})}};var GI;!function(t){t.NONE="none",t.BLACK_AND_WHITE="blackAndWhite",t.GRAY="gray",t.REMOVE_SHADOW="removeShadow",t.SAVE_INK="saveInk",t.ENHANCE="enhance",t.INVERT="invert"}(GI||(GI={}));const YI=[],$I={documentManager:NI,Core:zI,Elements:P_,DocumentDetect:Ju,ImageFilter:class{constructor(){an(this,cp),an(this,hp)}get defaultFilterType(){return Vu.NONE}async applyFilter(t,e,i,n){const s=new lr,o=sn(this,hp,dp).call(this,e,i),r=sn(this,cp,up).call(this,{outputType:xr[t.type],...n||{}});let a;try{const i=await s.initImage({source:t.data,isRGBA:t.type===tr.RGBA,width:t.width,height:t.height,isBGRA:t.type===tr.BGRA});let n;i.srcBuffer&&(t.data=i.srcBuffer),e===Vu.NONE?(n=await s.getImage({jpegQuality:r.jpegQuality,ifDeleteObject:!0,isRGBA:t.type===tr.RGBA,bitDepth:r.bitDepth,xDpi:r.xdpi,yDpi:r.ydpi,outputType:r.outputType,returnType:ir.RT_BINARY}),s.freeReservedData()):n=await s.filter(ap.get(e),o,r),a=new Blob([n.imageData],{type:n.blobType})}finally{s.terminate()}return a}querySupported(){return[{type:Vu.NONE,label:"Original"},{type:Vu.BLACK_AND_WHITE,label:"B&W"},{type:Vu.GRAY,label:"Grayscale"},{type:Vu.SAVE_INK,label:"Save Toner"}]}destroy(){}},BrowseViewer:ZA,CaptureViewer:dP,CustomViewer:eI,EditViewer:OA,PerspectiveViewer:XA,get lastError(){return pp.getLastError()},clearLastError(){pp.lastError=void 0},Experiments:{get(t,e){switch(t){case"WasmEnv":return $o;case"ImageProcess":return new yp;case"FileParser.Options":return T_.getFileParserDefaultOptions(e);case"InnerViewer":return T_.getViewer(e);case"PageSourceInfo":return T_.getPageSourceInfo(e);case"AnnotationInkSignatureBoard":return Vx;case"AnnotationCustomStampBoard":return Kx;default:return}},set(t,e){switch(t){case"FileParser.Options":return T_.setFileParserDefaultOptions(e.type,e.options);case"ClearExternalHandler":return T_.clearExternalHandler(e.type);default:return}}},async addFonts(t){const e="DDV.addFonts";if(E_(t,0,e,"fonts"))return[];const i=function(t,e,i,n){const s=fp.formatError({isValid:Ts(t)});if(s)return fp.output(0,i,n,void 0,s);const o=[];return t.forEach((t,e)=>{const i=fp.formatDetails(gp("Array","font",`[${e}]`,!0),Ds(t));o.push(...i)}),!!o.length&&fp.output(0,i,n,o)}(t,0,e,"fonts");if(i)return[];const n=[];try{for(let i=0;i<t.length;i++){const s=t[i],o=new ur,r=await o.getFontInfo(s).catch(t=>{throw o.terminate(),t});o.terminate();for(let t=0;t<r.fontInfo.length;t++){const i=r.fontInfo[t];if(n.includes(i.family)||n.push(i.family),!YI.includes(i.family)){let t=i.family;try{const e=new FontFace(t,r.srcBuffer,{style:"normal",weight:"normal",display:"swap"}),i=await e.load();document.fonts.add(i)}catch(e){t=`"${t}"`;const i=new FontFace(t,r.srcBuffer,{style:"normal",weight:"normal",display:"swap"}),n=await i.load();document.fonts.add(n)}YI.push(i.family);const n=`${t}${i.isBold?"Bold":""}${i.isItalic?"Italic":""}`;dr.addPdfFont(n,r.srcBuffer),T_.getViewers().forEach(e=>{e.addFontToUi(t),e.context.render()})}}}}catch(t){return pp.reject(pp.PARAM_INVALID,e,"fonts")}return Promise.resolve(n)},getDefaultUiConfig(t){const e="DDV.getDefaultUiConfig",i="viewerType";if(E_(t,1,i,e)||!tP(t,1,e,i)||!function(t,e,i){return!!["editViewer","perspectiveViewer","captureViewer","browseViewer"].includes(t)||fp.output(1,e,i,void 0,pp.PARAM_NOT_SUPPORT)}(t,e,i))return null;let n=null;return n=Ms()?{editViewer:I_,perspectiveViewer:D_,captureViewer:A_,browseViewer:L_}[t]:{editViewer:M_,perspectiveViewer:k_,captureViewer:R_,browseViewer:L_}[t],_s(n)},setProcessingHandler(t,e){const i="DDV.setProcessingHandler",n="type",s="handler";switch(E_(t,0,i,n),E_(e,0,i,s),function(t,e,i,n){const s=fp.formatError(TI.isHandlerTypeValid(t));s&&fp.output(0,i,n,void 0,s)}(t,0,i,n),t){case"documentBoundariesDetect":("function"!=typeof(o=e).detect||"function"!=typeof o.destroy)&&fp.error(i,s);break;case"imageFilter":(function(t){return"function"==typeof t.querySupported&&"defaultFilterType"in t&&"function"==typeof t.applyFilter&&"function"==typeof t.destroy})(e)||fp.error(i,s)}var o;try{switch(t){case"documentBoundariesDetect":T_.setDetectHandler(t,e);break;case"imageFilter":T_.setImageFilterHandler(e)}}catch(t){pp.throw(t,i)}},setFileParser(t,e){T_.setFileParser(t,e)},unload(){this.Core.deviceFriendlyName="",this.Core.engineResourcePath=VI(),this.Core.license="",T_.unload(),fA.clear(),this.off("error"),this.off("warning"),this.off("verbose"),this.off("info")},on(t,e){const i="DDV.on";if(E_(t,1,i,"eventName")||E_(e,1,i,"listener")||!tP(t,1,i,"eventName",!1)||!Q_(e,i,"listener",1))return;const n={error:"error",warning:"warning",verbose:"verbose",info:"info"}[t];n?pp.on(n,e):pp.throw(pp.PARAM_NOT_SUPPORT,i,"eventName")},off(t,e){const i="DDV.off";if(E_(t,1,i,"eventName")||!tP(t,1,i,"eventName",!1))return;if(!Ps(e)&&!Q_(e,i,"listener",1))return;const n={error:"error",warning:"warning",verbose:"verbose",info:"info"}[t];n?pp.off(n,e):pp.throw(pp.PARAM_NOT_SUPPORT,i,"eventName")},EnumImageDataType:tr,EnumConvertMode:hu,EnumDocumentDetectionStatus:Fu,EnumImageFilterType:GI,EnumPDFCompressionType:Ir,EnumPDFPageType:Dr,EnumTIFFCompressionType:Ar,EnumStampIcon:B_,EnumLineEnding:N_,EnumAnnotationRenderMode:cu,annotationManager:SA};window.Dynamsoft||(window.Dynamsoft={}),window.Dynamsoft.DDV=$I;var XI=Object.freeze({__proto__:null,BrowseViewer:ZA,CaptureViewer:dP,CustomViewer:eI,DDV:$I,EditViewer:OA,get EnumAnnotationRenderMode(){return cu},get EnumConvertMode(){return hu},get EnumDocumentDetectionStatus(){return Fu},get EnumImageDataType(){return tr},get EnumImageFilterType(){return GI},get EnumPDFCompressionType(){return Ir},get EnumPDFPageType(){return Dr},get EnumTIFFCompressionType(){return Ar},PerspectiveViewer:XA});const qI=t=>t&&"object"==typeof t&&"function"==typeof t.then,ZI=(async()=>{})().constructor;let JI=class extends ZI{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,qI(t)?e=t:"function"==typeof t&&(e=new ZI(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,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(qI(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function KI(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function QI(t,e,i,n,s){if("function"==typeof e||!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}var tD,eD,iD;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(tD||(tD={})),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"}(eD||(eD={})),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"}(iD||(iD={}));const nD="undefined"==typeof self,sD="function"==typeof importScripts,oD=(()=>{if(!sD){if(!nD&&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"./"}})(),rD=t=>{if(null==t&&(t="./"),nD||sD);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},aD=t=>Object.prototype.toString.call(t),lD=t=>Array.isArray?Array.isArray(t):"[object Array]"===aD(t),hD=t=>"number"==typeof t&&!Number.isNaN(t),cD=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),dD=t=>!!(t=>!(!cD(t)||!hD(t.width)||t.width<=0||!hD(t.height)||t.height<=0||!hD(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!pD(t.tag)))(t)&&t.bytes instanceof Uint8Array,uD=t=>!(!cD(t)||!hD(t.left)||t.left<0||!hD(t.top)||t.top<0||!hD(t.right)||t.right<0||!hD(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),pD=t=>null===t||!!cD(t)&&!!hD(t.imageId)&&"type"in t,gD=t=>!!cD(t)&&!!hD(t.x)&&!!hD(t.y),fD=t=>!!cD(t)&&!!lD(t.points)&&0!=t.points.length&&!t.points.some(t=>!gD(t)),mD=t=>!!cD(t)&&!!lD(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!gD(t)),vD=t=>!(!cD(t)||!hD(t.x)||!hD(t.y)||!hD(t.width)||t.width<0||!hD(t.height)||t.height<0),yD=async(t,e,i)=>await new Promise((i,n)=>{let s=new XMLHttpRequest;s.responseType=e,s.onloadstart=()=>{},s.onloadend=async()=>{s.status<200||s.status>=300?n(new Error(t+" "+s.status)):i(s.response)},s.onprogress=t=>{},s.onerror=()=>{n(new Error("Network Error: "+s.statusText))},s.open("GET",t,!0),s.send()}),xD=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t<i.length&&t<n.length;++t){let e=i[t],s=n[t];if(e===s)continue;let o=parseInt(i[t]),r=parseInt(n[t]);return o===r||Number.isNaN(o)&&Number.isNaN(r)?e<s?-1:1:o<r||Number.isNaN(o)&&Number.isInteger(r)?-1:1}return i.length===n.length?0:i.length<n.length?-1:1},wD=t=>{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,s=t[n],o=s&&"object"==typeof s&&s.path?s.path:s,r=t.rootDirectory;if(r&&!r.endsWith("/")&&(r+="/"),"object"==typeof s&&s.isInternal)r&&(o=t[n].version?`${r}${ED[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${r}${ED[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof o&&(o=o.replace(i,r||"")),"object"==typeof o&&"dwt"===n){const s=t[n].resourcesPath,o=t[n].serviceInstallerLocation;e[n]={resourcesPath:s.replace(i,r||""),serviceInstallerLocation:o.replace(i,r||"")};continue}}e[n]=rD(o)}return e},CD=t=>{dD(t)&&(t=TD(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},bD=(t,e)=>{dD(e)&&(e=TD(e));const i=CD(e);let n=new Image,s=i.toDataURL(t);return n.src=s,n},SD=async(t,e)=>{dD(e)&&(e=TD(e));const i=CD(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},TD=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===iD.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;++n)e[4*n]=i[3*n],e[4*n+1]=i[3*n+1],e[4*n+2]=i[3*n+2],e[4*n+3]=255}else if(Number(t.format)===iD.IPF_RGB_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;++n)e[4*n]=i[3*n+2],e[4*n+1]=i[3*n+1],e[4*n+2]=i[3*n],e[4*n+3]=255}else if(Number(t.format)===iD.IPF_GRAYSCALED){const t=i.length;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;n++)e[4*n]=e[4*n+1]=e[4*n+2]=i[n],e[4*n+3]=255}else if(Number(t.format)===iD.IPF_BINARY_8){const n=i.length,s=t.width,o=t.height,r=t.stride;e=new Uint8ClampedArray(s*o*4);for(let t=0;t<n;t++){let n=i[t],o=t%r,a=Math.floor(t/r);for(let t=0;t<8;t++){let i=o+t,r=4*(a*s+i);if(i>=s)break;e[r]=e[r+1]=e[r+2]=(128&n)/128*255,e[r+3]=255,n<<=1}}}else if(Number(t.format)===iD.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n<t;++n)e[4*n]=i[4*n],e[4*n+1]=i[4*n+1],e[4*n+2]=i[4*n+2],e[4*n+3]=i[4*n+3]}else if(Number(t.format)===iD.IPF_ARGB_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n<t;++n)e[4*n]=i[4*n+2],e[4*n+1]=i[4*n+1],e[4*n+2]=i[4*n],e[4*n+3]=i[4*n+3]}else if(Number(t.format)===iD.IPF_BINARY_8_INVERTED){const n=i.length,s=t.width,o=t.height,r=t.stride;e=new Uint8ClampedArray(s*o*4);for(let t=0;t<n;t++){let n=i[t],o=t%r,a=Math.floor(t/r);for(let t=0;t<8;t++){let i=o+t,r=4*(a*s+i);if(i>=s)break;e[r]=e[r+1]=e[r+2]=128&n?0:255,e[r+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},ED={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",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var _D,PD,AD,ID,DD,RD,kD,MD;let LD,OD,BD,ND,UD,FD=class t{get _isFetchingStarted(){return KI(this,DD,"f")}constructor(){_D.add(this),PD.set(this,[]),AD.set(this,1),ID.set(this,tD.BOPM_BLOCK),DD.set(this,!1),RD.set(this,void 0),kD.set(this,eD.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!dD(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(KI(this,PD,"f").length>=KI(this,AD,"f"))switch(KI(this,ID,"f")){case tD.BOPM_BLOCK:break;case tD.BOPM_UPDATE:if(KI(this,PD,"f").push(t),cD(KI(this,RD,"f"))&&hD(KI(this,RD,"f").imageId)&&1==KI(this,RD,"f").keepInBuffer)for(;KI(this,PD,"f").length>KI(this,AD,"f");){const t=KI(this,PD,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==KI(this,RD,"f").imageId});KI(this,PD,"f").splice(t,1)}else KI(this,PD,"f").splice(0,KI(this,PD,"f").length-KI(this,AD,"f"))}else KI(this,PD,"f").push(t)}getImage(){if(0===KI(this,PD,"f").length)return null;let e;if(KI(this,RD,"f")&&hD(KI(this,RD,"f").imageId)){const t=KI(this,_D,"m",MD).call(this,KI(this,RD,"f").imageId);if(t<0)throw new Error(`Image with id ${KI(this,RD,"f").imageId} doesn't exist.`);e=KI(this,PD,"f").slice(t,t+1)[0]}else e=KI(this,PD,"f").pop();if([iD.IPF_RGB_565,iD.IPF_RGB_555,iD.IPF_RGB_888,iD.IPF_ARGB_8888,iD.IPF_RGB_161616,iD.IPF_ARGB_16161616,iD.IPF_ABGR_8888,iD.IPF_ABGR_16161616,iD.IPF_BGR_888].includes(e.format)){if(KI(this,kD,"f")===eD.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t<i.length;t++)switch(e.format){case iD.IPF_RGB_565:case iD.IPF_RGB_555:case iD.IPF_RGB_888:case iD.IPF_RGB_161616:i[t]=e.bytes[3*t+2];break;case iD.IPF_ARGB_8888:case iD.IPF_ARGB_16161616:i[t]=e.bytes[4*t+2];break;case iD.IPF_BGR_888:i[t]=e.bytes[3*t];break;case iD.IPF_ABGR_8888:case iD.IPF_ABGR_16161616:i[t]=e.bytes[4*t]}e.bytes=i,e.stride=e.width,e.format=iD.IPF_GRAYSCALED}else if(KI(this,kD,"f")===eD.CCUT_RGB_G_CHANNEL_ONLY){t._onLog&&t._onLog("only get G channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t<i.length;t++)switch(e.format){case iD.IPF_RGB_565:case iD.IPF_RGB_555:case iD.IPF_RGB_888:case iD.IPF_RGB_161616:case iD.IPF_BGR_888:i[t]=e.bytes[3*t+1];break;case iD.IPF_ARGB_8888:case iD.IPF_ARGB_16161616:case iD.IPF_ABGR_8888:case iD.IPF_ABGR_16161616:i[t]=e.bytes[4*t+1]}e.bytes=i,e.stride=e.width,e.format=iD.IPF_GRAYSCALED}else if(KI(this,kD,"f")===eD.CCUT_RGB_B_CHANNEL_ONLY){t._onLog&&t._onLog("only get B channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t<i.length;t++)switch(e.format){case iD.IPF_RGB_565:case iD.IPF_RGB_555:case iD.IPF_RGB_888:case iD.IPF_RGB_161616:i[t]=e.bytes[3*t];break;case iD.IPF_ARGB_8888:case iD.IPF_ARGB_16161616:i[t]=e.bytes[4*t];break;case iD.IPF_BGR_888:i[t]=e.bytes[3*t+2];break;case iD.IPF_ABGR_8888:case iD.IPF_ABGR_16161616:i[t]=e.bytes[4*t+2]}e.bytes=i,e.stride=e.width,e.format=iD.IPF_GRAYSCALED}}else[iD.IPF_NV21,iD.IPF_NV12].includes(e.format)&&t._onLog&&t._onLog("NV21 or NV12 is not supported.");return e}setNextImageToReturn(t,e){if(!((...t)=>0!==t.length&&t.every(t=>hD(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==aD(e))throw new TypeError("Invalid 'keepInBuffer'.");QI(this,RD,{imageId:t,keepInBuffer:e})}_resetNextReturnedImage(){QI(this,RD,null)}hasImage(t){return KI(this,_D,"m",MD).call(this,t)>=0}startFetching(){QI(this,DD,!0)}stopFetching(){QI(this,DD,!1)}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(QI(this,AD,t);KI(this,PD,"f")&&KI(this,PD,"f").length>t;)KI(this,PD,"f").shift()}getMaxImageCount(){return KI(this,AD,"f")}getImageCount(){return KI(this,PD,"f").length}clearBuffer(){KI(this,PD,"f").length=0}isBufferEmpty(){return 0===KI(this,PD,"f").length}setBufferOverflowProtectionMode(t){QI(this,ID,t)}getBufferOverflowProtectionMode(){return KI(this,ID,"f")}setColourChannelUsageType(t){QI(this,kD,t)}getColourChannelUsageType(){return KI(this,kD,"f")}};PD=new WeakMap,AD=new WeakMap,ID=new WeakMap,DD=new WeakMap,RD=new WeakMap,kD=new WeakMap,_D=new WeakSet,MD=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return KI(this,PD,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&(LD=navigator,OD=LD.userAgent,BD=LD.platform,ND=LD.mediaDevices),function(){if(!nD){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:LD.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:BD,search:"Win"},Mac:{str:BD},Linux:{str:BD}};let i="unknownBrowser",n=0,s="unknownOS";for(let e in t){const s=t[e]||{};let o=s.str||OD,r=s.search||e,a=s.verStr||OD,l=s.verSearch||e;if(l instanceof Array||(l=[l]),-1!=o.indexOf(r)){i=e;for(let t of l){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||OD,o=i.search||t;if(-1!=n.indexOf(o)){s=t;break}}"Linux"==s&&-1!=OD.indexOf("Windows NT")&&(s="HarmonyOS"),UD={browser:i,version:n,OS:s}}nD&&(UD={browser:"ssr",version:0,OS:"ssr"})}();const VD="undefined"!=typeof WebAssembly&&OD&&!(/Safari/.test(OD)&&!/Chrome/.test(OD)&&/\(.+\s11_2_([2-6]).*\)/.test(OD)),WD=!("undefined"==typeof Worker),HD=!(!ND||!ND.getUserMedia),jD=async()=>{let t=!1;if(HD)try{(await ND.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var zD,GD,YD,$D,XD,qD,ZD,JD,KD;"Chrome"===UD.browser&&UD.version>66||"Safari"===UD.browser&&UD.version>13||"OPR"===UD.browser&&UD.version>43||"Edge"===UD.browser&&UD.version,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_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(zD||(zD={})),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"}(GD||(GD={})),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_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",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_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",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_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",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_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"}(YD||(YD={})),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",t[t.GEM_END=-1]="GEM_END"}($D||($D={})),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",t[t.GTM_END=-1]="GTM_END"}(XD||(XD={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(qD||(qD={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(ZD||(ZD={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(JD||(JD={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(KD||(KD={}));const QD={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_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_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_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var tR,eR,iR,nR,sR,oR;!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_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(tR||(tR={})),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_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(eR||(eR={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(iR||(iR={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(nR||(nR={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(sR||(sR={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(oR||(oR={}));const rR={},aR=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(rR[t]=rR[t]||new JI);await Promise.all(i)},lR=async(t,e)=>{let i,n="string"==typeof t?[t]:t,s=[];for(let t of n){let n;s.push(n=rR[t]=rR[t]||new JI(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(s)};let hR,cR=0;const dR=()=>cR++,uR={};let pR,gR=!1;const fR={},mR={},vR={dip:{wasm:!0}},yR={std:{version:"2.0.0",path:rD(oD+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.2.20-dev-20251029130528",path:oD,isInternal:!0}};let xR=5;"undefined"!=typeof navigator&&(xR=navigator.hardwareConcurrency?navigator.hardwareConcurrency-1:5),uR[-3]=async t=>{wR.onWasmLoadProgressChanged&&wR.onWasmLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};class wR{static get engineResourcePaths(){return yR}static set engineResourcePaths(t){Object.assign(yR,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return pR}static set _onLog(t){(t=>{pR=t,hR&&hR.postMessage({type:"setBLog",body:{value:!!t}})})(t)}static get _bDebug(){return gR}static set _bDebug(t){(t=>{gR=t,hR&&hR.postMessage({type:"setBDebug",body:{value:!!t}})})(t)}static get _workerName(){return`${wR._bundleEnv.toLowerCase()}.bundle.worker.js`}static get wasmLoadOptions(){return wR._wasmLoadOptions}static set wasmLoadOptions(t){Object.assign(wR._wasmLoadOptions,t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!rR[t]&&rR[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=rR.core;e=!i||i.isEmpty,e||await aR("core");let n=new Map;const s=t=>{if(t=t.toLowerCase(),sR.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||sR.MN_DYNAMSOFT_CORE==t)return;let e=vR[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=rR[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)s(e);let o=[];e&&o.push("core"),o.push(...n.keys());const r=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await lR(o,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await aR(r);const i=wD(yR),s={};for(let e of t)s[e]=vR[e];const o={engineResourcePaths:i,autoResources:s,names:t,_bundleEnv:wR._bundleEnv,wasmLoadOptions:wR.wasmLoadOptions};let a=new JI;if(e){o.needLoadCore=!0;let t=i[`${wR._bundleEnv.toLowerCase()}Bundle`]+wR._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),hR=new Worker(t),hR.onerror=t=>{let e=new Error(t.message);a.reject(e)},hR.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,s=e.body;switch(i){case"log":pR&&pR(e.message);break;case"warning":console.warn(e.message);break;case"task":try{uR[n](s),delete uR[n]}catch(t){throw delete uR[n],t}break;case"event":try{uR[n](s)}catch(t){throw t}break;default:console.log(t)}}),o.bLog=!!pR,o.bd=gR,o.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await aR("core");let l=cR++;uR[l]=t=>{if(t.success)Object.assign(fR,t.versions),"{}"!==JSON.stringify(t.versions)&&(wR._versions=t.versions),wR.loadedWasmType=t.loadedWasmType,a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},hR.postMessage({type:"loadWasm",id:l,body:o}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:VD,worker:WD,getUserMedia:HD,camera:await jD(),browser:UD.browser,version:UD.version,OS:UD.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=dR();uR[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)}},hR.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.2.20-dev-20251029130528(Worker: ${fR.core&&fR.core.worker||"Not Loaded"}, Wasm: ${fR.core&&fR.core.wasm||"Not Loaded"})`}static enableLogging(){FD._onLog=console.log,wR._onLog=console.log}static disableLogging(){FD._onLog=null,wR._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},hR.postMessage({type:"cfd",id:n,body:{count:t}})})}}wR._bSupportDce4Module=-1,wR._bSupportIRTModule=-1,wR._versions=null,wR._bundleEnv="DCV",wR._wasmLoadOptions={wasmType:"auto",pthreadPoolSize:xR},wR.loadedWasmType="ml-simd-pthread",wR.browserInfo=UD;const CR="undefined"==typeof self,bR="function"==typeof importScripts,SR=(()=>{if(!bR){if(!CR&&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"./"}})();function TR(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function ER(t,e,i,n,s){if("function"==typeof e||!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const _R=t=>t&&"object"==typeof t&&"function"==typeof t.then,PR=(async()=>{})().constructor;let AR=class extends PR{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,_R(t)?e=t:"function"==typeof t&&(e=new PR(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,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(_R(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},IR=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=dR();uR[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)}},hR.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},hR.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=dR();uR[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)}},hR.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var DR={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1};const RR=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])};let kR=class{constructor(t){this._irrRegistryState=DR,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),RR(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,n)=>{let s=dR();uR[s]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},hR.postMessage({type:"cvr_setIrrRegistry",id:s,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})})}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),RR(this),await new Promise((t,e)=>{let i=dR();uR[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},hR.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const MR="undefined"==typeof self,LR="function"==typeof importScripts,OR=(()=>{if(!LR){if(!MR&&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"./"}})(),BR=t=>{if(null==t&&(t="./"),MR||LR);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var NR;wR.engineResourcePaths.cvr={version:"3.2.20-dev-20251030140710",path:OR,isInternal:!0},vR.cvr={js:!0,wasm:!0,deps:[sR.MN_DYNAMSOFT_LICENSE,sR.MN_DYNAMSOFT_IMAGE_PROCESSING,sR.MN_DYNAMSOFT_NEURAL_NETWORK]},vR.dnn={wasm:!0,deps:[sR.MN_DYNAMSOFT_IMAGE_PROCESSING]},mR.cvr={};const UR="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,UR)<0&&(wR.engineResourcePaths.std={version:UR,path:BR(OR+`../../dynamsoft-capture-vision-std@${UR}/dist/`),isInternal:!0});const FR="3.0.10";(!wR.engineResourcePaths.dip||"string"!=typeof wR.engineResourcePaths.dip&&xD(wR.engineResourcePaths.dip.version,FR)<0)&&(wR.engineResourcePaths.dip={version:FR,path:BR(OR+`../../dynamsoft-image-processing@${FR}/dist/`),isInternal:!0});const VR="2.0.10";(!wR.engineResourcePaths.dnn||"string"!=typeof wR.engineResourcePaths.dnn&&xD(wR.engineResourcePaths.dnn.version,VR)<0)&&(wR.engineResourcePaths.dnn={version:VR,path:BR(OR+`../../dynamsoft-capture-vision-dnn@${VR}/dist/`),isInternal:!0});let WR=class{static getVersion(){return this._version}};var HR,jR,zR,GR,YR,$R,XR,qR,ZR,JR,KR,QR,tk,ek,ik,nk,sk,ok,rk,ak,lk,hk,ck,dk;function uk(t,e){if(t){if(t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}if(t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}uk(t.referencedItem,e)}}function pk(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function gk(t){return{type:zD.CRIT_ORIGINAL_IMAGE,referenceItem:null,targetROIDefName:"",taskName:"",imageData:t,toCanvas:()=>CD(t),toImage:e=>bD(e,t),toBlob:e=>SD(e,t)}}function fk(t){const e=[YD.EC_UNSUPPORTED_JSON_KEY_WARNING,YD.EC_LICENSE_AUTH_QUOTA_EXCEEDED,YD.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&e.includes(t.errorCode))return void console.warn(t.message);let i=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(i.stack&&(i.stack=t.stack),t.isShouleThrow)throw i;return t.rj&&t.rj(i),!0}WR._version=`3.2.20-dev-20251030140710(Worker: ${null===(NR=fR.cvr)||void 0===NR?void 0:NR.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(HR||(HR={}));const mk={onTaskResultsReceived:()=>{},isFilter:!0};uR[-2]=async t=>{vk.onDataLoadProgressChanged&&vk.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let vk=class t{constructor(){jR.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(wR.browserInfo.OS)?2048:4096,this.onCaptureError=null,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,this._dynamsoft=!0,zR.set(this,null),GR.set(this,null),YR.set(this,null),$R.set(this,null),XR.set(this,null),qR.set(this,new Set),ZR.set(this,new Set),JR.set(this,new Set),KR.set(this,500),QR.set(this,0),tk.set(this,0),ek.set(this,!1),ik.set(this,!1),nk.set(this,!1),sk.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return TR(this,nk,"f")}static async createInstance(e=!0){if(!mR.license)throw Error("The `license` module cannot be found.");await mR.license.dynamsoft(),await wR.loadWasm();const i=new t,n=new AR;let s=dR();return uR[s]=async e=>{e.success?(i._instanceID=e.instanceID,i._currentSettings=JSON.parse(JSON.parse(e.outputSettings).data),t._isNoOnnx=e.isNoOnnx,WR._version=`3.2.20-dev-20251030140710(Worker: ${fR.cvr.worker}, Wasm: ${e.version})`,ER(i,ik,!0),ER(i,$R,i.getIntermediateResultManager()),ER(i,ik,!1),n.resolve(i)):fk({message:e.message,rj:n.reject,stack:e.stack,functionName:"createInstance"})},hR.postMessage({type:"cvr_createInstance",id:s,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendDLModelBuffer(e,i){return await wR.loadWasm(),t._isNoOnnx?Promise.reject("Model not supported in the current environment."):await new Promise((t,n)=>{let s=dR();const o=wD(wR.engineResourcePaths);let r;uR[s]=async e=>{if(e.success){const i=JSON.parse(e.response);return 0!==i.errorCode&&fk({message:i.errorString?i.errorString:"Append Model Buffer Failed.",rj:n,errorCode:i.errorCode,functionName:"appendDLModelBuffer"}),t(i)}fk({message:e.message,rj:n,stack:e.stack,functionName:"appendDLModelBuffer"})},i?r=i:"DCV"===wR._bundleEnv?r=o.dcvData+"models/":"DBR"===wR._bundleEnv&&(r=o.dbrBundle+"models/"),hR.postMessage({type:"cvr_appendDLModelBuffer",id:s,body:{modelName:e,path:r}})})}static async clearDLModelBuffers(){return await new Promise((t,e)=>{let i=dR();uR[i]=async i=>{if(i.success)return t();fk({message:i.message,rj:e,stack:i.stack,functionName:"clearDLModelBuffers"})},hR.postMessage({type:"cvr_clearDLModelBuffers",id:i})})}async _singleFrameModeCallback(t){for(let e of TR(this,qR,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived(gk(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,TR(this,zR,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}),TR(this,jR,"m",ak).call(this,i)}setInput(t){if(pk(this),!t)return TR(this,sk,"f")&&(TR(this,$R,"f").removeResultReceiver(TR(this,sk,"f")),ER(this,sk,null)),void ER(this,zR,null);ER(this,zR,t),t.isCameraEnhancer&&TR(this,$R,"f")&&(TR(this,zR,"f")._intermediateResultReceiver.isDce=!0,TR(this,$R,"f").addResultReceiver(TR(this,zR,"f")._intermediateResultReceiver),ER(this,sk,TR(this,zR,"f")._intermediateResultReceiver))}getInput(){return TR(this,zR,"f")}addImageSourceStateListener(t){if(pk(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&TR(this,ZR,"f").add(t)}removeImageSourceStateListener(t){return pk(this),TR(this,ZR,"f").delete(t)}addResultReceiver(t){if(pk(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(TR(this,qR,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){pk(this),TR(this,qR,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of TR(this,qR,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new AR;let i=dR();return uR[i]=async t=>{t.success?e.resolve():fk({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},hR.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(pk(this),!t._dynamsoft)throw new Error("User defined CapturedResultFilter is not supported.");if(!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");TR(this,JR,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){pk(this),TR(this,JR,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(TR(this,$R,"f").removeResultReceiver(mk),0===TR(this,JR,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[zD.CRIT_BARCODE]:!1,[zD.CRIT_TEXT_LINE]:!1,[zD.CRIT_DETECTED_QUAD]:!1,[zD.CRIT_DESKEWED_IMAGE]:!1,[zD.CRIT_ENHANCED_IMAGE]:!1},e={[zD.CRIT_BARCODE]:!1,[zD.CRIT_TEXT_LINE]:!1,[zD.CRIT_DETECTED_QUAD]:!1,[zD.CRIT_DESKEWED_IMAGE]:!1,[zD.CRIT_ENHANCED_IMAGE]:!1};return await TR(this,jR,"m",lk).call(this,t),void await TR(this,jR,"m",hk).call(this,e)}for(let t of TR(this,JR,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(zD.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(zD.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(zD.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(zD.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(zD.CRIT_BARCODE)&&([...TR(this,$R,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||TR(this,$R,"f").addResultReceiver(mk)),await TR(this,jR,"m",lk).call(this,t.verificationEnabled),await TR(this,jR,"m",hk).call(this,t.duplicateFilterEnabled),await TR(this,jR,"m",ck).call(this,t.duplicateForgetTime)}async startCapturing(e){if(pk(this),!this._isPauseScan)return;if(!TR(this,zR,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);for(let t of TR(this,JR,"f"))await this.addResultFilter(t);const i=wD(wR.engineResourcePaths);return void 0!==TR(this,zR,"f").singleFrameMode&&"disabled"!==TR(this,zR,"f").singleFrameMode?(this._templateName=e,void TR(this,zR,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):TR(this,YR,"f")&&TR(this,YR,"f").isPending?TR(this,YR,"f"):(ER(this,YR,new AR((t,n)=>{if(this.disposed)return;let s=dR();uR[s]=async i=>{TR(this,YR,"f")&&!TR(this,YR,"f").isFulfilled&&(i.success?(this._isPauseScan=!1,this._isOutputOriginalImage=i.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&TR(this,zR,"f").startFetching(),this._loopReadVideo(e),t()},0)):fk({message:i.message,rj:n,stack:i.stack,functionName:"startCapturing"}))},hR.postMessage({type:"cvr_startCapturing",id:s,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:i}})})),await TR(this,YR,"f"))}stopCapturing(){pk(this),TR(this,zR,"f")&&(TR(this,zR,"f").isCameraEnhancer&&void 0!==TR(this,zR,"f").singleFrameMode&&"disabled"!==TR(this,zR,"f").singleFrameMode?TR(this,zR,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(TR(this,jR,"m",dk).call(this),TR(this,zR,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,ER(this,YR,null),TR(this,zR,"f").setColourChannelUsageType(eD.CCUT_AUTO)))}async containsTask(t){return pk(this),await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));fk({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},hR.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async switchCapturingTemplate(t){this.stopCapturing(),await this.startCapturing(t)}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(ER(this,ek,!0),TR(this,zR,"f").isBufferEmpty())if(TR(this,zR,"f").hasNextImageToFetch())for(let t of TR(this,ZR,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(HR.ISS_BUFFER_EMPTY);else if(!TR(this,zR,"f").hasNextImageToFetch())for(let t of TR(this,ZR,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(HR.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||TR(this,zR,"f").isBufferEmpty()&&TR(this,zR,"f").isCameraEnhancer)try{TR(this,zR,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=TR(this,zR,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),TR(this,zR,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(TR(this,zR,"f").isCameraEnhancer&&TR(this,zR,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=TR(this,zR,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of TR(this,qR,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived(gk(this._dsImage));const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null,TR(this,zR,"f").isCameraEnhancer&&TR(this,zR,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify});for(let t of TR(this,JR,"f")){const e=t;e.onOriginalImageResultReceived(n),e.onDecodedBarcodesReceived(n),e.onRecognizedTextLinesReceived(n),e.onProcessedDocumentResultReceived(n),e.onParsedResultsReceived(n)}TR(this,jR,"m",ak).call(this,n);const s=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()-i),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,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-s;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{TR(this,zR,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{TR(this,zR,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async getClarity(t,e,i,n,s){const{bytes:o,width:r,height:a,stride:l,format:h}=t;let c=dR();return new Promise((t,d)=>{uR[c]=async e=>{e.success?t(e.clarity):fk({message:e.message,rj:d,stack:e.stack,functionName:"getClarity"})},hR.postMessage({type:"cvr_getClarity",id:c,instanceID:this._instanceID,body:{bytes:o,width:r,height:a,stride:l,format:h,bitcount:e,wr:i,hr:n,grayThreshold:s}},[o.buffer])})}async capture(e,i){let n;if(pk(this),i||(i=t._defaultTemplate),ER(this,ek,!1),dD(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await yD(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,s=new Uint8Array(n);for(;n--;)s[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([s]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(e){return await new Promise((i,n)=>{let s=URL.createObjectURL(e),o=new Image;o.src=s,o.onload=()=>{URL.revokeObjectURL(o.dbrObjUrl),i(o)},o.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(t));let s=await this._captureImage(i||n,e);return i&&i.close(),s}async _captureImage(t,e){let i,n,s=t instanceof HTMLImageElement?t.naturalWidth:t.width,o=t instanceof HTMLImageElement?t.naturalHeight:t.height,r=Math.max(s,o);r>this.maxImageSideLength?(ER(this,tk,this.maxImageSideLength/r),i=Math.round(s*TR(this,tk,"f")),n=Math.round(o*TR(this,tk,"f"))):(i=s,n=o),TR(this,GR,"f")||ER(this,GR,document.createElement("canvas"));const a=TR(this,GR,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,s,o,0,0,i,n),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}),n={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(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,s=t.videoWidth,o=t.videoHeight,r=Math.max(s,o);r>this.maxImageSideLength?(ER(this,tk,this.maxImageSideLength/r),i=Math.round(s*TR(this,tk,"f")),n=Math.round(o*TR(this,tk,"f"))):(i=s,n=o),TR(this,GR,"f")||ER(this,GR,document.createElement("canvas"));const a=TR(this,GR,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,s,o,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:s,height:o,stride:r,format:a}=e;let l=dR();const h=new AR;return uR[l]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;e.bytes=i.bytes,TR(this,jR,"m",ok).call(this,t,e),i.isScanner||ER(this,tk,0),TR(this,jR,"m",rk).call(this,t,e);const n=Date.now();return n-TR(this,QR,"f")>TR(this,KR,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),ER(this,QR,n)),h.resolve(t)}catch(i){fk({message:i.message,rj:h.reject,stack:i.stack,functionName:"capture"})}}else fk({message:i.message,rj:h.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),hR.postMessage({type:"cvr_capture",id:l,instanceID:this._instanceID,body:{bytes:n,width:s,height:o,stride:r,format:a,templateName:i||"",isScanner:TR(this,ek,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),h}async initSettings(e){if(pk(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await yD(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let s=dR();uR[s]=async s=>{if(s.success){const o=JSON.parse(s.response);if(0!==o.errorCode&&fk({message:o.errorString?o.errorString:"Init Settings Failed.",rj:n,errorCode:o.errorCode,functionName:"initSettings"}))return;const r=JSON.parse(e);return this._currentSettings=r,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(o)}fk({message:s.message,rj:n,stack:s.stack,functionName:"initSettings"})},hR.postMessage({type:"cvr_initSettings",id:s,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return pk(this),await new Promise((i,n)=>{let s=dR();uR[s]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&fk({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}fk({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},hR.postMessage({type:"cvr_outputSettings",id:s,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const s=await this.outputSettings(t,n),o=new Blob([JSON.stringify(s,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(o),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return o}async getTemplateNames(){return pk(this),await new Promise((t,e)=>{let i=dR();uR[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&fk({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}fk({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},hR.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return pk(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&fk({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const s=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return s.minImageCaptureInterval=this._minImageCaptureInterval,e(s)}fk({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},hR.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return pk(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let s=dR();uR[s]=async t=>{if(t.success){const s=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==s.errorCode&&fk({message:s.errorString?s.errorString:"Update Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(s)}fk({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},hR.postMessage({type:"cvr_updateSettings",id:s,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return pk(this),await new Promise((t,e)=>{let i=dR();uR[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&fk({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}fk({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},hR.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return TR(this,XR,"f")||ER(this,XR,new IR(this)),TR(this,XR,"f")}getIntermediateResultManager(){if(pk(this),!TR(this,ik,"f")&&0!==wR.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return TR(this,$R,"f")||ER(this,$R,new kR(this)),TR(this,$R,"f")}static async setGlobalIntraOpNumThreads(t=0){return t>4||t<0?Promise.reject(new RangeError("'intraOpNumThreads' should be between 0 and 4.")):(await wR.loadWasm(),await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e();fk({message:t.message,rj:i,stack:t.stack,functionName:"setGlobalIntraOpNumThreads"})},hR.postMessage({type:"cvr_setGlobalIntraOpNumThreads",id:n,body:{intraOpNumThreads:t}})}))}async parseRequiredResources(t){return pk(this),await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));fk({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},hR.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){pk(this),TR(this,YR,"f")&&this.stopCapturing(),ER(this,zR,null),TR(this,qR,"f").clear(),TR(this,ZR,"f").clear(),TR(this,JR,"f").clear(),TR(this,$R,"f")._intermediateResultReceiverSet.clear(),ER(this,nk,!0);let t=dR();uR[t]=t=>{t.success||fk({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},hR.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:TR(this,zR,"f"),promiseStartScan:TR(this,YR,"f"),intermediateResultManager:TR(this,$R,"f"),bufferdItemsManager:TR(this,XR,"f"),resultReceiverSet:TR(this,qR,"f"),isaStateListenerSet:TR(this,ZR,"f"),resultFilterSet:TR(this,JR,"f"),compressRate:TR(this,tk,"f"),canvas:TR(this,GR,"f"),isScanner:TR(this,ek,"f"),innerUseTag:TR(this,ik,"f"),isDestroyed:TR(this,nk,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=dR();uR[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}fk({message:i.message,rj:e,stack:i.stack,functionName:""})},hR.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};zR=new WeakMap,GR=new WeakMap,YR=new WeakMap,$R=new WeakMap,XR=new WeakMap,qR=new WeakMap,ZR=new WeakMap,JR=new WeakMap,KR=new WeakMap,QR=new WeakMap,tk=new WeakMap,ek=new WeakMap,ik=new WeakMap,nk=new WeakMap,sk=new WeakMap,jR=new WeakSet,ok=function(t,e){var i,n,s,o,r,a,l,h,c,d,u,p;for(let g=0;g<t.items.length;g++){const f=t.items[g];0!==TR(this,tk,"f")&&uk(f,TR(this,tk,"f")),f.type===zD.CRIT_ORIGINAL_IMAGE?t.items[g]=gk(e):f.type===zD.CRIT_BARCODE?(null!==(i=(l=t.decodedBarcodesResult).barcodeResultItems)&&void 0!==i||(l.barcodeResultItems=[]),t.decodedBarcodesResult.barcodeResultItems.push(f)):f.type===zD.CRIT_TEXT_LINE?(null!==(n=(h=t.recognizedTextLinesResult).textLineResultItems)&&void 0!==n||(h.textLineResultItems=[]),t.recognizedTextLinesResult.textLineResultItems.push(f)):f.type===zD.CRIT_DETECTED_QUAD?(null!==(s=(c=t.processedDocumentResult).detectedQuadResultItems)&&void 0!==s||(c.detectedQuadResultItems=[]),t.processedDocumentResult.detectedQuadResultItems.push(f)):f.type===zD.CRIT_DESKEWED_IMAGE?(mR.ddn&&mR.ddn.handleDeskewedAndEnhancedImageResultItem(f),null!==(o=(d=t.processedDocumentResult).deskewedImageResultItems)&&void 0!==o||(d.deskewedImageResultItems=[]),t.processedDocumentResult.deskewedImageResultItems.push(f)):f.type===zD.CRIT_ENHANCED_IMAGE?(mR.ddn&&mR.ddn.handleDeskewedAndEnhancedImageResultItem(f),null!==(r=(u=t.processedDocumentResult).enhancedImageResultItems)&&void 0!==r||(u.enhancedImageResultItems=[]),t.processedDocumentResult.enhancedImageResultItems.push(f)):f.type===zD.CRIT_PARSED_RESULT&&(mR.dcp&&mR.dcp.handleParsedResultItem(f),null!==(a=(p=t.parsedResult).parsedResultItems)&&void 0!==a||(p.parsedResultItems=[]),t.parsedResult.parsedResultItems.push(f))}},rk=function(t,e){const i=t.intermediateResult;if(i){let t=0;for(let n of TR(this,$R,"f")._intermediateResultReceiverSet){t++;for(let s of i){if(["onTaskResultsReceived","onTargetROIResultsReceived"].includes(s.info.callbackName)){for(let t of s.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;n[s.info.callbackName]&&n[s.info.callbackName]({intermediateResultUnits:s.intermediateResultUnits},s.info)}else n[s.info.callbackName]&&n[s.info.callbackName](s.result,s.info);t===TR(this,$R,"f")._intermediateResultReceiverSet.size&&delete s.info.callbackName}}}t&&t.hasOwnProperty("intermediateResult")&&delete t.intermediateResult},ak=function(t){for(let e of TR(this,qR,"f"))t.decodedBarcodesResult&&e.onDecodedBarcodesReceived&&e.onDecodedBarcodesReceived(t.decodedBarcodesResult),t.recognizedTextLinesResult&&e.onRecognizedTextLinesReceived&&e.onRecognizedTextLinesReceived(t.recognizedTextLinesResult),t.processedDocumentResult&&e.onProcessedDocumentResultReceived&&e.onProcessedDocumentResultReceived(t.processedDocumentResult),t.parsedResult&&e.onParsedResultsReceived&&e.onParsedResultsReceived(t.parsedResult),e.onCapturedResultReceived&&e.onCapturedResultReceived(t)},lk=async function(t){return pk(this),await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e(t.result);fk({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},hR.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},hk=async function(t){return pk(this),await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e(t.result);fk({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},hR.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},ck=async function(t){return pk(this),await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return e(t.result);fk({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},hR.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},dk=async function(){let t=dR();const e=new AR;return uR[t]=async t=>{if(t.success)return e.resolve();fk({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},hR.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},vk._defaultTemplate="Default",vk._isNoOnnx=!1;let yk=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}};var xk;!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="ReadSingleBarcode",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"}(xk||(xk={}));const wk="undefined"==typeof self,Ck=wk?{}:self,bk="function"==typeof importScripts,Sk=(()=>{if(!bk){if(!wk&&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"./"}})(),Tk=t=>t&&"object"==typeof t&&"function"==typeof t.then,Ek=(async()=>{})().constructor;let _k=class extends Ek{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,Tk(t)?e=t:"function"==typeof t&&(e=new Ek(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,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Tk(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Pk=" is not allowed to change after `createInstance` or `loadWasm` is called.",Ak=!wk&&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"))||"",Ik=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Pk);i._license=e}};!wk&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Dk=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e<t.length;++e){if(!wk){let i=document.createElement("a");i.href=t[e],t[e]=i.href}t[e].endsWith("/")||(t[e]+="/")}}return t},Rk=(t,e)=>{e=Dk(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Pk);i._licenseServer=e}},kk=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Pk);i._deviceFriendlyName=e}};let Mk,Lk,Ok,Bk,Nk;"undefined"!=typeof navigator&&(Mk=navigator,Lk=Mk.userAgent,Ok=Mk.platform,Bk=Mk.mediaDevices),function(){if(!wk){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Mk.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:Ok,search:"Win"},Mac:{str:Ok},Linux:{str:Ok}};let i="unknownBrowser",n=0,s="unknownOS";for(let e in t){const s=t[e]||{};let o=s.str||Lk,r=s.search||e,a=s.verStr||Lk,l=s.verSearch||e;if(l instanceof Array||(l=[l]),-1!=o.indexOf(r)){i=e;for(let t of l){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Lk,o=i.search||t;if(-1!=n.indexOf(o)){s=t;break}}"Linux"==s&&-1!=Lk.indexOf("Windows NT")&&(s="HarmonyOS"),Nk={browser:i,version:n,OS:s}}wk&&(Nk={browser:"ssr",version:0,OS:"ssr"})}(),Bk&&Bk.getUserMedia,"Chrome"===Nk.browser&&Nk.version>66||"Safari"===Nk.browser&&Nk.version>13||"OPR"===Nk.browser&&Nk.version>43||"Edge"===Nk.browser&&Nk.version;const Uk=()=>(wR.loadWasm(),lR("dynamsoft_inited",async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:s,cv:o}=((t,e=!1)=>{const i=Vk;if(i._pLoad.isEmpty){let n,s,o,r=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),l=i._sessionPassword,h=0;if(r.startsWith("t")||r.startsWith("f"))h=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))h=1;else{h=2;const e=r.indexOf(":");-1!=e&&(r=r.substring(e+1));const i=r.indexOf("?");if(-1!=i&&(s=r.substring(i+1),r=r.substring(0,i)),r.startsWith("DLC2"))h=0;else{if(r.startsWith("DLS2")){let e;try{let t=r.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(r=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Dk(t)}!l&&e.sessionPassword&&(l=e.sessionPassword),n=e.remark}r&&"200001"!==r&&!r.startsWith("200001-")||(h=1)}}if(h&&(e||(Ck.crypto||(o="Please upgrade your browser to support online key."),Ck.crypto.subtle||(o="Require https to use online key in this browser."))),o)throw new Error(o);return 1===h&&(r="",console.warn("Applying for a public trial license ...")),{lt:h,l:r,ls:a,sp:l,rmk:n,cv:s}}throw new Error("Can't preprocess license again"+Pk)})(),r=new _k;Vk._pLoad.task=r,(async()=>{try{await Vk._pLoad}catch(t){}})();let a=dR();uR[a]=e=>{if(e.message&&Vk._onAuthMessage){let t=Vk._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(pR&&pR("init license success"),e.message&&console.warn(e.message),wR._bSupportIRTModule=e.bSupportIRTModule,wR._bSupportDce4Module=e.bSupportDce4Module,Vk.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):r.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=wD(wR.engineResourcePaths),i=("DCV"===wR._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let s=await n.text();if(!s.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let o=document.createElement("div");o.insertAdjacentHTML("beforeend",s);let r=[];for(let t=0;t<o.childElementCount;++t){let e=o.children[t];e instanceof HTMLStyleElement&&(r.push(e),document.head.append(e))}let a=1==o.childElementCount?o.children[0]:o;a.remove();let l,h,c,d,u,p=[a],g=a.children;for(let t of g)p.push(t);for(let t=0;t<p.length;++t)for(let e of p[t].children)p.push(e);for(let t of p)if(!l&&t.classList.contains("dls-license-mask"))l=t,t.addEventListener("click",e=>{if(t==e.target){a.remove();for(let t of r)t.remove()}});else if(!h&&t.classList.contains("dls-license-icon-close"))h=t,t.addEventListener("click",()=>{a.remove();for(let t of r)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-icon-warn"))d=t,"warn"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-msg-content")){u=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),s=e.indexOf("(",n),o=e.indexOf(")",s);if(-1==i||-1==n||-1==s||-1==o){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let r=document.createElement("a"),a=e.substring(i+1,n);r.innerText=a;let l=e.substring(s+1,o);r.setAttribute("href",l),r.setAttribute("target","_blank"),t.appendChild(r),e=e.substring(o+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Vk._bNeverShowDialog,engineResourcePath:i,_onLog:pR},e.success?"warn":"error",e.message)}e.success?r.resolve(void 0):r.reject(i)},await aR("core");const l=await wR.getModuleVersion();hR.postMessage({type:"license_dynamsoft",body:{v:"DCV"===wR._bundleEnv?l.CVR.replace(/\.\d+$/,""):l.DBR.replace(/\.\d+$/,""),brtk:!!t,bptk:1===t,l:e,os:Nk,fn:Vk.deviceFriendlyName,ls:i,sp:n,rmk:s,cv:o},id:a}),Vk.bCallInitLicense=!0,await r}));let Fk;mR.license={},mR.license.dynamsoft=Uk,mR.license.getAR=async()=>{{let t=rR.dynamsoft_inited;t&&t.isRejected&&await t}return hR?new Promise((t,e)=>{let i=dR();uR[i]=async i=>{if(i.success){delete i.success;{let t=Vk.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)}},hR.postMessage({type:"license_getAR",id:i})}):null};let Vk=class t{static setLicenseServer(e){Rk(t,e)}static get license(){return this._license}static set license(e){Ik(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Rk(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){kk(t,e)}static initLicense(e,i){if(Ik(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Uk()}static setDeviceFriendlyName(e){kk(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await lR("dynamsoft_uuid",async()=>{await wR.loadWasm();let t=new _k,e=dR();uR[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},hR.postMessage({type:"license_getDeviceUUID",id:e}),Fk=await t}),Fk))()}};Vk._pLoad=new _k,Vk.bPassValidation=!1,Vk.bCallInitLicense=!1,Vk._license=Ak,Vk._licenseServer=[],Vk._deviceFriendlyName="",wR.engineResourcePaths.license={version:"4.2.20-dev-20251029130543",path:Sk,isInternal:!0},vR.license={wasm:!0,js:!0},mR.license.LicenseManager=Vk;const Wk="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,Wk)<0&&(wR.engineResourcePaths.std={version:Wk,path:(t=>{if(null==t&&(t="./"),wk||bk);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Sk+`../../dynamsoft-capture-vision-std@${Wk}/dist/`),isInternal:!0});const Hk="undefined"==typeof self,jk="function"==typeof importScripts,zk=(()=>{if(!jk){if(!Hk&&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"./"}})();wR.engineResourcePaths.dce={version:"4.3.3-dev-20251029130621",path:zk,isInternal:!0},vR.dce={wasm:!1,js:!1},mR.dce={};let Gk,Yk,$k,Xk,qk;function Zk(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Jk(t,e,i,n,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s?s.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Gk=navigator,Yk=Gk.userAgent,$k=Gk.platform,Xk=Gk.mediaDevices),function(){if(!Hk){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Gk.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:$k,search:"Win"},Mac:{str:$k},Linux:{str:$k}};let i="unknownBrowser",n=0,s="unknownOS";for(let e in t){const s=t[e]||{};let o=s.str||Yk,r=s.search||e,a=s.verStr||Yk,l=s.verSearch||e;if(l instanceof Array||(l=[l]),-1!=o.indexOf(r)){i=e;for(let t of l){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Yk,o=i.search||t;if(-1!=n.indexOf(o)){s=t;break}}"Linux"==s&&-1!=Yk.indexOf("Windows NT")&&(s="HarmonyOS"),qk={browser:i,version:n,OS:s}}Hk&&(qk={browser:"ssr",version:0,OS:"ssr"})}();const Kk="undefined"!=typeof WebAssembly&&Yk&&!(/Safari/.test(Yk)&&!/Chrome/.test(Yk)&&/\(.+\s11_2_([2-6]).*\)/.test(Yk)),Qk=!("undefined"==typeof Worker),tM=!(!Xk||!Xk.getUserMedia),eM=async()=>{let t=!1;if(tM)try{(await Xk.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===qk.browser&&qk.version>66||"Safari"===qk.browser&&qk.version>13||"OPR"===qk.browser&&qk.version>43||"Edge"===qk.browser&&qk.version;var iM={653:(t,e,i)=>{var n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x,w,C,b,S,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 E=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=E.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=E,DOMParser=T.window.DOMParser}function _(t,e){var i=t.canvas,n=e.targetCanvas,s=n.getContext("2d");s.translate(0,n.height),s.scale(1,-1);var o=i.height-n.height;s.drawImage(i,0,o,n.width,n.height,0,0,n.width,n.height)}function P(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,s=e.destinationHeight,o=n*s*4,r=new Uint8Array(this.imageBuffer,0,o),a=new Uint8ClampedArray(this.imageBuffer,0,o);t.readPixels(0,0,n,s,t.RGBA,t.UNSIGNED_BYTE,r);var l=new ImageData(a,n,s);i.putImageData(l,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 n=0,s=i.length;n<s;n++)i[n]&&i[n].call(this,e||{});return this.__eventListeners[t]=i.filter(function(t){return!1!==t}),this},on:function(t,e){if(this.__eventListeners||(this.__eventListeners={}),1===arguments.length)for(var i in t)this.on(i,t[i]);else this.__eventListeners[t]||(this.__eventListeners[t]=[]),this.__eventListeners[t].push(e);return this},once:function(t,i){if(1===arguments.length)for(var n in t)e.call(this,n,t[n]);else e.call(this,t,i);return this},off:function(e,i){if(!this.__eventListeners)return this;if(0===arguments.length)for(e in this.__eventListeners)t.call(this,e);else if(1===arguments.length&&"object"==typeof arguments[0])for(var n in e)t.call(this,n,e[n]);else t.call(this,e,i);return this}}}(),T.Collection={_objects:[],add:function(){if(this._objects.push.apply(this._objects,arguments),this._onObjectAdded)for(var t=0,e=arguments.length;t<e;t++)this._onObjectAdded(arguments[t]);return this.renderOnAddRemove&&this.requestRenderAll(),this},insertAt:function(t,e,i){var n=this._objects;return i?n[e]=t:n.splice(e,0,t),this._onObjectAdded&&this._onObjectAdded(t),this.renderOnAddRemove&&this.requestRenderAll(),this},remove:function(){for(var t,e=this._objects,i=!1,n=0,s=arguments.length;n<s;n++)-1!==(t=e.indexOf(arguments[n]))&&(i=!0,e.splice(t,1),this._onObjectRemoved&&this._onObjectRemoved(arguments[n]));return this.renderOnAddRemove&&i&&this.requestRenderAll(),this},forEachObject:function(t,e){for(var i=this.getObjects(),n=0,s=i.length;n<s;n++)t.call(e,i[n],n,i);return this},getObjects:function(t){return void 0===t?this._objects.concat():this._objects.filter(function(e){return e.type===t})},item:function(t){return this._objects[t]},isEmpty:function(){return 0===this._objects.length},size:function(){return this._objects.length},contains:function(t,e){return this._objects.indexOf(t)>-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]}},n=e,s=Math.sqrt,o=Math.atan2,r=Math.pow,a=Math.PI/180,l=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/l){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/l){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 n=new T.Point(t.x-e.x,t.y-e.y),s=T.util.rotateVector(n,i);return new T.Point(s.x,s.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),n=T.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},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 n=T.util.createVector(t,e),s=T.util.createVector(t,i),o=T.util.calcAngleBetweenVectors(n,s),r=o*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(n,o),s)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(n,r)),angle:o}},projectStrokeOnPoints:function(t,e,i){var n=[],s=e.strokeWidth/2,o=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),r=function(t){var e=s/Math.hypot(t.x,t.y);return new T.Point(t.x*e*o.x,t.y*e*o.y)};return t.length<=1||t.forEach(function(a,l){var h,c,d=new T.Point(a.x,a.y);0===l?(c=t[l+1],h=i?r(T.util.createVector(c,d)).addEquals(d):t[t.length-1]):l===t.length-1?(h=t[l-1],c=i?r(T.util.createVector(h,d)).addEquals(d):t[0]):(h=t[l-1],c=t[l+1]);var u,p,g=T.util.getBisector(d,h,c),f=g.vector,m=g.angle;if("miter"===e.strokeLineJoin&&(u=-s/Math.sin(m/2),p=new T.Point(f.x*u*o.x,f.y*u*o.y),Math.hypot(p.x,p.y)/s<=e.strokeMiterLimit))return n.push(d.add(p)),void n.push(d.subtract(p));u=-s*Math.SQRT2,p=new T.Point(f.x*u*o.x,f.y*u*o.y),n.push(d.add(p)),n.push(d.subtract(p))}),n},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;i<t.length;i++)t[i]=T.util.transformPoint(t[i],e);var n=[t[0].x,t[1].x,t[2].x,t[3].x],s=T.util.array.min(n),o=T.util.array.max(n)-s,r=[t[0].y,t[1].y,t[2].y,t[3].y],a=T.util.array.min(r);return{left:s,top:a,width:o,height:T.util.array.max(r)-a}},invertTransform:function(t){var e=1/(t[0]*t[3]-t[1]*t[2]),i=[e*t[3],-e*t[1],-e*t[2],e*t[0]],n=T.util.transformPoint({x:t[4],y:t[5]},i,!0);return i[4]=-n.x,i[5]=-n.y,i},toFixed:function(t,e){return parseFloat(Number(t).toFixed(e))},parseUnit:function(t,e){var i=/\D{0,2}$/.exec(t),n=parseFloat(t);switch(e||(e=T.Text.DEFAULT_SVG_FONT_SIZE),i[0]){case"mm":return n*T.DPI/25.4;case"cm":return n*T.DPI/2.54;case"in":return n*T.DPI;case"pt":return n*T.DPI/72;case"pc":return n*T.DPI/72*12;case"em":return n*e;default:return n}},falseFunction:function(){return!1},getKlass:function(t,e){return t=T.util.string.camelize(t.charAt(0).toUpperCase()+t.slice(1)),T.util.resolveNamespace(e)[t]},getSvgAttributes:function(t){var e=["instantiated_by_use","style","id","class"];switch(t){case"linearGradient":e=e.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);break;case"radialGradient":e=e.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);break;case"stop":e=e.concat(["offset","stop-color","stop-opacity"])}return e},resolveNamespace:function(t){if(!t)return T;var e,i=t.split("."),s=i.length,o=n||T.window;for(e=0;e<s;++e)o=o[i[e]];return o},loadImage:function(t,e,i,n){if(t){var s=T.util.createImage(),o=function(){e&&e.call(i,s,!1),s=s.onload=s.onerror=null};s.onload=o,s.onerror=function(){T.log("Error loading "+s.src),e&&e.call(i,null,!0),s=s.onload=s.onerror=null},0!==t.indexOf("data")&&null!=n&&(s.crossOrigin=n),"data:image/svg"===t.substring(0,14)&&(s.onload=null,T.util.loadImageInDom(s,o)),s.src=t}else e&&e.call(i,t)},loadImageInDom:function(t,e){var i=T.document.createElement("div");i.style.width=i.style.height="1px",i.style.left=i.style.top="-100%",i.style.position="absolute",i.appendChild(t),T.document.querySelector("body").appendChild(i),t.onload=function(){e(),i.parentNode.removeChild(i),i=null}},enlivenObjects:function(t,e,i,n){var s=[],o=0,r=(t=t||[]).length;function a(){++o===r&&e&&e(s.filter(function(t){return t}))}r?t.forEach(function(t,e){t&&t.type?T.util.getKlass(t.type,i).fromObject(t,function(i,o){o||(s[e]=i),n&&n(t,i,o),a()}):a()}):e&&e(s)},enlivenObjectEnlivables:function(t,e,i){var n=T.Object.ENLIVEN_PROPS.filter(function(e){return!!t[e]});T.util.enlivenObjects(n.map(function(e){return t[e]}),function(t){var s={};n.forEach(function(i,n){s[i]=t[n],e&&(e[i]=t[n])}),i&&i(s)})},enlivenPatterns:function(t,e){function i(){++s===o&&e&&e(n)}var n=[],s=0,o=(t=t||[]).length;o?t.forEach(function(t,e){t&&t.source?new T.Pattern(t,function(t){n[e]=t,i()}):(n[e]=t,i())}):e&&e(n)},groupSVGElements:function(t,e,i){var n;return t&&1===t.length?t[0]:(e&&(e.width&&e.height?e.centerPoint={x:e.width/2,y:e.height/2}:(delete e.width,delete e.height)),n=new T.Group(t,e),void 0!==i&&(n.sourcePath=i),n)},populateWithProperties:function(t,e,i){if(i&&Array.isArray(i))for(var n=0,s=i.length;n<s;n++)i[n]in t&&(e[i[n]]=t[i[n]])},createCanvasElement:function(){return T.document.createElement("canvas")},copyCanvasElement:function(t){var e=T.util.createCanvasElement();return e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0),e},toDataURL:function(t,e,i){return t.toDataURL("image/"+e,i)},createImage:function(){return T.document.createElement("img")},multiplyTransformMatrices:function(t,e,i){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],i?0:t[0]*e[4]+t[2]*e[5]+t[4],i?0:t[1]*e[4]+t[3]*e[5]+t[5]]},qrDecompose:function(t){var e=o(t[1],t[0]),i=r(t[0],2)+r(t[1],2),n=s(i),l=(t[0]*t[3]-t[2]*t[1])/n,h=o(t[0]*t[2]+t[1]*t[3],i);return{angle:e/a,scaleX:n,scaleY:l,skewX:h/a,skewY:0,translateX:t[4],translateY:t[5]}},calcRotateMatrix:function(t){if(!t.angle)return T.iMatrix.concat();var e=T.util.degreesToRadians(t.angle),i=T.util.cos(e),n=T.util.sin(e);return[i,n,-n,i,0,0]},calcDimensionsMatrix:function(t){var e=void 0===t.scaleX?1:t.scaleX,i=void 0===t.scaleY?1:t.scaleY,n=[t.flipX?-e:e,0,0,t.flipY?-i:i,0,0],s=T.util.multiplyTransformMatrices,o=T.util.degreesToRadians;return t.skewX&&(n=s(n,[1,0,Math.tan(o(t.skewX)),1],!0)),t.skewY&&(n=s(n,[1,Math.tan(o(t.skewY)),0,1],!0)),n},composeMatrix:function(t){var e=[1,0,0,1,t.translateX||0,t.translateY||0],i=T.util.multiplyTransformMatrices;return t.angle&&(e=i(e,T.util.calcRotateMatrix(t))),(1!==t.scaleX||1!==t.scaleY||t.skewX||t.skewY||t.flipX||t.flipY)&&(e=i(e,T.util.calcDimensionsMatrix(t))),e},resetObjectTransform:function(t){t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.rotate(0)},saveObjectTransform:function(t){return{scaleX:t.scaleX,scaleY:t.scaleY,skewX:t.skewX,skewY:t.skewY,angle:t.angle,left:t.left,flipX:t.flipX,flipY:t.flipY,top:t.top}},isTransparent:function(t,e,i,n){n>0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var s,o=!0,r=t.getImageData(e,i,2*n||1,2*n||1),a=r.data.length;for(s=3;s<a&&0!=(o=r.data[s]<=0);s+=4);return r=null,o},parsePreserveAspectRatioAttribute:function(t){var e,i="meet",n=t.split(" ");return n&&n.length&&("meet"!==(i=n.pop())&&"slice"!==i?(e=i,i="meet"):n.length&&(e=n.pop())),{meetOrSlice:i,alignX:"none"!==e?e.slice(1,4):"none",alignY:"none"!==e?e.slice(5,8):"none"}},clearFabricFontCache:function(t){(t=(t||"").toLowerCase())?T.charWidthsCache[t]&&delete T.charWidthsCache[t]:T.charWidthsCache={}},limitDimsByArea:function(t,e){var i=Math.sqrt(e*t),n=Math.floor(e/i);return{x:Math.floor(i),y:n}},capValue:function(t,e,i){return Math.max(t,Math.min(e,i))},findScaleToFit:function(t,e){return Math.min(e.width/t.width,e.height/t.height)},findScaleToCover:function(t,e){return Math.max(e.width/t.width,e.height/t.height)},matrixToSVG:function(t){return"matrix("+t.map(function(t){return T.util.toFixed(t,T.Object.NUM_FRACTION_DIGITS)}).join(" ")+")"},removeTransformFromObject:function(t,e){var i=T.util.invertTransform(e),n=T.util.multiplyTransformMatrices(i,t.calcOwnMatrix());T.util.applyTransformToObject(t,n)},addTransformToObject:function(t,e){T.util.applyTransformToObject(t,T.util.multiplyTransformMatrices(e,t.calcOwnMatrix()))},applyTransformToObject:function(t,e){var i=T.util.qrDecompose(e),n=new T.Point(i.translateX,i.translateY);t.flipX=!1,t.flipY=!1,t.set("scaleX",i.scaleX),t.set("scaleY",i.scaleY),t.skewX=i.skewX,t.skewY=i.skewY,t.angle=i.angle,t.setPositionByOrigin(n,"center","center")},sizeAfterTransform:function(t,e,i){var n=t/2,s=e/2,o=[{x:-n,y:-s},{x:n,y:-s},{x:-n,y:s},{x:n,y:s}],r=T.util.calcDimensionsMatrix(i),a=T.util.makeBoundingBoxFromPoints(o,r);return{x:a.width,y:a.height}},mergeClipPaths:function(t,e){var i=t,n=e;i.inverted&&!n.inverted&&(i=e,n=t),T.util.applyTransformToObject(n,T.util.multiplyTransformMatrices(T.util.invertTransform(i.calcTransformMatrix()),n.calcTransformMatrix()));var s=i.inverted&&n.inverted;return s&&(i.inverted=n.inverted=!1),new T.Group([i],{clipPath:n,inverted:s})}},function(){var t=Array.prototype.join,e={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},i={m:"l",M:"L"};function n(t,e,i,n,s,o,r,a,l,h,c){var d=T.util.cos(t),u=T.util.sin(t),p=T.util.cos(e),g=T.util.sin(e),f=i*s*p-n*o*g+r,m=n*s*p+i*o*g+a;return["C",h+l*(-i*s*u-n*o*d),c+l*(-n*s*u+i*o*d),f+l*(i*s*g+n*o*p),m+l*(n*s*g-i*o*p),f,m]}function s(t,e,i,n){var s=Math.atan2(e,t),o=Math.atan2(n,i);return o>=s?o-s:2*Math.PI-(s-o)}function o(t,e,i){for(var o=i[1],r=i[2],a=i[3],l=i[4],h=i[5],c=function(t,e,i,o,r,a,l){var h=Math.PI,c=l*h/180,d=T.util.sin(c),u=T.util.cos(c),p=0,g=0,f=-u*t*.5-d*e*.5,m=-u*e*.5+d*t*.5,v=(i=Math.abs(i))*i,y=(o=Math.abs(o))*o,x=m*m,w=f*f,C=v*y-v*x-y*w,b=0;if(C<0){var S=Math.sqrt(1-C/(v*y));i*=S,o*=S}else b=(r===a?-1:1)*Math.sqrt(C/(v*x+y*w));var E=b*i*m/o,_=-b*o*f/i,P=u*E-d*_+.5*t,A=d*E+u*_+.5*e,I=s(1,0,(f-E)/i,(m-_)/o),D=s((f-E)/i,(m-_)/o,(-f-E)/i,(-m-_)/o);0===a&&D>0?D-=2*h:1===a&&D<0&&(D+=2*h);for(var R=Math.ceil(Math.abs(D/h*2)),k=[],M=D/R,L=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),O=I+M,B=0;B<R;B++)k[B]=n(I,O,u,d,i,o,P,A,L,p,g),p=k[B][5],g=k[B][6],I=O,O+=M;return k}(i[6]-t,i[7]-e,o,r,l,h,a),d=0,u=c.length;d<u;d++)c[d][1]+=t,c[d][2]+=e,c[d][3]+=t,c[d][4]+=e,c[d][5]+=t,c[d][6]+=e;return c}function r(t,e,i,n){return Math.sqrt((i-t)*(i-t)+(n-e)*(n-e))}function a(t,e,i,n,s,o,r,a){return function(l){var h,c=(h=l)*h*h,d=function(t){return 3*t*t*(1-t)}(l),u=function(t){return 3*t*(1-t)*(1-t)}(l),p=function(t){return(1-t)*(1-t)*(1-t)}(l);return{x:r*c+s*d+i*u+t*p,y:a*c+o*d+n*u+e*p}}}function l(t,e,i,n,s,o,r,a){return function(l){var h=1-l,c=3*h*h*(i-t)+6*h*l*(s-i)+3*l*l*(r-s),d=3*h*h*(n-e)+6*h*l*(o-n)+3*l*l*(a-o);return Math.atan2(d,c)}}function h(t,e,i,n,s,o){return function(r){var a,l=(a=r)*a,h=function(t){return 2*t*(1-t)}(r),c=function(t){return(1-t)*(1-t)}(r);return{x:s*l+i*h+t*c,y:o*l+n*h+e*c}}}function c(t,e,i,n,s,o){return function(r){var a=1-r,l=2*a*(i-t)+2*r*(s-i),h=2*a*(n-e)+2*r*(o-n);return Math.atan2(h,l)}}function d(t,e,i){var n,s,o={x:e,y:i},a=0;for(s=1;s<=100;s+=1)n=t(s/100),a+=r(o.x,o.y,n.x,n.y),o=n;return a}function u(t){for(var e,i,n,s,o=0,u=t.length,p=0,g=0,f=0,m=0,v=[],y=0;y<u;y++){switch(n={x:p,y:g,command:(e=t[y])[0]},e[0]){case"M":n.length=0,f=p=e[1],m=g=e[2];break;case"L":n.length=r(p,g,e[1],e[2]),p=e[1],g=e[2];break;case"C":i=a(p,g,e[1],e[2],e[3],e[4],e[5],e[6]),s=l(p,g,e[1],e[2],e[3],e[4],e[5],e[6]),n.iterator=i,n.angleFinder=s,n.length=d(i,p,g),p=e[5],g=e[6];break;case"Q":i=h(p,g,e[1],e[2],e[3],e[4]),s=c(p,g,e[1],e[2],e[3],e[4]),n.iterator=i,n.angleFinder=s,n.length=d(i,p,g),p=e[3],g=e[4];break;case"Z":case"z":n.destX=f,n.destY=m,n.length=r(p,g,f,m),p=f,g=m}o+=n.length,v.push(n)}return v.push({length:o,x:p,y:g}),v}T.util.joinPath=function(t){return t.map(function(t){return t.join(" ")}).join(" ")},T.util.parsePath=function(t){var n,s,o,r,a,l=[],h=[],c=T.rePathCommand,d="[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?\\s*",u="("+d+")"+T.commaWsp,p="([01])"+T.commaWsp+"?",g=new RegExp(u+"?"+u+"?"+u+p+p+u+"?("+d+")","g");if(!t||!t.match)return l;for(var f,m=0,v=(a=t.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi)).length;m<v;m++){r=(n=a[m]).slice(1).trim(),h.length=0;var y=n.charAt(0);if(f=[y],"a"===y.toLowerCase())for(var x;x=g.exec(r);)for(var w=1;w<x.length;w++)h.push(x[w]);else for(;o=c.exec(r);)h.push(o[0]);w=0;for(var C=h.length;w<C;w++)s=parseFloat(h[w]),isNaN(s)||f.push(s);var b=e[y.toLowerCase()],S=i[y]||y;if(f.length-1>b)for(var E=1,_=f.length;E<_;E+=b)l.push([y].concat(f.slice(E,E+b))),y=S;else l.push(f)}return l},T.util.makePathSimpler=function(t){var e,i,n,s,r,a,l=0,h=0,c=t.length,d=0,u=0,p=[];for(i=0;i<c;++i){switch(n=!1,(e=t[i].slice(0))[0]){case"l":e[0]="L",e[1]+=l,e[2]+=h;case"L":l=e[1],h=e[2];break;case"h":e[1]+=l;case"H":e[0]="L",e[2]=h,l=e[1];break;case"v":e[1]+=h;case"V":e[0]="L",h=e[1],e[1]=l,e[2]=h;break;case"m":e[0]="M",e[1]+=l,e[2]+=h;case"M":l=e[1],h=e[2],d=e[1],u=e[2];break;case"c":e[0]="C",e[1]+=l,e[2]+=h,e[3]+=l,e[4]+=h,e[5]+=l,e[6]+=h;case"C":r=e[3],a=e[4],l=e[5],h=e[6];break;case"s":e[0]="S",e[1]+=l,e[2]+=h,e[3]+=l,e[4]+=h;case"S":"C"===s?(r=2*l-r,a=2*h-a):(r=l,a=h),l=e[3],h=e[4],e[0]="C",e[5]=e[3],e[6]=e[4],e[3]=e[1],e[4]=e[2],e[1]=r,e[2]=a,r=e[3],a=e[4];break;case"q":e[0]="Q",e[1]+=l,e[2]+=h,e[3]+=l,e[4]+=h;case"Q":r=e[1],a=e[2],l=e[3],h=e[4];break;case"t":e[0]="T",e[1]+=l,e[2]+=h;case"T":"Q"===s?(r=2*l-r,a=2*h-a):(r=l,a=h),e[0]="Q",l=e[1],h=e[2],e[1]=r,e[2]=a,e[3]=l,e[4]=h;break;case"a":e[0]="A",e[6]+=l,e[7]+=h;case"A":n=!0,p=p.concat(o(l,h,e)),l=e[6],h=e[7];break;case"z":case"Z":l=d,h=u}n||p.push(e),s=e[0]}return p},T.util.getSmoothPathFromPoints=function(t,e){var i,n=[],s=new T.Point(t[0].x,t[0].y),o=new T.Point(t[1].x,t[1].y),r=t.length,a=1,l=0,h=r>2;for(e=e||0,h&&(a=t[2].x<o.x?-1:t[2].x===o.x?0:1,l=t[2].y<o.y?-1:t[2].y===o.y?0:1),n.push(["M",s.x-a*e,s.y-l*e]),i=1;i<r;i++){if(!s.eq(o)){var c=s.midPointFrom(o);n.push(["Q",s.x,s.y,c.x,c.y])}s=t[i],i+1<t.length&&(o=t[i+1])}return h&&(a=s.x>t[i-2].x?1:s.x===t[i-2].x?0:-1,l=s.y>t[i-2].y?1:s.y===t[i-2].y?0:-1),n.push(["L",s.x+a*e,s.y+l*e]),n},T.util.getPathSegmentsInfo=u,T.util.getBoundsOfCurve=function(e,i,n,s,o,r,a,l){var h;if(T.cachesBoundsOfCurve&&(h=t.call(arguments),T.boundsOfCurveCache[h]))return T.boundsOfCurveCache[h];var c,d,u,p,g,f,m,v,y=Math.sqrt,x=Math.min,w=Math.max,C=Math.abs,b=[],S=[[],[]];d=6*e-12*n+6*o,c=-3*e+9*n-9*o+3*a,u=3*n-3*e;for(var E=0;E<2;++E)if(E>0&&(d=6*i-12*s+6*r,c=-3*i+9*s-9*r+3*l,u=3*s-3*i),C(c)<1e-12){if(C(d)<1e-12)continue;0<(p=-u/d)&&p<1&&b.push(p)}else(m=d*d-4*u*c)<0||(0<(g=(-d+(v=y(m)))/(2*c))&&g<1&&b.push(g),0<(f=(-d-v)/(2*c))&&f<1&&b.push(f));for(var _,P,A,I=b.length,D=I;I--;)_=(A=1-(p=b[I]))*A*A*e+3*A*A*p*n+3*A*p*p*o+p*p*p*a,S[0][I]=_,P=A*A*A*i+3*A*A*p*s+3*A*p*p*r+p*p*p*l,S[1][I]=P;S[0][D]=e,S[1][D]=i,S[0][D+1]=a,S[1][D+1]=l;var R=[{x:x.apply(null,S[0]),y:x.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[h]=R),R},T.util.getPointOnPath=function(t,e,i){i||(i=u(t));for(var n=0;e-i[n].length>0&&n<i.length-2;)e-=i[n].length,n++;var s,o=i[n],a=e/o.length,l=o.command,h=t[n];switch(l){case"M":return{x:o.x,y:o.y,angle:0};case"Z":case"z":return(s=new T.Point(o.x,o.y).lerp(new T.Point(o.destX,o.destY),a)).angle=Math.atan2(o.destY-o.y,o.destX-o.x),s;case"L":return(s=new T.Point(o.x,o.y).lerp(new T.Point(h[1],h[2]),a)).angle=Math.atan2(h[2]-o.y,h[1]-o.x),s;case"C":case"Q":return function(t,e){for(var i,n,s,o=0,a=0,l=t.iterator,h={x:t.x,y:t.y},c=.01,d=t.angleFinder;a<e&&c>1e-4;)i=l(o),s=o,(n=r(h.x,h.y,i.x,i.y))+a>e?(o-=c,c/=2):(h=i,o+=c,a+=n);return i.angle=d(s),i}(o,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),n={},s=1;s<t.length-1;s+=2)n.x=t[s],n.y=t[s+1],n=T.util.transformPoint(n,e),i[s]=n.x,i[s+1]=n.y;return i})}}(),function(){var t=Array.prototype.slice;function e(t,e,i){if(t&&0!==t.length){var n=t.length-1,s=e?t[n][e]:t[n];if(e)for(;n--;)i(t[n][e],s)&&(s=t[n][e]);else for(;n--;)i(t[n],s)&&(s=t[n]);return s}}T.util.array={fill:function(t,e){for(var i=t.length;i--;)t[i]=e;return t},invoke:function(e,i){for(var n=t.call(arguments,2),s=[],o=0,r=e.length;o<r;o++)s[o]=n.length?e[o][i].apply(e[o],n):e[o][i].call(e[o]);return s},min:function(t,i){return e(t,i,function(t,e){return t<e})},max:function(t,i){return e(t,i,function(t,e){return t>=e})}}}(),function(){function t(e,i,n){if(n)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var s=0,o=i.length;s<o;s++)e[s]=t({},i[s],n)}else if(i&&"object"==typeof i)for(var r in i)"canvas"===r||"group"===r?e[r]=null:i.hasOwnProperty(r)&&(e[r]=t({},i[r],n));else e=i;else for(var r in i)e[r]=i[r];return e}T.util.object={extend:t,clone:function(e,i){return t({},e,i)}},T.util.object.extend(T.util,T.Observable)}(),function(){function t(t,e){var i=t.charCodeAt(e);if(isNaN(i))return"";if(i<55296||i>57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>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 s=t.charCodeAt(e-1);if(55296>s||s>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,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},graphemeSplit:function(e){var i,n=0,s=[];for(n=0;n<e.length;n++)!1!==(i=t(e,n))&&s.push(i);return s}}}(),function(){var t=Array.prototype.slice,e=function(){},i=function(){for(var t in{toString:1})if("toString"===t)return!1;return!0}(),n=function(t,e,n){for(var s in e)s in t.prototype&&"function"==typeof t.prototype[s]&&(e[s]+"").indexOf("callSuper")>-1?t.prototype[s]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var s=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return s}}(s):t.prototype[s]=e[s],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function s(){}function o(e){for(var i=null,n=this;n.constructor.superclass;){var s=n.constructor.superclass.prototype[e];if(n[e]!==s){i=s;break}n=n.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,r=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof r[0]&&(i=r.shift()),a.superclass=i,a.subclasses=[],i&&(s.prototype=i.prototype,a.prototype=new s,i.subclasses.push(a));for(var l=0,h=r.length;l<h;l++)n(a,r[l],i);return a.prototype.initialize||(a.prototype.initialize=e),a.prototype.constructor=a,a.prototype.callSuper=o,a}}(),h=!!T.document.createElement("div").attachEvent,c=["touchstart","touchmove","touchend"],T.util.addListener=function(t,e,i,n){t&&t.addEventListener(e,i,!h&&n)},T.util.removeListener=function(t,e,i,n){t&&t.removeEventListener(e,i,!h&&n)},T.util.getPointer=function(t){var e=t.target,i=T.util.getScrollLeftTop(e),n=function(t){var e=t.changedTouches;return e&&e[0]?e[0]:t}(t);return{x:n.clientX+i.left,y:n.clientY+i.top}},T.util.isTouchEvent=function(t){return c.indexOf(t.type)>-1||"touch"===t.pointerType},u="string"==typeof(d=T.document.createElement("div")).style.opacity,p="string"==typeof d.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,f=function(t){return t},u?f=function(t,e){return t.style.opacity=e,t}:p&&(f=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?f(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?f(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,s=Array.prototype.slice,o=function(t){return s.call(t,0)};try{t=o(T.document.childNodes)instanceof Array}catch(t){}function r(t,e){var i=T.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=T.document.documentElement,s=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=s.scrollLeft||n.scrollLeft||0,i=s.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(o=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,n="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),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"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=o,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=r,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=r(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=a,T.util.getElementOffset=function(t){var i,n,s=t&&t.ownerDocument,o={left:0,top:0},r={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!s)return r;for(var h in l)r[l[h]]+=parseInt(e(t,h),10)||0;return i=s.documentElement,void 0!==t.getBoundingClientRect&&(o=t.getBoundingClientRect()),n=a(t),{left:o.left+n.left-(i.clientLeft||0)+r.left,top:o.top+n.top-(i.clientTop||0)+r.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 n=i.method?i.method.toUpperCase():"GET",s=i.onComplete||function(){},o=new T.window.XMLHttpRequest,r=i.body||i.parameters;return o.onreadystatechange=function(){4===o.readyState&&(s(o),o.onreadystatechange=t)},"GET"===n&&(r=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),o.open(n,e,!0),"POST"!==n&&"PUT"!==n||o.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),o.send(r),o}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function n(){return!1}function s(t,e,i,n){return-i*Math.cos(t/n*(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 o=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},r=T.window.cancelAnimationFrame||T.window.clearTimeout;function a(){return o.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var o,r=!1,l=function(){var t=T.runningAnimations.indexOf(o);return t>-1&&T.runningAnimations.splice(t,1)[0]};return o=t(e(i),{cancel:function(){return r=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(o),a(function(t){var e,h=t||+new Date,c=i.duration||500,d=h+c,u=i.onChange||n,p=i.abort||n,g=i.onComplete||n,f=i.easing||s,m="startValue"in i&&i.startValue.length>0,v="startValue"in i?i.startValue:0,y="endValue"in i?i.endValue:100,x=i.byValue||(m?v.map(function(t,e){return y[e]-v[e]}):y-v);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>d?c:e-h,s=n/c,w=m?v.map(function(t,e){return f(n,v[e],x[e],c)}):f(n,v,x,c),C=m?Math.abs((w[0]-v[0])/x[0]):Math.abs((w-v)/x);if(o.currentValue=m?w.slice():w,o.completionRate=C,o.durationRate=s,!r){if(!p(w,C,s))return e>d?(o.currentValue=m?y.slice():y,o.completionRate=1,o.durationRate=1,u(m?y.slice():y,1,1),g(y,1,1),void l()):(u(w,C,s),void a(t));l()}}(h)}),o.cancel},T.util.requestAnimFrame=a,T.util.cancelAnimFrame=function(){return r.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var n="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(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,n,s){var o=new T.Color(e).getSource(),r=new T.Color(i).getSource(),a=s.onComplete,l=s.onChange;return s=s||{},T.util.animate(T.util.object.extend(s,{duration:n||500,startValue:o,endValue:r,byValue:r,easing:function(e,i,n,o){return t(i,n,s.colorEasing?s.colorEasing(e,o):1-Math.cos(e/o*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(r,r,0),i,n)},onChange:function(e,i,n){if(l){if(Array.isArray(e))return l(t(e,e,0),i,n);l(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t<Math.abs(e)?(t=e,n=i/4):n=0===e&&0===t?i/(2*Math.PI)*Math.asin(1):i/(2*Math.PI)*Math.asin(e/t),{a:t,c:e,p:i,s:n}}function e(t,e,i){return t.a*Math.pow(2,10*(e-=1))*Math.sin((e*i-t.s)*(2*Math.PI)/t.p)}function i(t,e,i,s){return i-n(s-t,0,i,s)+e}function n(t,e,i,n){return(t/=n)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e}T.util.ease={easeInQuad:function(t,e,i,n){return i*(t/=n)*t+e},easeOutQuad:function(t,e,i,n){return-i*(t/=n)*(t-2)+e},easeInOutQuad:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,n){return i*(t/=n)*t*t+e},easeOutCubic:function(t,e,i,n){return i*((t=t/n-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,n){return i*(t/=n)*t*t*t+e},easeOutQuart:function(t,e,i,n){return-i*((t=t/n-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,n){return i*(t/=n)*t*t*t*t+e},easeOutQuint:function(t,e,i,n){return i*((t=t/n-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,n){return i*Math.sin(t/n*(Math.PI/2))+e},easeInOutSine:function(t,e,i,n){return-i/2*(Math.cos(Math.PI*t/n)-1)+e},easeInExpo:function(t,e,i,n){return 0===t?e:i*Math.pow(2,10*(t/n-1))+e},easeOutExpo:function(t,e,i,n){return t===n?e+i:i*(1-Math.pow(2,-10*t/n))+e},easeInOutExpo:function(t,e,i,n){return 0===t?e:t===n?e+i:(t/=n/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,n){return-i*(Math.sqrt(1-(t/=n)*t)-1)+e},easeOutCirc:function(t,e,i,n){return i*Math.sqrt(1-(t=t/n-1)*t)+e},easeInOutCirc:function(t,e,i,n){return(t/=n/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(i,n,s,o){var r=0;return 0===i?n:1==(i/=o)?n+s:(r||(r=.3*o),-e(t(s,s,r,1.70158),i,o)+n)},easeOutElastic:function(e,i,n,s){var o=0;if(0===e)return i;if(1==(e/=s))return i+n;o||(o=.3*s);var r=t(n,n,o,1.70158);return r.a*Math.pow(2,-10*e)*Math.sin((e*s-r.s)*(2*Math.PI)/r.p)+r.c+i},easeInOutElastic:function(i,n,s,o){var r=0;if(0===i)return n;if(2==(i/=o/2))return n+s;r||(r=o*(.3*1.5));var a=t(s,s,r,1.70158);return i<1?-.5*e(a,i,o)+n:a.a*Math.pow(2,-10*(i-=1))*Math.sin((i*o-a.s)*(2*Math.PI)/a.p)*.5+a.c+n},easeInBack:function(t,e,i,n,s){return void 0===s&&(s=1.70158),i*(t/=n)*t*((s+1)*t-s)+e},easeOutBack:function(t,e,i,n,s){return void 0===s&&(s=1.70158),i*((t=t/n-1)*t*((s+1)*t+s)+1)+e},easeInOutBack:function(t,e,i,n,s){return void 0===s&&(s=1.70158),(t/=n/2)<1?i/2*(t*t*((1+(s*=1.525))*t-s))+e:i/2*((t-=2)*t*((1+(s*=1.525))*t+s)+2)+e},easeInBounce:i,easeOutBounce:n,easeInOutBounce:function(t,e,s,o){return t<o/2?.5*i(2*t,0,s,o)+e:.5*n(2*t-o,0,s,o)+.5*s+e}}}(),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,s=e.util.toFixed,o=e.util.parseUnit,r=e.util.multiplyTransformMatrices,a={cx:"left",x:"left",r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing"},l={stroke:"strokeOpacity",fill:"fillOpacity"},h="font-size",c="clip-path";function d(t){return t in a?a[t]:t}function u(t,i,n,s){var a,l=Array.isArray(i);if("fill"!==t&&"stroke"!==t||"none"!==i){if("strokeUniform"===t)return"non-scaling-stroke"===i;if("strokeDashArray"===t)i="none"===i?null:i.replace(/,/g," ").split(/\s+/).map(parseFloat);else if("transformMatrix"===t)i=n&&n.transformMatrix?r(n.transformMatrix,e.parseTransformAttribute(i)):e.parseTransformAttribute(i);else if("visible"===t)i="none"!==i&&"hidden"!==i,n&&!1===n.visible&&(i=!1);else if("opacity"===t)i=parseFloat(i),n&&void 0!==n.opacity&&(i*=n.opacity);else if("textAnchor"===t)i="start"===i?"left":"end"===i?"right":"center";else if("charSpacing"===t)a=o(i,s)/s*1e3;else if("paintFirst"===t){var h=i.indexOf("fill"),c=i.indexOf("stroke");i="fill",(h>-1&&c>-1&&c<h||-1===h&&c>-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=l?i.map(o):o(i,s)}}else i="";return!l&&isNaN(a)?i:a}function p(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,s,o,r=[];for(s=0,o=e.length;s<o;s++)i=e[s],n=t.getElementsByTagName(i),r=r.concat(Array.prototype.slice.call(n));return r}function f(t,e){var i,n=!0;return(i=m(t,e.pop()))&&e.length&&(n=function(t,e){for(var i,n=!0;t.parentNode&&1===t.parentNode.nodeType&&e.length;)n&&(i=e.pop()),n=m(t=t.parentNode,i);return 0===e.length}(t,e)),i&&n&&0===e.length}function m(t,e){var i,n,s=t.nodeName,o=t.getAttribute("class"),r=t.getAttribute("id");if(i=new RegExp("^"+s,"i"),e=e.replace(i,""),r&&e.length&&(i=new RegExp("#"+r+"(?![a-zA-Z\\-]+)","i"),e=e.replace(i,"")),o&&e.length)for(n=(o=o.split(" ")).length;n--;)i=new RegExp("\\."+o[n]+"(?![a-zA-Z\\-]+)","i"),e=e.replace(i,"");return 0===e.length}function v(t,e){var i;if(t.getElementById&&(i=t.getElementById(e)),i)return i;var n,s,o,r=t.getElementsByTagName("*");for(s=0,o=r.length;s<o;s++)if(e===(n=r[s]).getAttribute("id"))return n}e.svgValidTagNamesRegEx=p(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),e.svgViewBoxElementsRegEx=p(["symbol","image","marker","pattern","view","svg"]),e.svgInvalidAncestorsRegEx=p(["pattern","defs","symbol","metadata","clipPath","mask","desc"]),e.svgValidParentsRegEx=p(["symbol","g","a","svg","clipPath","defs"]),e.cssRules={},e.gradientDefs={},e.clipPaths={},e.parseTransformAttribute=function(){function t(t,i,n){t[n]=Math.tan(e.util.degreesToRadians(i[0]))}var i=e.iMatrix,n=e.reNum,s=e.commaWsp,o="(?:(?:(matrix)\\s*\\(\\s*("+n+")"+s+"("+n+")"+s+"("+n+")"+s+"("+n+")"+s+"("+n+")"+s+"("+n+")\\s*\\))|(?:(translate)\\s*\\(\\s*("+n+")(?:"+s+"("+n+"))?\\s*\\))|(?:(scale)\\s*\\(\\s*("+n+")(?:"+s+"("+n+"))?\\s*\\))|(?:(rotate)\\s*\\(\\s*("+n+")(?:"+s+"("+n+")"+s+"("+n+"))?\\s*\\))|(?:(skewX)\\s*\\(\\s*("+n+")\\s*\\))|(?:(skewY)\\s*\\(\\s*("+n+")\\s*\\)))",r=new RegExp("^\\s*(?:(?:"+o+"(?:"+s+"*"+o+")*)?)\\s*$"),a=new RegExp(o,"g");return function(n){var s=i.concat(),l=[];if(!n||n&&!r.test(n))return s;n.replace(a,function(n){var r=new RegExp(o).exec(n).filter(function(t){return!!t}),a=r[1],h=r.slice(2).map(parseFloat);switch(a){case"translate":!function(t,e){t[4]=e[0],2===e.length&&(t[5]=e[1])}(s,h);break;case"rotate":h[0]=e.util.degreesToRadians(h[0]),function(t,i){var n=e.util.cos(i[0]),s=e.util.sin(i[0]),o=0,r=0;3===i.length&&(o=i[1],r=i[2]),t[0]=n,t[1]=s,t[2]=-s,t[3]=n,t[4]=o-(n*o-s*r),t[5]=r-(s*o+n*r)}(s,h);break;case"scale":!function(t,e){var i=e[0],n=2===e.length?e[1]:e[0];t[0]=i,t[3]=n}(s,h);break;case"skewX":t(s,h,2);break;case"skewY":t(s,h,1);break;case"matrix":s=h}l.push(s.concat()),s=i.concat()});for(var h=l[0];l.length>1;)l.shift(),h=e.util.multiplyTransformMatrices(h,l[0]);return h}}();var y=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function x(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,s,r,a,l,h=t.getAttribute("viewBox"),c=1,d=1,u=t.getAttribute("width"),p=t.getAttribute("height"),g=t.getAttribute("x")||0,f=t.getAttribute("y")||0,m=t.getAttribute("preserveAspectRatio")||"",v=!h||!(h=h.match(y)),x=!u||!p||"100%"===u||"100%"===p,w=v&&x,C={},b="",S=0,T=0;if(C.width=0,C.height=0,C.toBeParsed=w,v&&(g||f)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(b=" translate("+o(g)+" "+o(f)+") ",a=(t.getAttribute("transform")||"")+b,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(v)return C.width=o(u),C.height=o(p),C;if(i=-parseFloat(h[1]),n=-parseFloat(h[2]),s=parseFloat(h[3]),r=parseFloat(h[4]),C.minX=i,C.minY=n,C.viewBoxWidth=s,C.viewBoxHeight=r,x?(C.width=s,C.height=r):(C.width=o(u),C.height=o(p),c=C.width/s,d=C.height/r),"none"!==(m=e.util.parsePreserveAspectRatioAttribute(m)).alignX&&("meet"===m.meetOrSlice&&(d=c=c>d?d:c),"slice"===m.meetOrSlice&&(d=c=c>d?c:d),S=C.width-s*c,T=C.height-r*c,"Mid"===m.alignX&&(S/=2),"Mid"===m.alignY&&(T/=2),"Min"===m.alignX&&(S=0),"Min"===m.alignY&&(T=0)),1===c&&1===d&&0===i&&0===n&&0===g&&0===f)return C;if((g||f)&&"#document"!==t.parentNode.nodeName&&(b=" translate("+o(g)+" "+o(f)+") "),a=b+" matrix("+c+" 0 0 "+d+" "+(i*c+S)+" "+(n*d+T)+") ","svg"===t.nodeName){for(l=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)l.appendChild(t.firstChild);t.appendChild(l)}else(l=t).removeAttribute("x"),l.removeAttribute("y"),a=l.getAttribute("transform")+a;return l.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",n=v(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach(function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))}),!e.children.length)for(var s=n.cloneNode(!0);s.firstChild;)e.appendChild(s.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,s,o){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&n<i.length;){var s=i[n],o=s.getAttribute("xlink:href")||s.getAttribute("href");if(null===o)return;var r,a,l,h,c=o.slice(1),d=s.getAttribute("x")||0,u=s.getAttribute("y")||0,p=v(t,c).cloneNode(!0),f=(p.getAttribute("transform")||"")+" translate("+d+", "+u+")",m=i.length,y=e.svgNS;if(x(p),/^svg$/i.test(p.nodeName)){var w=p.ownerDocument.createElementNS(y,"g");for(a=0,h=(l=p.attributes).length;a<h;a++)r=l.item(a),w.setAttributeNS(y,r.nodeName,r.nodeValue);for(;p.firstChild;)w.appendChild(p.firstChild);p=w}for(a=0,h=(l=s.attributes).length;a<h;a++)"x"!==(r=l.item(a)).nodeName&&"y"!==r.nodeName&&"xlink:href"!==r.nodeName&&"href"!==r.nodeName&&("transform"===r.nodeName?f=r.nodeValue+" "+f:p.setAttribute(r.nodeName,r.nodeValue));p.setAttribute("transform",f),p.setAttribute("instantiated_by_use","1"),p.removeAttribute("id"),s.parentNode.replaceChild(p,s),i.length===m&&n++}}(t);var r,a,l=e.Object.__uid++,h=x(t),c=e.util.toArray(t.getElementsByTagName("*"));if(h.crossOrigin=o&&o.crossOrigin,h.svgUid=l,0===c.length&&e.isLikelyNode){var d=[];for(r=0,a=(c=t.selectNodes('//*[name(.)!="svg"]')).length;r<a;r++)d[r]=c[r];c=d}var u=c.filter(function(t){return x(t),e.svgValidTagNamesRegEx.test(t.nodeName.replace("svg:",""))&&!function(t,e){for(;t&&(t=t.parentNode);)if(t.nodeName&&e.test(t.nodeName.replace("svg:",""))&&!t.getAttribute("instantiated_by_use"))return!0;return!1}(t,e.svgInvalidAncestorsRegEx)});if(!u||u&&!u.length)i&&i([],{});else{var p={};c.filter(function(t){return"clipPath"===t.nodeName.replace("svg:","")}).forEach(function(t){var i=t.getAttribute("id");p[i]=e.util.toArray(t.getElementsByTagName("*")).filter(function(t){return e.svgValidTagNamesRegEx.test(t.nodeName.replace("svg:",""))})}),e.gradientDefs[l]=e.getGradientDefs(t),e.cssRules[l]=e.getCSSRules(t),e.clipPaths[l]=p,e.parseElements(u,function(t,n){i&&(i(t,h,n,c),delete e.gradientDefs[l],delete e.cssRules[l],delete e.clipPaths[l])},n(h),s,o)}}};var C=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+e.reNum+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+e.reNum+"))?\\s+(.*)");i(e,{parseFontDeclaration:function(t,e){var i=t.match(C);if(i){var n=i[1],s=i[3],r=i[4],a=i[5],l=i[6];n&&(e.fontStyle=n),s&&(e.fontWeight=isNaN(parseFloat(s))?s:parseFloat(s)),r&&(e.fontSize=o(r)),l&&(e.fontFamily=l),a&&(e.lineHeight="normal"===a?1:a)}},getGradientDefs:function(t){var e,i=g(t,["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"]),n=0,s={};for(n=i.length;n--;)(e=i[n]).getAttribute("xlink:href")&&w(t,e),s[e.getAttribute("id")]=e;return s},parseAttributes:function(t,n,r){if(t){var a,p,g,m={};void 0===r&&(r=t.getAttribute("svgUid")),t.parentNode&&e.svgValidParentsRegEx.test(t.parentNode.nodeName)&&(m=e.parseAttributes(t.parentNode,n,r));var v=n.reduce(function(e,i){return(a=t.getAttribute(i))&&(e[i]=a),e},{}),y=i(function(t,i){var n={};for(var s in e.cssRules[i])if(f(t,s.split(" ")))for(var o in e.cssRules[i][s])n[o]=e.cssRules[i][s][o];return n}(t,r),e.parseStyleAttribute(t));v=i(v,y),y[c]&&t.setAttribute(c,y[c]),p=g=m.fontSize||e.Text.DEFAULT_SVG_FONT_SIZE,v[h]&&(v[h]=p=o(v[h],g));var x,w,C={};for(var b in v)w=u(x=d(b),v[b],m,p),C[x]=w;C&&C.font&&e.parseFontDeclaration(C.font,C);var S=i(m,C);return e.svgValidParentsRegEx.test(t.nodeName)?S:function(t){for(var i in l)if(void 0!==t[l[i]]&&""!==t[i]){if(void 0===t[i]){if(!e.Object.prototype[i])continue;t[i]=e.Object.prototype[i]}if(0!==t[i].indexOf("url(")){var n=new e.Color(t[i]);t[i]=n.setAlpha(s(n.getAlpha()*t[l[i]],2)).toRgba()}}return t}(S)}},parseElements:function(t,i,n,s,o){new e.ElementsParser(t,i,n,s,o).parse()},parseStyleAttribute:function(t){var e={},i=t.getAttribute("style");return i?("string"==typeof i?function(t,e){var i,n;t.replace(/;\s*$/,"").split(";").forEach(function(t){var s=t.split(":");i=s[0].trim().toLowerCase(),n=s[1].trim(),e[i]=n})}(i,e):function(t,e){var i,n;for(var s in t)void 0!==t[s]&&(i=s.toLowerCase(),n=t[s],e[i]=n)}(i,e),e):e},parsePointsAttribute:function(t){if(!t)return null;var e,i,n=[];for(e=0,i=(t=(t=t.replace(/,/g," ").trim()).split(/\s+/)).length;e<i;e+=2)n.push({x:parseFloat(t[e]),y:parseFloat(t[e+1])});return n},getCSSRules:function(t){var i,n,s=t.getElementsByTagName("style"),o={};for(i=0,n=s.length;i<n;i++){var r=s[i].textContent;""!==(r=r.replace(/\/\*[\s\S]*?\*\//g,"")).trim()&&r.split("}").filter(function(t){return t.trim()}).forEach(function(t){var s=t.split("{"),r={},a=s[1].trim().split(";").filter(function(t){return t.trim()});for(i=0,n=a.length;i<n;i++){var l=a[i].split(":"),h=l[0].trim(),c=l[1].trim();r[h]=c}(t=s[0].trim()).split(",").forEach(function(t){""!==(t=t.replace(/^svg/i,"").trim())&&(o[t]?e.util.object.extend(o[t],r):o[t]=e.util.object.clone(r))})})}return o},loadSVGFromURL:function(t,i,n,s){t=t.replace(/^\n\s*/,"").trim(),new e.util.request(t,{method:"get",onComplete:function(t){var o=t.responseXML;if(!o||!o.documentElement)return i&&i(null),!1;e.parseSVGDocument(o.documentElement,function(t,e,n,s){i&&i(t,e,n,s)},n,s)}})},loadSVGFromString:function(t,i,n,s){var o=(new e.window.DOMParser).parseFromString(t.trim(),"text/xml");e.parseSVGDocument(o.documentElement,function(t,e,n,s){i(t,e,n,s)},n,s)}})}(e),T.ElementsParser=function(t,e,i,n,s,o){this.elements=t,this.callback=e,this.options=i,this.reviver=n,this.svgUid=i&&i.svgUid||0,this.parsingOptions=s,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=o},(m=T.ElementsParser.prototype).parse=function(){this.instances=new Array(this.elements.length),this.numElements=this.elements.length,this.createObjects()},m.createObjects=function(){var t=this;this.elements.forEach(function(e,i){e.setAttribute("svgUid",t.svgUid),t.createObject(e,i)})},m.findTag=function(t){return T[T.util.string.capitalize(t.tagName.replace("svg:",""))]},m.createObject=function(t,e){var i=this.findTag(t);if(i&&i.fromElement)try{i.fromElement(t,this.createCallback(e,t),this.options)}catch(t){T.log(t)}else this.checkIfDone()},m.createCallback=function(t,e){var i=this;return function(n){var s;i.resolveGradient(n,e,"fill"),i.resolveGradient(n,e,"stroke"),n instanceof T.Image&&n._originalElement&&(s=n.parsePreserveAspectRatioAttribute(e)),n._removeTransformMatrix(s),i.resolveClipPath(n,e),i.reviver&&i.reviver(e,n),i.instances[t]=n,i.checkIfDone()}},m.extractPropertyDefinition=function(t,e,i){var n=t[e],s=this.regexUrl;if(s.test(n)){s.lastIndex=0;var o=s.exec(n)[1];return s.lastIndex=0,T[i][this.svgUid][o]}},m.resolveGradient=function(t,e,i){var n=this.extractPropertyDefinition(t,i,"gradientDefs");if(n){var s=e.getAttribute(i+"-opacity"),o=T.Gradient.fromElement(n,t,s,this.options);t.set(i,o)}},m.createClipPathCallback=function(t,e){return function(t){t._removeTransformMatrix(),t.fillRule=t.clipRule,e.push(t)}},m.resolveClipPath=function(t,e){var i,n,s,o,r=this.extractPropertyDefinition(t,"clipPath","clipPaths");if(r){s=[],n=T.util.invertTransform(t.calcTransformMatrix());for(var a=r[0].parentNode,l=e;l.parentNode&&l.getAttribute("clip-path")!==t.clipPath;)l=l.parentNode;l.parentNode.appendChild(a);for(var h=0;h<r.length;h++)i=r[h],this.findTag(i).fromElement(i,this.createClipPathCallback(t,s),this.options);r=1===s.length?s[0]:new T.Group(s),o=T.util.multiplyTransformMatrices(n,r.calcTransformMatrix()),r.clipPath&&this.resolveClipPath(r,l);var c=T.util.qrDecompose(o);r.flipX=!1,r.flipY=!1,r.set("scaleX",c.scaleX),r.set("scaleY",c.scaleY),r.angle=c.angle,r.skewX=c.skewX,r.skewY=0,r.setPositionByOrigin({x:c.translateX,y:c.translateY},"center","center"),t.clipPath=r}else delete t.clipPath},m.checkIfDone=function(){0==--this.numElements&&(this.instances=this.instances.filter(function(t){return null!=t}),this.callback(this.instances,this.elements))},function(t){var e=t.fabric||(t.fabric={});function i(t,e){this.x=t,this.y=e}e.Point?e.warn("fabric.Point is already defined"):(e.Point=i,i.prototype={type:"point",constructor:i,add:function(t){return new i(this.x+t.x,this.y+t.y)},addEquals:function(t){return this.x+=t.x,this.y+=t.y,this},scalarAdd:function(t){return new i(this.x+t,this.y+t)},scalarAddEquals:function(t){return this.x+=t,this.y+=t,this},subtract:function(t){return new i(this.x-t.x,this.y-t.y)},subtractEquals:function(t){return this.x-=t.x,this.y-=t.y,this},scalarSubtract:function(t){return new i(this.x-t,this.y-t)},scalarSubtractEquals:function(t){return this.x-=t,this.y-=t,this},multiply:function(t){return new i(this.x*t,this.y*t)},multiplyEquals:function(t){return this.x*=t,this.y*=t,this},divide:function(t){return new i(this.x/t,this.y/t)},divideEquals:function(t){return this.x/=t,this.y/=t,this},eq:function(t){return this.x===t.x&&this.y===t.y},lt:function(t){return this.x<t.x&&this.y<t.y},lte:function(t){return this.x<=t.x&&this.y<=t.y},gt:function(t){return this.x>t.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,n,s,o){var r,a=(o.x-s.x)*(t.y-s.y)-(o.y-s.y)*(t.x-s.x),l=(n.x-t.x)*(t.y-s.y)-(n.y-t.y)*(t.x-s.x),h=(o.y-s.y)*(n.x-t.x)-(o.x-s.x)*(n.y-t.y);if(0!==h){var c=a/h,d=l/h;0<=c&&c<=1&&0<=d&&d<=1?(r=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):r=new i}else r=new i(0===a||0===l?"Coincident":"Parallel");return r},e.Intersection.intersectLinePolygon=function(t,e,n){var s,o,r,a,l=new i,h=n.length;for(a=0;a<h;a++)s=n[a],o=n[(a+1)%h],r=i.intersectLineLine(t,e,s,o),l.appendPoints(r.points);return l.points.length>0&&(l.status="Intersection"),l},e.Intersection.intersectPolygonPolygon=function(t,e){var n,s=new i,o=t.length;for(n=0;n<o;n++){var r=t[n],a=t[(n+1)%o],l=i.intersectLinePolygon(r,a,e);s.appendPoints(l.points)}return s.points.length>0&&(s.status="Intersection"),s},e.Intersection.intersectPolygonRectangle=function(t,n,s){var o=n.min(s),r=n.max(s),a=new e.Point(r.x,o.y),l=new e.Point(o.x,r.y),h=i.intersectLinePolygon(o,a,t),c=i.intersectLinePolygon(a,r,t),d=i.intersectLinePolygon(r,l,t),u=i.intersectLinePolygon(l,o,t),p=new i;return p.appendPoints(h.points),p.appendPoints(c.points),p.appendPoints(d.points),p.appendPoints(u.points),p.points.length>0&&(p.status="Intersection"),p})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(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,n){t/=255,i/=255,n/=255;var s,o,r,a=e.util.array.max([t,i,n]),l=e.util.array.min([t,i,n]);if(r=(a+l)/2,a===l)s=o=0;else{var h=a-l;switch(o=r>.5?h/(2-a-l):h/(a+l),a){case t:s=(i-n)/h+(i<n?6:0);break;case i:s=(n-t)/h+2;break;case n:s=(t-i)/h+4}s/=6}return[Math.round(360*s),Math.round(100*o),Math.round(100*r)]},getSource:function(){return this._source},setSource:function(t){this._source=t},toRgb:function(){var t=this.getSource();return"rgb("+t[0]+","+t[1]+","+t[2]+")"},toRgba:function(){var t=this.getSource();return"rgba("+t[0]+","+t[1]+","+t[2]+","+t[3]+")"},toHsl:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsl("+e[0]+","+e[1]+"%,"+e[2]+"%)"},toHsla:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsla("+e[0]+","+e[1]+"%,"+e[2]+"%,"+t[3]+")"},toHex:function(){var t,e,i,n=this.getSource();return t=1===(t=n[0].toString(16)).length?"0"+t:t,e=1===(e=n[1].toString(16)).length?"0"+e:e,i=1===(i=n[2].toString(16)).length?"0"+i:i,t.toUpperCase()+e.toUpperCase()+i.toUpperCase()},toHexa:function(){var t,e=this.getSource();return t=1===(t=(t=Math.round(255*e[3])).toString(16)).length?"0"+t:t,this.toHex()+t.toUpperCase()},getAlpha:function(){return this.getSource()[3]},setAlpha:function(t){var e=this.getSource();return e[3]=t,this.setSource(e),this},toGrayscale:function(){var t=this.getSource(),e=parseInt((.3*t[0]+.59*t[1]+.11*t[2]).toFixed(0),10),i=t[3];return this.setSource([e,e,e,i]),this},toBlackWhite:function(t){var e=this.getSource(),i=(.3*e[0]+.59*e[1]+.11*e[2]).toFixed(0),n=e[3];return t=t||127,i=Number(i)<Number(t)?0:255,this.setSource([i,i,i,n]),this},overlayWith:function(t){t instanceof i||(t=new i(t));var e,n=[],s=this.getAlpha(),o=this.getSource(),r=t.getSource();for(e=0;e<3;e++)n.push(Math.round(.5*o[e]+.5*r[e]));return n[3]=s,this.setSource(n),this}},e.Color.reRGBa=/^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*((?:\d*\.?\d+)?)\s*)?\)$/i,e.Color.reHSLa=/^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/i,e.Color.reHex=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,e.Color.colorNameMap={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#00FFFF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",blue:"#0000FF",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#00FFFF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",darkgreen:"#006400",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#FF00FF",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",lightgreen:"#90EE90",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#00FF00",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#663399",red:"#FF0000",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFFFFF",whitesmoke:"#F5F5F5",yellow:"#FFFF00",yellowgreen:"#9ACD32"},e.Color.fromRgb=function(t){return i.fromSource(i.sourceFromRgb(t))},e.Color.sourceFromRgb=function(t){var e=t.match(i.reRGBa);if(e){var n=parseInt(e[1],10)/(/%$/.test(e[1])?100:1)*(/%$/.test(e[1])?255:1),s=parseInt(e[2],10)/(/%$/.test(e[2])?100:1)*(/%$/.test(e[2])?255:1),o=parseInt(e[3],10)/(/%$/.test(e[3])?100:1)*(/%$/.test(e[3])?255:1);return[parseInt(n,10),parseInt(s,10),parseInt(o,10),e[4]?parseFloat(e[4]):1]}},e.Color.fromRgba=i.fromRgb,e.Color.fromHsl=function(t){return i.fromSource(i.sourceFromHsl(t))},e.Color.sourceFromHsl=function(t){var e=t.match(i.reHSLa);if(e){var s,o,r,a=(parseFloat(e[1])%360+360)%360/360,l=parseFloat(e[2])/(/%$/.test(e[2])?100:1),h=parseFloat(e[3])/(/%$/.test(e[3])?100:1);if(0===l)s=o=r=h;else{var c=h<=.5?h*(l+1):h+l-h*l,d=2*h-c;s=n(d,c,a+1/3),o=n(d,c,a),r=n(d,c,a-1/3)}return[Math.round(255*s),Math.round(255*o),Math.round(255*r),e[4]?parseFloat(e[4]):1]}},e.Color.fromHsla=i.fromHsl,e.Color.fromHex=function(t){return i.fromSource(i.sourceFromHex(t))},e.Color.sourceFromHex=function(t){if(t.match(i.reHex)){var e=t.slice(t.indexOf("#")+1),n=3===e.length||4===e.length,s=8===e.length||4===e.length,o=n?e.charAt(0)+e.charAt(0):e.substring(0,2),r=n?e.charAt(1)+e.charAt(1):e.substring(2,4),a=n?e.charAt(2)+e.charAt(2):e.substring(4,6),l=s?n?e.charAt(3)+e.charAt(3):e.substring(6,8):"FF";return[parseInt(o,16),parseInt(r,16),parseInt(a,16),parseFloat((parseInt(l,16)/255).toFixed(2))]}},e.Color.fromSource=function(t){var e=new i;return e.setSource(t),e})}(e),function(t){var e=t.fabric||(t.fabric={}),i=["e","se","s","sw","w","nw","n","ne","e"],n=["ns","nesw","ew","nwse"],s={},o="left",r="top",a="right",l="bottom",h="center",c={top:l,bottom:r,left:a,right:o,center:h},d=e.util.radiansToDegrees,u=Math.sign||function(t){return(t>0)-(t<0)||+t};function p(t,e){var i=t.angle+d(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,s=n.canvas,o=e.util.object.clone(i);o.target=n,s&&s.fire("object:"+t,o),n.fire(t,i)}function f(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function m(t){return t.originX===h&&t.originY===h}function v(t,e,i){var n=t.lockScalingX,s=t.lockScalingY;return!((!n||!s)&&(e||!n&&!s||!i)&&(!n||"x"!==e)&&(!s||"y"!==e))}function y(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function x(t){return function(e,i,n,s){var o=i.target,r=o.getCenterPoint(),a=o.translateToOriginPoint(r,i.originX,i.originY),l=t(e,i,n,s);return o.setPositionByOrigin(a,i.originX,i.originY),l}}function w(t,e){return function(i,n,s,o){var r=e(i,n,s,o);return r&&g(t,y(i,n,s,o)),r}}function C(t,i,n,s,o){var r=t.target,a=r.controls[t.corner],l=r.canvas.getZoom(),h=r.padding/l,c=r.toLocalPoint(new e.Point(s,o),i,n);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=a.offsetX,c.y-=a.offsetY,c}function b(t){return t.flipX!==t.flipY}function S(t,e,i,n,s){if(0!==t[e]){var o=s/t._getTransformedDimensions()[n]*t[i];t.set(i,o)}}function T(t,e,i,n){var s,h=e.target,c=h._getTransformedDimensions(0,h.skewY),u=C(e,e.originX,e.originY,i,n),p=Math.abs(2*u.x)-c.x,g=h.skewX;p<2?s=0:(s=d(Math.atan2(p/h.scaleX,c.y/h.scaleY)),e.originX===o&&e.originY===l&&(s=-s),e.originX===a&&e.originY===r&&(s=-s),b(h)&&(s=-s));var f=g!==s;if(f){var m=h._getTransformedDimensions().y;h.set("skewX",s),S(h,"skewY","scaleY","y",m)}return f}function E(t,e,i,n){var s,h=e.target,c=h._getTransformedDimensions(h.skewX,0),u=C(e,e.originX,e.originY,i,n),p=Math.abs(2*u.y)-c.y,g=h.skewY;p<2?s=0:(s=d(Math.atan2(p/h.scaleY,c.x/h.scaleX)),e.originX===o&&e.originY===l&&(s=-s),e.originX===a&&e.originY===r&&(s=-s),b(h)&&(s=-s));var f=g!==s;if(f){var m=h._getTransformedDimensions().x;h.set("skewY",s),S(h,"skewX","scaleX","x",m)}return f}function _(t,e,i,n,s){s=s||{};var o,r,a,l,h,d,p=e.target,g=p.lockScalingX,y=p.lockScalingY,x=s.by,w=f(t,p),b=v(p,x,w),S=e.gestureScale;if(b)return!1;if(S)r=e.scaleX*S,a=e.scaleY*S;else{if(o=C(e,e.originX,e.originY,i,n),h="y"!==x?u(o.x):1,d="x"!==x?u(o.y):1,e.signX||(e.signX=h),e.signY||(e.signY=d),p.lockScalingFlip&&(e.signX!==h||e.signY!==d))return!1;if(l=p._getTransformedDimensions(),w&&!x){var T=Math.abs(o.x)+Math.abs(o.y),E=e.original,_=T/(Math.abs(l.x*E.scaleX/p.scaleX)+Math.abs(l.y*E.scaleY/p.scaleY));r=E.scaleX*_,a=E.scaleY*_}else r=Math.abs(o.x*p.scaleX/l.x),a=Math.abs(o.y*p.scaleY/l.y);m(e)&&(r*=2,a*=2),e.signX!==h&&"y"!==x&&(e.originX=c[e.originX],r*=-1,e.signX=h),e.signY!==d&&"x"!==x&&(e.originY=c[e.originY],a*=-1,e.signY=d)}var P=p.scaleX,A=p.scaleY;return x?("x"===x&&p.set("scaleX",r),"y"===x&&p.set("scaleY",a)):(!g&&p.set("scaleX",r),!y&&p.set("scaleY",a)),P!==p.scaleX||A!==p.scaleY}s.scaleCursorStyleHandler=function(t,e,n){var s=f(t,n),o="";if(0!==e.x&&0===e.y?o="x":0===e.x&&0!==e.y&&(o="y"),v(n,o,s))return"not-allowed";var r=p(n,e);return i[r]+"-resize"},s.skewCursorStyleHandler=function(t,e,i){var s="not-allowed";if(0!==e.x&&i.lockSkewingY)return s;if(0!==e.y&&i.lockSkewingX)return s;var o=p(i,e)%4;return n[o]+"-resize"},s.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?s.skewCursorStyleHandler(t,e,i):s.scaleCursorStyleHandler(t,e,i)},s.rotationWithSnapping=w("rotating",x(function(t,e,i,n){var s=e,o=s.target,r=o.translateToOriginPoint(o.getCenterPoint(),s.originX,s.originY);if(o.lockRotation)return!1;var a,l=Math.atan2(s.ey-r.y,s.ex-r.x),h=Math.atan2(n-r.y,i-r.x),c=d(h-l+s.theta);if(o.snapAngle>0){var u=o.snapAngle,p=o.snapThreshold||u,g=Math.ceil(c/u)*u,f=Math.floor(c/u)*u;Math.abs(c-f)<p?c=f:Math.abs(c-g)<p&&(c=g)}return c<0&&(c=360+c),c%=360,a=o.angle!==c,o.angle=c,a})),s.scalingEqually=w("scaling",x(function(t,e,i,n){return _(t,e,i,n)})),s.scalingX=w("scaling",x(function(t,e,i,n){return _(t,e,i,n,{by:"x"})})),s.scalingY=w("scaling",x(function(t,e,i,n){return _(t,e,i,n,{by:"y"})})),s.scalingYOrSkewingX=function(t,e,i,n){return t[e.target.canvas.altActionKey]?s.skewHandlerX(t,e,i,n):s.scalingY(t,e,i,n)},s.scalingXOrSkewingY=function(t,e,i,n){return t[e.target.canvas.altActionKey]?s.skewHandlerY(t,e,i,n):s.scalingX(t,e,i,n)},s.changeWidth=w("resizing",x(function(t,e,i,n){var s=e.target,o=C(e,e.originX,e.originY,i,n),r=s.strokeWidth/(s.strokeUniform?s.scaleX:1),a=m(e)?2:1,l=s.width,h=Math.abs(o.x*a/s.scaleX)-r;return s.set("width",Math.max(h,0)),l!==h})),s.skewHandlerX=function(t,e,i,n){var s,l=e.target,c=l.skewX,d=e.originY;return!l.lockSkewingX&&(0===c?s=C(e,h,h,i,n).x>0?o:a:(c>0&&(s=d===r?o:a),c<0&&(s=d===r?a:o),b(l)&&(s=s===o?a:o)),e.originX=s,w("skewing",x(T))(t,e,i,n))},s.skewHandlerY=function(t,e,i,n){var s,a=e.target,c=a.skewY,d=e.originX;return!a.lockSkewingY&&(0===c?s=C(e,h,h,i,n).y>0?r:l:(c>0&&(s=d===o?r:l),c<0&&(s=d===o?l:r),b(a)&&(s=s===r?l:r)),e.originY=s,w("skewing",x(E))(t,e,i,n))},s.dragHandler=function(t,e,i,n){var s=e.target,o=i-e.offsetX,r=n-e.offsetY,a=!s.get("lockMovementX")&&s.left!==o,l=!s.get("lockMovementY")&&s.top!==r;return a&&s.set("left",o),l&&s.set("top",r),(a||l)&&g("moving",y(t,e,i,n)),a||l},s.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},s.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},s.fireEvent=g,s.wrapWithFixedAnchor=x,s.wrapWithFireEvent=w,s.getLocalPoint=C,e.controlsUtils=s}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,s){n=n||{};var o,r=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||s.cornerStrokeColor),d=e,u=i;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,r>a?(o=r,t.scale(1,a/r),u=i*r/a):a>r?(o=a,t.scale(r/a,1),d=e*a/r):o=r,t.lineWidth=1,t.beginPath(),t.arc(d,u,o/2,0,2*Math.PI,!1),t[h](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,s,o){s=s||{};var r=this.sizeX||s.cornerSize||o.cornerSize,a=this.sizeY||s.cornerSize||o.cornerSize,l=void 0!==s.transparentCorners?s.transparentCorners:o.transparentCorners,h=l?"stroke":"fill",c=!l&&(s.cornerStrokeColor||o.cornerStrokeColor),d=r/2,u=a/2;t.save(),t.fillStyle=s.cornerColor||o.cornerColor,t.strokeStyle=s.cornerStrokeColor||o.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(o.angle)),t[h+"Rect"](-d,-u,r,a),c&&t.strokeRect(-d,-u,r,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,n,s,o){var r,a,l,h,c=o?this.touchSizeX:this.sizeX,d=o?this.touchSizeY:this.sizeY;if(c&&d&&c!==d){var u=Math.atan2(d,c),p=Math.sqrt(c*c+d*d)/2,g=u-e.util.degreesToRadians(t),f=Math.PI/2-u-e.util.degreesToRadians(t);r=p*e.util.cos(g),a=p*e.util.sin(g),l=p*e.util.cos(f),h=p*e.util.sin(f)}else p=.7071067812*(c&&d?c:i),g=e.util.degreesToRadians(45-t),r=l=p*e.util.cos(g),a=h=p*e.util.sin(g);return{tl:{x:n-h,y:s-l},tr:{x:n+r,y:s-a},bl:{x:n-r,y:s+a},br:{x:n+h,y:s+l}}},render:function(t,i,n,s,o){"circle"===((s=s||{}).cornerStyle||o.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,s,o):e.controlsUtils.renderSquareControl.call(this,t,i,n,s,o)}}}(e),function(){function t(t,e){var i,n,s,o,r=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,r){var l=r.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),o=l.length;o--;){var h=l[o].split(/\s*:\s*/),c=h[0].trim(),d=h[1].trim();"stop-color"===c?i=d:"stop-opacity"===c&&(s=d)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),s||(s=t.getAttribute("stop-opacity")),n=(i=new T.Color(i)).getAlpha(),s=isNaN(parseFloat(s))?1:parseFloat(s),s*=n*e,{offset:a,color:i.toRgb(),opacity:s}}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 n,s,o,r,a=e(this.coords,!0),l=(i=i||{},e(this.colorStops,!0)),h=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),d=-this.offsetX,u=-this.offsetY,p=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===g?(d/=t.width,u/=t.height):(d+=t.width/2,u+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(d-=t.pathOffset.x,u-=t.pathOffset.y),c[4]-=d,c[5]-=u,r='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',r+=' gradientTransform="'+(p?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?o=["<linearGradient ",r,' x1="',a.x1,'" y1="',a.y1,'" x2="',a.x2,'" y2="',a.y2,'">\n']:"radial"===this.type&&(o=["<radialGradient ",r,' cx="',h?a.x1:a.x2,'" cy="',h?a.y1:a.y2,'" r="',h?a.r1:a.r2,'" fx="',h?a.x2:a.x1,'" fy="',h?a.y2:a.y1,'">\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),n=0,s=l.length;n<s;n++)l[n].offset=1-l[n].offset;var f=Math.min(a.r1,a.r2);if(f>0){var m=f/Math.max(a.r1,a.r2);for(n=0,s=l.length;n<s;n++)l[n].offset+=m*(1-l[n].offset)}}for(n=0,s=l.length;n<s;n++){var v=l[n];o.push("<stop ",'offset="',100*v.offset+"%",'" style="stop-color:',v.color,void 0!==v.opacity?";stop-opacity: "+v.opacity:";",'"/>\n')}return o.push("linear"===this.type?"</linearGradient>\n":"</radialGradient>\n"),o.join("")},toLive:function(t){var e,i,n,s=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(s.x1,s.y1,s.x2,s.y2):"radial"===this.type&&(e=t.createRadialGradient(s.x1,s.y1,s.r1,s.x2,s.y2,s.r2)),i=0,n=this.colorStops.length;i<n;i++){var o=this.colorStops[i].color,r=this.colorStops[i].opacity,a=this.colorStops[i].offset;void 0!==r&&(o=new T.Color(o).setAlpha(r).toRgba()),e.addColorStop(a,o)}return e}}}),T.util.object.extend(T.Gradient,{fromElement:function(e,i,n,s){var o=parseFloat(n)/(/%$/.test(n)?100:1);o=o<0?0:o>1?1:o,isNaN(o)&&(o=1);var r,a,l,h,c=e.getElementsByTagName("stop"),d="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",u=e.getAttribute("gradientTransform")||"",p=[],g=0,f=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(r="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)):(r="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)),l=c.length;l--;)p.push(t(c[l],o));return h=T.parseTransformAttribute(u),function(t,e,i,n){var s,o;Object.keys(e).forEach(function(t){"Infinity"===(s=e[t])?o=1:"-Infinity"===s?o=0:(o=parseFloat(e[t],10),"string"==typeof s&&/^(\d+\.\d+)%|(\d+)%$/.test(s)&&(o*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(o*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(o*=i.viewBoxHeight||i.height)))),e[t]=o})}(0,a,s,d),"pixels"===d&&(g=-i.left,f=-i.top),new T.Gradient({id:e.getAttribute("id"),type:r,coords:a,colorStops:p,gradientUnits:d,gradientTransform:h,offsetX:g,offsetY:f})}})}(),v=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,n){i.source=t,e&&e(i,n)},null,this.crossOrigin)}},toObject:function(t){var e,i,n=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:v(this.offsetX,n),offsetY:v(this.offsetY,n),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,n=e.height/t.height,s=this.offsetX/t.width,o=this.offsetY/t.height,r="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,o&&(n+=Math.abs(o))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,s&&(i+=Math.abs(s))),e.src?r=e.src:e.toDataURL&&(r=e.toDataURL()),'<pattern id="SVGID_'+this.id+'" x="'+s+'" y="'+o+'" width="'+i+'" height="'+n+'">\n<image x="0" y="0" width="'+e.width+'" height="'+e.height+'" xlink:href="'+r+'"></image>\n</pattern>\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(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,s=40,o=e.Object.NUM_FRACTION_DIGITS,r=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&&(n=100*i((Math.abs(r.x)+this.blur)/t.width,o)+20,s=100*i((Math.abs(r.y)+this.blur)/t.height,o)+20),t.flipX&&(r.x*=-1),t.flipY&&(r.y*=-1),'<filter id="SVGID_'+this.id+'" y="-'+s+'%" height="'+(100+2*s)+'%" x="-'+n+'%" width="'+(100+2*n)+'%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="'+i(this.blur?this.blur/2:0,o)+'"></feGaussianBlur>\n\t<feOffset dx="'+i(r.x,o)+'" dy="'+i(r.y,o)+'" result="oBlur" ></feOffset>\n\t<feFlood flood-color="'+a.toRgb()+'" flood-opacity="'+a.getAlpha()+'"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\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,n=T.util.toFixed,s=T.util.transformPoint,o=T.util.invertTransform,r=T.util.getNodeCanvas,a=T.util.createCanvasElement,l=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,n){return"string"==typeof e?T.util.loadImage(e,function(e,s){if(e){var o=new T.Image(e,n);this[t]=o,o.canvas=this}i&&i(e,s)},this,n&&n.crossOrigin):(n&&e.setOptions(n),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 l;if(t.style||(t.style={}),void 0===t.getContext)throw l;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 n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,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,n,s=this._activeObject,o=this.backgroundImage,r=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i<n;i++)(e=this._objects[i]).group||e.setCoords(!0);return s&&s.setCoords(),o&&o.setCoords(!0),r&&r.setCoords(!0),this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll(),this},zoomToPoint:function(t,e){var i=t,n=this.viewportTransform.slice(0);t=s(t,o(this.viewportTransform)),n[0]=e,n[3]=e;var r=s(t,n);return n[4]+=i.x-r.x,n[5]+=i.y-r.y,this.setViewportTransform(n)},setZoom:function(t){return this.zoomToPoint(new T.Point(0,0),t),this},absolutePan:function(t){var e=this.viewportTransform.slice(0);return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)},relativePan:function(t){return this.absolutePan(new T.Point(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))},getElement:function(){return this.lowerCanvasEl},_onObjectAdded:function(t){this.stateful&&t.setupState(),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added")},_onObjectRemoved:function(t){this.fire("object:removed",{target:t}),t.fire("removed"),delete t.canvas},clearContext:function(t){return t.clearRect(0,0,this.width,this.height),this},getContext:function(){return this.contextContainer},clear:function(){return this.remove.apply(this,this.getObjects()),this.backgroundImage=null,this.overlayImage=null,this.backgroundColor="",this.overlayColor="",this._hasITextHandlers&&(this.off("mouse:up",this._mouseUpITextHandler),this._iTextInstances=null,this._hasITextHandlers=!1),this.clearContext(this.contextContainer),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll(),this},renderAll:function(){var t=this.contextContainer;return this.renderCanvas(t,this._objects),this},renderAndReset:function(){this.isRendering=0,this.renderAll()},requestRenderAll:function(){return this.isRendering||(this.isRendering=T.util.requestAnimFrame(this.renderAndResetBound)),this},calcViewportBoundaries:function(){var t={},e=this.width,i=this.height,n=o(this.viewportTransform);return t.tl=s({x:0,y:0},n),t.br=s({x:e,y:i},n),t.tr=new T.Point(t.br.x,t.tl.y),t.bl=new T.Point(t.tl.x,t.br.y),this.vptCoords=t,t},cancelRequestedRender:function(){this.isRendering&&(T.util.cancelAnimFrame(this.isRendering),this.isRendering=0)},renderCanvas:function(t,e){var i=this.viewportTransform,n=this.clipPath;this.cancelRequestedRender(),this.calcViewportBoundaries(),this.clearContext(t),T.util.setImageSmoothing(t,this.imageSmoothingEnabled),this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this._renderObjects(t,e),t.restore(),!this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),n&&(n.canvas=this,n.shouldCache(),n._transformDone=!0,n.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t)),this._renderOverlay(t),this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),this.fire("after:render",{ctx:t})},drawClipPathOnCanvas:function(t){var e=this.viewportTransform,i=this.clipPath;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t.globalCompositeOperation="destination-in",i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},_renderObjects:function(t,e){var i,n;for(i=0,n=e.length;i<n;++i)e[i]&&e[i].render(t)},_renderBackgroundOrOverlay:function(t,e){var i=this[e+"Color"],n=this[e+"Image"],s=this.viewportTransform,o=this[e+"Vpt"];if(i||n){if(i){t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=i.toLive?i.toLive(t,this):i,o&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),t.transform(1,0,0,1,i.offsetX||0,i.offsetY||0);var r=i.gradientTransform||i.patternTransform;r&&t.transform(r[0],r[1],r[2],r[3],r[4],r[5]),t.fill(),t.restore()}n&&(t.save(),o&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),n.render(t),t.restore())}},_renderBackground:function(t){this._renderBackgroundOrOverlay(t,"background")},_renderOverlay:function(t){this._renderBackgroundOrOverlay(t,"overlay")},getCenter:function(){return{top:this.height/2,left:this.width/2}},getCenterPoint:function(){return new T.Point(this.width/2,this.height/2)},centerObjectH:function(t){return this._centerObject(t,new T.Point(this.getCenterPoint().x,t.getCenterPoint().y))},centerObjectV:function(t){return this._centerObject(t,new T.Point(t.getCenterPoint().x,this.getCenterPoint().y))},centerObject:function(t){var e=this.getCenterPoint();return this._centerObject(t,e)},viewportCenterObject:function(t){var e=this.getVpCenter();return this._centerObject(t,e)},viewportCenterObjectH:function(t){var e=this.getVpCenter();return this._centerObject(t,new T.Point(e.x,t.getCenterPoint().y)),this},viewportCenterObjectV:function(t){var e=this.getVpCenter();return this._centerObject(t,new T.Point(t.getCenterPoint().x,e.y))},getVpCenter:function(){var t=this.getCenterPoint(),e=o(this.viewportTransform);return s(t,e)},_centerObject:function(t,e){return t.setPositionByOrigin(e,"center","center"),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll(),this},toDatalessJSON:function(t){return this.toDatalessObject(t)},toObject:function(t){return this._toObjectMethod("toObject",t)},toDatalessObject:function(t){return this._toObjectMethod("toDatalessObject",t)},_toObjectMethod:function(e,i){var n=this.clipPath,s={version:T.version,objects:this._toObjects(e,i)};return n&&!n.excludeFromExport&&(s.clipPath=this._toObject(this.clipPath,e,i)),t(s,this.__serializeBgOverlay(e,i)),T.util.populateWithProperties(this,s,i),s},_toObjects:function(t,e){return this._objects.filter(function(t){return!t.excludeFromExport}).map(function(i){return this._toObject(i,t,e)},this)},_toObject:function(t,e,i){var n;this.includeDefaultValues||(n=t.includeDefaultValues,t.includeDefaultValues=!1);var s=t[e](i);return this.includeDefaultValues||(t.includeDefaultValues=n),s},__serializeBgOverlay:function(t,e){var i={},n=this.backgroundImage,s=this.overlayImage,o=this.backgroundColor,r=this.overlayColor;return o&&o.toObject?o.excludeFromExport||(i.background=o.toObject(e)):o&&(i.background=o),r&&r.toObject?r.excludeFromExport||(i.overlay=r.toObject(e)):r&&(i.overlay=r),n&&!n.excludeFromExport&&(i.backgroundImage=this._toObject(n,t,e)),s&&!s.excludeFromExport&&(i.overlayImage=this._toObject(s,t,e)),i},svgViewportTransformation:!0,toSVG:function(t,e){t||(t={}),t.reviver=e;var i=[];return this._setSVGPreamble(i,t),this._setSVGHeader(i,t),this.clipPath&&i.push('<g clip-path="url(#'+this.clipPath.clipPathId+')" >\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("</g>\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push("</svg>"),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')},_setSVGHeader:function(t,e){var i,s=e.width||this.width,o=e.height||this.height,r='viewBox="0 0 '+this.width+" "+this.height+'" ',a=T.Object.NUM_FRACTION_DIGITS;e.viewBox?r='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,r='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',o,'" ',r,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",T.version,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"</defs>\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'<clipPath id="'+e.clipPathId+'" >\n'+this.clipPath.toClipPathSVG(t.reviver)+"</clipPath>\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map(function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],s=t.viewportTransform,o={width:t.width/(n?s[0]:1),height:t.height/(n?s[3]:1)};return i.toSVG(o,{additionalTransform:n?T.util.matrixToSVG(s):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,s,o,r,a,l="",h={},c=T.fontPaths,d=[];for(this._objects.forEach(function t(e){d.push(e),e._objects&&e._objects.forEach(t)}),r=0,a=d.length;r<a;r++)if(e=(t=d[r]).fontFamily,-1!==t.type.indexOf("text")&&!h[e]&&c[e]&&(h[e]=!0,t.styles))for(s in i=t.styles)for(o in n=i[s])!h[e=n[o].fontFamily]&&c[e]&&(h[e]=!0);for(var u in h)l+=["\t\t@font-face {\n","\t\t\tfont-family: '",u,"';\n","\t\t\tsrc: url('",c[u],"');\n","\t\t}\n"].join("");return l&&(l=['\t<style type="text/css">',"<![CDATA[\n",l,"]]>","</style>\n"].join("")),l},_setSVGObjects:function(t,e){var i,n,s,o=this._objects;for(n=0,s=o.length;n<s;n++)(i=o[n]).excludeFromExport||this._setSVGObject(t,i,e)},_setSVGObject:function(t,e,i){t.push(e.toSVG(i))},_setSVGBgOverlayImage:function(t,e,i){this[e]&&!this[e].excludeFromExport&&this[e].toSVG&&t.push(this[e].toSVG(i))},_setSVGBgOverlayColor:function(t,e){var i=this[e+"Color"],n=this.viewportTransform,s=this.width,o=this.height;if(i)if(i.toLive){var r=i.repeat,a=T.util.invertTransform(n),l=this[e+"Vpt"]?T.util.matrixToSVG(a):"";t.push('<rect transform="'+l+" translate(",s/2,",",o/2,')"',' x="',i.offsetX-s/2,'" y="',i.offsetY-o/2,'" ','width="',"repeat-y"===r||"no-repeat"===r?i.source.width:s,'" height="',"repeat-x"===r||"no-repeat"===r?i.source.height:o,'" fill="url(#SVGID_'+i.id+')"',"></rect>\n")}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',i,'"',"></rect>\n")},sendToBack:function(t){if(!t)return this;var e,n,s,o=this._activeObject;if(t===o&&"activeSelection"===t.type)for(e=(s=o._objects).length;e--;)n=s[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,s,o=this._activeObject;if(t===o&&"activeSelection"===t.type)for(s=o._objects,e=0;e<s.length;e++)n=s[e],i(this._objects,n),this._objects.push(n);else i(this._objects,t),this._objects.push(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},sendBackwards:function(t,e){if(!t)return this;var n,s,o,r,a,l=this._activeObject,h=0;if(t===l&&"activeSelection"===t.type)for(a=l._objects,n=0;n<a.length;n++)s=a[n],(o=this._objects.indexOf(s))>0+h&&(r=o-1,i(this._objects,s),this._objects.splice(r,0,s)),h++;else 0!==(o=this._objects.indexOf(t))&&(r=this._findNewLowerIndex(t,o,e),i(this._objects,t),this._objects.splice(r,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,s;if(i){for(n=e,s=e-1;s>=0;--s)if(t.intersectsWithObject(this._objects[s])||t.isContainedWithinObject(this._objects[s])||this._objects[s].isContainedWithinObject(t)){n=s;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,s,o,r,a,l=this._activeObject,h=0;if(t===l&&"activeSelection"===t.type)for(n=(a=l._objects).length;n--;)s=a[n],(o=this._objects.indexOf(s))<this._objects.length-1-h&&(r=o+1,i(this._objects,s),this._objects.splice(r,0,s)),h++;else(o=this._objects.indexOf(t))!==this._objects.length-1&&(r=this._findNewUpperIndex(t,o,e),i(this._objects,t),this._objects.splice(r,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewUpperIndex:function(t,e,i){var n,s,o;if(i){for(n=e,s=e+1,o=this._objects.length;s<o;++s)if(t.intersectsWithObject(this._objects[s])||t.isContainedWithinObject(this._objects[s])||this._objects[s].isContainedWithinObject(t)){n=s;break}}else n=e+1;return n},moveTo:function(t,e){return i(this._objects,t),this._objects.splice(e,0,t),this.renderOnAddRemove&&this.requestRenderAll()},dispose:function(){return this.isRendering&&(T.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"),T.util.setStyle(this.lowerCanvasEl,this._originalCanvasStyle),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),T.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},toString:function(){return"#<fabric.Canvas ("+this.complexity()+"): { objects: "+this._objects.length+" }>"}}),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=r(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=r(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,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},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 n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},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,n=i.length,s=this.canvas.contextTop;this._saveAndTransform(s),this.oldEnd&&(s.beginPath(),s.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(s,i[n-2],i[n-1],!0),s.stroke(),s.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,n=this._points[0],s=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===s.x&&n.y===s.y){var o=this.width/1e3;n=new T.Point(n.x,n.y),s=new T.Point(s.x,s.y),n.x-=o,s.x+=o}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e<i;e++)this._drawSegment(t,n,s),n=this._points[e],s=this._points[e+1];t.lineTo(n.x,n.y),t.stroke(),t.restore()},convertPointsToSVGPath:function(t){var e=this.width/1e3;return T.util.getSmoothPathFromPoints(t,e)},_isEmptySVGPath:function(t){return"M 0 0 Q 0 0 0 0 L 0 0"===T.util.joinPath(t)},createPath:function(t){var e=new T.Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new T.Shadow(this.shadow)),e},decimatePoints:function(t,e){if(t.length<=2)return t;var i,n=this.canvas.getZoom(),s=Math.pow(e/n,2),o=t.length-1,r=t[0],a=[r];for(i=1;i<o-1;i++)Math.pow(r.x-t[i].x,2)+Math.pow(r.y-t[i].y,2)>=s&&(r=t[i],a.push(r));return a.push(t[o]),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,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t<e;t++)this.dot(i,n[t]);i.restore()},onMouseMove:function(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.needsFullRender()?(this.canvas.clearContext(this.canvas.contextTop),this.addPoint(t),this._render()):this.drawDot(t))},onMouseUp:function(){var t,e,i=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;var n=[];for(t=0,e=this.points.length;t<e;t++){var s=this.points[t],o=new T.Circle({radius:s.radius,left:s.x,top:s.y,originX:"center",originY:"center",fill:s.fill});this.shadow&&(o.shadow=new T.Shadow(this.shadow)),n.push(o)}var r=new T.Group(n);r.canvas=this.canvas,this.canvas.fire("before:path:created",{path:r}),this.canvas.add(r),this.canvas.fire("path:created",{path:r}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=i,this.canvas.requestRenderAll()},addPoint:function(t){var e=new T.Point(t.x,t.y),i=T.util.getRandomInt(Math.max(0,this.width-20),this.width+20)/2,n=new T.Color(this.color).setAlpha(T.util.getRandomInt(0,100)/100).toRgba();return e.radius=i,e.fill=n,this.points.push(e),e}}),T.SprayBrush=T.util.createClass(T.BaseBrush,{width:10,density:20,dotWidth:1,dotWidthVariance:1,randomOpacity:!1,optimizeOverlapping:!0,initialize:function(t){this.canvas=t,this.sprayChunks=[]},onMouseDown:function(t){this.sprayChunks.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.addSprayChunk(t),this.render(this.sprayChunkPoints)},onMouseMove:function(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.addSprayChunk(t),this.render(this.sprayChunkPoints))},onMouseUp:function(){var t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;for(var e=[],i=0,n=this.sprayChunks.length;i<n;i++)for(var s=this.sprayChunks[i],o=0,r=s.length;o<r;o++){var a=new T.Rect({width:s[o].width,height:s[o].width,left:s[o].x+1,top:s[o].y+1,originX:"center",originY:"center",fill:this.color});e.push(a)}this.optimizeOverlapping&&(e=this._getOptimizedRects(e));var l=new T.Group(e);this.shadow&&l.set("shadow",new T.Shadow(this.shadow)),this.canvas.fire("before:path:created",{path:l}),this.canvas.add(l),this.canvas.fire("path:created",{path:l}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()},_getOptimizedRects:function(t){var e,i,n,s={};for(i=0,n=t.length;i<n;i++)s[e=t[i].left+""+t[i].top]||(s[e]=t[i]);var o=[];for(e in s)o.push(s[e]);return o},render:function(t){var e,i,n=this.canvas.contextTop;for(n.fillStyle=this.color,this._saveAndTransform(n),e=0,i=t.length;e<i;e++){var s=t[e];void 0!==s.opacity&&(n.globalAlpha=s.opacity),n.fillRect(s.x,s.y,s.width,s.width)}n.restore()},_render:function(){var t,e,i=this.canvas.contextTop;for(i.fillStyle=this.color,this._saveAndTransform(i),t=0,e=this.sprayChunks.length;t<e;t++)this.render(this.sprayChunks[t]);i.restore()},addSprayChunk:function(t){this.sprayChunkPoints=[];var e,i,n,s,o=this.width/2;for(s=0;s<this.density;s++){e=T.util.getRandomInt(t.x-o,t.x+o),i=T.util.getRandomInt(t.y-o,t.y+o),n=this.dotWidthVariance?T.util.getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance):this.dotWidth;var r=new T.Point(e,i);r.width=n,this.randomOpacity&&(r.opacity=T.util.getRandomInt(0,100)/100),this.sprayChunkPoints.push(r)}this.sprayChunks.push(this.sprayChunkPoints)}}),T.PatternBrush=T.util.createClass(T.PencilBrush,{getPatternSrc:function(){var t=T.util.createCanvasElement(),e=t.getContext("2d");return t.width=t.height=25,e.fillStyle=this.color,e.beginPath(),e.arc(10,10,10,0,2*Math.PI,!1),e.closePath(),e.fill(),t},getPatternSrcFunction:function(){return String(this.getPatternSrc).replace("this.color",'"'+this.color+'"')},getPattern:function(t){return t.createPattern(this.source||this.getPatternSrc(),"repeat")},_setBrushStyles:function(t){this.callSuper("_setBrushStyles",t),t.strokeStyle=this.getPattern(t)},createPath:function(t){var e=this.callSuper("createPath",t),i=e._getLeftTopCoords().scalarAdd(e.strokeWidth/2);return e.stroke=new T.Pattern({source:this.source||this.getPatternSrcFunction(),offsetX:-i.x,offsetY:-i.y}),e}}),function(){var t=T.util.getPointer,e=T.util.degreesToRadians,i=T.util.isTouchEvent;for(var n in T.Canvas=T.util.createClass(T.StaticCanvas,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e),this._initInteractive(),this._createCacheCanvas()},uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",interactive:!0,selection:!0,selectionKey:"shiftKey",altSelectionKey:null,selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",containerClass:"canvas-container",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,isDrawingMode:!1,preserveObjectStacking:!1,snapAngle:0,snapThreshold:null,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,targets:[],enablePointerEvents:!1,_hoveredTarget:null,_hoveredTargets:[],_initInteractive:function(){this._currentTransform=null,this._groupSelector=null,this._initWrapperElement(),this._createUpperCanvas(),this._initEventListeners(),this._initRetinaScaling(),this.freeDrawingBrush=T.PencilBrush&&new T.PencilBrush(this),this.calcOffset()},_chooseObjectsToRender:function(){var t,e,i,n=this.getActiveObjects();if(n.length>0&&!this.preserveObjectStacking){e=[],i=[];for(var s=0,o=this._objects.length;s<o;s++)t=this._objects[s],-1===n.indexOf(t)?e.push(t):i.push(t);n.length>1&&(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(),n=T.util.invertTransform(i),s=this.restorePointerVpt(e);return T.util.transformPoint(s,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),s=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),o=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(s),Math.round(o),this.targetFindTolerance)}var r=this.contextCache,a=t.selectionBackgroundColor,l=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(r),r.save(),r.transform(l[0],l[1],l[2],l[3],l[4],l[5]),t.render(r),r.restore(),t.selectionBackgroundColor=a,T.util.isTransparent(r,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(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!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,n){if(!e||!t)return"drag";var s=n.controls[e];return s.getActionName(i,s,n)},_setupCurrentTransform:function(t,i,n){if(i){var s=this.getPointer(t),o=i.__corner,r=i.controls[o],a=n&&o?r.getActionHandler(t,i,r):T.controlsUtils.dragHandler,l=this._getActionFromCorner(n,o,t,i),h=this._getOriginFromCorner(i,o),c=t[this.centeredKey],d={target:i,action:l,actionHandler:a,corner:o,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:s.x-i.left,offsetY:s.y-i.top,originX:h.x,originY:h.y,ex:s.x,ey:s.y,lastX:s.x,lastY:s.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,l,c)&&(d.originX="center",d.originY="center"),d.original.originX=h.x,d.original.originY=h.y,this._currentTransform=d,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),n=T.util.transformPoint(i,this.viewportTransform),s=new T.Point(e.ex+e.left,e.ey+e.top),o=T.util.transformPoint(s,this.viewportTransform),r=Math.min(n.x,o.x),a=Math.min(n.y,o.y),l=Math.max(n.x,o.x),h=Math.max(n.y,o.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(r,a,l-r,h-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,r+=c,a+=c,l-=c,h-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(r,a,l-r,h-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,s,o=this.getPointer(t,!0),r=this._activeObject,a=this.getActiveObjects(),l=i(t),h=a.length>1&&!e||1===a.length;if(this.targets=[],h&&r._findTargetCorner(o,l))return r;if(a.length>1&&!e&&r===this._searchPossibleTargets([r],o))return r;if(1===a.length&&r===this._searchPossibleTargets([r],o)){if(!this.preserveObjectStacking)return r;n=r,s=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,o);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=s),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,n,s=t.length;s--;){var o=t[s],r=o.group?this._normalizePointer(o.group,e):e;if(this._checkTarget(r,o,e)){(i=t[s]).subTargetCheck&&i instanceof T.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);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 n,s=t(e),o=this.upperCanvasEl,r=o.getBoundingClientRect(),a=r.width||0,l=r.height||0;a&&l||("top"in r&&"bottom"in r&&(l=Math.abs(r.top-r.bottom)),"right"in r&&"left"in r&&(a=Math.abs(r.right-r.left))),this.calcOffset(),s.x=s.x-this._offset.left,s.y=s.y-this._offset.top,i||(s=this.restorePointerVpt(s));var h=this.getRetinaScaling();return 1!==h&&(s.x/=h,s.y/=h),n=0===a||0===l?{width:1,height:1}:{width:o.width/a,height:o.height/l},{x:s.x*n.width,y:s.y*n.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,n=this.getActiveObjects(),s=[],o=[];t.forEach(function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),o.push(t))}),n.forEach(function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e:e,target:n}),s.push(n))}),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e:e,selected:s,deselected:o}):n.length>0?this.fire("selection:created",{e:e,selected:s}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:o})},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 n=this._realizeGroupTransformOnObject(t),s=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),s},_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 n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==n&&(T.Canvas[n]=T.StaticCanvas[n])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function n(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 n=this.upperCanvasEl,s=this._getEventPrefix();t(T.window,"resize",this._onResize),t(n,s+"down",this._onMouseDown),t(n,s+"move",this._onMouseMove,i),t(n,s+"out",this._onMouseOut),t(n,s+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"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(n){i.fire("mouse:out",{target:e,e:t}),n&&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(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var s=this.upperCanvasEl,o=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(s,o+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var s=this.upperCanvasEl,o=this._getEventPrefix();e(s,o+"move",this._onMouseMove,i),t(T.document,o+"up",this._onMouseUp),t(T.document,o+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var s=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var o=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(function(){t(o.upperCanvasEl,s+"down",o._onMouseDown),o._willAddMouseDown=0},400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var s=this.upperCanvasEl,o=this._getEventPrefix();this._isMainEvent(n)&&(e(T.document,o+"up",this._onMouseUp),e(T.document,o+"move",this._onMouseMove,i),t(s,o+"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,s=this._groupSelector,o=!1,r=!s||0===s.left&&0===s.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,r);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,r),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),o=i.actionPerformed),!r){var a=e===this._activeObject;this._maybeGroupObjects(t),o||(o=this._shouldRender(e)||!a&&e===this._activeObject)}var l,h;if(e){if(l=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),o=!0;else{var c=e.controls[l],d=c&&c.getMouseUpHandler(t,e,c);d&&d(t,i,(h=this.getPointer(t)).x,h.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==l)){var u=i.target&&i.target.controls[i.corner],p=u&&u.getMouseUpHandler(t,e,c);h=h||this.getPointer(t),p&&p(t,i,h.x,h.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,r),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),o?this.requestRenderAll():r||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,s={e:e,target:i,subTargets:n};if(this.fire(t,s),i&&i.fire(t,s),!n)return i;for(var o=0;o<n.length;o++)n[o].fire(t,s);return i},_handleEvent:function(t,e,i,n){var s=this._target,o=this.targets||[],r={e:t,target:s,subTargets:o,button:i||1,isClick:n||!1,pointer:this._pointer,absolutePointer:this._absolutePointer,transform:this._currentTransform};"up"===e&&(r.currentTarget=this.findTarget(t),r.currentSubTargets=this.targets),this.fire("mouse:"+e,r),s&&s.fire("mouse"+e,r);for(var a=0;a<o.length;a++)o[a].fire("mouse"+e,r)},_finalizeCurrentTransform:function(t){var e=this._currentTransform,i=e.target,n={e:t,target:i,transform:e,action:e.action};i._scaling&&(i._scaling=!1),i.setCoords(),(e.actionPerformed||this.stateful&&i.hasStateChanged())&&this._fire("modified",n)},_onMouseDownInDrawingMode:function(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&this.discardActiveObject(t).requestRenderAll();var e=this.getPointer(t);this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down")},_onMouseMoveInDrawingMode:function(t){if(this._isCurrentlyDrawing){var e=this.getPointer(t);this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")},_onMouseUpInDrawingMode:function(t){var e=this.getPointer(t);this._isCurrentlyDrawing=this.freeDrawingBrush.onMouseUp({e:t,pointer:e}),this._handleEvent(t,"up")},__onMouseDown:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"down:before");var e=this._target;if(n(t,3))this.fireRightClick&&this._handleEvent(t,"down",3);else if(n(t,2))this.fireMiddleClick&&this._handleEvent(t,"down",2);else if(this.isDrawingMode)this._onMouseDownInDrawingMode(t);else if(this._isMainEvent(t)&&!this._currentTransform){var i=this._pointer;this._previousPointer=i;var s=this._shouldRender(e),o=this._shouldGroup(t,e);if(this._shouldClearSelection(t,e)?this.discardActiveObject(t):o&&(this._handleGrouping(t,e),e=this._activeObject),!this.selection||e&&(e.selectable||e.isEditing||e===this._activeObject)||(this._groupSelector={ex:this._absolutePointer.x,ey:this._absolutePointer.y,top:0,left:0}),e){var r=e===this._activeObject;e.selectable&&"down"===e.activeOn&&this.setActiveObject(e,t);var a=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t));if(e.__corner=a,e===this._activeObject&&(a||!o)){this._setupCurrentTransform(t,e,r);var l=e.controls[a],h=(i=this.getPointer(t),l&&l.getMouseDownHandler(t,e,l));h&&h(t,this._currentTransform,i.x,i.y)}}this._handleEvent(t,"down"),(s||o)&&this.requestRenderAll()}},_resetTransformEventData:function(){this._target=null,this._pointer=null,this._absolutePointer=null},_cacheTransformEventData:function(t){this._resetTransformEventData(),this._pointer=this.getPointer(t,!0),this._absolutePointer=this.restorePointerVpt(this._pointer),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)||null},_beforeTransform:function(t){var e=this._currentTransform;this.stateful&&e.target.saveState(),this.fire("before:transform",{e:t,transform:e})},__onMouseMove:function(t){var e,i;if(this._handleEvent(t,"move:before"),this._cacheTransformEventData(t),this.isDrawingMode)this._onMouseMoveInDrawingMode(t);else if(this._isMainEvent(t)){var n=this._groupSelector;n?(i=this._absolutePointer,n.left=i.x-n.ex,n.top=i.y-n.ey,this.renderTop()):this._currentTransform?this._transformObject(t):(e=this.findTarget(t)||null,this._setCursorFromEvent(t,e),this._fireOverOutEvents(e,t)),this._handleEvent(t,"move"),this._resetTransformEventData()}},_fireOverOutEvents:function(t,e){var i=this._hoveredTarget,n=this._hoveredTargets,s=this.targets,o=Math.max(n.length,s.length);this.fireSyntheticInOutEvents(t,e,{oldTarget:i,evtOut:"mouseout",canvasEvtOut:"mouse:out",evtIn:"mouseover",canvasEvtIn:"mouse:over"});for(var r=0;r<o;r++)this.fireSyntheticInOutEvents(s[r],e,{oldTarget:n[r],evtOut:"mouseout",evtIn:"mouseover"});this._hoveredTarget=t,this._hoveredTargets=this.targets.concat()},_fireEnterLeaveEvents:function(t,e){var i=this._draggedoverTarget,n=this._hoveredTargets,s=this.targets,o=Math.max(n.length,s.length);this.fireSyntheticInOutEvents(t,e,{oldTarget:i,evtOut:"dragleave",evtIn:"dragenter"});for(var r=0;r<o;r++)this.fireSyntheticInOutEvents(s[r],e,{oldTarget:n[r],evtOut:"dragleave",evtIn:"dragenter"});this._draggedoverTarget=t},fireSyntheticInOutEvents:function(t,e,i){var n,s,o,r=i.oldTarget,a=r!==t,l=i.canvasEvtIn,h=i.canvasEvtOut;a&&(n={e:e,target:t,previousTarget:r},s={e:e,target:r,nextTarget:t}),o=t&&a,r&&a&&(h&&this.fire(h,s),r.fire(i.evtOut,s)),o&&(l&&this.fire(l,n),t.fire(i.evtIn,n))},__onMouseWheel:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()},_transformObject:function(t){var e=this.getPointer(t),i=this._currentTransform;i.reset=!1,i.shiftKey=t.shiftKey,i.altKey=t[this.centeredKey],this._performTransformAction(t,i,e),i.actionPerformed&&this.requestRenderAll()},_performTransformAction:function(t,e,i){var n=i.x,s=i.y,o=e.action,r=!1,a=e.actionHandler;a&&(r=a(t,e,n,s)),"drag"===o&&r&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||r},_fire:T.controlsUtils.fireEvent,_setCursorFromEvent:function(t,e){if(!e)return this.setCursor(this.defaultCursor),!1;var i=e.hoverCursor||this.hoverCursor,n=this._activeObject&&"activeSelection"===this._activeObject.type?this._activeObject:null,s=(!n||!n.contains(e))&&e._findTargetCorner(this.getPointer(t,!0));s?this.setCursor(this.getCornerCursor(s,e,t)):(e.subTargetCheck&&this.targets.concat().reverse().map(function(t){i=t.hoverCursor||i}),this.setCursor(i))},getCornerCursor:function(t,e,i){var n=e.controls[t];return n.cursorStyleHandler(i,n,e)}})}(),y=Math.min,x=Math.max,T.util.object.extend(T.Canvas.prototype,{_shouldGroup:function(t,e){var i=this._activeObject;return i&&this._isSelectionKeyPressed(t)&&e&&e.selectable&&this.selection&&(i!==e||"activeSelection"===i.type)&&!e.onSelect({e:t})},_handleGrouping:function(t,e){var i=this._activeObject;i.__corner||(e!==i||(e=this.findTarget(t,!0))&&e.selectable)&&(i&&"activeSelection"===i.type?this._updateActiveSelection(e,t):this._createActiveSelection(e,t))},_updateActiveSelection:function(t,e){var i=this._activeObject,n=i._objects.slice(0);i.contains(t)?(i.removeWithUpdate(t),this._hoveredTarget=t,this._hoveredTargets=this.targets.concat(),1===i.size()&&this._setActiveObject(i.item(0),e)):(i.addWithUpdate(t),this._hoveredTarget=i,this._hoveredTargets=this.targets.concat()),this._fireSelectionEvents(n,e)},_createActiveSelection:function(t,e){var i=this.getActiveObjects(),n=this._createGroup(t);this._hoveredTarget=n,this._setActiveObject(n,e),this._fireSelectionEvents(i,e)},_createGroup:function(t){var e=this._objects,i=e.indexOf(this._activeObject)<e.indexOf(t)?[this._activeObject,t]:[t,this._activeObject];return this._activeObject.isEditing&&this._activeObject.exitEditing(),new T.ActiveSelection(i,{canvas:this})},_groupSelectedObjects:function(t){var e,i=this._collectObjects(t);1===i.length?this.setActiveObject(i[0],t):i.length>1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,s=this._groupSelector.ey,o=n+this._groupSelector.left,r=s+this._groupSelector.top,a=new T.Point(y(n,o),y(s,r)),l=new T.Point(x(n,o),x(s,r)),h=!this.selectionFullyContained,c=n===o&&s===r,d=this._objects.length;d--&&!((e=this._objects[d])&&e.selectable&&e.visible&&(h&&e.intersectsWithRect(a,l,!0)||e.isContainedWithinRect(a,l,!0)||h&&e.containsPoint(a,null,!0)||h&&e.containsPoint(l,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,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),s=this.toCanvasElement(n,t);return T.util.toDataURL(s,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,s=this.getZoom(),o=this.width,r=this.height,a=s*t,l=this.viewportTransform,h=(l[4]-(e.left||0))*t,c=(l[5]-(e.top||0))*t,d=this.interactive,u=[a,0,0,a,h,c],p=this.enableRetinaScaling,g=T.util.createCanvasElement(),f=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=u,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=l,this.width=o,this.height=r,this.calcViewportBoundaries(),this.interactive=d,this.enableRetinaScaling=p,this.contextTop=f,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):T.util.object.clone(t),s=this,o=n.clipPath,r=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,function(t){s.clear(),s._setBgOverlay(n,function(){o?s._enlivenObjects([o],function(i){s.clipPath=i[0],s.__setupCanvas.call(s,n,t,r,e)}):s.__setupCanvas.call(s,n,t,r,e)})},i),this}},__setupCanvas:function(t,e,i,n){var s=this;e.forEach(function(t,e){s.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(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var s=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],function(e){s[t]=e[0],i[t]=!0,n&&n()}):this["set"+T.util.string.capitalize(t,!0)](e,function(){i[t]=!0,n&&n()})},_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(n){i(n.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,n=e.util.object.clone,s=e.util.toFixed,o=e.util.string.capitalize,r=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,n=t.width,s=t.height,o=e.maxCacheSideLimit,r=e.minCacheSideLimit;if(n<=o&&s<=o&&n*s<=i)return n<r&&(t.width=r),s<r&&(t.height=r),t;var a=n/s,l=e.util.limitDimsByArea(a,i),h=e.util.capValue,c=h(r,l.x,o),d=h(r,l.y,o);return n>c&&(t.zoomX/=n/c,t.width=c,t.capped=!0),s>d&&(t.zoomY/=s/d,t.height=d,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var s,o,r=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),l=e.minCacheSideLimit,h=a.width,c=a.height,d=a.zoomX,u=a.zoomY,p=h!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==d||this.zoomY!==u,f=p||g,m=0,v=0,y=!1;if(p){var x=this._cacheCanvas.width,w=this._cacheCanvas.height,C=h>x||c>w;y=C||(h<.9*x||c<.9*w)&&x>l&&w>l,C&&!a.capped&&(h>l||c>l)&&(m=.1*h,v=.1*c)}return this instanceof e.Text&&this.path&&(f=!0,y=!0,m+=this.getHeightOfLine(0)*this.zoomX,v+=this.getHeightOfLine(0)*this.zoomY),!!f&&(y?(r.width=Math.ceil(h+m),r.height=Math.ceil(c+v)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,r.width,r.height)),s=a.x/2,o=a.y/2,this.cacheTranslationX=Math.round(r.width/2-s)+s,this.cacheTranslationY=Math.round(r.height/2-o)+o,this.cacheWidth=h,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(d,u),this.zoomX=d,this.zoomY=u,!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,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:s(this.left,i),top:s(this.top,i),width:s(this.width,i),height:s(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:s(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:s(this.strokeMiterLimit,i),scaleX:s(this.scaleX,i),scaleY:s(this.scaleY,i),angle:s(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:s(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:s(this.skewX,i),skewY:s(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},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"#<fabric."+o(this.type)+">"},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 n=this.canvas.getZoom(),s=this.canvas.getRetinaScaling();e*=n*s,i*=n*s}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,s=this[t]!==i,o=!1;return n&&(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,s&&(o=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,o&&this.group.set("dirty",!0)):o&&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 n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[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,n=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=n},_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 n,s,o,a=this.getViewportTransform(),l=this.calcTransformMatrix();s=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,o=void 0!==i.hasControls?i.hasControls:this.hasControls,l=e.util.multiplyTransformMatrices(a,l),n=e.util.qrDecompose(l),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(r(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?s&&this.drawBordersInGroup(t,n,i):s&&this.drawBorders(t,i),o&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,s=this.canvas,o=s&&s.viewportTransform[0]||1,r=s&&s.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),s&&s._isRetinaScaling()&&(o*=e.devicePixelRatio,r*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(o+r)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*o*i.scaleX,t.shadowOffsetY=n.offsetY*r*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,n=-this.width/2+e.offsetX||0,s=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,s):t.transform(1,0,0,1,n,s),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:s}},_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 n,s=this._limitCacheSize(this._getCacheCanvasDimensions()),o=e.util.createCanvasElement(),r=this.canvas.getRetinaScaling(),a=s.x/this.scaleX/r,l=s.y/this.scaleY/r;o.width=a,o.height=l,(n=o.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,l),n.lineTo(0,l),n.closePath(),n.translate(a/2,l/2),n.scale(s.zoomX/this.scaleX/r,s.zoomY/this.scaleY/r),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(r*this.scaleX/s.zoomX,r*this.scaleY/s.zoomY),t.strokeStyle=n.createPattern(o,"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 n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),s=this.group,o=this.shadow,r=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 l,h,c,d,u=e.util.createCanvasElement(),p=this.getBoundingRect(!0,!0),g=this.shadow,f={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),f.x=2*Math.round(r(g.offsetX)+h)*r(l.scaleX),f.y=2*Math.round(r(g.offsetY)+h)*r(l.scaleY)),c=p.width+f.x,d=p.height+f.y,u.width=Math.ceil(c),u.height=Math.ceil(d);var m=new e.StaticCanvas(u,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(m.width/2,m.height/2),"center","center");var v=this.canvas;m.add(this);var y=m.toCanvasElement(a||1,t);return this.shadow=o,this.set("canvas",v),s&&(this.group=s),this.set(n).setCoords(),m._objects=[],m.dispose(),m=null,y},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 n=new e.Point(i.x,i.y),s=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,s,r(-this.angle))),{x:n.x-s.x,y:n.y-s.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,s,o){var r=e[t];i=n(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=o?new r(i[o],i):new r(i);s&&s(t)})})},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,C={left:-.5,center:0,right:.5},b={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,s){var o,r,a,l=t.x,h=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=b[i]:i-=.5,"string"==typeof s?s=b[s]:s-=.5,r=s-i,((o=n-e)||r)&&(a=this._getTransformedDimensions(),l=t.x+o*a.x,h=t.y+r*a.y),new T.Point(l,h)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},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 n,s,o=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(o,"center","center",e,i):new T.Point(this.left,this.top),s=new T.Point(t.x,t.y),this.angle&&(s=T.util.rotatePoint(s,o,-w(this.angle))),s.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),s=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",s.x),this.set("top",s.y)},adjustPosition:function(t){var e,i,n=w(this.angle),s=this.getScaledWidth(),o=T.util.cos(n)*s,r=T.util.sin(n)*s;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=o*(i-e),this.top+=r*(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,n=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,n){var s=this.getCoords(i,n);return"Intersection"===T.Intersection.intersectPolygonRectangle(s,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 n=this.getCoords(e,i),s=e?t.aCoords:t.lineCoords,o=0,r=t._getImageLines(s);o<4;o++)if(!t.containsPoint(n[o],r))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var s=this.getBoundingRect(i,n);return s.left>=t.x&&s.left+s.width<=e.x&&s.top>=t.y&&s.top+s.height<=e.y},containsPoint:function(t,e,i,n){var s=this._getCoords(i,n),o=(e=e||this._getImageLines(s),this._findCrossPoints(t,e));return 0!==o&&o%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 n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,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,n,s,o=0;for(var r in e)if(!((s=e[r]).o.y<t.y&&s.d.y<t.y||s.o.y>=t.y&&s.d.y>=t.y||(s.o.x===s.d.x&&s.o.x>=t.x?n=s.o.x:(i=(s.d.y-s.o.y)/(s.d.x-s.o.x),n=-(t.y-0*t.x-(s.o.y-i*s.o.x))/(0-i)),n>=t.x&&(o+=1),2!==o)))break;return o},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:0===t?1e-4:t},scale:function(t){return this._set("scaleX",t),this._set("scaleY",t),this.setCoords()},scaleToWidth:function(t,e){var i=this.getBoundingRect(e).width/this.getScaledWidth();return this.scale(t/this.width/i)},scaleToHeight:function(t,e){var i=this.getBoundingRect(e).height/this.getScaledHeight();return this.scale(t/this.height/i)},calcLineCoords:function(){var i=this.getViewportTransform(),s=this.padding,o=e(this.angle),r=t.cos(o)*s,a=t.sin(o)*s,l=r+a,h=r-a,c=this.calcACoords(),d={tl:n(c.tl,i),tr:n(c.tr,i),bl:n(c.bl,i),br:n(c.br,i)};return s&&(d.tl.x-=h,d.tl.y-=l,d.tr.x+=l,d.tr.y-=h,d.bl.x-=l,d.bl.y+=h,d.br.x+=h,d.br.y+=l),d},calcOCoords:function(){var t=this._calcRotateMatrix(),e=this._calcTranslateMatrix(),n=this.getViewportTransform(),s=i(n,e),o=i(s,t),r=(o=i(o,[1/n[0],0,0,1/n[3],0,0]),this._calculateCurrentDimensions()),a={};return this.forEachControl(function(t,e,i){a[e]=t.positionHandler(r,o,i)}),a},calcACoords:function(){var t=this._calcRotateMatrix(),e=this._calcTranslateMatrix(),s=i(e,t),o=this._getTransformedDimensions(),r=o.x/2,a=o.y/2;return{tl:n({x:-r,y:-a},s),tr:n({x:r,y:-a},s),bl:n({x:-r,y:a},s),br:n({x:r,y:a},s)}},setCoords:function(t){return this.aCoords=this.calcACoords(),this.lineCoords=this.group?this.aCoords:this.calcLineCoords(),t||(this.oCoords=this.calcOCoords(),this._setCornerCoords&&this._setCornerCoords()),this},_calcRotateMatrix:function(){return t.calcRotateMatrix(this)},_calcTranslateMatrix:function(){var t=this.getCenterPoint();return[1,0,0,1,t.x,t.y]},transformMatrixKey:function(t){var e="_",i="";return!t&&this.group&&(i=this.group.transformMatrixKey(t)+e),i+this.top+e+this.left+e+this.scaleX+e+this.scaleY+e+this.skewX+e+this.skewY+e+this.angle+e+this.originX+e+this.originY+e+this.width+e+this.height+e+this.strokeWidth+this.flipX+this.flipY},calcTransformMatrix:function(t){var e=this.calcOwnMatrix();if(t||!this.group)return e;var n=this.transformMatrixKey(t),s=this.matrixCache||(this.matrixCache={});return s.key===n?s.value:(this.group&&(e=i(this.group.calcTransformMatrix(!1),e)),s.key=n,s.value=e,e)},calcOwnMatrix:function(){var e=this.transformMatrixKey(!0),i=this.ownMatrixCache||(this.ownMatrixCache={});if(i.key===e)return i.value;var n=this._calcTranslateMatrix(),s={angle:this.angle,translateX:n[4],translateY:n[5],scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY};return i.key=e,i.value=t.composeMatrix(s),i.value},_getNonTransformedDimensions:function(){var t=this.strokeWidth;return{x:this.width+t,y:this.height+t}},_getTransformedDimensions:function(e,i){void 0===e&&(e=this.skewX),void 0===i&&(i=this.skewY);var n,s,o,r=0===e&&0===i;if(this.strokeUniform?(s=this.width,o=this.height):(s=(n=this._getNonTransformedDimensions()).x,o=n.y),r)return this._finalizeDimensions(s*this.scaleX,o*this.scaleY);var a=t.sizeAfterTransform(s,o,{scaleX:this.scaleX,scaleY:this.scaleY,skewX:e,skewY:i});return this._finalizeDimensions(a.x,a.y)},_finalizeDimensions:function(t,e){return this.strokeUniform?{x:t+this.strokeWidth,y:e+this.strokeWidth}:{x:t,y:e}},_calculateCurrentDimensions:function(){var t=this.getViewportTransform(),e=this._getTransformedDimensions();return n(e,t,!0).scalarAdd(2*this.padding)}})}(),T.util.object.extend(T.Object.prototype,{sendToBack:function(){return this.group?T.StaticCanvas.prototype.sendToBack.call(this.group,this):this.canvas&&this.canvas.sendToBack(this),this},bringToFront:function(){return this.group?T.StaticCanvas.prototype.bringToFront.call(this.group,this):this.canvas&&this.canvas.bringToFront(this),this},sendBackwards:function(t){return this.group?T.StaticCanvas.prototype.sendBackwards.call(this.group,this,t):this.canvas&&this.canvas.sendBackwards(this,t),this},bringForward:function(t){return this.group?T.StaticCanvas.prototype.bringForward.call(this.group,this,t):this.canvas&&this.canvas.bringForward(this,t),this},moveTo:function(t){return this.group&&"activeSelection"!==this.group.type?T.StaticCanvas.prototype.moveTo.call(this.group,this,t):this.canvas&&this.canvas.moveTo(this,t),this}}),function(){function t(t,e){if(e){if(e.toLive)return t+": url(#SVGID_"+e.id+"); ";var i=new T.Color(e),n=t+": "+i.toRgb()+"; ",s=i.getAlpha();return 1!==s&&(n+=t+"-opacity: "+s.toString()+"; "),n}return t+": none; "}var e=T.util.toFixed;T.util.object.extend(T.Object.prototype,{getSvgStyles:function(e){var i=this.fillRule?this.fillRule:"nonzero",n=this.strokeWidth?this.strokeWidth:"0",s=this.strokeDashArray?this.strokeDashArray.join(" "):"none",o=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",l=this.strokeMiterLimit?this.strokeMiterLimit:"4",h=void 0!==this.opacity?this.opacity:"1",c=this.visible?"":" visibility: hidden;",d=e?"":this.getSvgFilter(),u=t("fill",this.fill);return[t("stroke",this.stroke),"stroke-width: ",n,"; ","stroke-dasharray: ",s,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",o,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",l,"; ",u,"fill-rule: ",i,"; ","opacity: ",h,";",d,c].join("")},getSvgSpanStyles:function(e,i){var n="; ",s=e.fontFamily?"font-family: "+(-1===e.fontFamily.indexOf("'")&&-1===e.fontFamily.indexOf('"')?"'"+e.fontFamily+"'":e.fontFamily)+n:"",o=e.strokeWidth?"stroke-width: "+e.strokeWidth+n:"",r=e.fontSize?"font-size: "+e.fontSize+"px"+n:"",a=e.fontStyle?"font-style: "+e.fontStyle+n:"",l=e.fontWeight?"font-weight: "+e.fontWeight+n:"",h=e.fill?t("fill",e.fill):"",c=e.stroke?t("stroke",e.stroke):"",d=this.getSvgTextDecoration(e);return d&&(d="text-decoration: "+d+n),[c,o,s,r,a,l,d,h,e.deltaY?"baseline-shift: "+-e.deltaY+"; ":"",i?"white-space: pre; ":""].join("")},getSvgTextDecoration:function(t){return["overline","underline","line-through"].filter(function(e){return t[e.replace("-","")]}).join(" ")},getSvgFilter:function(){return this.shadow?"filter: url(#SVGID_"+this.shadow.id+");":""},getSvgCommons:function(){return[this.id?'id="'+this.id+'" ':"",this.clipPath?'clip-path="url(#'+this.clipPath.clipPathId+')" ':""].join("")},getSvgTransform:function(t,e){var i=t?this.calcTransformMatrix():this.calcOwnMatrix();return'transform="'+T.util.matrixToSVG(i)+(e||"")+'" '},_setSVGBg:function(t){if(this.backgroundColor){var i=T.Object.NUM_FRACTION_DIGITS;t.push("\t\t<rect ",this._getFillAttributes(this.backgroundColor),' x="',e(-this.width/2,i),'" y="',e(-this.height/2,i),'" width="',e(this.width,i),'" height="',e(this.height,i),'"></rect>\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,n=e.additionalTransform||"",s=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),o=t.indexOf("COMMON_PARTS");return t[o]=s,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,s=(e=e||{}).noStyle,o=e.reviver,r=s?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,d=this.stroke,u=this.fill,p=this.shadow,g=[],f=t.indexOf("COMMON_PARTS"),m=e.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+T.Object.__uid++,n='<clipPath id="'+l.clipPathId+'" >\n'+l.toClipPathSVG(o)+"</clipPath>\n"),c&&g.push("<g ",a,this.getSvgCommons()," >\n"),g.push("<g ",this.getSvgTransform(!1),c?"":a+this.getSvgCommons()," >\n"),i=[r,h,s?"":this.addPaintOrder()," ",m?'transform="'+m+'" ':""].join(""),t[f]=i,u&&u.toLive&&g.push(u.toSVG(this)),d&&d.toLive&&g.push(d.toSVG(this)),p&&g.push(p.toSVG(this)),l&&g.push(n),g.push(t.join("")),g.push("</g>\n"),c&&g.push("</g>\n"),o?o(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,n){var s={};n.forEach(function(t){s[t]=e[t]}),t(e[i],s,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var s=0,o=t.length;s<o;s++)if(!n(t[s],e[s]))return!1;return!0}if(t&&"object"==typeof t){var r,a=Object.keys(t);if(!e||"object"!=typeof e||!i&&a.length!==Object.keys(e).length)return!1;for(s=0,o=a.length;s<o;s++)if("canvas"!==(r=a[s])&&"group"!==r&&!n(t[r],e[r]))return!1;return!0}}T.util.object.extend(T.Object.prototype,{hasStateChanged:function(t){var i="_"+(t=t||e);return Object.keys(this[i]).length<this[t].length||!n(this[i],this,!0)},saveState:function(t){var n=t&&t.propertySet||e,s="_"+n;return this[s]?(i(this,s,this[n]),t&&t.stateProperties&&i(this,s,t.stateProperties),this):this.setupState(t)},setupState:function(t){var i=(t=t||{}).propertySet||e;return t.propertySet=i,this["_"+i]={},this.saveState(t),this}})}(),function(){var t=T.util.degreesToRadians;T.util.object.extend(T.Object.prototype,{_findTargetCorner:function(t,e){if(!this.hasControls||this.group||!this.canvas||this.canvas._activeObject!==this)return!1;var i,n,s,o=t.x,r=t.y,a=Object.keys(this.oCoords),l=a.length-1;for(this.__corner=0;l>=0;l--)if(s=a[l],this.isControlVisible(s)&&(n=this._getImageLines(e?this.oCoords[s].touchCorner:this.oCoords[s].corner),0!==(i=this._findCrossPoints({x:o,y:r},n))&&i%2==1))return this.__corner=s,s;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(),n=this._calculateCurrentDimensions(),s=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/s[0],1/s[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,s=i.x+n,o=i.y+n,r=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(-s/2,-o/2,s,o),r&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*s,e.y*o),t.lineTo(e.x*s+e.offsetX,e.y*o+e.offsetY))}),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=T.util.sizeAfterTransform(this.width,this.height,e),s=this.strokeWidth,o=this.strokeUniform,r=this.borderScaleFactor,a=n.x+s*(o?this.canvas.getZoom():e.scaleX)+r,l=n.y+s*(o?this.canvas.getZoom():e.scaleY)+r;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-l/2,a,l),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,s=this.canvas.getRetinaScaling();return t.setTransform(s,0,0,s,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(s,o,r){n=r.oCoords[o],s.getVisibility(r,o)&&(i&&(n=T.util.transformPoint(n,i)),s.render(t,n.x,n.y,e,r))}),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(){},n=(e=e||{}).onComplete||i,s=e.onChange||i,o=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),o.requestRenderAll(),s()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,s=e.onChange||i,o=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),o.requestRenderAll(),s()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,s=e.onChange||i,o=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),o.requestRenderAll(),s()},onComplete:function(){o.remove(t),n()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var s=0,o=i.length;s<o;s++)t=i[s],e=s!==o-1,n.push(this._animate(t,arguments[0][t],arguments[1],e));return n}return this._animate.apply(this,arguments)},_animate:function(t,e,i,n){var s,o=this;e=e.toString(),i=i?T.util.object.clone(i):{},~t.indexOf(".")&&(s=t.split("."));var r=o.colorProperties.indexOf(t)>-1||s&&o.colorProperties.indexOf(s[1])>-1,a=s?this.get(s[0])[s[1]]:this.get(t);"from"in i||(i.from=a),r||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var l={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(o,t,e,n)},onChange:function(e,r,a){s?o[s[0]][s[1]]=e:o.set(t,e),n||i.onChange&&i.onChange(e,r,a)},onComplete:function(t,e,s){n||(o.setCoords(),i.onComplete&&i.onComplete(t,e,s))}};return r?T.util.animateColor(l.startValue,l.endValue,l.duration,l):T.util.animate(l)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,s={x1:1,x2:1,y1:1,y2:1};function o(t,e){var i=t.origin,n=t.axis1,s=t.axis2,o=t.dimension,r=e.nearest,a=e.center,l=e.farthest;return function(){switch(this.get(i)){case r:return Math.min(this.get(n),this.get(s));case a:return Math.min(this.get(n),this.get(s))+.5*this.get(o);case l:return Math.max(this.get(n),this.get(s))}}}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!==s[t]&&this._setWidthHeight(),this},_getLeftToOriginX:o({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:o({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,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="',t.x1,'" y1="',t.y1,'" x2="',t.x2,'" y2="',t.y2,'" />\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,s){s=s||{};var o=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),r=[o.x1||0,o.y1||0,o.x2||0,o.y2||0];n(new e.Line(r,i(o,s)))},e.Line.fromObject=function(t,i){var s=n(t,!0);s.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",s,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,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',this.radius,'" />\n'];else{var s=i(this.startAngle),o=i(this.endAngle),r=this.radius;t=['<path d="M '+e.util.cos(s)*r+" "+e.util.sin(s)*r," A "+r+" "+r," 0 ",+(n>180?"1":"0")+" 1"," "+e.util.cos(o)*r+" "+e.util.sin(o)*r,'" ',"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 n,s=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=s)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");s.left=(s.left||0)-s.radius,s.top=(s.top||0)-s.radius,i(new e.Circle(s))},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["<polygon ","COMMON_PARTS",'points="',[-t+" "+e,"0 "+-e,t+" "+e].join(","),'" />']}}),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["<ellipse ","COMMON_PARTS",'cx="0" cy="0" ','rx="',this.rx,'" ry="',this.ry,'" />\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 n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},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,n=this.width,s=this.height,o=-this.width/2,r=-this.height/2,a=0!==e||0!==i,l=.4477152502;t.beginPath(),t.moveTo(o+e,r),t.lineTo(o+n-e,r),a&&t.bezierCurveTo(o+n-l*e,r,o+n,r+l*i,o+n,r+i),t.lineTo(o+n,r+s-i),a&&t.bezierCurveTo(o+n,r+s-l*i,o+n-l*e,r+s,o+n-e,r+s),t.lineTo(o+e,r+s),a&&t.bezierCurveTo(o+l*e,r+s,o,r+s-l*i,o,r+s-i),t.lineTo(o,r+i),a&&t.bezierCurveTo(o,r+l*i,o+l*e,r,o+e,r),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["<rect ","COMMON_PARTS",'x="',-this.width/2,'" y="',-this.height/2,'" rx="',this.rx,'" ry="',this.ry,'" width="',this.width,'" height="',this.height,'" />\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,s){if(!t)return n(null);s=s||{};var o=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);o.left=o.left||0,o.top=o.top||0,o.height=o.height||0,o.width=o.width||0;var r=new e.Rect(i(s?e.util.object.clone(s):{},o));r.visible=r.visible&&r.width>0&&r.height>0,n(r)},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,n=e.util.array.min,s=e.util.array.max,o=e.util.toFixed,r=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 r(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/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+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(s(t,"x")||0)-e,height:(s(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,n=this.pathOffset.y,s=e.Object.NUM_FRACTION_DIGITS,r=0,a=this.points.length;r<a;r++)t.push(o(this.points[r].x-i,s),",",o(this.points[r].y-n,s)," ");return["<"+this.type+" ","COMMON_PARTS",'points="',t.join(""),'" />\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,s=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-s);for(var o=0;o<i;o++)e=this.points[o],t.lineTo(e.x-n,e.y-s);return!0},_render:function(t){this.commonRender(t)&&this._renderPaintInOrder(t)},complexity:function(){return this.get("points").length}}),e.Polyline.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polyline.fromElementGenerator=function(t){return function(n,s,o){if(!n)return s(null);o||(o={});var r=e.parsePointsAttribute(n.getAttribute("points")),a=e.parseAttributes(n,e[t].ATTRIBUTE_NAMES);a.fromSVG=!0,s(new e[t](r,i(a,o)))}},e.Polyline.fromElement=e.Polyline.fromElementGenerator("Polyline"),e.Polyline.fromObject=function(t,i){return e.Object._fromObject("Polyline",t,i,"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.projectStrokeOnPoints;e.Polygon?e.warn("fabric.Polygon is already defined"):(e.Polygon=e.util.createClass(e.Polyline,{type:"polygon",_projectStrokeOnPoints:function(){return i(this.points,this)},_render:function(t){this.commonRender(t)&&(t.closePath(),this._renderPaintInOrder(t))}}),e.Polygon.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polygon.fromElement=e.Polyline.fromElementGenerator("Polygon"),e.Polygon.fromObject=function(t,i){e.Object._fromObject("Polygon",t,i,"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.array.min,n=e.util.array.max,s=e.util.object.extend,o=e.util.object.clone,r=e.util.toFixed;e.Path?e.warn("fabric.Path is already defined"):(e.Path=e.util.createClass(e.Object,{type:"path",path:null,cacheProperties:e.Object.prototype.cacheProperties.concat("path","fillRule"),stateProperties:e.Object.prototype.stateProperties.concat("path"),initialize:function(t,e){delete(e=o(e||{})).path,this.callSuper("initialize",e),this._setPath(t||[],e)},_setPath:function(t,i){this.path=e.util.makePathSimpler(Array.isArray(t)?t:e.util.parsePath(t)),e.Polyline.prototype._setPositionDimensions.call(this,i||{})},_renderPathCommands:function(t){var e,i=0,n=0,s=0,o=0,r=0,a=0,l=-this.pathOffset.x,h=-this.pathOffset.y;t.beginPath();for(var c=0,d=this.path.length;c<d;++c)switch((e=this.path[c])[0]){case"L":s=e[1],o=e[2],t.lineTo(s+l,o+h);break;case"M":i=s=e[1],n=o=e[2],t.moveTo(s+l,o+h);break;case"C":s=e[5],o=e[6],r=e[3],a=e[4],t.bezierCurveTo(e[1]+l,e[2]+h,r+l,a+h,s+l,o+h);break;case"Q":t.quadraticCurveTo(e[1]+l,e[2]+h,e[3]+l,e[4]+h),s=e[3],o=e[4],r=e[1],a=e[2];break;case"z":case"Z":s=i,o=n,t.closePath()}},_render:function(t){this._renderPathCommands(t),this._renderPaintInOrder(t)},toString:function(){return"#<fabric.Path ("+this.complexity()+'): { "top": '+this.top+', "left": '+this.left+" }>"},toObject:function(t){return s(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["<path ","COMMON_PARTS",'d="',e.util.joinPath(this.path),'" stroke-linecap="round" ',"/>\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+r(-this.pathOffset.x,t)+", "+r(-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,s,o=[],r=[],a=0,l=0,h=0,c=0,d=0,u=this.path.length;d<u;++d){switch((t=this.path[d])[0]){case"L":h=t[1],c=t[2],s=[];break;case"M":a=h=t[1],l=c=t[2],s=[];break;case"C":s=e.util.getBoundsOfCurve(h,c,t[1],t[2],t[3],t[4],t[5],t[6]),h=t[5],c=t[6];break;case"Q":s=e.util.getBoundsOfCurve(h,c,t[1],t[2],t[1],t[2],t[3],t[4]),h=t[3],c=t[4];break;case"z":case"Z":h=a,c=l}s.forEach(function(t){o.push(t.x),r.push(t.y)}),o.push(h),r.push(c)}var p=i(o)||0,g=i(r)||0;return{left:p,top:g,width:(n(o)||0)-p,height:(n(r)||0)-g}}}),e.Path.fromObject=function(t,i){if("string"==typeof t.sourcePath){var n=t.sourcePath;e.loadSVGFromURL(n,function(e){var n=e[0];n.setOptions(t),i&&i(n)})}else e.Object._fromObject("Path",t,i,"path")},e.Path.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(["d"]),e.Path.fromElement=function(t,i,n){var o=e.parseAttributes(t,e.Path.ATTRIBUTE_NAMES);o.fromSVG=!0,i(new e.Path(o.d,s(o,n)))})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.array.min,n=e.util.array.max;e.Group||(e.Group=e.util.createClass(e.Object,e.Collection,{type:"group",strokeWidth:0,subTargetCheck:!1,cacheProperties:[],useSetOnGroup:!1,initialize:function(t,e,i){e=e||{},this._objects=[],i&&this.callSuper("initialize",e),this._objects=t||[];for(var n=this._objects.length;n--;)this._objects[n].group=this;if(i)this._updateObjectsACoords();else{var s=e&&e.centerPoint;void 0!==e.originX&&(this.originX=e.originX),void 0!==e.originY&&(this.originY=e.originY),s||this._calcBounds(),this._updateObjectsCoords(s),delete e.centerPoint,this.callSuper("initialize",e)}this.setCoords()},_updateObjectsACoords:function(){for(var t=this._objects.length;t--;)this._objects[t].setCoords(!0)},_updateObjectsCoords:function(t){t=t||this.getCenterPoint();for(var e=this._objects.length;e--;)this._updateObjectCoords(this._objects[e],t)},_updateObjectCoords:function(t,e){var i=t.left,n=t.top;t.set({left:i-e.x,top:n-e.y}),t.group=this,t.setCoords(!0)},toString:function(){return"#<fabric.Group: ("+this.complexity()+")>"},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 n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter(function(t){return!t.excludeFromExport}).map(function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var s=e.toObject(t);return e.includeDefaultValues=n,s}),s=e.Object.prototype.toObject.call(this,t);return s.objects=n,s},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var s=this.includeDefaultValues;i=this._objects.map(function(e){var i=e.includeDefaultValues;e.includeDefaultValues=s;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n})}var o=e.Object.prototype.toDatalessObject.call(this,t);return o.objects=i,o},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,n=this._objects.length;i<n;i++)if(this._objects[i].willDrawShadow())return this.ownCaching=!1,!1;return t},willDrawShadow:function(){if(e.Object.prototype.willDrawShadow.call(this))return!0;for(var t=0,i=this._objects.length;t<i;t++)if(this._objects[t].willDrawShadow())return!0;return!1},isOnACache:function(){return this.ownCaching||this.group&&this.group.isOnACache()},drawObject:function(t){for(var e=0,i=this._objects.length;e<i;e++)this._objects[e].render(t);this._drawClipPath(t,this.clipPath)},isCacheDirty:function(t){if(this.callSuper("isCacheDirty",t))return!0;if(!this.statefullCache)return!1;for(var e=0,i=this._objects.length;e<i;e++)if(this._objects[e].isCacheDirty(!0)){if(this._cacheCanvas){var n=this.cacheWidth/this.zoomX,s=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-n/2,-s/2,n,s)}return!0}return!1},_restoreObjectsState:function(){var t=this.calcOwnMatrix();return this._objects.forEach(function(i){e.util.addTransformToObject(i,t),delete i.group,i.setCoords()}),this},destroy:function(){return this._objects.forEach(function(t){t.set("dirty",!0)}),this._restoreObjectsState()},dispose:function(){this.callSuper("dispose"),this.forEachObject(function(t){t.dispose&&t.dispose()}),this._objects=[]},toActiveSelection:function(){if(this.canvas){var t=this._objects,i=this.canvas;this._objects=[];var n=this.toObject();delete n.objects;var s=new e.ActiveSelection([]);return s.set(n),s.type="activeSelection",i.remove(this),t.forEach(function(t){t.group=s,t.dirty=!0,i.add(t)}),s.canvas=i,s._objects=t,i._activeObject=s,s.setCoords(),s}},ungroupOnCanvas:function(){return this._restoreObjectsState()},setObjectsCoords:function(){return this.forEachObject(function(t){t.setCoords(!0)}),this},_calcBounds:function(t){for(var e,i,n,s,o=[],r=[],a=["tr","br","bl","tl"],l=0,h=this._objects.length,c=a.length;l<h;++l){for(n=(e=this._objects[l]).calcACoords(),s=0;s<c;s++)i=a[s],o.push(n[i].x),r.push(n[i].y);e.aCoords=n}this._getBounds(o,r,t)},_getBounds:function(t,s,o){var r=new e.Point(i(t),i(s)),a=new e.Point(n(t),n(s)),l=r.y||0,h=r.x||0,c=a.x-r.x||0,d=a.y-r.y||0;this.width=c,this.height=d,o||this.setPositionByOrigin({x:h,y:l},"left","top")},_toSVG:function(t){for(var e=["<g ","COMMON_PARTS"," >\n"],i=0,n=this._objects.length;i<n;i++)e.push("\t\t",this._objects[i].toSVG(t));return e.push("</g>\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,n=this._objects.length;i<n;i++)e.push("\t",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}}),e.Group.fromObject=function(t,i){var n=t.objects,s=e.util.object.clone(t,!0);delete s.objects,"string"!=typeof n?e.util.enlivenObjects(n,function(n){var s=e.util.object.clone(t,!0);delete s.objects,e.util.enlivenObjectEnlivables(t,s,function(){i&&i(new e.Group(n,s,!0))})}):e.loadSVGFromURL(n,function(o){var r=e.util.groupSVGElements(o,t,n);r.set(s),i&&i(r)})})}(e),function(t){var e=t.fabric||(t.fabric={});e.ActiveSelection||(e.ActiveSelection=e.util.createClass(e.Group,{type:"activeSelection",initialize:function(t,i){i=i||{},this._objects=t||[];for(var n=this._objects.length;n--;)this._objects[n].group=this;i.originX&&(this.originX=i.originX),i.originY&&(this.originY=i.originY),this._calcBounds(),this._updateObjectsCoords(),e.Object.prototype.initialize.call(this,i),this.setCoords()},toGroup:function(){var t=this._objects.concat();this._objects=[];var i=e.Object.prototype.toObject.call(this),n=new e.Group([]);if(delete i.type,n.set(i),t.forEach(function(t){t.canvas.remove(t),t.group=n}),n._objects=t,!this.canvas)return n;var s=this.canvas;return s.add(n),s._activeObject=n,n.setCoords(),n},onDeselect:function(){return this.destroy(),!1},toString:function(){return"#<fabric.ActiveSelection: ("+this.complexity()+")>"},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 n=0,s=this._objects.length;n<s;n++)this._objects[n]._renderControls(t,i);t.restore()}}),e.ActiveSelection.fromObject=function(t,i){e.util.enlivenObjects(t.objects,function(n){delete t.objects,i&&i(new e.ActiveSelection(n,t,!0))})})}(e),function(t){var e=T.util.object.extend;t.fabric||(t.fabric={}),t.fabric.Image?T.warn("fabric.Image is already defined."):(T.Image=T.util.createClass(T.Object,{type:"image",strokeWidth:0,srcFromAttribute:!1,_lastScaleX:1,_lastScaleY:1,_filterScalingX:1,_filterScalingY:1,minimumScaleTrigger:.5,stateProperties:T.Object.prototype.stateProperties.concat("cropX","cropY"),cacheProperties:T.Object.prototype.cacheProperties.concat("cropX","cropY"),cacheKey:"",cropX:0,cropY:0,imageSmoothing:!0,initialize:function(t,e){e||(e={}),this.filters=[],this.cacheKey="texture"+T.Object.__uid++,this.callSuper("initialize",e),this._initElement(t,e)},getElement:function(){return this._element||{}},setElement:function(t,e){return this.removeTexture(this.cacheKey),this.removeTexture(this.cacheKey+"_filtered"),this._element=t,this._originalElement=t,this._initConfig(e),0!==this.filters.length&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters(),this},removeTexture:function(t){var e=T.filterBackend;e&&e.evictCachesForKey&&e.evictCachesForKey(t)},dispose:function(){this.callSuper("dispose"),this.removeTexture(this.cacheKey),this.removeTexture(this.cacheKey+"_filtered"),this._cacheContext=void 0,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this))},getCrossOrigin:function(){return this._originalElement&&(this._originalElement.crossOrigin||null)},getOriginalSize:function(){var t=this.getElement();return{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}},_stroke:function(t){if(this.stroke&&0!==this.strokeWidth){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,-i),t.lineTo(e,-i),t.lineTo(e,i),t.lineTo(-e,i),t.lineTo(-e,-i),t.closePath()}},toObject:function(t){var i=[];this.filters.forEach(function(t){t&&i.push(t.toObject())});var n=e(this.callSuper("toObject",["cropX","cropY"].concat(t)),{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:i});return this.resizeFilter&&(n.resizeFilter=this.resizeFilter.toObject()),n},hasCrop:function(){return this.cropX||this.cropY||this.width<this._element.width||this.height<this._element.height},_toSVG:function(){var t,e=[],i=[],n=this._element,s=-this.width/2,o=-this.height/2,r="",a="";if(!n)return[];if(this.hasCrop()){var l=T.Object.__uid++;e.push('<clipPath id="imageCrop_'+l+'">\n','\t<rect x="'+s+'" y="'+o+'" width="'+this.width+'" height="'+this.height+'" />\n',"</clipPath>\n"),r=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t<image ","COMMON_PARTS",'xlink:href="',this.getSvgSrc(!0),'" x="',s-this.cropX,'" y="',o-this.cropY,'" width="',n.width||n.naturalWidth,'" height="',n.height||n.height,a,'"',r,"></image>\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,t=["\t<rect ",'x="',s,'" y="',o,'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'"/>\n'],this.fill=h}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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)},this,i&&i.crossOrigin),this},toString:function(){return'#<fabric.Image: { src: "'+this.getSrc()+'" }>'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,s=i.scaleY,o=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&s>e)return this._element=o,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=s);T.filterBackend||(T.filterBackend=T.initFilterBackend());var r=T.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,l=o.width,h=o.height;r.width=l,r.height=h,this._element=r,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=s,T.filterBackend.applyFilters([t],o,l,h,this._element,a),this._filterScalingX=r.width/this._originalElement.width,this._filterScalingY=r.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,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var s=T.util.createCanvasElement();s.width=i,s.height=n,this._element=s,this._filteredEl=s}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,n,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,n=this._filterScalingY,s=this.width,o=this.height,r=Math.min,a=Math.max,l=a(this.cropX,0),h=a(this.cropY,0),c=e.naturalWidth||e.width,d=e.naturalHeight||e.height,u=l*i,p=h*n,g=r(s*i,c-u),f=r(o*n,d-p),m=-s/2,v=-o/2,y=r(s,c/i-l),x=r(o,d/n-h);e&&t.drawImage(e,u,p,g,f,m,v,y,x)}},_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,n=this._element.height,s=1,o=1,r=0,a=0,l=0,h=0,c=this.width,d=this.height,u={width:c,height:d};return!e||"none"===e.alignX&&"none"===e.alignY?(s=c/i,o=d/n):("meet"===e.meetOrSlice&&(t=(c-i*(s=o=T.util.findScaleToFit(this._element,u)))/2,"Min"===e.alignX&&(r=-t),"Max"===e.alignX&&(r=t),t=(d-n*o)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(s=o=T.util.findScaleToCover(this._element,u)),"Mid"===e.alignX&&(l=t/2),"Max"===e.alignX&&(l=t),t=n-d/o,"Mid"===e.alignY&&(h=t/2),"Max"===e.alignY&&(h=t),i=c/s,n=d/o)),{width:i,height:n,scaleX:s,scaleY:o,offsetLeft:r,offsetTop:a,cropX:l,cropY:h}}}),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,n){n?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,function(n){i.filters=n||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],function(n){i.resizeFilter=n[0],T.util.enlivenObjectEnlivables(i,i,function(){var n=new T.Image(t,i);e(n,!1)})})})},null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,function(t,n){e&&e(new T.Image(t,i),n)},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,n){var s=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(s["xlink:href"],i,e(n?T.util.object.clone(n):{},s))})}(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,n=t.onChange||e,s=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){s.rotate(t),n()},onComplete:function(){s.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(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,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"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),s=!1;if(n){T.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),s=T.maxTextureSize>=e;for(var o=["highp","mediump","lowp"],r=0;r<3;r++)if(t(n,o[r])){T.webGlPrecision=o[r];break}}return this.isSupported=s,s},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,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var s="undefined"!=typeof ArrayBuffer,o="undefined"!=typeof Uint8ClampedArray;if(n&&i&&s&&o){var r=T.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=P);var l,h,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:r};r.width=t,r.height=e,l=window.performance.now(),_.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),P.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=a,this.copyGLTo2D=P):this.copyGLTo2D=_}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},s=i.getContext("webgl",n);s||(s=i.getContext("experimental-webgl",n)),s&&(s.clearColor(0,0,0,0),this.canvas=i,this.gl=s)},applyFilters:function(t,e,i,n,s,o){var r,a=this.gl;o&&(r=this.getCachedTexture(o,e));var l={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!r&&e),targetTexture:this.createTexture(a,i,n),originalTexture:r||this.createTexture(a,i,n,!r&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:s},h=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,h),t.forEach(function(t){t&&t.applyTo(l)}),function(t){var e=t.targetCanvas,i=e.width,n=e.height,s=t.destinationWidth,o=t.destinationHeight;i===s&&n===o||(e.width=s,e.height=o)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(h),s.getContext("2d").setTransform(1,0,0,1,0,0),l},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var s=t.createTexture();return t.bindTexture(t.TEXTURE_2D,s),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),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),s},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:_,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 n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),s=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),s&&(e.vendor=s.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,n,s){var o=s.getContext("2d");o.drawImage(e,0,0,i,n);var r={sourceWidth:i,sourceHeight:n,imageData:o.getImageData(0,0,i,n),originalEl:e,originalImageData:o.getImageData(0,0,i,n),canvasEl:s,ctx:o,filterBackend:this};return t.forEach(function(t){t.applyTo(r)}),r.imageData.width===i&&r.imageData.height===n||(s.width=r.imageData.width,s.height=r.imageData.height),o.putImageData(r.imageData,0,0),r}}}(),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 n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(s,e),t.compileShader(s),!t.getShaderParameter(s,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(s));var o=t.createProgram();if(t.attachShader(o,n),t.attachShader(o,s),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(o));var r=this.getAttributeLocations(t,o),a=this.getUniformLocations(t,o)||{};return a.uStepW=t.getUniformLocation(o,"uStepW"),a.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:r,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,s=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,s),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.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,n=e.util.createClass;i.ColorMatrix=n(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,n,s,o,r=t.imageData.data,a=r.length,l=this.matrix,h=this.colorsOnly;for(o=0;o<a;o+=4)e=r[o],i=r[o+1],n=r[o+2],h?(r[o]=e*l[0]+i*l[1]+n*l[2]+255*l[4],r[o+1]=e*l[5]+i*l[6]+n*l[7]+255*l[9],r[o+2]=e*l[10]+i*l[11]+n*l[12]+255*l[14]):(s=r[o+3],r[o]=e*l[0]+i*l[1]+n*l[2]+s*l[3]+255*l[4],r[o+1]=e*l[5]+i*l[6]+n*l[7]+s*l[8]+255*l[9],r[o+2]=e*l[10]+i*l[11]+n*l[12]+s*l[13]+255*l[14],r[o+3]=e*l[15]+i*l[16]+n*l[17]+s*l[18]+255*l[19])},getUniformLocations:function(t,e){return{uColorMatrix:t.getUniformLocation(e,"uColorMatrix"),uConstants:t.getUniformLocation(e,"uConstants")}},sendUniformData:function(t,e){var i=this.matrix,n=[i[0],i[1],i[2],i[3],i[5],i[6],i[7],i[8],i[10],i[11],i[12],i[13],i[15],i[16],i[17],i[18]],s=[i[4],i[9],i[14],i[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,n),t.uniform4fv(e.uConstants,s)}}),e.Image.filters.ColorMatrix.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Brightness=n(i.BaseFilter,{type:"Brightness",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBrightness;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += uBrightness;\ngl_FragColor = color;\n}",brightness:0,mainParameter:"brightness",applyTo2d:function(t){if(0!==this.brightness){var e,i=t.imageData.data,n=i.length,s=Math.round(255*this.brightness);for(e=0;e<n;e+=4)i[e]=i[e]+s,i[e+1]=i[e+1]+s,i[e+2]=i[e+2]+s}},getUniformLocations:function(t,e){return{uBrightness:t.getUniformLocation(e,"uBrightness")}},sendUniformData:function(t,e){t.uniform1f(e.uBrightness,this.brightness)}}),e.Image.filters.Brightness.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,s=e.util.createClass;n.Convolute=s(n.BaseFilter,{type:"Convolute",opaque:!1,matrix:[0,0,0,0,1,0,0,0,0],fragmentSource:{Convolute_3_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_3_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_5_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_5_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_7_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_7_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_9_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_9_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}"},retrieveShader:function(t){var e=Math.sqrt(this.matrix.length),i=this.type+"_"+e+"_"+(this.opaque?1:0),n=this.fragmentSource[i];return t.programCache.hasOwnProperty(i)||(t.programCache[i]=this.createProgram(t.context,n)),t.programCache[i]},applyTo2d:function(t){var e,i,n,s,o,r,a,l,h,c,d,u,p,g=t.imageData,f=g.data,m=this.matrix,v=Math.round(Math.sqrt(m.length)),y=Math.floor(v/2),x=g.width,w=g.height,C=t.ctx.createImageData(x,w),b=C.data,S=this.opaque?1:0;for(d=0;d<w;d++)for(c=0;c<x;c++){for(o=4*(d*x+c),e=0,i=0,n=0,s=0,p=0;p<v;p++)for(u=0;u<v;u++)r=c+u-y,(a=d+p-y)<0||a>=w||r<0||r>=x||(l=4*(a*x+r),h=m[p*v+u],e+=f[l]*h,i+=f[l+1]*h,n+=f[l+2]*h,S||(s+=f[l+3]*h));b[o]=e,b[o+1]=i,b[o+2]=n,b[o+3]=S?f[o+3]:s}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,n=e.util.createClass;i.Grayscale=n(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,n=t.imageData.data,s=n.length,o=this.mode;for(e=0;e<s;e+=4)"average"===o?i=(n[e]+n[e+1]+n[e+2])/3:"lightness"===o?i=(Math.min(n[e],n[e+1],n[e+2])+Math.max(n[e],n[e+1],n[e+2]))/2:"luminosity"===o&&(i=.21*n[e]+.72*n[e+1]+.07*n[e+2]),n[e]=i,n[e+1]=i,n[e+2]=i},retrieveShader:function(t){var e=this.type+"_"+this.mode;if(!t.programCache.hasOwnProperty(e)){var i=this.fragmentSource[this.mode];t.programCache[e]=this.createProgram(t.context,i)}return t.programCache[e]},getUniformLocations:function(t,e){return{uMode:t.getUniformLocation(e,"uMode")}},sendUniformData:function(t,e){t.uniform1i(e.uMode,1)},isNeutralState:function(){return!1}}),e.Image.filters.Grayscale.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Invert=n(i.BaseFilter,{type:"Invert",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uInvert;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nif (uInvert == 1) {\ngl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n} else {\ngl_FragColor = color;\n}\n}",invert:!0,mainParameter:"invert",applyTo2d:function(t){var e,i=t.imageData.data,n=i.length;for(e=0;e<n;e+=4)i[e]=255-i[e],i[e+1]=255-i[e+1],i[e+2]=255-i[e+2]},isNeutralState:function(){return!this.invert},getUniformLocations:function(t,e){return{uInvert:t.getUniformLocation(e,"uInvert")}},sendUniformData:function(t,e){t.uniform1i(e.uInvert,this.invert)}}),e.Image.filters.Invert.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,s=e.util.createClass;n.Noise=s(n.BaseFilter,{type:"Noise",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uStepH;\nuniform float uNoise;\nuniform float uSeed;\nvarying vec2 vTexCoord;\nfloat rand(vec2 co, float seed, float vScale) {\nreturn fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n}\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\ngl_FragColor = color;\n}",mainParameter:"noise",noise:0,applyTo2d:function(t){if(0!==this.noise){var e,i,n=t.imageData.data,s=n.length,o=this.noise;for(e=0,s=n.length;e<s;e+=4)i=(.5-Math.random())*o,n[e]+=i,n[e+1]+=i,n[e+2]+=i}},getUniformLocations:function(t,e){return{uNoise:t.getUniformLocation(e,"uNoise"),uSeed:t.getUniformLocation(e,"uSeed")}},sendUniformData:function(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())},toObject:function(){return i(this.callSuper("toObject"),{noise:this.noise})}}),e.Image.filters.Noise.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Pixelate=n(i.BaseFilter,{type:"Pixelate",blocksize:4,mainParameter:"blocksize",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBlocksize;\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nfloat blockW = uBlocksize * uStepW;\nfloat blockH = uBlocksize * uStepW;\nint posX = int(vTexCoord.x / blockW);\nint posY = int(vTexCoord.y / blockH);\nfloat fposX = float(posX);\nfloat fposY = float(posY);\nvec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\nvec4 color = texture2D(uTexture, squareCoords);\ngl_FragColor = color;\n}",applyTo2d:function(t){var e,i,n,s,o,r,a,l,h,c,d,u=t.imageData,p=u.data,g=u.height,f=u.width;for(i=0;i<g;i+=this.blocksize)for(n=0;n<f;n+=this.blocksize)for(s=p[e=4*i*f+4*n],o=p[e+1],r=p[e+2],a=p[e+3],c=Math.min(i+this.blocksize,g),d=Math.min(n+this.blocksize,f),l=i;l<c;l++)for(h=n;h<d;h++)p[e=4*l*f+4*h]=s,p[e+1]=o,p[e+2]=r,p[e+3]=a},isNeutralState:function(){return 1===this.blocksize},getUniformLocations:function(t,e){return{uBlocksize:t.getUniformLocation(e,"uBlocksize"),uStepW:t.getUniformLocation(e,"uStepW"),uStepH:t.getUniformLocation(e,"uStepH")}},sendUniformData:function(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}),e.Image.filters.Pixelate.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,s=e.util.createClass;n.RemoveColor=s(n.BaseFilter,{type:"RemoveColor",color:"#FFFFFF",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\ngl_FragColor.a = 0.0;\n}\n}",distance:.02,useAlpha:!1,applyTo2d:function(t){var i,n,s,o,r=t.imageData.data,a=255*this.distance,l=new e.Color(this.color).getSource(),h=[l[0]-a,l[1]-a,l[2]-a],c=[l[0]+a,l[1]+a,l[2]+a];for(i=0;i<r.length;i+=4)n=r[i],s=r[i+1],o=r[i+2],n>h[0]&&s>h[1]&&o>h[2]&&n<c[0]&&s<c[1]&&o<c[2]&&(r[i+3]=0)},getUniformLocations:function(t,e){return{uLow:t.getUniformLocation(e,"uLow"),uHigh:t.getUniformLocation(e,"uHigh")}},sendUniformData:function(t,i){var n=new e.Color(this.color).getSource(),s=parseFloat(this.distance),o=[0+n[0]/255-s,0+n[1]/255-s,0+n[2]/255-s,1],r=[n[0]/255+s,n[1]/255+s,n[2]/255+s,1];t.uniform4fv(i.uLow,o),t.uniform4fv(i.uHigh,r)},toObject:function(){return i(this.callSuper("toObject"),{color:this.color,distance:this.distance})}}),e.Image.filters.RemoveColor.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass,s={Brownie:[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0],Vintage:[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0],Kodachrome:[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0],Technicolor:[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0],Polaroid:[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],Sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],BlackWhite:[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]};for(var o in s)i[o]=n(i.ColorMatrix,{type:o,matrix:s[o],mainParameter:!1,colorsOnly:!0}),e.Image.filters[o].fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric,i=e.Image.filters,n=e.util.createClass;i.BlendColor=n(i.BaseFilter,{type:"BlendColor",color:"#F95C63",mode:"multiply",alpha:1,fragmentSource:{multiply:"gl_FragColor.rgb *= uColor.rgb;\n",screen:"gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",add:"gl_FragColor.rgb += uColor.rgb;\n",diff:"gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",subtract:"gl_FragColor.rgb -= uColor.rgb;\n",lighten:"gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",darken:"gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",exclusion:"gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",overlay:"if (uColor.r < 0.5) {\ngl_FragColor.r *= 2.0 * uColor.r;\n} else {\ngl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n}\nif (uColor.g < 0.5) {\ngl_FragColor.g *= 2.0 * uColor.g;\n} else {\ngl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n}\nif (uColor.b < 0.5) {\ngl_FragColor.b *= 2.0 * uColor.b;\n} else {\ngl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n}\n",tint:"gl_FragColor.rgb *= (1.0 - uColor.a);\ngl_FragColor.rgb += uColor.rgb;\n"},buildSource:function(t){return"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ngl_FragColor = color;\nif (color.a > 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,n,s,o,r,a,l,h=t.imageData.data,c=h.length,d=1-this.alpha;i=(l=new e.Color(this.color).getSource())[0]*this.alpha,n=l[1]*this.alpha,s=l[2]*this.alpha;for(var u=0;u<c;u+=4)switch(o=h[u],r=h[u+1],a=h[u+2],this.mode){case"multiply":h[u]=o*i/255,h[u+1]=r*n/255,h[u+2]=a*s/255;break;case"screen":h[u]=255-(255-o)*(255-i)/255,h[u+1]=255-(255-r)*(255-n)/255,h[u+2]=255-(255-a)*(255-s)/255;break;case"add":h[u]=o+i,h[u+1]=r+n,h[u+2]=a+s;break;case"diff":case"difference":h[u]=Math.abs(o-i),h[u+1]=Math.abs(r-n),h[u+2]=Math.abs(a-s);break;case"subtract":h[u]=o-i,h[u+1]=r-n,h[u+2]=a-s;break;case"darken":h[u]=Math.min(o,i),h[u+1]=Math.min(r,n),h[u+2]=Math.min(a,s);break;case"lighten":h[u]=Math.max(o,i),h[u+1]=Math.max(r,n),h[u+2]=Math.max(a,s);break;case"overlay":h[u]=i<128?2*o*i/255:255-2*(255-o)*(255-i)/255,h[u+1]=n<128?2*r*n/255:255-2*(255-r)*(255-n)/255,h[u+2]=s<128?2*a*s/255:255-2*(255-a)*(255-s)/255;break;case"exclusion":h[u]=i+o-2*i*o/255,h[u+1]=n+r-2*n*r/255,h[u+2]=s+a-2*s*a/255;break;case"tint":h[u]=i+o*d,h[u+1]=n+r*d,h[u+2]=s+a*d}},getUniformLocations:function(t,e){return{uColor:t.getUniformLocation(e,"uColor")}},sendUniformData:function(t,i){var n=new e.Color(this.color).getSource();n[0]=this.alpha*n[0]/255,n[1]=this.alpha*n[1]/255,n[2]=this.alpha*n[2]/255,n[3]=this.alpha,t.uniform4fv(i.uColor,n)},toObject:function(){return{type:this.type,color:this.color,mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendColor.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric,i=e.Image.filters,n=e.util.createClass;i.BlendImage=n(i.BaseFilter,{type:"BlendImage",image:null,mode:"multiply",alpha:1,vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nuniform mat3 uTransformMatrix;\nvoid main() {\nvTexCoord = aPosition;\nvTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:{multiply:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.rgba *= color2.rgba;\ngl_FragColor = color;\n}",mask:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.a = color2.a;\ngl_FragColor = color;\n}"},retrieveShader:function(t){var e=this.type+"_"+this.mode,i=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,i)),t.programCache[e]},applyToWebGL:function(t){var e=t.context,i=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,i,e.TEXTURE1),this.callSuper("applyToWebGL",t),this.unbindAdditionalTexture(e,e.TEXTURE1)},createTexture:function(t,e){return t.getCachedTexture(e.cacheKey,e._element)},calculateMatrix:function(){var t=this.image,e=t._element.width,i=t._element.height;return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/i,1]},applyTo2d:function(t){var i,n,s,o,r,a,l,h,c,d,u,p=t.imageData,g=t.filterBackend.resources,f=p.data,m=f.length,v=p.width,y=p.height,x=this.image;g.blendImage||(g.blendImage=e.util.createCanvasElement()),d=(c=g.blendImage).getContext("2d"),c.width!==v||c.height!==y?(c.width=v,c.height=y):d.clearRect(0,0,v,y),d.setTransform(x.scaleX,0,0,x.scaleY,x.left,x.top),d.drawImage(x._element,0,0,v,y),u=d.getImageData(0,0,v,y).data;for(var w=0;w<m;w+=4)switch(r=f[w],a=f[w+1],l=f[w+2],h=f[w+3],i=u[w],n=u[w+1],s=u[w+2],o=u[w+3],this.mode){case"multiply":f[w]=r*i/255,f[w+1]=a*n/255,f[w+2]=l*s/255,f[w+3]=h*o/255;break;case"mask":f[w+3]=o}},getUniformLocations:function(t,e){return{uTransformMatrix:t.getUniformLocation(e,"uTransformMatrix"),uImage:t.getUniformLocation(e,"uImage")}},sendUniformData:function(t,e){var i=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,i)},toObject:function(){return{type:this.type,image:this.image&&this.image.toObject(),mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendImage.fromObject=function(t,i){e.Image.fromObject(t.image,function(n){var s=e.util.object.clone(t);s.image=n,i(new e.Image.filters.BlendImage(s))})}}(e),function(t){var e=t.fabric||(t.fabric={}),i=Math.pow,n=Math.floor,s=Math.sqrt,o=Math.abs,r=Math.round,a=Math.sin,l=Math.ceil,h=e.Image.filters,c=e.util.createClass;h.Resize=c(h.BaseFilter,{type:"Resize",resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3,getUniformLocations:function(t,e){return{uDelta:t.getUniformLocation(e,"uDelta"),uTaps:t.getUniformLocation(e,"uTaps")}},sendUniformData:function(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)},retrieveShader:function(t){var e=this.getFilterWindow(),i=this.type+"_"+e;if(!t.programCache.hasOwnProperty(i)){var n=this.generateShader(e);t.programCache[i]=this.createProgram(t.context,n)}return t.programCache[i]},getFilterWindow:function(){var t=this.tempScale;return Math.ceil(this.lanczosLobes/t)},getTaps:function(){for(var t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,i=this.getFilterWindow(),n=new Array(i),s=1;s<=i;s++)n[s-1]=t(s*e);return n},generateShader:function(t){for(var e=new Array(t),i=this.fragmentSourceTOP,n=1;n<=t;n++)e[n-1]=n+".0 * uDelta";return i+="uniform float uTaps["+t+"];\n",i+="void main() {\n",i+="  vec4 color = texture2D(uTexture, vTexCoord);\n",i+="  float sum = 1.0;\n",e.forEach(function(t,e){i+="  color += texture2D(uTexture, vTexCoord + "+t+") * uTaps["+e+"];\n",i+="  color += texture2D(uTexture, vTexCoord - "+t+") * uTaps["+e+"];\n",i+="  sum += 2.0 * uTaps["+e+"];\n"}),i+="  gl_FragColor = color / sum;\n",i+="}"},fragmentSourceTOP:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\n",applyTo:function(t){t.webgl?(t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t),t.sourceHeight=t.destinationHeight):this.applyTo2d(t)},isNeutralState:function(){return 1===this.scaleX&&1===this.scaleY},lanczosCreate:function(t){return function(e){if(e>=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,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var s,o=e.width,a=e.height,l=r(o*i),h=r(a*n);"sliceHack"===this.resizeType?s=this.sliceByTwo(t,o,a,l,h):"hermite"===this.resizeType?s=this.hermiteFastResize(t,o,a,l,h):"bilinear"===this.resizeType?s=this.bilinearFiltering(t,o,a,l,h):"lanczos"===this.resizeType&&(s=this.lanczosResize(t,o,a,l,h)),t.imageData=s},sliceByTwo:function(t,i,s,o,r){var a,l,h=t.imageData,c=.5,d=!1,u=!1,p=i*c,g=s*c,f=e.filterBackend.resources,m=0,v=0,y=i,x=0;for(f.sliceByTwo||(f.sliceByTwo=document.createElement("canvas")),((a=f.sliceByTwo).width<1.5*i||a.height<s)&&(a.width=1.5*i,a.height=s),(l=a.getContext("2d")).clearRect(0,0,1.5*i,s),l.putImageData(h,0,0),o=n(o),r=n(r);!d||!u;)i=p,s=g,o<n(p*c)?p=n(p*c):(p=o,d=!0),r<n(g*c)?g=n(g*c):(g=r,u=!0),l.drawImage(a,m,v,i,s,y,x,p,g),m=y,v=x,x+=g;return l.getImageData(m,v,o,r)},lanczosResize:function(t,e,r,a,h){var c=t.imageData.data,d=t.ctx.createImageData(a,h),u=d.data,p=this.lanczosCreate(this.lanczosLobes),g=this.rcpScaleX,f=this.rcpScaleY,m=2/this.rcpScaleX,v=2/this.rcpScaleY,y=l(g*this.lanczosLobes/2),x=l(f*this.lanczosLobes/2),w={},C={},b={};return function t(l){var S,T,E,_,P,A,I,D,R,k,M;for(C.x=(l+.5)*g,b.x=n(C.x),S=0;S<h;S++){for(C.y=(S+.5)*f,b.y=n(C.y),P=0,A=0,I=0,D=0,R=0,T=b.x-y;T<=b.x+y;T++)if(!(T<0||T>=e)){k=n(1e3*o(T-C.x)),w[k]||(w[k]={});for(var L=b.y-x;L<=b.y+x;L++)L<0||L>=r||(M=n(1e3*o(L-C.y)),w[k][M]||(w[k][M]=p(s(i(k*m,2)+i(M*v,2))/1e3)),(E=w[k][M])>0&&(P+=E,A+=E*c[_=4*(L*e+T)],I+=E*c[_+1],D+=E*c[_+2],R+=E*c[_+3]))}u[_=4*(S*a+l)]=A/P,u[_+1]=I/P,u[_+2]=D/P,u[_+3]=R/P}return++l<a?t(l):d}(0)},bilinearFiltering:function(t,e,i,s,o){var r,a,l,h,c,d,u,p,g,f=0,m=this.rcpScaleX,v=this.rcpScaleY,y=4*(e-1),x=t.imageData.data,w=t.ctx.createImageData(s,o),C=w.data;for(l=0;l<o;l++)for(h=0;h<s;h++)for(c=m*h-(r=n(m*h)),d=v*l-(a=n(v*l)),g=4*(a*e+r),u=0;u<4;u++)p=x[g+u]*(1-c)*(1-d)+x[g+4+u]*c*(1-d)+x[g+y+u]*d*(1-c)+x[g+y+4+u]*c*d,C[f++]=p;return w},hermiteFastResize:function(t,e,i,r,a){for(var h=this.rcpScaleX,c=this.rcpScaleY,d=l(h/2),u=l(c/2),p=t.imageData.data,g=t.ctx.createImageData(r,a),f=g.data,m=0;m<a;m++)for(var v=0;v<r;v++){for(var y=4*(v+m*r),x=0,w=0,C=0,b=0,S=0,T=0,E=0,_=(m+.5)*c,P=n(m*c);P<(m+1)*c;P++)for(var A=o(_-(P+.5))/u,I=(v+.5)*h,D=A*A,R=n(v*h);R<(v+1)*h;R++){var k=o(I-(R+.5))/d,M=s(D+k*k);M>1&&M<-1||(x=2*M*M*M-3*M*M+1)>0&&(E+=x*p[3+(k=4*(R+P*e))],C+=x,p[k+3]<255&&(x=x*p[k+3]/250),b+=x*p[k],S+=x*p[k+1],T+=x*p[k+2],w+=x)}f[y]=b/w,f[y+1]=S/w,f[y+2]=T/w,f[y+3]=E/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,n=e.util.createClass;i.Contrast=n(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,n=i.length,s=Math.floor(255*this.contrast),o=259*(s+255)/(255*(259-s));for(e=0;e<n;e+=4)i[e]=o*(i[e]-128)+128,i[e+1]=o*(i[e+1]-128)+128,i[e+2]=o*(i[e+2]-128)+128}},getUniformLocations:function(t,e){return{uContrast:t.getUniformLocation(e,"uContrast")}},sendUniformData:function(t,e){t.uniform1f(e.uContrast,this.contrast)}}),e.Image.filters.Contrast.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Saturation=n(i.BaseFilter,{type:"Saturation",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uSaturation;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat rgMax = max(color.r, color.g);\nfloat rgbMax = max(rgMax, color.b);\ncolor.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\ncolor.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\ncolor.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\ngl_FragColor = color;\n}",saturation:0,mainParameter:"saturation",applyTo2d:function(t){if(0!==this.saturation){var e,i,n=t.imageData.data,s=n.length,o=-this.saturation;for(e=0;e<s;e+=4)i=Math.max(n[e],n[e+1],n[e+2]),n[e]+=i!==n[e]?(i-n[e])*o:0,n[e+1]+=i!==n[e+1]?(i-n[e+1])*o:0,n[e+2]+=i!==n[e+2]?(i-n[e+2])*o:0}},getUniformLocations:function(t,e){return{uSaturation:t.getUniformLocation(e,"uSaturation")}},sendUniformData:function(t,e){t.uniform1f(e.uSaturation,-this.saturation)}}),e.Image.filters.Saturation.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Vibrance=n(i.BaseFilter,{type:"Vibrance",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uVibrance;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat max = max(color.r, max(color.g, color.b));\nfloat avg = (color.r + color.g + color.b) / 3.0;\nfloat amt = (abs(max - avg) * 2.0) * uVibrance;\ncolor.r += max != color.r ? (max - color.r) * amt : 0.00;\ncolor.g += max != color.g ? (max - color.g) * amt : 0.00;\ncolor.b += max != color.b ? (max - color.b) * amt : 0.00;\ngl_FragColor = color;\n}",vibrance:0,mainParameter:"vibrance",applyTo2d:function(t){if(0!==this.vibrance){var e,i,n,s,o=t.imageData.data,r=o.length,a=-this.vibrance;for(e=0;e<r;e+=4)i=Math.max(o[e],o[e+1],o[e+2]),n=(o[e]+o[e+1]+o[e+2])/3,s=2*Math.abs(i-n)/255*a,o[e]+=i!==o[e]?(i-o[e])*s:0,o[e+1]+=i!==o[e+1]?(i-o[e+1])*s:0,o[e+2]+=i!==o[e+2]?(i-o[e+2])*s:0}},getUniformLocations:function(t,e){return{uVibrance:t.getUniformLocation(e,"uVibrance")}},sendUniformData:function(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}}),e.Image.filters.Vibrance.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Blur=n(i.BaseFilter,{type:"Blur",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\nconst float nSamples = 15.0;\nvec3 v3offset = vec3(12.9898, 78.233, 151.7182);\nfloat random(vec3 scale) {\nreturn fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n}\nvoid main() {\nvec4 color = vec4(0.0);\nfloat total = 0.0;\nfloat offset = random(v3offset);\nfor (float t = -nSamples; t <= nSamples; t++) {\nfloat percent = (t + offset - 0.5) / nSamples;\nfloat weight = 1.0 - abs(percent);\ncolor += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\ntotal += weight;\n}\ngl_FragColor = color / total;\n}",blur:0,mainParameter:"blur",applyTo:function(t){t.webgl?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},applyTo2d:function(t){t.imageData=this.simpleBlur(t)},simpleBlur:function(t){var i,n,s=t.filterBackend.resources,o=t.imageData.width,r=t.imageData.height;s.blurLayer1||(s.blurLayer1=e.util.createCanvasElement(),s.blurLayer2=e.util.createCanvasElement()),i=s.blurLayer1,n=s.blurLayer2,i.width===o&&i.height===r||(n.width=i.width=o,n.height=i.height=r);var a,l,h,c,d=i.getContext("2d"),u=n.getContext("2d"),p=.06*this.blur*.5;for(d.putImageData(t.imageData,0,0),u.clearRect(0,0,o,r),c=-15;c<=15;c++)h=p*(l=c/15)*o+(a=(Math.random()-.5)/4),u.globalAlpha=1-Math.abs(l),u.drawImage(i,h,a),d.drawImage(n,0,0),u.globalAlpha=1,u.clearRect(0,0,n.width,n.height);for(c=-15;c<=15;c++)h=p*(l=c/15)*r+(a=(Math.random()-.5)/4),u.globalAlpha=1-Math.abs(l),u.drawImage(i,a,h),d.drawImage(n,0,0),u.globalAlpha=1,u.clearRect(0,0,n.width,n.height);t.ctx.drawImage(i,0,0);var g=t.ctx.getImageData(0,0,i.width,i.height);return d.globalAlpha=1,d.clearRect(0,0,i.width,i.height),g},getUniformLocations:function(t,e){return{delta:t.getUniformLocation(e,"uDelta")}},sendUniformData:function(t,e){var i=this.chooseRightDelta();t.uniform2fv(e.delta,i)},chooseRightDelta:function(){var t,e=1,i=[0,0];return this.horizontal?this.aspectRatio>1&&(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,n=e.util.createClass;i.Gamma=n(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,n=this.gamma,s=i.length,o=1/n[0],r=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,s=256;e<s;e++)this.rVals[e]=255*Math.pow(e/255,o),this.gVals[e]=255*Math.pow(e/255,r),this.bVals[e]=255*Math.pow(e/255,a);for(e=0,s=i.length;e<s;e+=4)i[e]=this.rVals[i[e]],i[e+1]=this.gVals[i[e+1]],i[e+2]=this.bVals[i[e+2]]},getUniformLocations:function(t,e){return{uGamma:t.getUniformLocation(e,"uGamma")}},sendUniformData:function(t,e){t.uniform3fv(e.uGamma,this.gamma)}}),e.Image.filters.Gamma.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Composed=n(i.BaseFilter,{type:"Composed",subFilters:[],initialize:function(t){this.callSuper("initialize",t),this.subFilters=this.subFilters.slice(0)},applyTo:function(t){t.passes+=this.subFilters.length-1,this.subFilters.forEach(function(e){e.applyTo(t)})},toObject:function(){return e.util.object.extend(this.callSuper("toObject"),{subFilters:this.subFilters.map(function(t){return t.toObject()})})},isNeutralState:function(){return!this.subFilters.some(function(t){return!t.isNeutralState()})}}),e.Image.filters.Composed.fromObject=function(t,i){var n=(t.subFilters||[]).map(function(t){return new e.Image.filters[t.type](t)}),s=new e.Image.filters.Composed({subFilters:n});return i&&i(s),s}}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.HueRotation=n(i.ColorMatrix,{type:"HueRotation",rotation:0,mainParameter:"rotation",calculateMatrix:function(){var t=this.rotation*Math.PI,i=e.util.cos(t),n=e.util.sin(t),s=1/3,o=Math.sqrt(s)*n,r=1-i;this.matrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],this.matrix[0]=i+r/3,this.matrix[1]=s*r-o,this.matrix[2]=s*r+o,this.matrix[5]=s*r+o,this.matrix[6]=i+s*r,this.matrix[7]=s*r-o,this.matrix[10]=s*r-o,this.matrix[11]=s*r+o,this.matrix[12]=i+s*r},isNeutralState:function(t){return this.calculateMatrix(),i.BaseFilter.prototype.isNeutralState.call(this,t)},applyTo:function(t){this.calculateMatrix(),i.BaseFilter.prototype.applyTo.call(this,t)}}),e.Image.filters.HueRotation.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.clone;if(e.Text)e.warn("fabric.Text is already defined");else{var n="fontFamily fontWeight fontSize text underline overline linethrough textAlign fontStyle lineHeight textBackgroundColor charSpacing styles direction path pathStartOffset pathSide pathAlign".split(" ");e.Text=e.util.createClass(e.Object,{_dimensionAffectingProps:["fontSize","fontWeight","fontFamily","fontStyle","lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],_reNewline:/\r?\n/,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,type:"text",fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:"left",fontStyle:"normal",lineHeight:1.16,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},textBackgroundColor:"",stateProperties:e.Object.prototype.stateProperties.concat(n),cacheProperties:e.Object.prototype.cacheProperties.concat(n),stroke:null,shadow:null,path:null,pathStartOffset:0,pathSide:"left",pathAlign:"baseline",_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.315,overline:-.88},_fontSizeMult:1.13,charSpacing:0,styles:null,_measuringContext:null,deltaY:0,direction:"ltr",_styleProperties:["stroke","strokeWidth","fill","fontFamily","fontSize","fontWeight","fontStyle","underline","overline","linethrough","deltaY","textBackgroundColor"],__charBounds:[],CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,initialize:function(t,e){this.styles=e&&e.styles||{},this.text=t,this.__skipDimension=!0,this.callSuper("initialize",e),this.path&&this.setPathInfo(),this.__skipDimension=!1,this.initDimensions(),this.setCoords(),this.setupState({propertySet:"_dimensionAffectingProps"})},setPathInfo:function(){var t=this.path;t&&(t.segmentsInfo=e.util.getPathSegmentsInfo(t.path))},getMeasuringContext:function(){return e._measuringContext||(e._measuringContext=this.canvas&&this.canvas.contextCache||e.util.createCanvasElement().getContext("2d")),e._measuringContext},_splitText:function(){var t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t},initDimensions:function(){this.__skipDimension||(this._splitText(),this._clearCache(),this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.saveState({propertySet:"_dimensionAffectingProps"}))},enlargeSpaces:function(){for(var t,e,i,n,s,o,r,a=0,l=this._textLines.length;a<l;a++)if(("justify"===this.textAlign||a!==l-1&&!this.isEndOfWrapping(a))&&(n=0,s=this._textLines[a],(e=this.getLineWidth(a))<this.width&&(r=this.textLines[a].match(this._reSpacesAndTabs)))){i=r.length,t=(this.width-e)/i;for(var h=0,c=s.length;h<=c;h++)o=this.__charBounds[a][h],this._reSpaceAndTab.test(s[h])?(o.width+=t,o.kernedWidth+=t,o.left+=n,n+=t):o.left+=n}},isEndOfWrapping:function(t){return t===this._textLines.length-1},missingNewlineOffset:function(){return 1},toString:function(){return"#<fabric.Text ("+this.complexity()+'): { "text": "'+this.text+'", "fontFamily": "'+this.fontFamily+'" }>'},_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;e<i;e++){var n=this.getLineWidth(e);n>t&&(t=n)}return t},_renderTextLine:function(t,e,i,n,s,o){this._renderChars(t,e,i,n,s,o)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,s,o,r,a,l=t.fillStyle,h=this._getLeftOffset(),c=this._getTopOffset(),d=0,u=0,p=this.path,g=0,f=this._textLines.length;g<f;g++)if(e=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){n=this._textLines[g],i=this._getLineLeftOffset(g),u=0,d=0,s=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var m=0,v=n.length;m<v;m++)o=this.__charBounds[g][m],r=this.getValueOfPropertyAt(g,m,"textBackgroundColor"),p?(t.save(),t.translate(o.renderLeft,o.renderTop),t.rotate(o.angle),t.fillStyle=r,r&&t.fillRect(-o.width/2,-e/this.lineHeight*(1-this._fontSizeFraction),o.width,e/this.lineHeight),t.restore()):r!==s?(a=h+i+d,"rtl"===this.direction&&(a=this.width-a-u),t.fillStyle=s,s&&t.fillRect(a,c,u,e/this.lineHeight),d=o.left,u=o.width,s=r):u+=o.kernedWidth;r&&!p&&(a=h+i+d,"rtl"===this.direction&&(a=this.width-a-u),t.fillStyle=r,t.fillRect(a,c,u,e/this.lineHeight)),c+=e}else c+=e;t.fillStyle=l,this._removeShadow(t)}},getFontCache:function(t){var i=t.fontFamily.toLowerCase();e.charWidthsCache[i]||(e.charWidthsCache[i]={});var n=e.charWidthsCache[i],s=t.fontStyle.toLowerCase()+"_"+(t.fontWeight+"").toLowerCase();return n[s]||(n[s]={}),n[s]},_measureChar:function(t,e,i,n){var s,o,r,a,l=this.getFontCache(e),h=i+t,c=this._getFontDeclaration(e)===this._getFontDeclaration(n),d=e.fontSize/this.CACHE_FONT_SIZE;if(i&&void 0!==l[i]&&(r=l[i]),void 0!==l[t]&&(a=s=l[t]),c&&void 0!==l[h]&&(a=(o=l[h])-r),void 0===s||void 0===r||void 0===o){var u=this.getMeasuringContext();this._setTextStyles(u,e,!0)}return void 0===s&&(a=s=u.measureText(t).width,l[t]=s),void 0===r&&c&&i&&(r=u.measureText(i).width,l[i]=r),c&&void 0===o&&(o=u.measureText(h).width,l[h]=o,a=o-r),{width:s*d,kernedWidth:a*d}},getHeightOfChar:function(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")},measureLine:function(t){var e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e},_measureLine:function(t){var i,n,s,o,r,a,l=0,h=this._textLines[t],c=new Array(h.length),d=0,u=this.path,p="right"===this.pathSide;for(this.__charBounds[t]=c,i=0;i<h.length;i++)n=h[i],o=this._getGraphemeBox(n,t,i,s),c[i]=o,l+=o.kernedWidth,s=n;if(c[i]={left:o?o.left+o.width:0,width:0,kernedWidth:0,height:this.fontSize},u){switch(a=u.segmentsInfo[u.segmentsInfo.length-1].length,(r=e.util.getPointOnPath(u.path,0,u.segmentsInfo)).x+=u.pathOffset.x,r.y+=u.pathOffset.y,this.textAlign){case"left":d=p?a-l:0;break;case"center":d=(a-l)/2;break;case"right":d=p?0:a-l}for(d+=this.pathStartOffset*(p?-1:1),i=p?h.length-1:0;p?i>=0:i<h.length;p?i--:i++)o=c[i],d>a?d%=a:d<0&&(d+=a),this._setGraphemeOnPath(d,o,r),d+=o.kernedWidth}return{width:l,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,n){var s=t+i.kernedWidth/2,o=this.path,r=e.util.getPointOnPath(o.path,s,o.segmentsInfo);i.renderLeft=r.x-n.x,i.renderTop=r.y-n.y,i.angle=r.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,s){var o,r=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},l=this._measureChar(t,r,n,a),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=o=this._getWidthOfCharSpacing(),h+=o);var d={width:c,left:0,height:r.fontSize,kernedWidth:h,deltaY:r.deltaY};if(i>0&&!s){var u=this.__charBounds[e][i-1];d.left=u.left+u.width+l.kernedWidth-l.width}return d},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,s=e.length;n<s;n++)i=Math.max(this.getHeightOfChar(t,n),i);return this.__lineHeights[t]=i*this.lineHeight*this._fontSizeMult},calcTextHeight:function(){for(var t,e=0,i=0,n=this._textLines.length;i<n;i++)t=this.getHeightOfLine(i),e+=i===n-1?t/this.lineHeight:t;return e},_getLeftOffset:function(){return"ltr"===this.direction?-this.width/2:this.width/2},_getTopOffset:function(){return-this.height/2},_renderTextCommon:function(t,e){t.save();for(var i=0,n=this._getLeftOffset(),s=this._getTopOffset(),o=0,r=this._textLines.length;o<r;o++){var a=this.getHeightOfLine(o),l=a/this.lineHeight,h=this._getLineLeftOffset(o);this._renderTextLine(e,t,this._textLines[o],n+h,s+i+l,o),i+=a}t.restore()},_renderTextFill:function(t){(this.fill||this.styleHas("fill"))&&this._renderTextCommon(t,"fillText")},_renderTextStroke:function(t){(this.stroke&&0!==this.strokeWidth||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())},_renderChars:function(t,e,i,n,s,o){var r,a,l,h,c,d=this.getHeightOfLine(o),u=-1!==this.textAlign.indexOf("justify"),p="",g=0,f=this.path,m=!u&&0===this.charSpacing&&this.isEmptyStyles(o)&&!f,v="ltr"===this.direction,y="ltr"===this.direction?1:-1,x=e.canvas.getAttribute("dir");if(e.save(),x!==this.direction&&(e.canvas.setAttribute("dir",v?"ltr":"rtl"),e.direction=v?"ltr":"rtl",e.textAlign=v?"left":"right"),s-=d*this._fontSizeFraction/this.lineHeight,m)return this._renderChar(t,e,o,0,i.join(""),n,s,d),void e.restore();for(var w=0,C=i.length-1;w<=C;w++)h=w===C||this.charSpacing||f,p+=i[w],l=this.__charBounds[o][w],0===g?(n+=y*(l.kernedWidth-l.width),g+=l.width):g+=l.kernedWidth,u&&!h&&this._reSpaceAndTab.test(i[w])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(o,w),a=this.getCompleteStyleDeclaration(o,w+1),h=this._hasStyleChanged(r,a)),h&&(f?(e.save(),e.translate(l.renderLeft,l.renderTop),e.rotate(l.angle),this._renderChar(t,e,o,w,p,-g/2,0,d),e.restore()):(c=n,this._renderChar(t,e,o,w,p,c,s,d)),p="",r=a,n+=y*g,g=0);e.restore()},_applyPatternGradientTransformText:function(t){var i,n=e.util.createCanvasElement(),s=this.width+this.strokeWidth,o=this.height+this.strokeWidth;return n.width=s,n.height=o,(i=n.getContext("2d")).beginPath(),i.moveTo(0,0),i.lineTo(s,0),i.lineTo(s,o),i.lineTo(0,o),i.closePath(),i.translate(s/2,o/2),i.fillStyle=t.toLive(i),this._applyPatternGradientTransform(i,t),i.fill(),i.createPattern(n,"no-repeat")},handleFiller:function(t,e,i){var n,s;return i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?(n=-this.width/2,s=-this.height/2,t.translate(n,s),t[e]=this._applyPatternGradientTransformText(i),{offsetX:n,offsetY:s}):(t[e]=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):(t[e]=i,{offsetX:0,offsetY:0})},_setStrokeStyles:function(t,e){return t.lineWidth=e.strokeWidth,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",e.stroke)},_setFillStyles:function(t,e){return this.handleFiller(t,"fillStyle",e.fill)},_renderChar:function(t,e,i,n,s,o,r){var a,l,h=this._getStyleDeclaration(i,n),c=this.getCompleteStyleDeclaration(i,n),d="fillText"===t&&c.fill,u="strokeText"===t&&c.stroke&&c.strokeWidth;(u||d)&&(e.save(),d&&(a=this._setFillStyles(e,c)),u&&(l=this._setStrokeStyles(e,c)),e.font=this._getFontDeclaration(c),h&&h.textBackgroundColor&&this._removeShadow(e),h&&h.deltaY&&(r+=h.deltaY),d&&e.fillText(s,o-a.offsetX,r-a.offsetY),u&&e.strokeText(s,o-l.offsetX,r-l.offsetY),e.restore())},setSuperscript:function(t,e){return this._setScript(t,e,this.superscript)},setSubscript:function(t,e){return this._setScript(t,e,this.subscript)},_setScript:function(t,e,i){var n=this.get2DCursorLocation(t,!0),s=this.getValueOfPropertyAt(n.lineIndex,n.charIndex,"fontSize"),o=this.getValueOfPropertyAt(n.lineIndex,n.charIndex,"deltaY"),r={fontSize:s*i.size,deltaY:o+s*i.baseline};return this.setSelectionStyles(r,t,e),this},_hasStyleChanged:function(t,e){return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle||t.deltaY!==e.deltaY},_hasStyleChangedForSvg:function(t,e){return this._hasStyleChanged(t,e)||t.overline!==e.overline||t.underline!==e.underline||t.linethrough!==e.linethrough},_getLineLeftOffset:function(t){var e=this.getLineWidth(t),i=this.width-e,n=this.textAlign,s=this.direction,o=0,r=this.isEndOfWrapping(t);return"justify"===n||"justify-center"===n&&!r||"justify-right"===n&&!r||"justify-left"===n&&!r?0:("center"===n&&(o=i/2),"right"===n&&(o=i),"justify-center"===n&&(o=i/2),"justify-right"===n&&(o=i),"rtl"===s&&(o-=i),o)},_clearCache:function(){this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]},_shouldClearDimensionCache:function(){var t=this._forceClearCache;return t||(t=this.hasStateChanged("_dimensionAffectingProps")),t&&(this.dirty=!0,this._forceClearCache=!1),t},getLineWidth:function(t){if(void 0!==this.__lineWidths[t])return this.__lineWidths[t];var e=this.measureLine(t).width;return this.__lineWidths[t]=e,e},_getWidthOfCharSpacing:function(){return 0!==this.charSpacing?this.fontSize*this.charSpacing/1e3:0},getValueOfPropertyAt:function(t,e,i){var n=this._getStyleDeclaration(t,e);return n&&void 0!==n[i]?n[i]:this[i]},_renderTextDecoration:function(t,e){if(this[e]||this.styleHas(e)){for(var i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y=this._getLeftOffset(),x=this._getTopOffset(),w=this.path,C=this._getWidthOfCharSpacing(),b=this.offsets[e],S=0,T=this._textLines.length;S<T;S++)if(i=this.getHeightOfLine(S),this[e]||this.styleHas(e,S)){l=this._textLines[S],f=i/this.lineHeight,o=this._getLineLeftOffset(S),d=0,u=0,h=this.getValueOfPropertyAt(S,0,e),v=this.getValueOfPropertyAt(S,0,"fill"),c=x+f*(1-this._fontSizeFraction),n=this.getHeightOfChar(S,0),r=this.getValueOfPropertyAt(S,0,"deltaY");for(var E=0,_=l.length;E<_;E++)if(p=this.__charBounds[S][E],g=this.getValueOfPropertyAt(S,E,e),m=this.getValueOfPropertyAt(S,E,"fill"),s=this.getHeightOfChar(S,E),a=this.getValueOfPropertyAt(S,E,"deltaY"),w&&g&&m)t.save(),t.fillStyle=v,t.translate(p.renderLeft,p.renderTop),t.rotate(p.angle),t.fillRect(-p.kernedWidth/2,b*s+a,p.kernedWidth,this.fontSize/15),t.restore();else if((g!==h||m!==v||s!==n||a!==r)&&u>0){var P=y+o+d;"rtl"===this.direction&&(P=this.width-P-u),h&&v&&(t.fillStyle=v,t.fillRect(P,c+b*n+r,u,this.fontSize/15)),d=p.left,u=p.width,h=g,v=m,n=s,r=a}else u+=p.kernedWidth;P=y+o+d,"rtl"===this.direction&&(P=this.width-P-u),t.fillStyle=m,g&&m&&t.fillRect(P,c+b*n+r,u-C,this.fontSize/15),x+=i}else x+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,s=this.fontFamily,o=e.Text.genericFonts.indexOf(s.toLowerCase())>-1,r=void 0===s||s.indexOf("'")>-1||s.indexOf(",")>-1||s.indexOf('"')>-1||o?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",r].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),n=new Array(i.length),s=["\n"],o=[],r=0;r<i.length;r++)n[r]=e.util.string.graphemeSplit(i[r]),o=o.concat(n[r],s);return o.pop(),{_unwrappedLines:n,lines:i,graphemeText:o,graphemeLines:n}},toObject:function(t){var e=n.concat(t),s=this.callSuper("toObject",e);return s.styles=i(this.styles,!0),s.path&&(s.path=this.path.toObject()),s},set:function(t,e){this.callSuper("set",t,e);var i=!1,n=!1;if("object"==typeof t)for(var s in t)"path"===s&&this.setPathInfo(),i=i||-1!==this._dimensionAffectingProps.indexOf(s),n=n||"path"===s;else i=-1!==this._dimensionAffectingProps.indexOf(t),n="path"===t;return n&&this.setPathInfo(),i&&(this.initDimensions(),this.setCoords()),this},complexity:function(){return 1}}),e.Text.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y dx dy font-family font-style font-weight font-size letter-spacing text-decoration text-anchor".split(" ")),e.Text.DEFAULT_SVG_FONT_SIZE=16,e.Text.fromElement=function(t,n,s){if(!t)return n(null);var o=e.parseAttributes(t,e.Text.ATTRIBUTE_NAMES),r=o.textAnchor||"left";if((s=e.util.object.extend(s?i(s):{},o)).top=s.top||0,s.left=s.left||0,o.textDecoration){var a=o.textDecoration;-1!==a.indexOf("underline")&&(s.underline=!0),-1!==a.indexOf("overline")&&(s.overline=!0),-1!==a.indexOf("line-through")&&(s.linethrough=!0),delete s.textDecoration}"dx"in o&&(s.left+=o.dx),"dy"in o&&(s.top+=o.dy),"fontSize"in s||(s.fontSize=e.Text.DEFAULT_SVG_FONT_SIZE);var l="";"textContent"in t?l=t.textContent:"firstChild"in t&&null!==t.firstChild&&"data"in t.firstChild&&null!==t.firstChild.data&&(l=t.firstChild.data),l=l.replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," ");var h=s.strokeWidth;s.strokeWidth=0;var c=new e.Text(l,s),d=c.getScaledHeight()/c.height,u=((c.height+c.strokeWidth)*c.lineHeight-c.height)*d,p=c.getScaledHeight()+u,g=0;"center"===r&&(g=c.getScaledWidth()/2),"right"===r&&(g=c.getScaledWidth()),c.set({left:c.left-g,top:c.top-(p-c.fontSize*(.07+c._fontSizeFraction))/c.lineHeight,strokeWidth:void 0!==h?h:1}),n(c)},e.Text.fromObject=function(t,n){var s=i(t),o=t.path;return delete s.path,e.Object._fromObject("Text",s,function(t){o?e.Object._fromObject("Path",o,function(e){t.set("path",e),n(t)},"path"):n(t)},"text")},e.Text.genericFonts=["sans-serif","serif","cursive","fantasy","monospace"],e.util.createAccessors&&e.util.createAccessors(e.Text)}}(e),T.util.object.extend(T.Text.prototype,{isEmptyStyles:function(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;var e=void 0===t?this.styles:{line:this.styles[t]};for(var i in e)for(var n in e[i])for(var s in e[i][n])return!1;return!0},styleHas:function(t,e){if(!this.styles||!t||""===t)return!1;if(void 0!==e&&!this.styles[e])return!1;var i=void 0===e?this.styles:{0:this.styles[e]};for(var n in i)for(var s in i[n])if(void 0!==i[n][s][t])return!0;return!1},cleanStyle:function(t){if(!this.styles||!t||""===t)return!1;var e,i,n=this.styles,s=0,o=!0,r=0;for(var a in n){for(var l in e=0,n[a]){var h;s++,(h=n[a][l]).hasOwnProperty(t)?(i?h[t]!==i&&(o=!1):i=h[t],h[t]===this[t]&&delete h[t]):o=!1,0!==Object.keys(h).length?e++:delete n[a][l]}0===e&&delete n[a]}for(var c=0;c<this._textLines.length;c++)r+=this._textLines[c].length;o&&s===r&&(this[t]=i,this.removeStyle(t))},removeStyle:function(t){if(this.styles&&t&&""!==t){var e,i,n,s=this.styles;for(i in s){for(n in e=s[i])delete e[n][t],0===Object.keys(e[n]).length&&delete e[n];0===Object.keys(e).length&&delete s[i]}}},_extendStyles:function(t,e){var i=this.get2DCursorLocation(t);this._getLineStyle(i.lineIndex)||this._setLineStyle(i.lineIndex),this._getStyleDeclaration(i.lineIndex,i.charIndex)||this._setStyleDeclaration(i.lineIndex,i.charIndex,{}),T.util.object.extend(this._getStyleDeclaration(i.lineIndex,i.charIndex),e)},get2DCursorLocation:function(t,e){void 0===t&&(t=this.selectionStart);for(var i=e?this._unwrappedTextLines:this._textLines,n=i.length,s=0;s<n;s++){if(t<=i[s].length)return{lineIndex:s,charIndex:t};t-=i[s].length+this.missingNewlineOffset(s)}return{lineIndex:s-1,charIndex:i[s-1].length<t?i[s-1].length:t}},getSelectionStyles:function(t,e,i){void 0===t&&(t=this.selectionStart||0),void 0===e&&(e=this.selectionEnd||t);for(var n=[],s=t;s<e;s++)n.push(this.getStyleAtPosition(s,i));return n},getStyleAtPosition:function(t,e){var i=this.get2DCursorLocation(t);return(e?this.getCompleteStyleDeclaration(i.lineIndex,i.charIndex):this._getStyleDeclaration(i.lineIndex,i.charIndex))||{}},setSelectionStyles:function(t,e,i){void 0===e&&(e=this.selectionStart||0),void 0===i&&(i=this.selectionEnd||e);for(var n=e;n<i;n++)this._extendStyles(n,t);return this._forceClearCache=!0,this},_getStyleDeclaration:function(t,e){var i=this.styles&&this.styles[t];return i?i[e]:null},getCompleteStyleDeclaration:function(t,e){for(var i,n=this._getStyleDeclaration(t,e)||{},s={},o=0;o<this._styleProperties.length;o++)s[i=this._styleProperties[o]]=void 0===n[i]?this[i]:n[i];return s},_setStyleDeclaration:function(t,e,i){this.styles[t][e]=i},_deleteStyleDeclaration:function(t,e){delete this.styles[t][e]},_getLineStyle:function(t){return!!this.styles[t]},_setLineStyle:function(t){this.styles[t]={}},_deleteLineStyle:function(t){delete this.styles[t]}}),function(){function t(t){t.textDecoration&&(t.textDecoration.indexOf("underline")>-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(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,s,o=0,r=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var l=0;l<i;l++)o+=this.getHeightOfLine(l);e=this._getLineLeftOffset(i);var h=this.__charBounds[i][n];return h&&(r=h.left),0!==this.charSpacing&&n===this._textLines[i].length&&(r-=this._getWidthOfCharSpacing()),s={top:o,left:e+(r>0?r:0)},"rtl"===this.direction&&(s.left*=-1),this.cursorOffsetCache=s,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,s=i.charIndex>0?i.charIndex-1:0,o=this.getValueOfPropertyAt(n,s,"fontSize"),r=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/r,l=t.topOffset,h=this.getValueOfPropertyAt(n,s,"deltaY");l+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-o*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,s,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,l+t.top+h,a,o)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,s=-1!==this.textAlign.indexOf("justify"),o=this.get2DCursorLocation(i),r=this.get2DCursorLocation(n),a=o.lineIndex,l=r.lineIndex,h=o.charIndex<0?0:o.charIndex,c=r.charIndex<0?0:r.charIndex,d=a;d<=l;d++){var u,p=this._getLineLeftOffset(d)||0,g=this.getHeightOfLine(d),f=0,m=0;if(d===a&&(f=this.__charBounds[a][h].left),d>=a&&d<l)m=s&&!this.isEndOfWrapping(d)?this.width:this.getLineWidth(d)||5;else if(d===l)if(0===c)m=this.__charBounds[l][c].left;else{var v=this._getWidthOfCharSpacing();m=this.__charBounds[l][c-1].left+this.__charBounds[l][c-1].width-v}u=g,(this.lineHeight<1||d===l&&this.lineHeight>1)&&(g/=this.lineHeight);var y=t.left+p+f,x=m-f,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(y=this.width-y-x),e.fillRect(y,t.top+t.topOffset+C,x,w),t.topOffset+=u}},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 n in e.styles)for(var s in e.styles[n])t(e.styles[n][s]);T.Object._fromObject("IText",e,i,"text")}}(),S=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,n){var s;return s={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){s.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return s.isAborted}}),s},_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<this._text.length;)e++,i++;return t+e},findLineBoundaryLeft:function(t){for(var e=0,i=t-1;!/\n/.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])&&i<this._text.length;)e++,i++;return t+e},searchWordBoundary:function(t,e){for(var i=this._text,n=this._reSpace.test(i[t])?t-1:t,s=i[n],o=T.reNonWord;!o.test(s)&&n>0&&n<i.length;)s=i[n+=e];return o.test(s)&&(n+=1===e?0:1),n},selectWord:function(t){t=t||this.selectionStart;var e=this.searchWordBoundary(t,-1),i=this.searchWordBoundary(t,1);this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()},selectLine:function(t){t=t||this.selectionStart;var e=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);return this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this},enterEditing:function(t){if(!this.isEditing&&this.editable)return this.canvas&&(this.canvas.calcOffset(),this.exitEditingOnOthers(this.canvas)),this.isEditing=!0,this.initHiddenTextarea(t),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick(),this.fire("editing:entered"),this._fireSelectionChanged(),this.canvas?(this.canvas.fire("text:editing:entered",{target:this}),this.initMouseMoveHandler(),this.canvas.requestRenderAll(),this):this},exitEditingOnOthers:function(t){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.selected=!1,t.isEditing&&t.exitEditing()})},initMouseMoveHandler:function(){this.canvas.on("mouse:move",this.mouseMoveHandler)},mouseMoveHandler:function(t){if(this.__isMousedown&&this.isEditing){var e=this.getSelectionStartFromPointer(t.e),i=this.selectionStart,n=this.selectionEnd;(e===this.__selectionStartOnMouseDown&&i!==n||i!==e&&n!==e)&&(e>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(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 n=i.slice(0,t),s=T.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:s,selectionEnd:s};var o=i.slice(t,e);return{selectionStart:s,selectionEnd:s+T.util.string.graphemeSplit(o).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+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),n=i.lineIndex,s=i.charIndex,o=this.getValueOfPropertyAt(n,s,"fontSize")*this.lineHeight,r=e.leftOffset,a=this.calcTransformMatrix(),l={x:e.left+r,y:e.top+e.topOffset+o},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,d=c.width/h,u=c.height/h,p=d-o,g=u-o,f=c.clientWidth/d,m=c.clientHeight/u;return l=T.util.transformPoint(l,a),(l=T.util.transformPoint(l,this.canvas.viewportTransform)).x*=f,l.y*=m,l.x<0&&(l.x=0),l.x>p&&(l.x=p),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.y+"px",fontSize:o+"px",charHeight:o}},_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,n,s=this.get2DCursorLocation(t,!0),o=this.get2DCursorLocation(e,!0),r=s.lineIndex,a=s.charIndex,l=o.lineIndex,h=o.charIndex;if(r!==l){if(this.styles[r])for(i=a;i<this._unwrappedTextLines[r].length;i++)delete this.styles[r][i];if(this.styles[l])for(i=h;i<this._unwrappedTextLines[l].length;i++)(n=this.styles[l][i])&&(this.styles[r]||(this.styles[r]={}),this.styles[r][a+i-h]=n);for(i=r+1;i<=l;i++)delete this.styles[i];this.shiftLineStyles(l,r-l)}else if(this.styles[r]){n=this.styles[r];var c,d,u=h-a;for(i=a;i<h;i++)delete n[i];for(d in this.styles[r])(c=parseInt(d,10))>=h&&(n[c-u]=n[d],delete n[d])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var s=parseInt(n,10);s>t&&(this.styles[s+e]=i[s],i[s-e]||delete this.styles[s])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var s,o={},r=!1,a=this._unwrappedTextLines[t].length===e;for(var l in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(s=this.styles[t][0===e?e:e-1]),this.styles[t]){var h=parseInt(l,10);h>=e&&(r=!0,o[h-e]=this.styles[t][l],a&&0===e||delete this.styles[t][l])}var c=!1;for(r&&!a&&(this.styles[t+i]=o,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:s?this.styles[t+i]={0:S(s)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var s=this.styles[t],o=s?S(s):{};for(var r in i||(i=1),o){var a=parseInt(r,10);a>=e&&(s[a+i]=o[a],o[a-i]||delete s[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(s)for(var l=s[e?e-1:1];l&&i--;)this.styles[t][e+i]=S(l)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),s=[0],o=0,r=0;r<t.length;r++)"\n"===t[r]?s[++o]=0:s[o]++;for(s[0]>0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,s[0],i),i=i&&i.slice(s[0]+1)),o&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+s[0],o),r=1;r<o;r++)s[r]>0?this.insertCharStyleObject(n.lineIndex+r,0,s[r],i):i&&this.styles[n.lineIndex+r]&&i[0]&&(this.styles[n.lineIndex+r][0]=i[0]),i=i&&i.slice(s[r]+1);s[r]>0&&this.insertCharStyleObject(n.lineIndex+r,0,s[r],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&&i<e?"right"===this._selectionDirection?this.selectionEnd=i:this.selectionStart=i:(e===t?this._selectionDirection="right":"left"===this._selectionDirection&&(this._selectionDirection="right",this.selectionStart=e),this.selectionEnd=i)},setSelectionInBoundaries:function(){var t=this.text.length;this.selectionStart>t?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,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,s=0,o=0,r=0,a=0,l=0,h=this._textLines.length;l<h&&o<=i.y;l++)o+=this.getHeightOfLine(l)*this.scaleY,a=l,l>0&&(r+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));s=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+s);for(var c=0,d=e.length;c<d&&(n=s,(s+=this.__charBounds[a][c].kernedWidth*this.scaleX)<=i.x);c++)r++;return this._getNewSelectionStartFromOffset(i,n,s,r,d)},_getNewSelectionStartFromOffset:function(t,e,i,n,s){var o=t.x-e,r=i-t.x,a=n+(r>o||r<0?0:1);return this.flipX&&(a=s-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,n,s,o,r,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,l=this._text.length,h=a.length,c=h-l,d=this.selectionStart,u=this.selectionEnd,p=d!==u;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),f=d>g.selectionStart;p?(i=this._text.slice(d,u),c+=u-d):h<l&&(i=f?this._text.slice(u+c,u):this._text.slice(d,d-c)),n=a.slice(g.selectionEnd-c,g.selectionEnd),i&&i.length&&(n.length&&(s=this.getSelectionStyles(d,d+1,!1),s=n.map(function(){return s[0]})),p?(o=d,r=u):f?(o=u-i.length,r=u):(o=u,r=u+i.length),this.removeStyleFromTo(o,r)),n.length&&(e&&n.join("")===T.copiedText&&!T.disableStyleCopyPaste&&(s=T.copiedTextStyle),this.insertNewStyleBlock(n,d,s)),this.updateFromTextArea(),this.fire("changed"),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())}},onCompositionStart:function(){this.inCompositionMode=!0},onCompositionEnd:function(){this.inCompositionMode=!1},onCompositionUpdate:function(t){this.compositionStart=t.target.selectionStart,this.compositionEnd=t.target.selectionEnd,this.updateTextareaPosition()},copy:function(){this.selectionStart!==this.selectionEnd&&(T.copiedText=this.getSelectedText(),T.disableStyleCopyPaste?T.copiedTextStyle=null:T.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0)},paste:function(){this.fromPaste=!0},_getClipboardData:function(t){return t&&t.clipboardData||T.window.clipboardData},_getWidthBeforeCursor:function(t,e){var i,n=this._getLineLeftOffset(t);return e>0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),s=n.lineIndex;if(s===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var o=n.charIndex,r=this._getWidthBeforeCursor(s,o),a=this._getIndexOnLine(s+1,r);return this._textLines[s].slice(o).length+a+1+this.missingNewlineOffset(s)},_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),n=this.get2DCursorLocation(i),s=n.lineIndex;if(0===s||t.metaKey||33===t.keyCode)return-i;var o=n.charIndex,r=this._getWidthBeforeCursor(s,o),a=this._getIndexOnLine(s-1,r),l=this._textLines[s].slice(0,o),h=this.missingNewlineOffset(s-1);return-this._textLines[s-1].length+a-l.length+(1-h)},_getIndexOnLine:function(t,e){for(var i,n,s=this._textLines[t],o=this._getLineLeftOffset(t),r=0,a=0,l=s.length;a<l;a++)if((o+=i=this.__charBounds[t][a].width)>e){n=!0;var h=o-i,c=o,d=Math.abs(h-e);r=Math.abs(c-e)<d?a:a-1;break}return n||(r=s.length-1),r},moveCursorDown:function(t){this.selectionStart>=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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!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,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var s=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(s,i,e),this._text=[].concat(this._text.slice(0,i),s,this._text.slice(n)),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<text xml:space="preserve" ',this.fontFamily?'font-family="'+this.fontFamily.replace(/"/g,"'")+'" ':"",this.fontSize?'font-size="'+this.fontSize+'" ':"",this.fontStyle?'font-style="'+this.fontStyle+'" ':"",this.fontWeight?'font-weight="'+this.fontWeight+'" ':"",e?'text-decoration="'+e+'" ':"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",t.textSpans.join(""),"</text>\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],s=[],o=t;this._setSVGBg(s);for(var r=0,a=this._textLines.length;r<a;r++)i=this._getLineLeftOffset(r),(this.textBackgroundColor||this.styleHas("textBackgroundColor",r))&&this._setSVGTextLineBg(s,r,e+i,o),this._setSVGTextLineText(n,r,e+i,o),o+=this.getHeightOfLine(r);return{textSpans:n,textBgRects:s}},_createTextCharSpan:function(i,n,s,o){var r=i!==i.trim()||i.match(e),a=this.getSvgSpanStyles(n,r),l=a?'style="'+a+'"':"",h=n.deltaY,c="",d=T.Object.NUM_FRACTION_DIGITS;return h&&(c=' dy="'+t(h,d)+'" '),['<tspan x="',t(s,d),'" y="',t(o,d),'" ',c,l,">",T.util.string.escapeXml(i),"</tspan>"].join("")},_setSVGTextLineText:function(t,e,i,n){var s,o,r,a,l,h=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),d="",u=0,p=this._textLines[e];n+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,f=p.length-1;g<=f;g++)l=g===f||this.charSpacing,d+=p[g],r=this.__charBounds[e][g],0===u?(i+=r.kernedWidth-r.width,u+=r.width):u+=r.kernedWidth,c&&!l&&this._reSpaceAndTab.test(p[g])&&(l=!0),l||(s=s||this.getCompleteStyleDeclaration(e,g),o=this.getCompleteStyleDeclaration(e,g+1),l=this._hasStyleChangedForSvg(s,o)),l&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(d,a,i,n)),d="",s=o,i+=u,u=0)},_pushTextBgRect:function(e,i,n,s,o,r){var a=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t<rect ",this._getFillAttributes(i),' x="',t(n,a),'" y="',t(s,a),'" width="',t(o,a),'" height="',t(r,a),'"></rect>\n')},_setSVGTextLineBg:function(t,e,i,n){for(var s,o,r=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,l=0,h=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),d=0,u=r.length;d<u;d++)s=this.__charBounds[e][d],(o=this.getValueOfPropertyAt(e,d,"textBackgroundColor"))!==c?(c&&this._pushTextBgRect(t,c,i+h,n,l,a),h=s.left,l=s.width,c=o):l+=s.kernedWidth;o&&this._pushTextBgRect(t,o,i+h,n,l,a)},_getFillAttributes:function(t){var e=t&&"string"==typeof t?new T.Color(t):"";return e&&e.getSource()&&1!==e.getAlpha()?'opacity="'+e.getAlpha()+'" fill="'+e.setAlpha(1).toRgb()+'"':'fill="'+t+'"'},_getSVGLineTopOffset:function(t){for(var e,i=0,n=0;n<t;n++)i+=this.getHeightOfLine(n);return e=this.getHeightOfLine(n),{lineTop:i,offset:(this._fontSizeMult-this._fontSizeFraction)*e/(this.lineHeight*this._fontSizeMult)}},getSvgStyles:function(t){return T.Object.prototype.getSvgStyles.call(this,t)+" white-space: pre;"}})}(),function(t){var e=t.fabric||(t.fabric={});e.Textbox=e.util.createClass(e.IText,e.Observable,{type:"textbox",minWidth:20,dynamicMinWidth:2,__cachedLines:null,lockScalingFlip:!0,noScaleCache:!1,_dimensionAffectingProps:e.Text.prototype._dimensionAffectingProps.concat("width"),_wordJoiners:/[ \t\r]/,splitByGrapheme:!1,initDimensions:function(){this.__skipDimension||(this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.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,n=0,s={},o=0;o<t.graphemeLines.length;o++)"\n"===t.graphemeText[n]&&o>0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&o>0&&(i++,n++),s[o]={line:e,offset:i},n+=t.graphemeLines[o].length,i+=t.graphemeLines[o].length;return s},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,s=!1,o=this._styleMap[t],r=this._styleMap[t+1];for(var a in o&&(t=o.line,n=o.offset),r&&(s=r.line===t,e=r.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var l in i[a])if(l>=n&&(!s||l<e))for(var h in i[a][l])return!1;return!0},_getStyleDeclaration:function(t,e){if(this._styleMap&&!this.isWrapping){var i=this._styleMap[t];if(!i)return null;t=i.line,e=i.offset+e}return this.callSuper("_getStyleDeclaration",t,e)},_setStyleDeclaration:function(t,e,i){var n=this._styleMap[t];t=n.line,e=n.offset+e,this.styles[t][e]=i},_deleteStyleDeclaration:function(t,e){var i=this._styleMap[t];t=i.line,e=i.offset+e,delete this.styles[t][e]},_getLineStyle:function(t){var e=this._styleMap[t];return!!this.styles[e.line]},_setLineStyle:function(t){var e=this._styleMap[t];this.styles[e.line]={}},_wrapText:function(t,e){var i,n=[];for(this.isWrapping=!0,i=0;i<t.length;i++)n=n.concat(this._wrapLine(t[i],i,e));return this.isWrapping=!1,n},_measureWord:function(t,e,i){var n,s=0;i=i||0;for(var o=0,r=t.length;o<r;o++)s+=this._getGraphemeBox(t[o],e,o+i,n,!0).kernedWidth,n=t[o];return s},_wrapLine:function(t,i,n,s){var o=0,r=this.splitByGrapheme,a=[],l=[],h=r?e.util.string.graphemeSplit(t):t.split(this._wordJoiners),c="",d=0,u=r?"":" ",p=0,g=0,f=0,m=!0,v=this._getWidthOfCharSpacing();s=s||0,0===h.length&&h.push([]),n-=s;for(var y=0;y<h.length;y++)c=r?h[y]:e.util.string.graphemeSplit(h[y]),p=this._measureWord(c,i,d),d+=c.length,(o+=g+p-v)>n&&!m?(a.push(l),l=[],o=p,m=!0):o+=v,m||r||l.push(u),l=l.concat(c),g=r?0:this._measureWord([u],i,d),d++,m=!1,p>f&&(f=p);return y&&a.push(l),f+s>this.dynamicMinWidth&&(this.dynamicMinWidth=f-v+s),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),n=this._wrapText(i.lines,this.width),s=new Array(n.length),o=0;o<n.length;o++)s[o]=n[o].join("");return i.lines=s,i.graphemeLines=n,i},getMinWidth:function(){return Math.max(this.minWidth,this.dynamicMinWidth)},_removeExtraneousStyles:function(){var t={};for(var e in this._styleMap)this._textLines[e]&&(t[this._styleMap[e].line]=1);for(var e in this.styles)t[e]||delete this.styles[e]},toObject:function(t){return this.callSuper("toObject",["minWidth","splitByGrapheme"].concat(t))}}),e.Textbox.fromObject=function(t,i){return e.Object._fromObject("Textbox",t,i,"text")}}(e),function(){var t=T.controlsUtils,e=t.scaleSkewCursorStyleHandler,i=t.scaleCursorStyleHandler,n=t.scalingEqually,s=t.scalingYOrSkewingX,o=t.scalingXOrSkewingY,r=t.scaleOrSkewActionName,a=T.Object.prototype.controls;if(a.ml=new T.Control({x:-.5,y:0,cursorStyleHandler:e,actionHandler:o,getActionName:r}),a.mr=new T.Control({x:.5,y:0,cursorStyleHandler:e,actionHandler:o,getActionName:r}),a.mb=new T.Control({x:0,y:.5,cursorStyleHandler:e,actionHandler:s,getActionName:r}),a.mt=new T.Control({x:0,y:-.5,cursorStyleHandler:e,actionHandler:s,getActionName:r}),a.tl=new T.Control({x:-.5,y:-.5,cursorStyleHandler:i,actionHandler:n}),a.tr=new T.Control({x:.5,y:-.5,cursorStyleHandler:i,actionHandler:n}),a.bl=new T.Control({x:-.5,y:.5,cursorStyleHandler:i,actionHandler:n}),a.br=new T.Control({x:.5,y:.5,cursorStyleHandler:i,actionHandler:n}),a.mtr=new T.Control({x:0,y:-.5,actionHandler:t.rotationWithSnapping,cursorStyleHandler:t.rotationStyleHandler,offsetY:-40,withConnection:!0,actionName:"rotate"}),T.Textbox){var l=T.Textbox.prototype.controls={};l.mtr=a.mtr,l.tr=a.tr,l.br=a.br,l.tl=a.tl,l.bl=a.bl,l.mt=a.mt,l.mb=a.mb,l.mr=new T.Control({x:.5,y:0,actionHandler:t.changeWidth,cursorStyleHandler:e,actionName:"resizing"}),l.ml=new T.Control({x:-.5,y:0,actionHandler:t.changeWidth,cursorStyleHandler:e,actionName:"resizing"})}}()},192:()=>{},898:()=>{},245:()=>{}},nM={};function sM(t){var e=nM[t];if(void 0!==e)return e.exports;var i=nM[t]={exports:{}};return iM[t](i,i.exports,sM),i.exports}sM.d=(t,e)=>{for(var i in e)sM.o(e,i)&&!sM.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},sM.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var oM={};(()=>{let t;sM.d(oM,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?sM(653).fabric:{version:"5.2.1"}})();var rM,aM,lM,hM,cM=oM.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"}(rM||(rM={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(aM||(aM={})),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"}(lM||(lM={})),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"}(hM||(hM={}));const dM=t=>"number"==typeof t&&!Number.isNaN(t),uM=t=>"string"==typeof t;var pM,gM,fM,mM,vM,yM,xM,wM,CM;!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"}(vM||(vM={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(yM||(yM={}));let bM=class{get mediaType(){return new Map([["rect",rM.DIMT_RECTANGLE],["quad",rM.DIMT_QUADRILATERAL],["text",rM.DIMT_TEXT],["arc",rM.DIMT_ARC],["image",rM.DIMT_IMAGE],["polygon",rM.DIMT_POLYGON],["line",rM.DIMT_LINE],["group",rM.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Zk(this,gM,"f")){case aM.DIS_DEFAULT:return"default";case aM.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"===Zk(this,fM,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Zk(this,fM,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Jk(this,fM,t)}get coordinateBase(){return Zk(this,fM,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(pM.add(this),gM.set(this,void 0),fM.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&&!dM(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(aM.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(aM.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(aM.DIS_SELECTED):this.setState(aM.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){Jk(this,gM,t)}getState(){return Zk(this,gM,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let s=n.get(e);s||(s=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,s,o;const r=i.target.getBoundingClientRect();t=r.left,e=r.top,s=t+window.scrollX,o=e+window.scrollY;const{width:a,height:l}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),h=this._drawingLayer.width,c=this._drawingLayer.height,d=a/l,u=h/c,p=this._drawingLayer._getObjectFit();let g,f,m,v,y=1;if("contain"===p)d<u?(y=a/h,g=t+this.get("x")*y,f=e+this.get("y")*y+(l-c*y)/2,m=s+this.get("x")*y,v=o+this.get("y")*y+(l-c*y)/2):(y=l/c,g=t+this.get("x")*y+(a-h*y)/2,f=e+this.get("y")*y,m=s+this.get("x")*y+(a-h*y)/2,v=o+this.get("y")*y);else if("cover"===p)if(d<u){y=l/c;let i=this.get("x")*y-(h*y-a)/2;i=Math.max(i,0),i=Math.min(i,a),g=t+i,f=e+this.get("y")*y,m=s+i,v=o+this.get("y")*y}else{y=a/h;let i=this.get("y")*y-(c*y-l)/2;i=Math.max(i,0),i=Math.min(i,l),g=t+this.get("x")*y,f=e+i,m=s+this.get("x")*y,v=o+i}n.itemClientX=Math.round(g),n.itemClientY=Math.round(f),n.itemPageX=Math.round(m),n.itemPageY=Math.round(v)}for(let t of Object.getOwnPropertyNames(n))Object.defineProperty(i,t,{value:n[t],writable:!0});e&&e.apply(this,[i])},n.set(e,s),this._fabricObject.on("dblclick"===i?"mousedblclick":i,s))}on(t,e){this._on(t,e)}_off(t,e){const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let s=n.get(e);s&&(n.delete(e),this._fabricObject.off("dblclick"===i?"mousedblclick":i,s))}off(t,e){this._off(t,e)}_setEditable(t){const e=this._fabricObject;t?(e.selectable=!0,e.hasControls=!0,e.hoverCursor=null):(e.selectable=!1,e.hasControls=!1,e.hoverCursor="default")}hasNote(t){return this.mapNoteName_Content.has(t)}addNote(t,e){if(this.hasNote(t.name)&&!e)throw new Error("A note with the same name already exists, please use a different name.");const i=t.content?JSON.parse(JSON.stringify(t.content)):t.content;this.mapNoteName_Content.set(t.name,[i])}getNote(t){const e=this.mapNoteName_Content.get(t);return e?1===e.length?{name:t,content:e[0]?JSON.parse(JSON.stringify(e[0])):e[0]}:{name:t,content:JSON.parse(JSON.stringify(e))}:null}getNotes(){const t=[];for(let e of this.mapNoteName_Content){let i=1===e[1].length?e[1][0]:e[1];i=i?JSON.parse(JSON.stringify(i)):i,t.push({name:e[0],content:i})}return t}updateNote(t,e,i){const n=this.mapNoteName_Content.get(t);if(!n)throw new Error("The note name does not exist.");i||(n.length=0),e=e?JSON.parse(JSON.stringify(e)):e,n.push(e)}deleteNote(t){this.mapNoteName_Content.delete(t)}clearNotes(){this.mapNoteName_Content.clear()}set(t,e){if(!this.extendSet(t,e))if("x"===t){const t=this._fabricObject.group;t?(this._fabricObject.set("left",e-t.left-t.width/2),t.addWithUpdate()):this._fabricObject.set("left",e)}else if("y"===t){const t=this._fabricObject.group;t?(this._fabricObject.set("top",e-t.top-t.height/2),t.addWithUpdate()):this._fabricObject.set("top",e)}else"styleId"===t?this.styleId=e:this._fabricObject.set(t,e);["vertices","startPoint","endPoint","x","y","left","top","width","height","scaleX","scaleY","skewX","skewY","padding","angle","strokeWidth"].includes(t)&&this._fabricObject.setCoords()}get(t){let e=this.extendGet(t);if(void 0===e)if("x"===t){const t=this._fabricObject.group;e=t?this._fabricObject.get("left")+t.left+t.width/2:this._fabricObject.get("left")}else if("y"===t){const t=this._fabricObject.group;e=t?this._fabricObject.get("top")+t.top+t.height/2:this._fabricObject.get("top")}else e="scaledWidth"===t?this._fabricObject.getScaledWidth():"scaledHeight"===t?this._fabricObject.getScaledHeight():["type","mediaType"].includes(t)?this.mediaType:"state"===t?this.getState():"styleId"===t?this.styleId:"drawingLayerId"===t?this.drawingLayerId:this._fabricObject.get(t);return e}remove(){this._drawingLayer&&this._drawingLayer.removeDrawingItems([this])}convertPropFromImageToView(t){if("number"!=typeof t)throw new TypeError("Invalid value.");return t*Zk(this,pM,"m",mM).call(this)}convertPropFromViewToImage(t){if("number"!=typeof t)throw new TypeError("Invalid value.");return t/Zk(this,pM,"m",mM).call(this)}_setLineWidth(t){if(this._drawingLayer)if("view"===this.coordinateBase)this.set("strokeWidth",this.convertPropFromViewToImage(t));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("strokeWidth",t)}}_getLineWidth(){if(this._drawingLayer){if("view"===this.coordinateBase)return this.convertPropFromImageToView(this.get("strokeWidth"));if("image"===this.coordinateBase)return this.get("strokeWidth");throw new Error("Invalid 'coordinateBase'.")}}_setFontSize(t){if(this._drawingLayer)if("view"===this.coordinateBase)this.set("fontSize",this.convertPropFromViewToImage(t));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("fontSize",t)}}_getFontSize(){if(this._drawingLayer){if("view"===this.coordinateBase)return this.convertPropFromImageToView(this.get("fontSize"));if("image"===this.coordinateBase)return this.get("fontSize");throw new Error("Invalid 'coordinateBase'.")}}};gM=new WeakMap,fM=new WeakMap,pM=new WeakSet,mM=function(){const t=this._drawingLayer;if(!t)return 1;const e=t.width,i=t.height,{width:n,height:s}=t.fabricCanvas.wrapperEl.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get drawing layer dimensions. Layer may not be rendered on the page.");const o=n/e,r=s/i,a=t._getObjectFit();let l=1;return"contain"===a?l=o<r?n/e:s/i:"cover"===a&&(l=o<r?s/i:n/e),l},bM.arrMediaTypes=["rect","arc","polygon","image","text","line","quad"],bM.mapItemType=new Map([[vM.ARC,"arc"],[vM.IMAGE,"image"],[vM.LINE,"line"],[vM.POLYGON,"polygon"],[vM.QUAD,"quad"],[vM.RECT,"rect"],[vM.TEXT,"text"],[vM.GROUP,"group"]]),bM.arrStyleSelectors=["default","selected"],bM.mapItemState=new Map([[yM.DEFAULT,"default"],[yM.SELECTED,"selected"]]);let SM=class extends bM{constructor(t,e){if(super(null,e),xM.set(this,void 0),!vD(t))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new cM.Rect({left:t.x,top:t.y,width:t.width,height:t.height})),Jk(this,xM,JSON.parse(JSON.stringify(t))),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(){Zk(this,xM,"f")&&this.setRect(Zk(this,xM,"f"))}setRect(t){if(!vD(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 Jk(this,xM,JSON.parse(JSON.stringify(t)))}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 Zk(this,xM,"f")?JSON.parse(JSON.stringify(Zk(this,xM,"f"))):null}};function TM(t,e,i){let n=i.points[this.pointIndex].x-i.pathOffset.x,s=i.points[this.pointIndex].y-i.pathOffset.y;return cM.util.transformPoint({x:n,y:s},i.calcTransformMatrix())}function EM(t){let e=new cM.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new cM.Point(t.width+e.x,t.height+e.y)}function _M(t,e,i,n){let s=e.target,o=s.controls[s.__corner],r=s.toLocalPoint(new cM.Point(i,n),"center","center"),a=EM(s),l=s._getTransformedDimensions(0,0),h={x:r.x*a.x/l.x+s.pathOffset.x,y:r.y*a.y/l.y+s.pathOffset.y};return s.points[o.pointIndex]=h,cM.controlsUtils.fireEvent("scaling",{e:t,transform:e,pointer:{x:i,y:n}}),!0}function PM(t,e){return function(i,n,s,o){let r=n.target,a=cM.util.transformPoint({x:r.points[t].x-r.pathOffset.x,y:r.points[t].y-r.pathOffset.y},r.calcTransformMatrix()),l=e(i,n,s,o);r._setPositionDimensions({});let h=EM(r),c=(r.points[t].x-r.pathOffset.x)/h.x,d=(r.points[t].y-r.pathOffset.y)/h.y;return r.setPositionByOrigin(a,c+.5,d+.5),l}}xM=new WeakMap;let AM=class extends bM{constructor(t,e){if(super(null,e),wM.set(this,void 0),!fD(t))throw new TypeError("Invalid 'polygon'.");this._setFabricObject(new cM.Polygon(t.points,{objectCaching:!1}));const i=this._fabricObject;let n=i.points.length-1;i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new cM.Control({positionHandler:TM,actionHandler:PM(i>0?i-1:n,_M),actionName:"modifyPolygon",pointIndex:i}),t},{}),Jk(this,wM,JSON.parse(JSON.stringify(t))),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,n){return t["p"+n]=new cM.Control({positionHandler:TM,actionHandler:PM(n>0?n-1:i,_M),actionName:"modifyPolygon",pointIndex:n}),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 n=i.x-e.pathOffset.x,s=i.y-e.pathOffset.y;const o=cM.util.transformPoint({x:n,y:s},e.calcTransformMatrix());t.push({x:o.x,y:o.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(){Zk(this,wM,"f")&&this.setPolygon(Zk(this,wM,"f"))}setPolygon(t){if(!fD(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 Jk(this,wM,JSON.parse(JSON.stringify(t)))}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 Zk(this,wM,"f")?JSON.parse(JSON.stringify(Zk(this,wM,"f"))):null}};wM=new WeakMap;const IM=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 n=0;n<t.length;n++){let s=t[n][e];void 0!==s&&s.length>i&&(i=s.length)}if(-1===i)break;for(let n=0;n<t.length;n++){if(e>=t[n].length-1)continue;let s=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(s)}}})(e),(t=>{let e="";for(let i=0;i<t.length;i++)e=e.concat(...t[i],i===t.length-1?"":"\n");return e})(e)};let DM=class extends bM{constructor(t,e,i){if(super(null,i),CM.set(this,void 0),!uM(t))throw new TypeError("Invalid 'text'.");if(!vD(e))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new cM.Textbox(IM(t),{left:e.x,top:e.y,width:e.width})),this._text=t,Jk(this,CM,JSON.parse(JSON.stringify(e))),this._mediaType="text"}extendSet(t,e){if("text"===t)return this._text=e,this._fabricObject.set("text",IM(e)),!0}extendGet(t){if("text"===t)return this._text}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")))}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")))}setPosition(t){this.setTextRect(t)}getPosition(){return this.getTextRect()}updatePosition(){Zk(this,CM,"f")&&this.setTextRect(Zk(this,CM,"f"))}setText(t){if(!uM(t))throw new TypeError("Invalid 'text'.");this.set("text",t)}getText(){return this.get("text")}setTextRect(t){if(!vD(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));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._drawingLayer.renderAll()}else Jk(this,CM,JSON.parse(JSON.stringify(t)))}getTextRect(){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 Zk(this,CM,"f")?JSON.parse(JSON.stringify(Zk(this,CM,"f"))):null}};var RM;CM=new WeakMap;class kM extends AM{constructor(t,e){if(super({points:null==t?void 0:t.points},e),RM.set(this,void 0),!mD(t))throw new TypeError("Invalid 'quad'.");Jk(this,RM,JSON.parse(JSON.stringify(t))),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Zk(this,RM,"f")&&this.setQuad(Zk(this,RM,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!mD(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 Jk(this,RM,JSON.parse(JSON.stringify(t)))}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 Zk(this,RM,"f")?JSON.parse(JSON.stringify(Zk(this,RM,"f"))):null}}RM=new WeakMap;let MM=class extends bM{constructor(t){super(new cM.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(aM.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(aM.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()))}};const LM=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),OM=t=>!!uM(t)&&""!==t,BM=t=>!(!LM(t)||"id"in t&&!dM(t.id)||"lineWidth"in t&&!dM(t.lineWidth)||"fillStyle"in t&&!OM(t.fillStyle)||"strokeStyle"in t&&!OM(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!OM(t.fontFamily)||"fontSize"in t&&!dM(t.fontSize));class NM{static convert(t,e,i,n){const s={x:0,y:0,width:e,height:i};if(!t)return s;const o=n.getVideoFit(),r=n.getVisibleRegionOfVideo({inPixels:!0});if(vD(t))t.isMeasuredInPercentage?"contain"===o||null===r?(s.x=t.x/100*e,s.y=t.y/100*i,s.width=t.width/100*e,s.height=t.height/100*i):(s.x=r.x+t.x/100*r.width,s.y=r.y+t.y/100*r.height,s.width=t.width/100*r.width,s.height=t.height/100*r.height):"contain"===o||null===r?(s.x=t.x,s.y=t.y,s.width=t.width,s.height=t.height):(s.x=t.x+r.x,s.y=t.y+r.y,s.width=t.width>r.width?r.width:t.width,s.height=t.height>r.height?r.height:t.height);else{if(!uD(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===o||null===r?(s.x=t.left/100*e,s.y=t.top/100*i,s.width=(t.right-t.left)/100*e,s.height=(t.bottom-t.top)/100*i):(s.x=r.x+t.left/100*r.width,s.y=r.y+t.top/100*r.height,s.width=(t.right-t.left)/100*r.width,s.height=(t.bottom-t.top)/100*r.height):"contain"===o||null===r?(s.x=t.left,s.y=t.top,s.width=t.right-t.left,s.height=t.bottom-t.top):(s.x=t.left+r.x,s.y=t.top+r.y,s.width=t.right-t.left>r.width?r.width:t.right-t.left,s.height=t.bottom-t.top>r.height?r.height:t.bottom-t.top)}return s.x=Math.round(s.x),s.y=Math.round(s.y),s.width=Math.round(s.width),s.height=Math.round(s.height),s}}var UM,FM;class VM{constructor(){UM.set(this,new Map),FM.set(this,!1)}get disposed(){return Zk(this,FM,"f")}on(t,e){t=t.toLowerCase();const i=Zk(this,UM,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Zk(this,UM,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Zk(this,UM,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Zk(this,UM,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Zk(this,UM,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let s of n){if(!s)continue;let o=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}o.push(i)}else o=e;let r=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(s)&&s.apply(i.target,o)},0);else try{r=s.apply(i.target,o)}catch(t){}if(!0===r)break}}}dispose(){Jk(this,FM,!0)}}function WM(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 HM(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function jM(t,e,i,n){let s=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),o=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((s^o)>=0&&0!==s&&0!==o||(s=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),o=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(s^o)>=0&&0!==s&&0!==o))}UM=new WeakMap,FM=new WeakMap;const zM=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 n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const s=new DocumentFragment;for(let t of n.children)s.append(t);return s};class GM{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const s=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*s[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return GM.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return GM.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return GM.multiply(t,[e,0,0,0,i,0,0,0,1])}}var YM,$M,XM,qM,ZM,JM,KM,QM,tL,eL,iL,nL,sL,oL,rL,aL,lL,hL,cL,dL,uL,pL,gL,fL,mL,vL,yL,xL,wL,CL,bL,SL,TL,EL,_L,PL,AL,IL,DL,RL,kL,ML,LL,OL,BL,NL,UL,FL,VL,WL,HL,jL,zL,GL,YL,$L,XL,qL,ZL,JL,KL,QL,tO,eO,iO,nO,sO,oO,rO,aO,lO,hO,cO,dO,uO,pO,gO,fO,mO,vO,yO,xO;class wO{static createDrawingStyle(t){if(!BM(t))throw new Error("Invalid style definition.");let e,i=wO.USER_START_STYLE_ID;for(;Zk(wO,YM,"f",$M).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Zk(wO,YM,"f",XM))n.hasOwnProperty(t)||(n[t]=Zk(wO,YM,"f",XM)[t]);return Zk(wO,YM,"f",$M).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Zk(wO,YM,"f",$M).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(Zk(wO,YM,"f",$M).values())))}static _updateDrawingStyle(t,e){if(!BM(e))throw new Error("Invalid style definition.");const i=Zk(wO,YM,"f",$M).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}YM=wO,wO.STYLE_BLUE_STROKE=1,wO.STYLE_GREEN_STROKE=2,wO.STYLE_ORANGE_STROKE=3,wO.STYLE_YELLOW_STROKE=4,wO.STYLE_BLUE_STROKE_FILL=5,wO.STYLE_GREEN_STROKE_FILL=6,wO.STYLE_ORANGE_STROKE_FILL=7,wO.STYLE_YELLOW_STROKE_FILL=8,wO.STYLE_BLUE_STROKE_TRANSPARENT=9,wO.STYLE_GREEN_STROKE_TRANSPARENT=10,wO.STYLE_ORANGE_STROKE_TRANSPARENT=11,wO.USER_START_STYLE_ID=1024,$M={value:new Map([[wO.STYLE_BLUE_STROKE,{id:wO.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[wO.STYLE_GREEN_STROKE,{id:wO.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}],[wO.STYLE_ORANGE_STROKE,{id:wO.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}],[wO.STYLE_YELLOW_STROKE,{id:wO.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[wO.STYLE_BLUE_STROKE_FILL,{id:wO.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}],[wO.STYLE_GREEN_STROKE_FILL,{id:wO.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}],[wO.STYLE_ORANGE_STROKE_FILL,{id:wO.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}],[wO.STYLE_YELLOW_STROKE_FILL,{id:wO.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}],[wO.STYLE_BLUE_STROKE_TRANSPARENT,{id:wO.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[wO.STYLE_GREEN_STROKE_TRANSPARENT,{id:wO.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[wO.STYLE_ORANGE_STROKE_TRANSPARENT,{id:wO.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},XM={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&&(cM.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(cM.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),cM.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},cM.Object.prototype.transparentCorners=!1,cM.Object.prototype.cornerSize=20,cM.Object.prototype.touchCornerSize=100,cM.Object.prototype.cornerColor="rgb(254,142,20)",cM.Object.prototype.cornerStyle="circle",cM.Object.prototype.strokeUniform=!0,cM.Object.prototype.hasBorders=!1,cM.Canvas.prototype.containerClass="",cM.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,s=cM.util.getPointer(t,i),o=i.getBoundingClientRect(),r=o.width||0,a=o.height||0;r&&a||("top"in o&&"bottom"in o&&(a=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(r=Math.abs(o.right-o.left))),this.calcOffset(),s.x=s.x-this._offset.left,s.y=s.y-this._offset.top,e||(s=this.restorePointerVpt(s));var l=this.getRetinaScaling();if(1!==l&&(s.x/=l,s.y/=l),0!==r&&0!==a){var h=window.getComputedStyle(i).objectFit,c=i.width,d=i.height,u=r,p=a;n={width:c/u,height:d/p};var g,f,m=c/d,v=u/p;return"contain"===h?m>v?(g=u,f=u/m,{x:s.x*n.width,y:(s.y-(p-f)/2)*n.width}):(g=p*m,f=p,{x:(s.x-(u-g)/2)*n.height,y:s.y*n.height}):"cover"===h?m>v?{x:(c-n.height*u)/2+s.x*n.height,y:s.y*n.height}:{x:s.x*n.width,y:(d-n.width*p)/2+s.y*n.width}:{x:s.x*n.width,y:s.y*n.height}}return n={width:1,height:1},{x:s.x*n.width,y:s.y*n.height}},cM.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;i<t.touches.length;i++){let n=t.touches[i];if(e=this.findTarget(n),e)break}100===this.id&&!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),100===this.id&&e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();let i=this.upperCanvasEl,n=this._getEventPrefix();cM.util.addListener(cM.document,"touchend",this._onTouchEnd,{passive:!1}),cM.util.addListener(cM.document,"touchmove",this._onMouseMove,{passive:!1}),cM.util.removeListener(i,n+"down",this._onMouseDown)},cM.Textbox.prototype._wrapLine=function(t,e,i,n){const s=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),o=!(!s||!s.length);var r=0,a=this.splitByGrapheme||o,l=[],h=[],c=a?cM.util.string.graphemeSplit(t):t.split(this._wordJoiners),d="",u=0,p=a?"":" ",g=0,f=0,m=0,v=!0,y=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var x=0;x<c.length;x++)d=a?c[x]:cM.util.string.graphemeSplit(c[x]),g=this._measureWord(d,e,u),u+=d.length,(r+=f+g-y)>i&&!v?(l.push(h),h=[],r=g,v=!0):r+=y,v||a||h.push(p),h=h.concat(d),f=a?0:this._measureWord([p],e,u),u++,v=!1,g>m&&(m=g);return x&&l.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-y+n),l});class CO{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 cM.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 n of e){const e=n.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 n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)},0)}}),e.on("selection:updated",function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],s=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&s.push(i)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(n,s)},0)}}),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,s;switch(this.fabricCanvas.id=e,this.id=e,e){case CO.DDN_LAYER_ID:n=wO.getDrawingStyle(wO.STYLE_BLUE_STROKE),s=wO.getDrawingStyle(wO.STYLE_BLUE_STROKE_FILL);break;case CO.DBR_LAYER_ID:n=wO.getDrawingStyle(wO.STYLE_ORANGE_STROKE),s=wO.getDrawingStyle(wO.STYLE_ORANGE_STROKE_FILL);break;case CO.DLR_LAYER_ID:n=wO.getDrawingStyle(wO.STYLE_GREEN_STROKE),s=wO.getDrawingStyle(wO.STYLE_GREEN_STROKE_FILL);break;default:n=wO.getDrawingStyle(wO.STYLE_YELLOW_STROKE),s=wO.getDrawingStyle(wO.STYLE_YELLOW_STROKE_FILL)}for(let t of bM.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:s.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){return t.styleId?wO.getDrawingStyle(t.styleId):wO.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const s=this.getDrawingItems(e=>e._mediaType===t);for(let t of s)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=wO.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.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=wO.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=wO.getDrawingStyle(n[t.styleSelector]);const s=()=>{this._changeItemStyle(e,wO.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},o=()=>{this._changeItemStyle(e,wO.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",s),e._on("deselected",o),e._funcChangeStyleToSelected=s,e._funcChangeStyleToDefault=o}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.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 bM))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 n=this.fabricCanvas.getObjects();let s,o;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){s=t.getChildDrawingItems();for(let t of s)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(s){for(let t of s){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bM.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)o=wO.getDrawingStyle(t.styleId);else{o=wO.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,wO.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,wO.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,o,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bM.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)o=wO.getDrawingStyle(t.styleId);else{o=wO.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,wO.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,wO.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,o)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const r=this._arrFabricObject.length;let a=n.length;if(r)a=n.indexOf(this._arrFabricObject[r-1])+1;else for(let e=0;e<n.length;e++)if(t._zIndex<n[e].getDrawingItem()._zIndex){a=e;break}this._arrDrwaingItem.push(t),this._arrFabricObject.push(i),this._visible?i.visible=!0:i.visible=!1,this.fabricCanvas.insertAt(i,a,!1)}addDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");if("viewer"===this.mode)t._setEditable(!1);else{if("editor"!==this.mode)throw new Error("Illegal 'mode'.");t._setEditable(!0)}this._addDrawingItem(t),t.updatePosition()}addDrawingItems(t){for(let e of t)this.addDrawingItem(e)}removeDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");if(!this.hasDrawingItem(t))return;if(t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,"group"===t._mediaType){const e=t.getChildDrawingItems();for(let t of e)t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,t._mapState_StyleId.clear()}else t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,t._mapState_StyleId.clear();const e=t._getFabricObject();"selected"===t.styleSelector&&(e.group?e.group.removeWithUpdate(e):this.fabricCanvas._activeObject=null,t.setState(aM.DIS_DEFAULT)),this.fabricCanvas.remove(e),this._arrDrwaingItem.splice(this._arrDrwaingItem.indexOf(t),1),this._arrFabricObject.splice(this._arrFabricObject.indexOf(e),1)}removeDrawingItems(t){for(let e of t)this.removeDrawingItem(e)}setDrawingItems(t){this.clearDrawingItems(),this.addDrawingItems(t)}getDrawingItems(t){return t&&"function"==typeof t?this._arrDrwaingItem.filter(t):Array.from(this._arrDrwaingItem)}getSelectedDrawingItems(){const t=this.fabricCanvas.getActiveObjects(),e=[];for(let i of t)this._arrFabricObject.includes(i)&&e.push(i.getDrawingItem());return e}hasDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");return this._arrDrwaingItem.includes(t)}clearDrawingItems(){this.removeDrawingItems(Array.from(this._arrDrwaingItem))}_setDefaultStyle(t,e,i){e?e.forEach(t=>t.toLowerCase()):e=bM.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=bM.arrStyleSelectors;const n=wO.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let s;for(let o of e)if(s=this.mapType_StateAndStyleId.get(o),s)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(o,e,n,!0),s[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===o&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&rM.DIMT_RECTANGLE&&n.push("rect"),i&rM.DIMT_QUADRILATERAL&&n.push("quad"),i&rM.DIMT_TEXT&&n.push("text"),i&rM.DIMT_ARC&&n.push("arc"),i&rM.DIMT_IMAGE&&n.push("image"),i&rM.DIMT_POLYGON&&n.push("polygon"),i&rM.DIMT_LINE&&n.push("line");const s=[];e&aM.DIS_DEFAULT&&s.push("default"),e&aM.DIS_SELECTED&&s.push("selected"),this._setDefaultStyle(t,n.length?n:null,s.length?s: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)}}CO.DDN_LAYER_ID=1,CO.DBR_LAYER_ID=2,CO.DLR_LAYER_ID=3,CO.USER_DEFINED_LAYER_BASE_ID=100,CO.TIP_LAYER_ID=999;class bO{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new CO(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){this._arrDrawingLayer.length&&(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 SO extends DM{constructor(t,e,i,n,s){super(t,{x:e,y:i,width:n,height:0},s),qM.set(this,void 0),ZM.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e<i;e++)t+=this.getHeightOfLine(e);return t+2*this.paddingTop},this._fabricObject._getTopOffset=function(){return-this.height/2+this.getHeightOfLine(0)*(1-1/this.lineHeight)/2+this.paddingTop},this.set("backgroundColor","rgba(50, 50, 52, .8)"),this.set("lineHeight",1.3),this.set("textAlign","center")}setDuration(t){Jk(this,qM,t),Zk(this,ZM,"f")&&clearTimeout(Zk(this,ZM,"f")),Zk(this,qM,"f")>=0&&Jk(this,ZM,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},Zk(this,qM,"f")))}getDuration(){return Zk(this,qM,"f")}}qM=new WeakMap,ZM=new WeakMap;class TO{constructor(){JM.add(this),KM.set(this,void 0),QM.set(this,void 0),tL.set(this,void 0),eL.set(this,!0),this._drawingLayerManager=new bO}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 n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let s;try{s=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==s?void 0:s.width)||1280),i||(i=(null==s?void 0:s.height)||720),n||(n=(null==s?void 0:s.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const s=this._layerBaseCvs,o=this._drawingLayerManager.createDrawingLayer(s,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",s.parentElement),o}createDrawingLayer(){let t;for(let e=CO.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==CO.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(t<CO.USER_DEFINED_LAYER_BASE_ID)throw new Error(`The drawing layer with id ${t} is not defined by users.`);this.deleteDrawingLayer(t)}_clearDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t)this.deleteDrawingLayer(e.getId())}clearUserDefinedDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t){const t=e.getId();t<CO.USER_DEFINED_LAYER_BASE_ID||this.deleteUserDefinedDrawingLayer(t)}}getDrawingLayer(t){return t==CO.TIP_LAYER_ID?null:this._drawingLayerManager.getDrawingLayer(t)||([CO.DDN_LAYER_ID,CO.DBR_LAYER_ID,CO.DLR_LAYER_ID].includes(t)?this._createDrawingLayer(t):null)}getAllDrawingLayers(){return this._drawingLayerManager.getAllDrawingLayers().filter(t=>t.getId()>=0&&t.getId()!==CO.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(!(LM(e=t)&&gD(e.topLeftPoint)&&dM(e.width))||e.width<=0||!dM(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Jk(this,KM,JSON.parse(JSON.stringify(t))),Zk(this,KM,"f").coordinateBase||(Zk(this,KM,"f").coordinateBase="view"),Jk(this,tL,t.duration),Zk(this,JM,"m",oL).call(this)}getTipConfig(){return Zk(this,KM,"f")?Zk(this,KM,"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()),Jk(this,eL,t)}isTipVisible(){return Zk(this,eL,"f")}updateTipMessage(t){if(!Zk(this,KM,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=wO.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(CO.TIP_LAYER_ID)||this._createDrawingLayer(CO.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Zk(this,JM,"m",iL).call(this,t,Zk(this,KM,"f").topLeftPoint.x,Zk(this,KM,"f").topLeftPoint.y,Zk(this,KM,"f").width,Zk(this,KM,"f").coordinateBase,this._tipStyleId),Zk(this,JM,"m",nL).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Zk(this,eL,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Zk(this,QM,"f")&&clearTimeout(Zk(this,QM,"f")),Zk(this,tL,"f")>=0&&Jk(this,QM,setTimeout(()=>{Zk(this,JM,"m",sL).call(this)},Zk(this,tL,"f")))}}KM=new WeakMap,QM=new WeakMap,tL=new WeakMap,eL=new WeakMap,JM=new WeakSet,iL=function(t,e,i,n,s,o){const r=new SO(t,e,i,n,o);return r.coordinateBase=s,r},nL=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},sL=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},oL=function(){if(!this._tip)return;const t=Zk(this,KM,"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 EO extends HTMLElement{constructor(){super(),rL.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Jk(this,rL,e);const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const s=document.createElement("slot");s.setAttribute("name","drawing-layer"),e.append(s);const o=document.createElement("style");o.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(o),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Zk(this,rL,"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())}}rL=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",EO);class _O extends TO{static get engineResourcePath(){const t=wD(wR.engineResourcePaths);return"DCV"===wR._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){_O._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=_O._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",_O.engineResourcePath)}static async createInstance(t){const e=new _O;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",_O.engineResourcePath)),await e.setUIElement(t||_O.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,s,o,r){const a=o/n,l=r/s;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/l+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Zk(this,mL,"f")){if(Jk(this,mL,t),Zk(this,aL,"m",xL).call(this))Jk(this,dL,null),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"),!Zk(this,dL,"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("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qk.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Jk(this,dL,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Zk(this,aL,"m",xL).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 Zk(this,mL,"f")}get disposed(){return Zk(this,yL,"f")}constructor(){super(),aL.add(this),lL.set(this,void 0),hL.set(this,void 0),cL.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",dL.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,this._poweredBy=null,uL.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,pL.set(this,!1),gL.set(this,!1),fL.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Zk(this,aL,"m",TL).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()&&Zk(this,aL,"m",SL).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{_O._onLog&&_O._onLog("window resize event triggered."),Zk(this,fL,"f").width===document.documentElement.clientWidth&&Zk(this,fL,"f").height===document.documentElement.clientHeight||(Zk(this,fL,"f").width=document.documentElement.clientWidth,Zk(this,fL,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},mL.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Zk(this,aL,"m",xL).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 n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),s=new Image;s.src=i,s.onload=()=>{URL.revokeObjectURL(s.src),t(s)},s.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const s=t.getContext("2d");s.clearRect(0,0,t.width,t.height),s.drawImage(e,0,0)},n=await t(e),s=n instanceof HTMLImageElement?n.naturalWidth:n.width,o=n instanceof HTMLImageElement?n.naturalHeight:n.height;let r=this._cvsSingleFrameMode;const a=null==r?void 0:r.width,l=null==r?void 0:r.height;r||(r=document.createElement("canvas"),this._cvsSingleFrameMode=r),i(r,n,s,o),this._innerComponent.setElement("content",r),a===r.width&&l===r.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()},vL.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,s,o;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const r=t.originalImageTag;if(!r)return;const a=t.items;if(!(null==a?void 0:a.length))return;const l=(null===(i=r.cropRegion)||void 0===i?void 0:i.left)||0,h=(null===(n=r.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(s=r.cropRegion)||void 0===s?void 0:s.right)?r.cropRegion.right-l:r.originalWidth,d=(null===(o=r.cropRegion)||void 0===o?void 0:o.bottom)?r.cropRegion.bottom-h:r.originalHeight,u=r.currentWidth,p=r.currentHeight,g=(t,e,i,n,s,o,r,a,l=[],h)=>{(e=JSON.parse(JSON.stringify(e))).forEach(t=>_O._transformCoordinates(t,i,n,s,o,r,a));const c=new kM({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}]},h);for(let t of l)c.addNote(t);t.addDrawingItems([c]),Zk(this,vL,"f").push(c)};let f,m;for(let t of a)switch(t.type){case zD.CRIT_ORIGINAL_IMAGE:break;case zD.CRIT_BARCODE:f=this.getDrawingLayer(CO.DBR_LAYER_ID),m=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(f,t.location.points,l,h,c,d,u,p,m):g(f,t.location.points,l,h,c,d,u,p,m,wO.STYLE_ORANGE_STROKE_TRANSPARENT):g(f,t.location.points,l,h,c,d,u,p,m);break;case zD.CRIT_TEXT_LINE:f=this.getDrawingLayer(CO.DLR_LAYER_ID),m=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(f,t.location.points,l,h,c,d,u,p,m):g(f,t.location.points,l,h,c,d,u,p,m,wO.STYLE_GREEN_STROKE_TRANSPARENT):g(f,t.location.points,l,h,c,d,u,p,m);break;case zD.CRIT_DETECTED_QUAD:f=this.getDrawingLayer(CO.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===KD.CVS_PASSED?g(f,t.location.points,l,h,c,d,u,p,[]):g(f,t.location.points,l,h,c,d,u,p,[],wO.STYLE_BLUE_STROKE_TRANSPARENT):g(f,t.location.points,l,h,c,d,u,p,[]);break;case zD.CRIT_DESKEWED_IMAGE:f=this.getDrawingLayer(CO.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===KD.CVS_PASSED?g(f,t.sourceLocation.points,l,h,c,d,u,p,[]):g(f,t.sourceLocation.points,l,h,c,d,u,p,[],wO.STYLE_BLUE_STROKE_TRANSPARENT):g(f,t.sourceLocation.points,l,h,c,d,u,p,[]);break;case zD.CRIT_PARSED_RESULT:case zD.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}}},yL.set(this,!1),this.eventHandler=new VM,this.eventHandler.on("content:updated",()=>{Zk(this,lL,"f")&&clearTimeout(Zk(this,lL,"f")),Jk(this,lL,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))}),this.eventHandler.on("videoEl:resized",()=>{Zk(this,hL,"f")&&clearTimeout(Zk(this,hL,"f")),Jk(this,hL,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0))})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await zM(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 n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),Zk(this,aL,"m",xL).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("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qk.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Jk(this,dL,t);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._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||Zk(this,aL,"m",xL).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['<option class="dce-opt-gotResolution" value="got"></option>','<option data-width="1920" data-height="1080">ask 1920x1080</option>','<option data-width="1280" data-height="720">ask 1280x720</option>','<option data-width="640" data-height="480">ask 640x480</option>'].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Zk(this,aL,"m",xL).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['<option class="dlr-opt-gotMinLtr" value="got"></option>','<option value="0" selected>any letter</option>','<option value="3">3+ letters</option>','<option value="5">5+ letters</option>','<option value="8">8+ letters</option>','<option value="12">12+ letters</option>','<option value="17">17+ letters</option>','<option value="30">30+ letters</option>','<option value="50">50+ letters</option>','<option value="80">80+ letters</option>','<option value="120">120+ letters</option>'].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Zk(this,aL,"m",TL).call(this),Zk(this,aL,"m",xL).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Zk(this,aL,"m",xL).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;_O._onLog&&_O._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)}Zk(this,fL,"f").width=document.documentElement.clientWidth,Zk(this,fL,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Zk(this,aL,"m",xL).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Zk(this,aL,"m",TL).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,Jk(this,dL,null),null===(n=this._videoContainer)||void 0===n||n.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 n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.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),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Zk(this,dL,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Zk(this,dL,"f"))return;if(Zk(this,dL,"f").style.objectFit=t,Zk(this,aL,"m",xL).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();Zk(this,aL,"m",EL).call(this,e,i),Zk(this,aL,"m",wL).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let s,o,r;if(Zk(this,aL,"m",xL).call(this)?(s=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,o=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,r="contain"):(s=null===(t=Zk(this,dL,"f"))||void 0===t?void 0:t.videoWidth,o=null===(e=Zk(this,dL,"f"))||void 0===e?void 0:e.videoHeight,r=this.getVideoFit()),!s||!o)throw new Error("Invalid content dimensions.");return{width:s,height:o,objectFit:r}}updateConvertedRegion(t){uD(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):vD(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=NM.convert(this.scanRegion,t.width,t.height,this);Jk(this,uL,e),Zk(this,cL,"f")&&clearTimeout(Zk(this,cL,"f")),Jk(this,cL,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Zk(this,aL,"m",wL).call(this,t,e),Zk(this,aL,"m",EL).call(this,t,e)},0))}getConvertedRegion(){return Zk(this,uL,"f")}setScanRegion(t){if(null!=t&&!uD(t)&&!vD(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("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Zk(this,dL,"f").videoWidth,i=Zk(this,dL,"f").videoHeight,n=this.getVideoFit(),{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return null;let r;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(s/o<e/i?(r=o/i,a.x=Math.floor((e-s/r)/2),a.y=0,a.width=Math.ceil(s/r),a.height=i):(r=s/e,a.x=0,a.y=Math.floor((i-o/r)/2),a.width=e,a.height=Math.ceil(o/r))),null==t?void 0:t.inPixels)return a;const l=a;return l.x=Math.ceil(l.x/i*100),l.y=Math.ceil(l.y/e*100),l.width=Math.floor(l.width/e*100),l.height=Math.floor(l.height/i*100),l.isMeasuredInPercentage=!0,a}setScanRegionMask(t,e,i,n){this._drawingLayerOfMask||(this._drawingLayerOfMask=this._createDrawingLayer(-2),this.isScanRegionMaskVisible()||Zk(this,aL,"m",bL).call(this)),this.clearScanRegionMask(),this._maskBackRectStyleId||(this._maskBackRectStyleId=wO.createDrawingStyle({paintMode:"fill",fillStyle:this.regionMaskFillStyle,lineWidth:0})),this._maskCenterRectStyleId||(this._maskCenterRectStyleId=wO.createDrawingStyle({paintMode:"stroke",strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth}));const s=this._drawingLayerOfMask.width,o=this._drawingLayerOfMask.height,r=new SM({x:0,y:0,width:s,height:o},this._maskBackRectStyleId),a=new SM({x:-s/2,y:-o/2+e,width:t,height:n}),l=new SM({x:-s/2+t+i,y:-o/2+e,width:s-t-i<0?0:s-t-i,height:n}),h=new SM({x:-s/2,y:-o/2,width:s,height:e}),c=new SM({x:-s/2,y:-o/2+e+n,width:s,height:o-e-n<0?0:o-e-n});a.set("strokeWidth",0),l.set("strokeWidth",0),h.set("strokeWidth",0),c.set("strokeWidth",0);const d=new MM([a,l,h,c])._getFabricObject();r.set("clipPath",d);const u=new SM({x:t,y:e,width:i-this.regionMaskLineWidth,height:n-this.regionMaskLineWidth},this._maskCenterRectStyleId);this._drawingLayerOfMask.addDrawingItems([r,u])}clearScanRegionMask(){this._drawingLayerOfMask&&this._drawingLayerOfMask.clearDrawingItems()}deleteScanRegionMask(){this._drawingLayerOfMask&&this.deleteDrawingLayer(this._drawingLayerOfMask.getId())}_setScanRegionMaskVisible(t){Jk(this,pL,t),t?Zk(this,aL,"m",CL).call(this):Zk(this,aL,"m",bL).call(this)}setScanRegionMaskVisible(t){this._setScanRegionMaskVisible(t),this._userSetMaskVisible=t}isScanRegionMaskVisible(){return Zk(this,pL,"f")}setScanRegionMaskStyle(t){if(!t)return;let e;t.fillStyle&&(this.regionMaskFillStyle=t.fillStyle),t.strokeStyle&&(this.regionMaskStrokeStyle=t.strokeStyle),t.lineWidth&&(this.regionMaskLineWidth=t.lineWidth),this._maskBackRectStyleId&&wO.updateDrawingStyle(this._maskBackRectStyleId,{fillStyle:this.regionMaskFillStyle}),this._maskCenterRectStyleId&&wO.updateDrawingStyle(this._maskCenterRectStyleId,{strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth});try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}const i=this.getConvertedRegion();Zk(this,aL,"m",wL).call(this,e,i),Zk(this,aL,"m",EL).call(this,e,i)}getScanRegionMaskStyle(){return{fillStyle:this.regionMaskFillStyle,strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth}}_setScanLaserVisible(t){Jk(this,gL,t),t?Zk(this,aL,"m",SL).call(this):Zk(this,aL,"m",TL).call(this)}setScanLaserVisible(t){this._setScanLaserVisible(t),this._userSetLaserVisible=t}isScanLaserVisible(){return Zk(this,gL,"f")}_updateVideoContainer(){if(!Zk(this,dL,"f"))return;if(Zk(this,aL,"m",xL).call(this))return;let t=1;const e=Zk(this,dL,"f").style.transform.match(/scale\((.+)\)/);e&&(t=parseFloat(e[1]));const i=this._videoContainer;if("contain"===this.videoFit&&t>1){const t=Zk(this,dL,"f").videoWidth,e=Zk(this,dL,"f").videoHeight,{width:n,height:s}=this._innerComponent.getBoundingClientRect(),o=t/e;if(n/s<o){let t=n/o;i.style.left="0",i.style.top=(s-t)/2/s*100+"%",i.style.width="100%",i.style.height=t/s*100+"%"}else{let t=s*o;i.style.left=(n-t)/2/n*100+"%",i.style.top="0",i.style.width=t/n*100+"%",i.style.height="100%"}}else i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%"}setPowerByMessageVisible(t){this._poweredBy&&(this._poweredBy.style.display=t?"":"none",this._poweredByVisible=t);let e=this.getUIElement();e=e.shadowRoot||e;const i=e.querySelector(".dce-mn-msg-poweredby");i&&(i.style.display=t?"":"none",this._poweredByVisible=t)}isPowerByMessageVisible(){return this._poweredByVisible}updateLayers(){let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}const e=this.getConvertedRegion();Zk(this,aL,"m",EL).call(this,t,e),this.updateDrawingLayers(t),Zk(this,aL,"m",wL).call(this,t,e)}clearAllInnerDrawingItems(){Zk(this,vL,"f").forEach(t=>t.remove()),Zk(this,vL,"f").length=0}dispose(){this._unbindUI(),Jk(this,yL,!0)}}lL=new WeakMap,hL=new WeakMap,cL=new WeakMap,dL=new WeakMap,uL=new WeakMap,pL=new WeakMap,gL=new WeakMap,fL=new WeakMap,mL=new WeakMap,vL=new WeakMap,yL=new WeakMap,aL=new WeakSet,xL=function(){return"disabled"!==this._singleFrameMode},wL=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)},CL=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},bL=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},SL=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},TL=function(){this._divScanLight&&(this._divScanLight.style.display="none")},EL=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:s}=t;e||(e={x:0,y:0,width:i,height:n});const{width:o,height:r}=this._innerComponent.getBoundingClientRect();if(o<=0||r<=0)return;const a=o/r,l=i/n;let h,c,d,u,p=1;if("contain"===s)a<l?(p=o/i,h=0,c=(r-n*p)/2):(p=r/n,h=(o-i*p)/2,c=0),h+=e.x*p,c+=e.y*p,d=e.width*p,u=e.height*p;else if("cover"===s)if(a<l){p=r/n,h=e.x*p-(i*p-o)/2,h=Math.max(h,0),h=Math.min(h,o),c=e.y*p;let t=(e.x+e.width)*p-(i*p-o)/2;t=Math.max(t,0),t=Math.min(t,o),d=t-h,u=e.height*p}else{p=o/i,h=e.x*p,c=e.y*p-(n*p-r)/2,c=Math.max(c,0),c=Math.min(c,r);let t=(e.y+e.height)*p-(n*p-r)/2;t=Math.max(t,0),t=Math.min(t,r),d=e.width*p,u=t-c}else h=0,c=0,d=0,u=0;this.scanRegion?(this._divScanArea.style.left=h+this.regionMaskLineWidth*p+"px",this._divScanArea.style.top=c+this.regionMaskLineWidth*p+"px",this._divScanArea.style.width=d-this.regionMaskLineWidth*p*2+"px",this._divScanArea.style.height=u-this.regionMaskLineWidth*p*2+"px"):(this._divScanArea.style.left=h+.005*d+"px",this._divScanArea.style.top=c+.005*d+"px",this._divScanArea.style.width=d-.01*d+"px",this._divScanArea.style.height=u-.01*d+"px")},_O._defaultUIElementURL="@engineResourcePath/dce.ui.xml";class PO{static get version(){return"4.3.3-dev-20251029130621"}static get webGLSupported(){return void 0===PO._webGLSupported&&(PO._webGLSupported=!!document.createElement("canvas").getContext("webgl")),PO._webGLSupported}get disposed(){return Zk(this,RL,"f")}constructor(){_L.set(this,hM.RGBA),PL.set(this,null),AL.set(this,null),IL.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,DL.set(this,null),RL.set(this,!1)}sourceIsReady(t){return t instanceof HTMLVideoElement?t.src?0!==t.readyState:4===t.readyState:!(t instanceof HTMLImageElement)||t.complete}drawImage(t,e,i,n,s,o){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==o?void 0:o.bUseWebGL)&&!PO.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(!this.sourceIsReady(e))throw new Error("The source is not loaded.");let r;PO._onLog&&(r=Date.now(),PO._onLog("drawImage(), START: "+r));let a=0,l=0,h=i,c=n,d=0,u=0,p=i,g=n;s&&(s.sx&&(a=Math.round(s.sx)),s.sy&&(l=Math.round(s.sy)),s.sWidth&&(h=Math.round(s.sWidth)),s.sHeight&&(c=Math.round(s.sHeight)),s.dx&&(d=Math.round(s.dx)),s.dy&&(u=Math.round(s.dy)),s.dWidth&&(p=Math.round(s.dWidth)),s.dHeight&&(g=Math.round(s.dHeight)));let f,m=hM.RGBA;if((null==o?void 0:o.pixelFormat)&&(m=o.pixelFormat),(null==o?void 0:o.bufferContainer)&&(f=o.bufferContainer,f.length<4*p*g))throw new Error("Unexpected size of the 'bufferContainer'.");const v=t;if(!PO.webGLSupported||!(this.useWebGLByDefault&&null==(null==o?void 0:o.bUseWebGL)||(null==o?void 0:o.bUseWebGL))){PO._onLog&&PO._onLog("drawImage() in context2d."),v.ctx2d||(v.ctx2d=v.getContext("2d",{willReadFrequently:!0}));const t=v.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(v.width<d+p||v.height<u+g)&&(v.width=d+p,v.height=u+g),t.drawImage(e,a,l,h,c,d,u,p,g),PO._onLog&&PO._onLog("drawImage() in context2d end. Costs: "+(Date.now()-r)),{context:t,pixelFormat:hM.RGBA,bUseWebGL:!1}}PO._onLog&&PO._onLog("drawImage() in WebGL.");try{(v.width<d+p||v.height<u+g)&&(v.width=d+p,v.height=u+g,v.ctxWebGL&&v.ctxWebGL.viewport(0,0,d+p,u+g));const t=v.ctxWebGL||v.getContext("webgl",{antialias:!1})||v.getContext("experimental-webgl",{antialias:!1});if(!t){PO._onLog&&PO._onLog("Browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");const t=new Error("Unable to get 'WebGLRenderingContext'. Your browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");throw t.name="WebGLError",t}if(!v.ctxWebGL||m!==Zk(this,_L,"f")){v.ctxWebGL=t;const e=t=>{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},n=(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},s=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},o="\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 r="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(m)&&(r=m.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.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n              gl_FragColor = vec4(sample.${r} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n            }\n          `,l=n(t,[s(t,t.VERTEX_SHADER,o),s(t,t.FRAGMENT_SHADER,a)]);Jk(this,AL,{program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}}),Jk(this,IL,e(t)),Jk(this,PL,i(t)),Jk(this,_L,m)}const s=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},y=(t,e,i)=>{const n=t.RGBA,s=t.RGBA,o=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,s,o,i)},x=(t,e,r,f)=>{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),s(t,r.positions,e.attribLocations.vertexPosition),s(t,r.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,f),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[hM.GREY,hM.GREY32].includes(m)?1:0);let v,y,x=GM.translate(GM.identity(),-1,-1);x=GM.scale(x,2,2),x=GM.scale(x,1/t.canvas.width,1/t.canvas.height),v=GM.translate(x,d,u),v=GM.scale(v,p,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,v),o.isEnableMirroring?(y=GM.translate(GM.identity(),1,0),y=GM.scale(y,-1,1),y=GM.translate(y,a/i,l/n),y=GM.scale(y,h/i,c/n)):(y=GM.translate(GM.identity(),a/i,l/n),y=GM.scale(y,h/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,y),t.drawArrays(t.TRIANGLES,0,6)};y(t,Zk(this,PL,"f"),e),x(t,Zk(this,AL,"f"),Zk(this,IL,"f"),Zk(this,PL,"f"));const w=f||new Uint8Array(4*p*g);if(t.readPixels(d,u,p,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){PO._onLog&&PO._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return PO._onLog&&PO._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-r)),{context:t,pixelFormat:m===hM.GREY?hM.GREY32:m,bUseWebGL:!0}}catch(r){if(this.forceLoseContext(),null==(null==o?void 0:o.bUseWebGL))return PO._onLog&&PO._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,s,Object.assign({},o,{bUseWebGL:!1}));throw r.name="WebGLError",r}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,s=0,o=0,r=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(s=e.x),e.y&&(o=e.y),e.width&&(r=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*r*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(s,o,r,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*r*a)):(n=new Uint8Array(4*r*a),e.readPixels(s,o,r,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(s,o,r,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let s,o;if(PO._onLog&&(s=Date.now(),PO._onLog("transformPixelFormat(), START: "+s)),e===i)return PO._onLog&&PO._onLog("transformPixelFormat() end. Costs: "+(Date.now()-s)),n?new Uint8Array(t):t;const r=[hM.RGBA,hM.RBGA,hM.GRBA,hM.GBRA,hM.BRGA,hM.BGRA];if(r.includes(e))if(i===hM.GREY){o=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4){const i=.3*t[e]+.59*t[e+1]+.11*t[e+2];o[e/4]=i}}else if(i===hM.GREY32){o=n?new Uint8Array(t):t;for(let e=0;e<t.length;e+=4){const i=.3*t[e]+.59*t[e+1]+.11*t[e+2];o[e]=i,o[e+1]=i,o[e+2]=i}}else{if(!r.includes(i))throw new Error("Unable to transform.");if(n){o=new Uint8Array(t);const n=e.indexOf("r"),s=e.indexOf("g"),r=e.indexOf("b"),a=i.indexOf("r"),l=i.indexOf("g"),h=i.indexOf("b");for(let e=0;e<t.length;e+=4)o[e+a]=t[e+n],o[e+l]=t[e+s],o[e+h]=t[e+r]}else{o=t;const n=e.indexOf("r"),s=e.indexOf("g"),r=e.indexOf("b"),a=i.indexOf("r"),l=i.indexOf("g"),h=i.indexOf("b");for(let e=0;e<t.length;e+=4){let i=[t[e],t[e+1],t[e+2]];o[e+a]=i[n],o[e+l]=i[s],o[e+h]=i[r]}}}else if(e===hM.GREY){if(i!==hM.GREY32)throw new Error("Unable to transform.");o=new Uint8Array(4*t.length);for(let e=0;e<t.length;e++)o[4*e]=t[e],o[4*e+1]=t[e],o[4*e+2]=t[e],o[4*e+3]=255}else{if(e!==hM.GREY32)throw new Error("Unable to transform.");if(i!==hM.GREY)throw new Error("Unable to transform.");o=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4)o[e/4]=t[e]}return PO._onLog&&PO._onLog("transformPixelFormat() end. Costs: "+(Date.now()-s)),o}getImageData(t,e,i){var n,s,o,r,a;if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!this.sourceIsReady(t))throw new Error("The source is not loaded.");let l,h;if(t instanceof HTMLImageElement)l=t.naturalWidth,h=t.naturalHeight;else if(t instanceof HTMLCanvasElement)l=t.width,h=t.height;else if(t instanceof HTMLVideoElement)l=t.videoWidth,h=t.videoHeight;else{if(!(t instanceof ImageBitmap))throw Error("The type of 'source' is not supported.");l=t.width,h=t.height}let c,d=PO.webGLSupported&&this.useWebGLByDefault;if(e.sx<0||e.sy<0||e.sx+e.sWidth>l||e.sy+e.sHeight>h)throw new Error("Invalid position.");null===(n=PO._onLog)||void 0===n||n.call(PO,"getImageData(), START: "+(c=Date.now()));const u=Math.round(e.sx),p=Math.round(e.sy),g=Math.round(e.sWidth),f=Math.round(e.sHeight),m=Math.round(e.dWidth),v=Math.round(e.dHeight);let y,x=(null==i?void 0:i.pixelFormat)||hM.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(hM.GREY===x&&w.length<m*v||hM.RGBA===x&&w.length<m*v*4))throw new Error("Unexpected size of the 'bufferContainer'.");if(d){null===(s=PO._onLog)||void 0===s||s.call(PO,"getImageData() in WebGL.");let r,a=this._reusedWebGLCvs=this._reusedWebGLCvs||document.createElement("canvas");try{if(w)if(x===hM.GREY){if(y=new Uint8Array(4*m*v),r=this.drawImage(a,t,l,h,{sx:u,sy:p,sWidth:g,sHeight:f,dWidth:m,dHeight:v},{pixelFormat:x,bUseWebGL:!0,bufferContainer:y,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),y=this.transformPixelFormat(y,r.pixelFormat,x),w){if(w.length<y.length)throw new Error("Unexpected size of the 'bufferContainer'.");w.set(y)}}else r=this.drawImage(a,t,l,h,{sx:u,sy:p,sWidth:g,sHeight:f,dWidth:m,dHeight:v},{pixelFormat:x,bUseWebGL:!0,bufferContainer:w,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),y=new Uint8Array(w.buffer,0,4*m*v),y=this.transformPixelFormat(y,r.pixelFormat,x);else x===hM.GREY?((!Zk(this,DL,"f")||Zk(this,DL,"f").length<4*m*v)&&Jk(this,DL,new Uint8Array(4*m*v)),y=new Uint8Array(Zk(this,DL,"f").buffer,0,4*m*v)):y=new Uint8Array(4*m*v),r=this.drawImage(a,t,l,h,{sx:u,sy:p,sWidth:g,sHeight:f,dWidth:m,dHeight:v},{pixelFormat:x,bUseWebGL:!0,bufferContainer:y,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),y=this.transformPixelFormat(y,r.pixelFormat,x)}catch(n){if("WebGLError"===n.name)return this.forceLoseContext(),console.warn("WebGLError: "+(null==n?void 0:n.message)),null===(o=PO._onLog)||void 0===o||o.call(PO,"getImageData() in WebGL failed, try again in context2d."),PO._webGLSupported=!1,this.getImageData(t,e,i);throw n}}else{null===(r=PO._onLog)||void 0===r||r.call(PO,"getImageData() in context2d.");let e=this._reusedCvs=this._reusedCvs||document.createElement("canvas");e.width!=m&&(e.width=m),e.height!=v&&(e.height=v);let n=e.getContext("2d",{willReadFrequently:!0});if(i.isEnableMirroring?(n.save(),n.translate(m,0),n.scale(-1,1),n.drawImage(t,u,p,g,f,0,0,m,v),n.restore()):n.drawImage(t,u,p,g,f,0,0,m,v),y=new Uint8Array(n.getImageData(0,0,m,v).data.buffer),hM.GREY===x){let t=w||new Uint8Array(m*v);for(let e=0;e<y.length;e+=4)t[e/4]=Math.round((y[e]+y[e+1]+y[e+2])/3);y=t}else null==w||w.set(y)}return null===(a=PO._onLog)||void 0===a||a.call(PO,"getImageData() end. Costs: "+(Date.now()-c)),{data:y,pixelFormat:x,width:m,height:v,bUseWebGL:d}}convertDataToCvs(t,e,i,n){if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new TypeError("Invalid 'data'.");if("number"!=typeof e||e<=0)throw new Error("Invalid 'width'.");if("number"!=typeof i||i<=0)throw new Error("Invalid 'height'.");const s=document.createElement("canvas");let o;if(s.width=e,s.height=i,n===hM.GREY){o=new Uint8ClampedArray(4*e*i);for(let e=0;e<o.length;e+=4)o[e]=t[e/4],o[e+1]=t[e/4],o[e+2]=t[e/4],o[e+3]=255}else o=new Uint8ClampedArray(t.buffer);const r=new ImageData(o,e,i);return s.getContext("2d").putImageData(r,0,0),s}forceLoseContext(){var t;if(!this._reusedWebGLCvs)return;const e=this._reusedWebGLCvs.ctxWebGL;e&&!e.isContextLost()&&(null===(t=e.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext()),Jk(this,PL,null),Jk(this,AL,null),Jk(this,IL,null),this._reusedWebGLCvs=null}dispose(){this.forceLoseContext(),Jk(this,RL,!0)}}_L=new WeakMap,PL=new WeakMap,AL=new WeakMap,IL=new WeakMap,DL=new WeakMap,RL=new WeakMap;const AO=(t,e,i,n)=>{if(!i)return t;let s=e+Math.round((t-e)/i)*i;return n&&(s=Math.min(s,n)),s};class IO{static get version(){return"4.3.3-dev-20251029130621"}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"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","ç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"],s=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!s.length)return null;const o=s.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(o)return o.deviceId;const r=s.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return r?r.deviceId:s[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(qk.OS))return IO.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(qk.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(n,s)=>{let o;const r=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",d),t.removeEventListener("play",u),t.removeEventListener("error",p),t.removeEventListener("loadedmetadata",m)};let a=!1;const l=()=>{a=!0,o&&clearTimeout(o),r(),n(t)},h=t=>{o&&clearTimeout(o),r(),s(t)},c=()=>{t.addEventListener("abort",d,{once:!0})},d=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",h(t)},u=()=>{l()},p=()=>{h(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const f=new Promise(t=>{g=t}),m=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",u,{once:!0}),t.addEventListener("error",p,{once:!0}),t.addEventListener("loadedmetadata",m,{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&&(o=setTimeout(()=>{r(),s(new Error("Failed to play video. Timeout."))},i)),await f;try{await t.play(),l()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),l()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),h(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 n;try{n=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==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!Zk(this,GL,"f"))return"closed";if("pending"===Zk(this,GL,"f"))return"opening";if("fulfilled"===Zk(this,GL,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?IO.isStorageAvailable("localStorage")?Jk(this,WL,!0):(Jk(this,WL,!1),console.warn("Local storage is unavailable")):Jk(this,WL,!1)}get ifSaveLastUsedCamera(){return Zk(this,WL,"f")}get isVideoPlaying(){return!(!Zk(this,LL,"f")||Zk(this,LL,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Zk(this,JL,"f"))||void 0===e||e.removeEventListener("click",Zk(this,ZL,"f")),null===(i=Zk(this,JL,"f"))||void 0===i||i.removeEventListener("touchend",Zk(this,ZL,"f")),null===(n=Zk(this,JL,"f"))||void 0===n||n.removeEventListener("touchmove",Zk(this,qL,"f")),Jk(this,JL,t),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(qk.OS)?(t.addEventListener("touchend",Zk(this,ZL,"f")),t.addEventListener("touchmove",Zk(this,qL,"f"))):t.addEventListener("click",Zk(this,ZL,"f")))}get tapFocusEventBoundEl(){return Zk(this,JL,"f")}get disposed(){return Zk(this,rO,"f")}constructor(t){var e,i;ML.add(this),LL.set(this,null),OL.set(this,void 0),this._zoomPreSetting=null,BL.set(this,()=>{"opened"===this.state&&Zk(this,eO,"f").fire("resumed",null,{target:this,async:!1})}),NL.set(this,()=>{Zk(this,eO,"f").fire("paused",null,{target:this,async:!1})}),UL.set(this,void 0),FL.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],VL.set(this,void 0),WL.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,HL.set(this,void 0),jL.set(this,!0),zL.set(this,void 0),GL.set(this,void 0),YL.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},$L.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const s=window.getComputedStyle(Zk(this,LL,"f")).objectFit,o=this.getResolution(),r=Zk(this,LL,"f").getBoundingClientRect(),a=r.left,l=r.top,{width:h,height:c}=Zk(this,LL,"f").getBoundingClientRect();if(h<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const d=h/c,u=o.width/o.height;let p=1;if("contain"===s)u>d?(p=h/o.width,i=(t-a)/p,n=(e-l-(c-h/u)/2)/p):(p=c/o.height,n=(e-l)/p,i=(t-a-(h-c*u)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");u>d?(p=c/o.height,n=(e-l)/p,i=(t-a+(c*u-h)/2)/p):(p=h/o.width,i=(t-a)/p,n=(e-l+(h/u-c)/2)/p)}return{x:i,y:n}},XL.set(this,!1),qL.set(this,()=>{Jk(this,XL,!0)}),ZL.set(this,async t=>{var e;if(Zk(this,XL,"f"))return void Jk(this,XL,!1);if(!Zk(this,$L,"f"))return;if(!this.isVideoPlaying)return;if(!Zk(this,OL,"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,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const s=this.getResolution(),o=2*Math.round(Math.min(s.width,s.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let r;try{r=this.calculateCoordInVideo(i,n)}catch(t){}if(r.x<0||r.x>s.width||r.y<0||r.y>s.height)return;const a={x:r.x+"px",y:r.y+"px"},l=o+"px",h=l;let c;IO._onLog&&(c=Date.now());try{await Zk(this,ML,"m",vO).call(this,a,l,h,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(IO._onLog)throw IO._onLog(t),t}IO._onLog&&IO._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;IO._onLog&&IO._onLog("Back to continuous focus."),null===(t=Zk(this,OL,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),Zk(this,eO,"f").fire("tapfocus",null,{target:this,async:!1})}),JL.set(this,null),KL.set(this,1),QL.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Zk(this,LL,"f"))return;const t=Zk(this,KL,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Zk(this,LL,"f").style.transform="";else{const e=window.getComputedStyle(Zk(this,LL,"f")).objectFit,i=Zk(this,LL,"f").videoWidth,n=Zk(this,LL,"f").videoHeight,{width:s,height:o}=Zk(this,LL,"f").getBoundingClientRect();if(s<=0||o<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const r=s/o,a=i/n;let l=1;"contain"===e?l=r<a?s/(i/t):o/(n/t):"cover"===e&&(l=a>r?o/(i/t):s/(n/t));const h=l*(1-1/t)*(i/2-Zk(this,QL,"f").x),c=l*(1-1/t)*(n/2-Zk(this,QL,"f").y);Zk(this,LL,"f").style.transform=`translate(${h}px, ${c}px) scale(${t})`}},tO.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===hM.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t<e.length;t+=4)e[t]=this.data[t/4],e[t+1]=this.data[t/4],e[t+2]=this.data[t/4],e[t+3]=255}else e=new Uint8ClampedArray(this.data.buffer);const i=new ImageData(e,this.width,this.height);return t.getContext("2d").putImageData(i,0,0),t}),eO.set(this,void 0),iO.set(this,["before:open","opened","before:close","closed","before:camera:change","camera:changed","before:resolution:change","resolution:changed","played","paused","resumed","tapfocus"]),this.detectedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],nO.set(this,new Map),sO.set(this,!1),oO.set(this,async()=>{var t,e;if("visible"===document.visibilityState){if(IO._onLog&&IO._onLog("document visible. video paused: "+(null===(t=Zk(this,LL,"f"))||void 0===t?void 0:t.paused)),function(){const t=navigator.userAgent||navigator.vendor||navigator.opera;return!!/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(t)||("ontouchstart"in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024}())"opened"===this.state&&await Zk(this,ML,"m",pO).call(this);else if("opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){IO._onLog&&IO._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){IO._onLog&&IO._onLog("document visible. 1st resume video failed, try open instead.")}e||await Zk(this,ML,"m",dO).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){IO._onLog&&IO._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){IO._onLog&&IO._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Zk(this,ML,"m",dO).call(this)}}}else"hidden"===document.visibilityState&&(IO._onLog&&IO._onLog("document hidden. video paused: "+(null===(e=Zk(this,LL,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),rO.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(()=>{IO.onWarning&&IO.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),Jk(this,eO,new VM),this.imageDataGetter=new PO,document.addEventListener("visibilitychange",Zk(this,oO,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Zk(this,BL,"f")),t.addEventListener("pause",Zk(this,NL,"f")),Jk(this,LL,t)}getVideoEl(){return Zk(this,LL,"f")}releaseVideoEl(){var t,e;null===(t=Zk(this,LL,"f"))||void 0===t||t.removeEventListener("play",Zk(this,BL,"f")),null===(e=Zk(this,LL,"f"))||void 0===e||e.removeEventListener("pause",Zk(this,NL,"f")),Jk(this,LL,null)}isVideoLoaded(){return!!Zk(this,LL,"f")&&(this.videoSrc?0!==Zk(this,LL,"f").readyState:4===Zk(this,LL,"f").readyState)}async open(){if(Zk(this,zL,"f")&&!Zk(this,jL,"f")){if("pending"===Zk(this,GL,"f"))return Zk(this,zL,"f");if("fulfilled"===Zk(this,GL,"f"))return}Zk(this,eO,"f").fire("before:open",null,{target:this}),await Zk(this,ML,"m",pO).call(this),Zk(this,eO,"f").fire("played",null,{target:this,async:!1}),Zk(this,eO,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Zk(this,eO,"f").fire("before:close",null,{target:this});const t=Zk(this,zL,"f");if(Zk(this,ML,"m",gO).call(this),t&&"pending"===Zk(this,GL,"f")){try{await t}catch(t){}if(!1===Zk(this,jL,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Jk(this,zL,null),Jk(this,GL,null),Zk(this,eO,"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.");Zk(this,LL,"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 Zk(this,LL,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Zk(this,UL,"f").video&&(Zk(this,UL,"f").video={}),delete Zk(this,UL,"f").video.facingMode,Zk(this,UL,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Zk(this,jL,"f"))){Zk(this,eO,"f").fire("before:camera:change",[],{target:this,async:!1}),await Zk(this,ML,"m",uO).call(this);try{this.resetSoftwareScale()}catch(t){}return Zk(this,FL,"f")}}async switchToFrontCamera(t){if("object"!=typeof Zk(this,UL,"f").video&&(Zk(this,UL,"f").video={}),(null==t?void 0:t.resolution)&&(Zk(this,UL,"f").video.width={ideal:t.resolution.width},Zk(this,UL,"f").video.height={ideal:t.resolution.height}),delete Zk(this,UL,"f").video.deviceId,Zk(this,UL,"f").video.facingMode={exact:"user"},Jk(this,VL,null),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Zk(this,jL,"f"))){Zk(this,eO,"f").fire("before:camera:change",[],{target:this,async:!1}),Zk(this,ML,"m",uO).call(this);try{this.resetSoftwareScale()}catch(t){}return Zk(this,FL,"f")}}getCamera(){var t;if(Zk(this,FL,"f"))return Zk(this,FL,"f");{let e=(null===(t=Zk(this,UL,"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 n=[];if(t)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const s=[],o=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&o.push(t);for(let t=0;t<n.length;t++){let e,i=n[t];for(let t of o)if(i.deviceId==t.deviceId){e=t;break}e||(e={deviceId:i.deviceId,label:i.label?i.label:"camera "+t,_checked:!1}),e.deviceId&&s.push(e)}return this._arrCameras=s,IO._onLog&&IO._onLog(JSON.stringify(this._arrCameras)),s}async getCameras(){var t,e;if(!(null===(e=null===(t=null===window||void 0===window?void 0:window.navigator)||void 0===t?void 0:t.mediaDevices)||void 0===e?void 0:e.enumerateDevices))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");const i=(await navigator.mediaDevices.enumerateDevices()).filter(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 Zk(this,UL,"f").video&&(Zk(this,UL,"f").video={}),i?(Zk(this,UL,"f").video.width={exact:t},Zk(this,UL,"f").video.height={exact:e}):(Zk(this,UL,"f").video.width={ideal:t},Zk(this,UL,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Zk(this,jL,"f"))return null;Zk(this,eO,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Zk(this,ML,"m",uO).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Zk(this,LL,"f"))return{width:Zk(this,LL,"f").videoWidth,height:Zk(this,LL,"f").videoHeight};if(Zk(this,OL,"f")){const t=Zk(this,OL,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Zk(this,LL,"f").videoWidth,height:Zk(this,LL,"f").videoHeight};{const t={width:0,height:0};let e=Zk(this,UL,"f").video.width||0,i=Zk(this,UL,"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,n,s,o,r,a,l,h,c,d;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 u="";const p=(t,e)=>{const i=Zk(this,nO,"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){u=null===(d=Zk(this,FL,"f"))||void 0===d?void 0:d.deviceId;let e=Zk(this,nO,"f").get(u);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Zk(this,nO,"f").set(u,e),Jk(this,YL,!0);try{for(let t of this.detectedResolutions){await Zk(this,OL,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Zk(this,ML,"m",lO).call(this);const i=Zk(this,OL,"f").getSettings(),n={width:i.width,height:i.height};p(u,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Zk(this,ML,"m",gO).call(this),Jk(this,YL,!1),t}try{await Zk(this,ML,"m",dO).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Jk(this,YL,!1)}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let s=null;try{s=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!s)return null;const o=s.getVideoTracks();let r=null;try{const t=o[0].getSettings();r={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=s,r={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return o.forEach(t=>{t.stop()}),r};let i=(null===(o=null===(s=null===(n=Zk(this,UL,"f"))||void 0===n?void 0:n.video)||void 0===s?void 0:s.deviceId)||void 0===o?void 0:o.exact)||(null===(l=null===(a=null===(r=Zk(this,UL,"f"))||void 0===r?void 0:r.video)||void 0===a?void 0:a.deviceId)||void 0===l?void 0:l.ideal)||(null===(c=null===(h=Zk(this,UL,"f"))||void 0===h?void 0:h.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let d=Zk(this,nO,"f").get(i);if(d&&!t)return JSON.parse(JSON.stringify(d));d=[],Zk(this,nO,"f").set(i,d);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!p(i,n)&&d.push({width:n.width,height:n.height})}return d}}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'.");Jk(this,UL,JSON.parse(JSON.stringify(t))),Jk(this,VL,null),e&&await Zk(this,ML,"m",uO).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Zk(this,UL,"f")))}resetMediaStreamConstraints(){Jk(this,UL,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null)}getCameraCapabilities(){if(!Zk(this,OL,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Zk(this,OL,"f").getCapabilities?Zk(this,OL,"f").getCapabilities():{}}getCameraSettings(){if(!Zk(this,OL,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Zk(this,OL,"f").getSettings()}async turnOnTorch(){if(!Zk(this,OL,"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 Zk(this,OL,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Zk(this,OL,"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 Zk(this,OL,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Zk(this,OL,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=AO(t,n.min,n.step,n.max)),await Zk(this,OL,"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(!Zk(this,OL,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=AO(t,n.min,n.step,n.max)),await Zk(this,OL,"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(!Zk(this,OL,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(t<n.min?t=n.min:t>n.max&&(t=n.max));const s=this.getResolution();return await Zk(this,OL,"f").applyConstraints({width:{ideal:Math.max(s.width,s.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(!Zk(this,OL,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,s=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const o=t.mode.toLowerCase();if(!n.includes(o))throw Error("Unsupported focus mode.");if("manual"===o){if(!s)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(i<s.min?i=s.min:i>s.max&&(i=s.max),i=AO(i,s.min,s.step,s.max)),this._focusParameters.focusArea=null,await Zk(this,OL,"f").applyConstraints({advanced:[{focusMode:o,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,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=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:n},await Zk(this,ML,"m",vO).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Zk(this,OL,"f").applyConstraints({advanced:[{focusMode:o}]})}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}enableTapToFocus(){Jk(this,$L,!0)}disableTapToFocus(){Jk(this,$L,!1)}isTapToFocusEnabled(){return Zk(this,$L,"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){t.centerPoint?Zk(this,ML,"m",yO).call(this,t.centerPoint):this.resetScaleCenter();try{if(Zk(this,ML,"m",xO).call(this,Zk(this,QL,"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)}}else this._zoomPreSetting=t}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*Zk(this,KL,"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(!Zk(this,OL,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=AO(t,n.min,n.step,n.max)),await Zk(this,OL,"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&&Zk(this,ML,"m",yO).call(this,e),Jk(this,KL,t),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Zk(this,KL,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Jk(this,QL,{x:t.width/2,y:t.height/2})}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(Zk(this,YL,"f"))return null;const e=Date.now();IO._onLog&&IO._onLog("getFrameData() START: "+e);const i=Zk(this,LL,"f").videoWidth,n=Zk(this,LL,"f").videoHeight;let s={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(s=JSON.parse(JSON.stringify(t.position)));let o=hM.RGBA;(null==t?void 0:t.pixelFormat)&&(o=t.pixelFormat);let r=Zk(this,KL,"f");(null==t?void 0:t.scale)&&(r=t.scale);let a=Zk(this,QL,"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,s=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"))s=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");s=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(s))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(s)}let l=null;if((null==t?void 0:t.bufferContainer)&&(l=t.bufferContainer),0==i||0==n)return null;1!==r&&(s.sWidth=Math.round(s.sWidth/r),s.sHeight=Math.round(s.sHeight/r),s.sx=Math.round((1-1/r)*a.x+s.sx/r),s.sy=Math.round((1-1/r)*a.y+s.sy/r));const h=this.imageDataGetter.getImageData(Zk(this,LL,"f"),s,{pixelFormat:o,bufferContainer:l,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!h)return null;const c=Date.now();return IO._onLog&&IO._onLog("getFrameData() END: "+c),{data:h.data,width:h.width,height:h.height,pixelFormat:h.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Zk(this,tO,"f")}}on(t,e){if(!Zk(this,iO,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Zk(this,eO,"f").on(t,e)}off(t,e){Zk(this,eO,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Zk(this,eO,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Zk(this,oO,"f")),Jk(this,rO,!0)}}var DO,RO,kO,MO,LO,OO,BO,NO,UO,FO,VO,WO,HO,jO,zO,GO,YO,$O,XO,qO,ZO,JO,KO,QO,tB,eB,iB,nB,sB,oB,rB,aB,lB,hB,cB,dB;LL=new WeakMap,OL=new WeakMap,BL=new WeakMap,NL=new WeakMap,UL=new WeakMap,FL=new WeakMap,VL=new WeakMap,WL=new WeakMap,HL=new WeakMap,jL=new WeakMap,zL=new WeakMap,GL=new WeakMap,YL=new WeakMap,$L=new WeakMap,XL=new WeakMap,qL=new WeakMap,ZL=new WeakMap,JL=new WeakMap,KL=new WeakMap,QL=new WeakMap,tO=new WeakMap,eO=new WeakMap,iO=new WeakMap,nO=new WeakMap,sO=new WeakMap,oO=new WeakMap,rO=new WeakMap,ML=new WeakSet,aO=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Zk(this,VL,"f"))delete t.video.facingMode,t.video.deviceId={exact:Zk(this,VL,"f")};else if(this.ifSaveLastUsedCamera&&IO.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(qk.OS)?(await this._getCameras(!1),Zk(this,ML,"m",lO).call(this),e=IO.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(qk.OS)||(await this._getCameras(!1),Zk(this,ML,"m",lO).call(this),e=IO.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 n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},lO=function(){if(Zk(this,jL,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},hO=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 n;try{IO._onLog&&IO._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const s=async t=>{for(let s of e){s&&(await new Promise(t=>setTimeout(t,s)),Zk(this,ML,"m",lO).call(this));try{IO._onLog&&IO._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Zk(this,ML,"m",lO).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,IO._onLog&&IO._onLog(t.message||t)}}};if(await s(t),!n&&"object"==typeof t.video&&!n){const e=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let i of e)try{n=await navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:i.deviceId}}});break}catch(t){continue}}if(!n)throw i;return n}catch(t){throw null==n||n.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}},cO=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),Jk(this,OL,null)},dO=async function(){Jk(this,jL,!1);const t=Jk(this,HL,Symbol());if(Zk(this,zL,"f")&&"pending"===Zk(this,GL,"f")){try{await Zk(this,zL,"f")}catch(t){}Zk(this,ML,"m",lO).call(this)}if(t!==Zk(this,HL,"f"))return;const e=Jk(this,zL,(async()=>{Jk(this,GL,"pending");try{if(this.videoSrc){if(!Zk(this,LL,"f"))throw new Error("'videoEl' should be set.");await IO.playVideo(Zk(this,LL,"f"),this.videoSrc,this.cameraOpenTimeout),Zk(this,ML,"m",lO).call(this)}else{let t=await Zk(this,ML,"m",aO).call(this);Zk(this,ML,"m",cO).call(this);let e=await Zk(this,ML,"m",hO).call(this,t);await this._getCameras(!1),Zk(this,ML,"m",lO).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;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,n=e;break}}return n},n=Zk(this,UL,"f");if("object"==typeof n.video){let s=n.video.facingMode;if(s instanceof Array&&s.length&&(s=s[0]),"object"==typeof s&&(s=s.exact||s.ideal),!(Zk(this,VL,"f")||this.ifSaveLastUsedCamera&&IO.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),o=IO.findBestCamera(this._arrCameras,s,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});o&&o!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:o},e=await Zk(this,ML,"m",hO).call(this,t),Zk(this,ML,"m",lO).call(this))}}const s=i();(null==s?void 0:s.deviceId)&&(Jk(this,VL,s&&s.deviceId),this.ifSaveLastUsedCamera&&IO.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Zk(this,VL,"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))))),Zk(this,LL,"f")&&(await IO.playVideo(Zk(this,LL,"f"),e,this.cameraOpenTimeout),Zk(this,ML,"m",lO).call(this)),this._mediaStream=e;const o=e.getVideoTracks();(null==o?void 0:o.length)&&Jk(this,OL,o[0]),Jk(this,FL,s)}}catch(t){throw Zk(this,ML,"m",gO).call(this),Jk(this,GL,null),t}Jk(this,GL,"fulfilled")})());return e},uO=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Zk(this,FL,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Zk(this,ML,"m",dO).call(this);const n=this.getResolution();e&&e!==Zk(this,FL,"f").deviceId&&Zk(this,eO,"f").fire("camera:changed",[Zk(this,FL,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Zk(this,eO,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Zk(this,eO,"f").fire("played",null,{target:this,async:!1})},pO=async function(){let t=0;for(;IO._tryToReopenTime>=t++;){try{await Zk(this,ML,"m",dO).call(this)}catch(t){await new Promise(t=>setTimeout(t,300));continue}break}},gO=function(){Zk(this,ML,"m",cO).call(this),Jk(this,FL,null),Zk(this,LL,"f")&&(Zk(this,LL,"f").srcObject=null,this.videoSrc&&(Zk(this,LL,"f").pause(),Zk(this,LL,"f").currentTime=0)),Jk(this,jL,!0);try{this.resetSoftwareScale()}catch(t){}},fO=async function t(e,i){const n=t=>{if(!Zk(this,OL,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Zk(this,OL,"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 s;i=AO(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Zk(this,OL,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),s=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,s)}),n(e);let o=e.focusL-e.focusW/2,r=e.focusT-e.focusH/2,a=e.focusW,l=e.focusH;const h=this.getResolution();o=Math.round(o),r=Math.round(r),a=Math.round(a),l=Math.round(l),a>h.width&&(a=h.width),l>h.height&&(l=h.height),o<0?o=0:o+a>h.width&&(o=h.width-a),r<0?r=0:r+l>h.height&&(r=h.height-l);const c=4*h.width*h.height*this._focusParameters.defaultTempBufferContainerLenRatio,d=4*a*l;let u=this._focusParameters.tempBufferContainer;if(u){const t=u.length;c>t&&c>=d?u=new Uint8Array(c):d>t&&d>=c&&(u=new Uint8Array(d))}else u=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,d));if(!this.imageDataGetter.getImageData(Zk(this,LL,"f"),{sx:o,sy:r,sWidth:a,sHeight:l,dWidth:a,dHeight:l},{pixelFormat:hM.RGBA,bufferContainer:u}))return Zk(this,ML,"m",t).call(this,e,i);const p=u;let g=0;for(let t=0,e=d-8;t<e;++t){let e=p[t]-p[t+8];++t;let i=p[t]-p[t+8];++t;let n=p[t]-p[t+8];++t,g+=e*e+i*i+n*n}return-g},mO=async function t(e,i,n,s,o,r,a){let l;if(i=AO(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=AO(s,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r?r=AO(r,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max):(r=AO(Math.sqrt((i||this._focusParameters.fds.step)*(s||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Zk(this,ML,"m",fO).call(this,e,r)),a<=n&&a<=o?l=3:n<o&&n<a?l=1:o<n&&o<a&&(l=2),(s-i)/2<=this._focusParameters.fds.step)return 3===l||(1===l?await Zk(this,OL,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}):2===l&&await Zk(this,OL,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:s}]})),!0;if(1===l)return await Zk(this,ML,"m",t).call(this,e,i,n,r,a);if(2===l)return await Zk(this,ML,"m",t).call(this,e,r,a,s,o);if(3!==l)return n=await Zk(this,ML,"m",fO).call(this,e,i),o=await Zk(this,ML,"m",fO).call(this,e,s),await Zk(this,ML,"m",t).call(this,e,i,n,s,o);let h=AO(Math.sqrt((i||this._focusParameters.fds.step)*(r||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),c=AO(Math.sqrt((s||this._focusParameters.fds.step)*(r||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max);if(Math.abs(1/this._focusParameters.oldDistance-1/h)<=Math.abs(1/this._focusParameters.oldDistance-1/c)){let l=await Zk(this,ML,"m",fO).call(this,e,h);if(l<a)return await Zk(this,ML,"m",t).call(this,e,i,n,r,a,h,l);if(l==a)return await Zk(this,ML,"m",t).call(this,e,h,l,r,a);let d=await Zk(this,ML,"m",fO).call(this,e,c);if(l>a&&a<d)return await Zk(this,ML,"m",t).call(this,e,h,l,c,d,r,a);if(a==d)return await Zk(this,ML,"m",t).call(this,e,r,a,c,d);if(a>d)return await Zk(this,ML,"m",t).call(this,e,r,a,s,o,c,d)}else{let l=await Zk(this,ML,"m",fO).call(this,e,c);if(a>l)return await Zk(this,ML,"m",t).call(this,e,r,a,s,o,c,l);if(a==l)return await Zk(this,ML,"m",t).call(this,e,r,a,c,l);let d=await Zk(this,ML,"m",fO).call(this,e,h);if(d>a&&a<l)return await Zk(this,ML,"m",t).call(this,e,h,d,c,l,r,a);if(d==a)return await Zk(this,ML,"m",t).call(this,e,h,d,r,a);if(d<a)return await Zk(this,ML,"m",t).call(this,e,i,n,r,a,h,d)}return!1},vO=async function(t,e,i,n,s){var o;if(1==this._focusParameters.isDoingFocus)return!1;if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'centerPoint'.");if(!e||"string"!=typeof e)throw new Error("Invalid 'width'.");if(!i||"string"!=typeof i)throw new Error("Invalid 'height'.");const r=this.getResolution();let a=0,l=0;if(t.x.endsWith("px"))a=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid 'centerPoint'.");a=parseFloat(t.x)/100*r.width}if(t.y.endsWith("px"))l=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid 'centerPoint'.");l=parseFloat(t.y)/100*r.height}if(isNaN(a)||isNaN(l)||a<0||a>r.width||l<0||l>r.height)throw new Error("Invalid 'centerPoint'.");let h=0;if(e.endsWith("px"))h=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");h=parseFloat(e)/100*r.width}if(isNaN(h)||h<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*r.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Zk(this,KL,"f")){const t=Zk(this,KL,"f"),e=Zk(this,QL,"f");h/=t,c/=t,a=(1-1/t)*e.x+a/t,l=(1-1/t)*e.y+l/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(o=this.getCameraCapabilities())||void 0===o?void 0:o.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 d={focusL:a,focusT:l,focusW:h,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},u=async(t,e,i)=>{try{(null==e||e<this._focusParameters.fds.min)&&(e=this._focusParameters.fds.min),(null==i||i>this._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=AO(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=AO(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=AO(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=await Zk(this,ML,"m",fO).call(this,t,o),a=await Zk(this,ML,"m",fO).call(this,t,s),l=await Zk(this,ML,"m",fO).call(this,t,n);if(a>l&&l<r){const e=await Zk(this,ML,"m",mO).call(this,t,s,a,o,r,n,l);return this._focusParameters.isDoingFocus=0,e}if(a<l&&a<r){let i=await Zk(this,ML,"m",fO).call(this,t,e);const o=await Zk(this,ML,"m",mO).call(this,t,e,i,n,l,s,a);return this._focusParameters.isDoingFocus=0,o}if(l>r&&a>r){let e=await Zk(this,ML,"m",fO).call(this,t,i);const s=await Zk(this,ML,"m",mO).call(this,t,n,l,i,e,o,r);return this._focusParameters.isDoingFocus=0,s}if(a==l&&l<r){const e=await Zk(this,ML,"m",mO).call(this,t,s,a,n,l);return this._focusParameters.isDoingFocus=0,e}if(l==r&&a>l){const e=await Zk(this,ML,"m",mO).call(this,t,n,l,o,r);return this._focusParameters.isDoingFocus=0,e}return u(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return u(d,n,s)},yO=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,n=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"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Jk(this,QL,{x:i,y:n})},xO=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},IO.browserInfo=qk,IO._tryToReopenTime=4,IO.onWarning=null===(kL=null===window||void 0===window?void 0:window.console)||void 0===kL?void 0:kL.warn;class uB{constructor(t){DO.add(this),RO.set(this,void 0),kO.set(this,0),MO.set(this,void 0),LO.set(this,0),OO.set(this,!1),Jk(this,RO,t)}startCharging(){Zk(this,OO,"f")||(uB._onLog&&uB._onLog("start charging."),Zk(this,DO,"m",NO).call(this),Jk(this,OO,!0))}stopCharging(){Zk(this,MO,"f")&&clearTimeout(Zk(this,MO,"f")),Zk(this,OO,"f")&&(uB._onLog&&uB._onLog("stop charging."),Jk(this,kO,Date.now()-Zk(this,LO,"f")),Jk(this,OO,!1))}}RO=new WeakMap,kO=new WeakMap,MO=new WeakMap,LO=new WeakMap,OO=new WeakMap,DO=new WeakSet,BO=function(){wR.cfd(1),uB._onLog&&uB._onLog("charge 1.")},NO=function t(){0==Zk(this,kO,"f")&&Zk(this,DO,"m",BO).call(this),Jk(this,LO,Date.now()),Zk(this,MO,"f")&&clearTimeout(Zk(this,MO,"f")),Jk(this,MO,setTimeout(()=>{Jk(this,kO,0),Zk(this,DO,"m",t).call(this)},Zk(this,RO,"f")-Zk(this,kO,"f")))};class pB{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Zk(this,UO,"f",WO)<100)){if(Jk(this,UO,e,0,WO),Zk(this,UO,"f",FO).size&&(t=Zk(this,UO,"f",FO).values().next().value,this.beepSoundSource==t.src?(Zk(this,UO,"f",FO).delete(t),t.play()):t=null),!t)if(Zk(this,UO,"f",VO).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{Zk(this,UO,"f",VO).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Zk(this,UO,"f",VO).delete(t),Zk(this,UO,"f",FO).add(t)})}else Zk(this,UO,"f",HO)||(Jk(this,UO,!0,0,HO),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Zk(this,UO,"f",VO).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(pB.vibrateDuration)}}}UO=pB,FO={value:new Set},VO={value:new Set},WO={value:0},HO={value:!1},pB.allowBeep=!0,pB.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",pB.allowVibrate=!0,pB.vibrateDuration=300;const gB=new Map([[hM.GREY,iD.IPF_GRAYSCALED],[hM.RGBA,iD.IPF_ABGR_8888]]),fB="function"==typeof BigInt?t=>BigInt(t):t=>t,mB=(fB("0x00"),fB("0xFFFFFFFFFFFFFFFF"),fB("0xFE3BFFFF"),fB("0x003007FF")),vB=(fB("0x0003F800"),fB("0x1"),fB("0x2"),fB("0x4"),fB("0x8"),fB("0x10"),fB("0x20"),fB("0x40"),fB("0x80"),fB("0x100"),fB("0x200"),fB("0x400"),fB("0x800"),fB("0x1000"),fB("0x2000"),fB("0x4000"),fB("0x8000"),fB("0x10000"),fB("0x20000"),fB("0x00040000"),fB("0x01000000"),fB("0x02000000"),fB("0x04000000")),yB=fB("0x08000000");fB("0x10000000"),fB("0x20000000"),fB("0x40000000"),fB("0x00080000"),fB("0x80000000"),fB("0x100000"),fB("0x200000"),fB("0x400000"),fB("0x800000"),fB("0x1000000000"),fB("0x3F0000000000000"),fB("0x100000000"),fB("0x10000000000000"),fB("0x20000000000000"),fB("0x40000000000000"),fB("0x80000000000000"),fB("0x100000000000000"),fB("0x200000000000000"),fB("0x200000000"),fB("0x400000000"),fB("0x800000000"),fB("0xC00000000"),fB("0x2000000000"),fB("0x4000000000");class xB extends FD{static set _onLog(t){Jk(xB,zO,t,0,GO),IO._onLog=t,uB._onLog=t}static get _onLog(){return Zk(xB,zO,"f",GO)}static async detectEnvironment(){return await(async()=>({wasm:Kk,worker:Qk,getUserMedia:tM,camera:await eM(),browser:qk.browser,version:qk.version,OS:qk.OS}))()}static async testCameraAccess(){const t=await IO.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 _O))throw new TypeError("Invalid view.");if(!xB._isRTU&&(null===(e=mR.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=mR.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await wR.loadWasm(),await mR.license.dynamsoft()}const n=new xB(t);return xB.onWarning&&(location&&"file:"===location.protocol?setTimeout(()=>{xB.onWarning&&xB.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(()=>{xB.onWarning&&xB.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})},0)),n}get isEnableMirroring(){return this._isEnableMirroring}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.");Jk(this,qO,t)}get singleFrameMode(){return Zk(this,qO,"f")}get _isFetchingStarted(){return Zk(this,eB,"f")}get disposed(){return Zk(this,rB,"f")}constructor(t){if(super(),jO.add(this),YO.set(this,"closed"),$O.set(this,void 0),XO.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,qO.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()},ZO.set(this,(t,e,i,n)=>{const s=Date.now(),o={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},r=Math.max(o.dWidth,o.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;o.dWidth>o.dHeight?(o.dWidth=this.canvasSizeLimit,o.dHeight=Math.round(o.dHeight*t)):(o.dWidth=Math.round(o.dWidth*t),o.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,o,{pixelFormat:this.getPixelFormat()===iD.IPF_GRAYSCALED?hM.GREY:hM.RGBA});let l=null;if(a){const t=Date.now();let r;r=a.pixelFormat===hM.GREY?a.width:4*a.width;let h=!0;0===o.sx&&0===o.sy&&o.sWidth===e&&o.sHeight===i&&(h=!1),l={bytes:a.data,width:a.width,height:a.height,stride:r,format:gB.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:qD.ITT_FILE_IMAGE,isCropped:h,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-s,timeStamp:t},toCanvas:Zk(this,JO,"f"),isDCEFrame:!0}}return l}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():NM.convert(Zk(this,QO,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Zk(this,ZO,"f").call(this,t,t.width,t.height,e);Zk(this,$O,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},JO.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===iD.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t<e.length;t+=4)e[t]=this.bytes[t/4],e[t+1]=this.bytes[t/4],e[t+2]=this.bytes[t/4],e[t+3]=255}else e=new Uint8ClampedArray(this.bytes.buffer);return t.getContext("2d").putImageData(new ImageData(e,this.width,this.height),0,0),t}),KO.set(this,void 0),QO.set(this,{left:0,right:100,top:0,bottom:100,isMeasuredInPercentage:!0}),tB.set(this,iD.IPF_ABGR_8888),eB.set(this,!1),this._imageId=-1,iB.set(this,void 0),this.fetchInterval=0,nB.set(this,{enhancedFocus:!1,autoZoom:!1,tapToFocus:!1}),sB.set(this,{minValue:1,maxValue:999,autoFocusFrameArray:[],autoFocusFrameLimit:[5,3],autoZoomDetectionArea:.5,autoZoomTargetBorder:.9,autoZoomIdealArea:[0,.05],autoZoomInFrameArray:[],autoZoomInFrameLimit:[5,3],autoZoomInMaxTimes:5,autoZoomInMinStep:Math.pow(10,.2),autoZoomInIdealModuleSize:6,autoZoomOutFrameCount:0,autoZoomOutFrameLimit:3,autoZoomOutStepRate:1/3,autoZoomOutStepRate_2:.05,autoZoomOutMinStep:2,frameArrayInIdealZoom:[],frameLimitInIdealZoom:[5,3]}),oB.set(this,void 0),rB.set(this,!1),this.isCameraEnhancer=!0,this._taskid4AutoTorch=null,this._delay4AutoTorch=250,this.grayThreshold4AutoTorch=20,this.maxDarkCount4AutoTroch=3,t&&!(t instanceof _O))throw new TypeError("Invalid view.");Jk(this,$O,new VM),this.cameraManager=new IO,this._imageDataGetter=this.cameraManager.imageDataGetter,this.cameraManager.updateVideoElWhenSoftwareScaled=()=>{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(qk.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",()=>{Zk(this,oB,"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",()=>{Zk(this,oB,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{Zk(this,nB,"f").tapToFocus&&Zk(this,oB,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,s,o;const r=t.intermediateResultUnits;if(Zk(this,jO,"m",aB).call(this)||!this.isOpen()||this.isPaused()||r[0]&&!r[0].originalImageTag)return;xB._onLog&&(xB._onLog("intermediateResultUnits:"),xB._onLog(r));let a=!1,l=!1;for(let t of r){if(t.unitType===QD.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===QD.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(l=!0)}if(xB._onLog&&(xB._onLog("hasLocalizedBarcodes:"),xB._onLog(l)),Zk(this,nB,"f").autoZoom||Zk(this,nB,"f").enhancedFocus)if(a)Zk(this,sB,"f").autoZoomInFrameArray.length=0,Zk(this,sB,"f").autoZoomOutFrameCount=0,Zk(this,sB,"f").frameArrayInIdealZoom.length=0,Zk(this,sB,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Zk(this,nB,"f").autoZoom&&Zk(this,oB,"f").startCharging()},a=async t=>{await this.setFocus(t),Zk(this,nB,"f").enhancedFocus&&Zk(this,oB,"f").startCharging()};if(l){const l=r[0].originalImageTag,h=(null===(i=l.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=l.cropRegion)||void 0===n?void 0:n.top)||0,d=(null===(s=l.cropRegion)||void 0===s?void 0:s.right)?l.cropRegion.right-h:l.originalWidth,u=(null===(o=l.cropRegion)||void 0===o?void 0:o.bottom)?l.cropRegion.bottom-c:l.originalHeight,p=l.currentWidth,g=l.currentHeight;let f;{let t,e,i,n,s;{const t=this.video.videoWidth*(1-Zk(this,sB,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Zk(this,sB,"f").autoZoomDetectionArea)/2,i=e,n=t,o=this.video.videoHeight*(1-Zk(this,sB,"f").autoZoomDetectionArea)/2,r=o,a=this.video.videoHeight*(1+Zk(this,sB,"f").autoZoomDetectionArea)/2;s=[{x:t,y:o},{x:e,y:r},{x:i,y:a},{x:n,y:a}]}xB._onLog&&(xB._onLog("detectionArea:"),xB._onLog(s));const o=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const s=t.length;if(s<=2)return!1;for(let o=0;o<s;o++){const r=t[o],a=t[(o+1)%s];if(WM(r,a,{x:e,y:i}))return!0;HM(r.y-i)>0!=HM(a.y-i)>0&&HM(e-(i-r.y)*(r.x-a.x)/(r.y-a.y)-r.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(jM([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||jM([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||jM([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||jM([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))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of r)if(e.unitType===QD.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{_O._transformCoordinates(t,h,c,d,u,p,g)}),t(s,e)&&o.push(i)}if(xB._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=wO.createDrawingStyle({strokeStyle:"red"}));for(let i of r)if(i.unitType===QD.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,s=new AM({points:i},e);t.addDrawingItems([s])}}}if(xB._onLog&&(xB._onLog("intersectedResults:"),xB._onLog(o)),!o.length)return;let a;if(o.length){let t=o.filter(t=>t.possibleFormats==vB||t.possibleFormats==yB);if(t.length||(t=o.filter(t=>t.possibleFormats==mB),t.length||(t=o)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-p/2)*(i-p/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n<t.length;n++){const s=e(t[n]);(t[n].confidence>1.1*a.confidence||t[n].confidence>.9*a.confidence&&s<i)&&(a=t[n],i=s)}}}if(xB._onLog&&(xB._onLog("highPriorityResult:"),xB._onLog(a)),a){const s=a.location.points;t=Math.min(s[0].x,s[1].x,s[2].x,s[3].x),e=Math.max(s[0].x,s[1].x,s[2].x,s[3].x),i=Math.min(s[0].y,s[1].y,s[2].y,s[3].y),n=Math.max(s[0].y,s[1].y,s[2].y,s[3].y),f={points:[{x:t,y:i},{x:e,y:i},{x:e,y:n},{x:t,y:n}],result:a}}}if(xB._onLog&&(xB._onLog("boundingRect:"),xB._onLog(f)),!f)return;if(xB._debug&&this.cameraView&&(null==f?void 0:f.points)){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99)),e=this.__styleId1||(this.__styleId1=wO.createDrawingStyle({strokeStyle:"blue"})),i=new AM({points:f.points},e);t.addDrawingItems([i])}if(Zk(this,sB,"f").autoZoomOutFrameCount=0,Zk(this,nB,"f").autoZoom){const i=Zk(this,sB,"f").autoZoomIdealArea[1];let n=(1-Zk(this,sB,"f").autoZoomTargetBorder)/2;const s=f.points[0].x/d,o=(d-f.points[2].x)/d,r=f.points[0].y/u,l=(u-f.points[2].y)/u;if(s>i&&o>i&&r>i&&l>i&&f.result.moduleSize<Zk(this,sB,"f").autoZoomInIdealModuleSize){if(Zk(this,sB,"f").autoZoomInFrameArray.push(!0),Zk(this,sB,"f").autoZoomInFrameArray.splice(0,Zk(this,sB,"f").autoZoomInFrameArray.length-Zk(this,sB,"f").autoZoomInFrameLimit[0]),Zk(this,sB,"f").frameArrayInIdealZoom.length=0,Zk(this,nB,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{}),Zk(this,sB,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=Zk(this,sB,"f").autoZoomInFrameLimit[1]){Zk(this,sB,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-r),(.5-n)/(.5-l)].filter(t=>t>0),a=Math.min(...i,Zk(this,sB,"f").autoZoomInIdealModuleSize/f.result.moduleSize),h=this.getZoomSettings().factor;let c=Math.max(Math.pow(h*a,1/Zk(this,sB,"f").autoZoomInMaxTimes),Zk(this,sB,"f").autoZoomInMinStep);c=Math.min(c,a);let d=h*c;d=Math.max(Zk(this,sB,"f").minValue,d),d=Math.min(Zk(this,sB,"f").maxValue,d);try{await e({factor:d})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Zk(this,sB,"f").autoZoomInFrameArray.length=0,Zk(this,sB,"f").frameArrayInIdealZoom.push(!0),Zk(this,sB,"f").frameArrayInIdealZoom.splice(0,Zk(this,sB,"f").frameArrayInIdealZoom.length-Zk(this,sB,"f").frameLimitInIdealZoom[0]),Zk(this,sB,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=Zk(this,sB,"f").frameLimitInIdealZoom[1]&&(Zk(this,sB,"f").frameArrayInIdealZoom.length=0,Zk(this,nB,"f").enhancedFocus)){const e=f.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(!Zk(this,nB,"f").autoZoom&&Zk(this,nB,"f").enhancedFocus&&(Zk(this,sB,"f").autoFocusFrameArray.push(!0),Zk(this,sB,"f").autoFocusFrameArray.splice(0,Zk(this,sB,"f").autoFocusFrameArray.length-Zk(this,sB,"f").autoFocusFrameLimit[0]),Zk(this,sB,"f").autoFocusFrameArray.filter(t=>!0===t).length>=Zk(this,sB,"f").autoFocusFrameLimit[1])){Zk(this,sB,"f").autoFocusFrameArray.length=0;try{const t=f.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(Zk(this,nB,"f").autoZoom){if(Zk(this,sB,"f").autoZoomInFrameArray.push(!1),Zk(this,sB,"f").autoZoomInFrameArray.splice(0,Zk(this,sB,"f").autoZoomInFrameArray.length-Zk(this,sB,"f").autoZoomInFrameLimit[0]),Zk(this,sB,"f").autoZoomOutFrameCount++,Zk(this,sB,"f").frameArrayInIdealZoom.push(!1),Zk(this,sB,"f").frameArrayInIdealZoom.splice(0,Zk(this,sB,"f").frameArrayInIdealZoom.length-Zk(this,sB,"f").frameLimitInIdealZoom[0]),Zk(this,sB,"f").autoZoomOutFrameCount>=Zk(this,sB,"f").autoZoomOutFrameLimit){Zk(this,sB,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Zk(this,sB,"f").autoZoomOutStepRate,Zk(this,sB,"f").autoZoomOutMinStep);n=Math.max(Zk(this,sB,"f").minValue,n),n=Math.min(Zk(this,sB,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Zk(this,nB,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!Zk(this,nB,"f").autoZoom&&Zk(this,nB,"f").enhancedFocus&&(Zk(this,sB,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},Jk(this,oB,new uB(1e4)),this.getColourChannelUsageType()===eD.CCUT_AUTO&&this.setColourChannelUsageType(eD.CCUT_Y_CHANNEL_ONLY),this.setPixelFormat(iD.IPF_GRAYSCALED)}setCameraView(t){if(!(t instanceof _O))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),Zk(this,jO,"m",aB).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;Zk(this,jO,"m",aB).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 Zk(this,jO,"m",aB).call(this)?Zk(this,YO,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,Zk(this,jO,"m",aB).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(Zk(this,jO,"m",aB).call(this));else{try{await this.cameraManager.open(),Jk(this,XO,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}))}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let s,o=e.getUIElement();if(o=o.shadowRoot||o,s=o.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=o.elTorchAuto=o.querySelector(".dce-mn-torch-auto"),e=o.elTorchOn=o.querySelector(".dce-mn-torch-on"),i=o.elTorchOff=o.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let r=o.elBeepOn=o.querySelector(".dce-mn-beep-on"),a=o.elBeepOff=o.querySelector(".dce-mn-beep-off");r&&(r.style.display=pB.allowBeep?"":"none"),a&&(a.style.display=pB.allowBeep?"none":"");let l=o.elVibrateOn=o.querySelector(".dce-mn-vibrate-on"),h=o.elVibrateOff=o.querySelector(".dce-mn-vibrate-off");l&&(l.style.display=pB.allowVibrate?"":"none"),h&&(h.style.display=pB.allowVibrate?"none":""),o.elResolutionBox=o.querySelector(".dce-mn-resolution-box");let c,d=o.elZoom=o.querySelector(".dce-mn-zoom");d&&(d.style.display="none",c=o.elZoomSpan=d.querySelector("span"));let u=o.elToast=o.querySelector(".dce-mn-toast"),p=o.elCameraClose=o.querySelector(".dce-mn-camera-close"),g=o.elTakePhoto=o.querySelector(".dce-mn-take-photo"),f=o.elCameraSwitch=o.querySelector(".dce-mn-camera-switch"),m=o.elCameraAndResolutionSettings=o.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const v=o.dceMnFs={},y=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",y);const x=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",x);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const C=()=>{pB.allowBeep=!pB.allowBeep,r&&(r.style.display=pB.allowBeep?"":"none"),a&&(a.style.display=pB.allowBeep?"none":"")};for(let t of[a,r])null==t||t.addEventListener("pointerdown",C);const b=()=>{pB.allowVibrate=!pB.allowVibrate,l&&(l.style.display=pB.allowVibrate?"":"none"),h&&(h.style.display=pB.allowVibrate?"none":"")};for(let t of[h,l])null==t||t.addEventListener("pointerdown",b);const S=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")),n=parseInt(e.getAttribute("data-height")),s=await this.setResolution({width:i,height:n});{let e=Math.max(s.width,s.height),i=Math.min(s.width,s.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&_(`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"))};o.addEventListener("click",S);let T=null;v.funcInfoZoomChange=(t,e=3e3)=>{d&&c&&(c.textContent=t.toFixed(1),d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};let E=null,_=v.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=E&&(clearTimeout(E),E=null),E=setTimeout(()=>{u.style.display="none",E=null},e))};const P=()=>{this.close()};null==p||p.addEventListener("click",P);const A=()=>{};null==g||g.addEventListener("pointerdown",A);const I=()=>{var t,e;let i,n=this.getVideoSettings(),s=n.video.facingMode,o=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),r=null==o?void 0:o.indexOf("front");-1===r&&(r=null==o?void 0:o.indexOf("前"));let a=null==o?void 0:o.indexOf("back");if(-1===a&&(a=null==o?void 0:o.indexOf("后")),"number"==typeof r&&-1!==r?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==s?void 0:s.ideal)||(null==s?void 0:s.exact)||s)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==f||f.addEventListener("pointerdown",I);let D=-1/0,R=1;const k=t=>{let e=Date.now();e-D>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),D=e};s.addEventListener("wheel",k);const M=new Map;let L=!1;const O=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],n=t.touches[1],s=M.get(i.identifier),o=M.get(n.identifier);if(!s||!o)break;let r=Math.pow(Math.pow(s.x-o.x,2)+Math.pow(s.y-o.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),l=Date.now();if(L||l-D<100)return;l-D>1e3&&(R=this.getZoomSettings().factor),R*=a/r,R>20&&(R=20),R<1&&(R=1);let h=!1;"safari"==(null===(e=null==qk?void 0:qk.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/r>1&&R<2?(R=2,h=!0):a/r<1&&R<2&&(R=1,h=!0)),L=!0,h&&_("zooming..."),await this.setZoom({factor:R}),h&&(u.textContent=""),L=!1,D=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};o.addEventListener("touchstart",O),o.addEventListener("touchmove",O),o.addEventListener("touchend",O),o.addEventListener("touchcancel",O),v.unbind=()=>{null==t||t.removeEventListener("pointerdown",y),null==e||e.removeEventListener("pointerdown",x),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,r])null==t||t.removeEventListener("pointerdown",C);for(let t of[h,l])null==t||t.removeEventListener("pointerdown",b);o.removeEventListener("click",S),null==p||p.removeEventListener("click",P),null==g||g.removeEventListener("pointerdown",A),null==f||f.removeEventListener("pointerdown",I),s.removeEventListener("wheel",k),o.removeEventListener("touchstart",O),o.removeEventListener("touchmove",O),o.removeEventListener("touchend",O),o.removeEventListener("touchcancel",O),delete o.dceMnFs,s.style.display="none"},s.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const r=this.getResolution();i.width=r.width,i.height=r.height,i.deviceId=this.getSelectedCamera().deviceId}return Jk(this,YO,"open"),e&&(e._innerComponent.style.display="",Zk(this,jO,"m",aB).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),Zk(this,$O,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}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(),Zk(this,jO,"m",aB).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())}Jk(this,YO,"closed"),Zk(this,oB,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Zk(this,jO,"m",aB).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Zk(this,$O,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Zk(this,jO,"m",aB).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Zk(this,jO,"m",aB).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Zk(this,jO,"m",aB).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),s=this.cameraView;if(s&&!s.disposed&&(s._stopLoading(),s._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),s._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=s.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.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})),this.toggleMirroring(this._isEnableMirroring),Zk(this,QO,"f")&&this.setScanRegion(Zk(this,QO,"f")),{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())?Zk(this,$O,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Zk(this,$O,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,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(Zk(this,jO,"m",aB).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(Zk(this,jO,"m",aB).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){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t<this._delay4AutoTorch))return;clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null}this._delay4AutoTorch=t;let n=!1,s=0,o=0;const r=async()=>{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++o>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let r;try{r=this.fetchImage()}catch(t){}if(!r||!r.width||!r.height)return;let a=0;if(iD.IPF_GRAYSCALED===r.format){for(let t=0;t<r.bytes.length;++t)a+=r.bytes[t];a/=r.bytes.length}else{if(iD.IPF_ABGR_8888!==r.format)return;for(let t=0;t<r.bytes.length;t+=4)a+=r.bytes[t],a+=r.bytes[t+1],a+=r.bytes[t+2];a/=r.bytes.length/4*3}if(a<this.grayThreshold4AutoTorch){if(++s>=this.maxDarkCount4AutoTroch){null===(t=xB._onLog)||void 0===t||t.call(xB,`darkCount ${s}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else s=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(Zk(this,jO,"m",aB).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(Zk(this,jO,"m",aB).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,n;if(Zk(this,jO,"m",aB).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===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.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(Zk(this,jO,"m",aB).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(Zk(this,jO,"m",aB).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(Zk(this,jO,"m",aB).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){Zk(this,sB,"f").minValue=t.min,Zk(this,sB,"f").maxValue=t.max}getAutoZoomRange(){return{min:Zk(this,sB,"f").minValue,max:Zk(this,sB,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=mR.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!==wR.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&lM.EF_ENHANCED_FOCUS&&(Zk(this,nB,"f").enhancedFocus=!0),t&lM.EF_AUTO_ZOOM&&(Zk(this,nB,"f").autoZoom=!0),t&lM.EF_TAP_TO_FOCUS&&(Zk(this,nB,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&lM.EF_ENHANCED_FOCUS&&(Zk(this,nB,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&lM.EF_AUTO_ZOOM&&(Zk(this,nB,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&lM.EF_TAP_TO_FOCUS&&(Zk(this,nB,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Zk(this,jO,"m",hB).call(this)&&Zk(this,jO,"m",lB).call(this)||Zk(this,oB,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!uD(t)&&!vD(t))throw TypeError("Invalid 'region'.");Jk(this,QO,t?JSON.parse(JSON.stringify(t)):null),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(Zk(this,QO,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Jk(this,KO,t)}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Zk(this,jO,"m",aB).call(this))}startFetching(){if(Zk(this,jO,"m",aB).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Zk(this,eB,"f")||(Jk(this,eB,!0),Zk(this,jO,"m",cB).call(this))}stopFetching(){Zk(this,eB,"f")&&(xB._onLog&&xB._onLog("DCE: stop fetching loop: "+Date.now()),Zk(this,iB,"f")&&clearTimeout(Zk(this,iB,"f")),Jk(this,eB,!1))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(Zk(this,jO,"m",aB).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i,n;if(i=NM.convert(Zk(this,QO,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");if(i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y),Zk(this,QO,"f")&&!t)n={sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};else{const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});n={sx:t.x,sy:t.y,sWidth:t.width,sHeight:t.height,dWidth:t.width,dHeight:t.height}}const s=Math.max(n.dWidth,n.dHeight);if(this.canvasSizeLimit&&s>this.canvasSizeLimit){const t=this.canvasSizeLimit/s;n.dWidth>n.dHeight?(n.dWidth=this.canvasSizeLimit,n.dHeight=Math.round(n.dHeight*t)):(n.dWidth=Math.round(n.dWidth*t),n.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.getFrameData({position:n,pixelFormat:this.getPixelFormat()===iD.IPF_GRAYSCALED?hM.GREY:hM.RGBA,isEnableMirroring:this._isEnableMirroring});if(!o)return null;let r;r=o.pixelFormat===hM.GREY?o.width:4*o.width;let a=!0;return 0===n.sx&&0===n.sy&&n.sWidth===e.width&&n.sHeight===e.height&&(a=!1),{bytes:o.data,width:o.width,height:o.height,stride:r,format:gB.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:qD.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:n.sx,top:n.sy,right:n.sx+n.sWidth,bottom:n.sy+n.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:o.width,currentHeight:o.height,timeSpent:o.timeSpent,timeStamp:o.timeStamp},toCanvas:Zk(this,JO,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Zk(this,eB,"f")&&(Zk(this,iB,"f")&&clearTimeout(Zk(this,iB,"f")),Jk(this,iB,setTimeout(()=>{this.disposed||Zk(this,jO,"m",cB).call(this)},t)))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Jk(this,tB,t)}getPixelFormat(){return Zk(this,tB,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Zk(this,jO,"m",aB).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],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),s=new Image;s.src=i,s.onload=()=>{URL.revokeObjectURL(s.src),t(s)},s.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i})(i),s=n instanceof HTMLImageElement?n.naturalWidth:n.width,o=n instanceof HTMLImageElement?n.naturalHeight:n.height;let r=NM.convert(Zk(this,QO,"f"),s,o,this.cameraView);r||(r={x:0,y:0,width:s,height:o});const a=Zk(this,ZO,"f").call(this,n,s,o,r);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=this.convertToContainCoordinates(t),i=Zk(this,jO,"m",dB).call(this,e);return{x:i.pageX,y:i.pageY}}convertToClientCoordinates(t){const e=this.convertToContainCoordinates(t),i=Zk(this,jO,"m",dB).call(this,e);return{x:i.clientX,y:i.clientY}}convertToScanRegionCoordinates(t){if(!Zk(this,QO,"f"))return JSON.parse(JSON.stringify(t));const e=this.convertToContainCoordinates(t);if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});Jk(this,XO,t||Zk(this,XO,"f"))}let i,n,s=Zk(this,QO,"f").left||Zk(this,QO,"f").x||0,o=Zk(this,QO,"f").top||Zk(this,QO,"f").y||0;if(!Zk(this,QO,"f").isMeasuredInPercentage)return{x:e.x-(s+Zk(this,XO,"f").x),y:e.y-(o+Zk(this,XO,"f").y)};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(!Zk(this,jO,"m",aB).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Zk(this,jO,"m",aB).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Zk(this,jO,"m",aB).call(this)){const t=this.cameraView._innerComponent.getElement("content");i=t.width,n=t.height}else i=Zk(this,XO,"f").width,n=Zk(this,XO,"f").height;return{x:e.x-(Math.round(s*i/100)+Zk(this,XO,"f").x),y:e.y-(Math.round(o*n/100)+Zk(this,XO,"f").y)}}convertToContainCoordinates(t){if("contain"===this.cameraView.getVideoFit())return t;const e=this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),i=JSON.parse(JSON.stringify(t));return uD(Zk(this,QO,"f"))?Zk(this,QO,"f").isMeasuredInPercentage?(i.x=e.width*(Zk(this,QO,"f").left/100)+e.x+t.x,i.y=e.height*(Zk(this,QO,"f").top/100)+e.y+t.y):(i.x=Zk(this,QO,"f").left+e.x+t.x,i.y=Zk(this,QO,"f").top+e.y+t.y):Zk(this,QO,"f").isMeasuredInPercentage?(i.x=e.width*(Zk(this,QO,"f").x/100)+e.x+t.x,i.y=e.height*(Zk(this,QO,"f").y/100)+e.y+t.y):(i.x=Zk(this,QO,"f").x+e.x+t.x,i.y=Zk(this,QO,"f").y+e.y+t.y),i}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Jk(this,rB,!0)}}var wB,CB,bB,SB,TB,EB,_B,PB;zO=xB,YO=new WeakMap,$O=new WeakMap,XO=new WeakMap,qO=new WeakMap,ZO=new WeakMap,JO=new WeakMap,KO=new WeakMap,QO=new WeakMap,tB=new WeakMap,eB=new WeakMap,iB=new WeakMap,nB=new WeakMap,sB=new WeakMap,oB=new WeakMap,rB=new WeakMap,jO=new WeakSet,aB=function(){return"disabled"!==this.singleFrameMode},lB=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},hB=function(){for(let t in Zk(this,nB,"f"))if(1==Zk(this,nB,"f")[t])return!0;return!1},cB=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Zk(this,eB,"f"))return Zk(this,iB,"f")&&clearTimeout(Zk(this,iB,"f")),void Jk(this,iB,setTimeout(()=>{this.disposed||Zk(this,jO,"m",t).call(this)},this.fetchInterval));const e=()=>{var t;let e;xB._onLog&&xB._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=Zk(this,KO,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=Zk(this,KO,"f"))||void 0===t||t.onErrorReceived(YD.EC_IMAGE_READ_FAILED,i)},0);console.warn(e)}e?(this.addImageToBuffer(e),xB._onLog&&xB._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Zk(this,$O,"f").fire("frameAddedToBuffer",null,{async:!1})):xB._onLog&&xB._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case tD.BOPM_BLOCK:break;case tD.BOPM_UPDATE:e()}else e();Zk(this,iB,"f")&&clearTimeout(Zk(this,iB,"f")),Jk(this,iB,setTimeout(()=>{this.disposed||Zk(this,jO,"m",t).call(this)},this.fetchInterval))},dB=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(!Zk(this,jO,"m",aB).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Zk(this,jO,"m",aB).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,s=i+window.scrollX,o=n+window.scrollY,{width:r,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(r<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let l,h,c;if(Zk(this,jO,"m",aB).call(this)){const t=this.cameraView._innerComponent.getElement("content");l=t.width,h=t.height,c="contain"}else{const t=this.getVideoEl();l=t.videoWidth,h=t.videoHeight,c=this.cameraView.getVideoFit()}const d=r/a,u=l/h;let p,g,f,m,v=1;if("contain"===c)d<u?(v=r/l,p=i+t.x*v,g=n+t.y*v+(a-h*v)/2,f=s+t.x*v,m=o+t.y*v+(a-h*v)/2):(v=a/h,p=i+t.x*v+(r-l*v)/2,g=n+t.y*v,f=s+t.x*v+(r-l*v)/2,m=o+t.y*v);else if("cover"===c)if(d<u){v=a/h;let e=t.x*v-(l*v-r)/2;e=Math.max(e,0),e=Math.min(e,r),p=i+e,g=n+t.y*v,f=s+e,m=o+t.y*v}else{v=r/l;let e=t.y*v-(h*v-a)/2;e=Math.max(e,0),e=Math.min(e,a),p=i+t.x*v,g=n+e,f=s+t.x*v,m=o+e}return{clientX:p,clientY:g,pageX:f,pageY:m}},xB._debug=!1,xB._isRTU=!1,GO={value:void 0},xB.browserInfo=qk;class AB{get magnifierCanvas(){return Zk(this,wB,"f")}constructor(){wB.set(this,void 0),Jk(this,wB,document.createElement("canvas")),Zk(this,wB,"f").style.borderRadius="50%"}update(t,e,i,n){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");const s=this.magnifierCanvas;s.width=s.height=t;let o=e.x-i/2,r=e.y-i/2,a=i,l=i,h=s.width,c=s.height,d=s.getContext("2d");for(let t of n)d.drawImage(t.image,o,r,a,l,0,0,h,c);s.style.width=s.width+"px",s.style.height=s.height+"px"}show(){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");this.magnifierCanvas.style.display="block"}hide(){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");this.magnifierCanvas.style.display="none"}}wB=new WeakMap;class IB extends TO{static async createInstance(t){const e=new IB;return await e.setUIElement(t||Zk(e,CB,"m",PB).call(e)),e}get disposed(){return Zk(this,_B,"f")}constructor(){super(),CB.add(this),this.containerClassName="dce-image-container",bB.set(this,void 0),SB.set(this,void 0),this.isUseMagnifier=!0,TB.set(this,t=>{var e;if(!this.isUseMagnifier)return;if(Zk(this,SB,"f")||Jk(this,SB,new AB),!Zk(this,SB,"f").magnifierCanvas)return;document.body.contains(Zk(this,SB,"f").magnifierCanvas)||(Zk(this,SB,"f").magnifierCanvas.style.position="fixed",Zk(this,SB,"f").magnifierCanvas.style.boxSizing="content-box",Zk(this,SB,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Zk(this,SB,"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 Zk(this,EB,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const s=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),o=1.5*s,r=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Zk(this,SB,"f").update(o,t.pointer,s,r);{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*o&&i<1.5*o?(Zk(this,SB,"f").magnifierCanvas.style.left="auto",Zk(this,SB,"f").magnifierCanvas.style.top="0",Zk(this,SB,"f").magnifierCanvas.style.right="0"):(Zk(this,SB,"f").magnifierCanvas.style.left="0",Zk(this,SB,"f").magnifierCanvas.style.top="0",Zk(this,SB,"f").magnifierCanvas.style.right="auto")}Zk(this,SB,"f").show()}),EB.set(this,()=>{Zk(this,SB,"f")&&Zk(this,SB,"f").hide()}),_B.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await zM(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=document.createElement("dce-component"),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 n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const s=n.getContext("2d");s.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),s.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&s.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(dD(t)){Jk(this,bB,t);const{width:e,height:i,bytes:n,format:s}=Object.assign({},t);let o;if(s===iD.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t<o.length;t+=4)o[t]=n[t/4],o[t+1]=n[t/4],o[t+2]=n[t/4],o[t+3]=255}else o=new Uint8ClampedArray(n.buffer);this.setImage(o,e,i)}else if(t instanceof HTMLCanvasElement)Jk(this,bB,t),this.setImage(t,t.width,t.height);else{if(!(t instanceof HTMLImageElement))throw new TypeError("Invalid img.");Jk(this,bB,t),this.setImage(t,t.naturalWidth,t.naturalHeight)}let e;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(e)}getOriginalImage(){return Zk(this,bB,"f")}getContentDimensions(){let t,e,i;if(this._innerComponent){const n=this._innerComponent.getElement("content");t=null==n?void 0:n.width,e=null==n?void 0:n.height,i="contain"}if(!t||!e)throw new Error("Invalid content dimensions.");return{width:t,height:e,objectFit:i}}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let s;try{s=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==s?void 0:s.width)||300),i||(i=(null==s?void 0:s.height)||150),n||(n=(null==s?void 0:s.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const s=this._layerBaseCvs,o=this._drawingLayerManager.createDrawingLayer(s,t);this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",s.parentElement),t!=CO.TIP_LAYER_ID&&o.setMode("editor");const r=this._drawingLayerManager._getFabricCanvas();return r&&(r.on("object:scaling",Zk(this,TB,"f")),r.on("object:rotating",Zk(this,TB,"f")),r.on("object:skewing",Zk(this,TB,"f")),r.on("mouse:up",Zk(this,EB,"f"))),o}dispose(){this._unbindUI(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}bB=new WeakMap,SB=new WeakMap,TB=new WeakMap,EB=new WeakMap,_B=new WeakMap,CB=new WeakSet,PB=function(){const t=document.createElement("div");return t.className=this.containerClassName,t.style.width="100%",t.style.height="100%",t};const DB="undefined"==typeof self,RB="function"==typeof importScripts,kB=(()=>{if(!RB){if(!DB&&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"./"}})(),MB=t=>{if(null==t&&(t="./"),DB||RB);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};wR.engineResourcePaths.dbr={version:"11.2.20-dev-20251029130556",path:kB,isInternal:!0},vR.dbr={js:!1,wasm:!0,deps:[sR.MN_DYNAMSOFT_LICENSE,sR.MN_DYNAMSOFT_IMAGE_PROCESSING]},mR.dbr={};const LB="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,LB)<0&&(wR.engineResourcePaths.std={version:LB,path:MB(kB+`../../dynamsoft-capture-vision-std@${LB}/dist/`),isInternal:!0});const OB="3.0.10";var BB,NB,UB,FB;function VB(t,e,i,n){if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}(!wR.engineResourcePaths.dip||"string"!=typeof wR.engineResourcePaths.dip&&xD(wR.engineResourcePaths.dip.version,OB)<0)&&(wR.engineResourcePaths.dip={version:OB,path:MB(kB+`../../dynamsoft-image-processing@${OB}/dist/`),isInternal:!0}),BigInt(0),BigInt("0xFFFFFFFEFFFFFFFF"),BigInt(4265345023),BigInt(3147775),BigInt(260096),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(131072),BigInt(262144),BigInt(16777216),BigInt(33554432),BigInt(67108864),BigInt(134217728),BigInt(268435456),BigInt(536870912),BigInt(1073741824),BigInt(524288),BigInt(2147483648),BigInt(1048576),BigInt(2097152),BigInt(4194304),BigInt(8388608),BigInt(68719476736),BigInt(0x3f0000000000000),BigInt(4294967296),BigInt(4503599627370496),BigInt(9007199254740992),BigInt(0x40000000000000),BigInt(0x80000000000000),BigInt(72057594037927940),BigInt(0x200000000000000),BigInt(8589934592),BigInt(17179869184),BigInt(34359738368),BigInt(51539607552),BigInt(137438953472),BigInt(274877906944),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"}(BB||(BB={})),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"}(NB||(NB={})),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_NEURAL_NETWORK=512]="LM_NEURAL_NETWORK",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(UB||(UB={})),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_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(FB||(FB={})),"function"==typeof SuppressedError&&SuppressedError;const WB="undefined"==typeof self,HB=(()=>{if(!WB&&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"./"})(),jB=t=>{if(null==t&&(t="./"),WB);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var zB,GB;wR.engineResourcePaths.dlr={version:"4.2.10-dev-20251029130602",path:HB,isInternal:!0},vR.dlr={js:!0,wasm:!0,deps:[sR.MN_DYNAMSOFT_LICENSE,sR.MN_DYNAMSOFT_IMAGE_PROCESSING]};const YB="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,YB)<0&&(wR.engineResourcePaths.std={version:YB,path:jB(HB+`../../dynamsoft-capture-vision-std@${YB}/dist/`),isInternal:!0});const $B="3.0.10";(!wR.engineResourcePaths.dip||"string"!=typeof wR.engineResourcePaths.dip&&xD(wR.engineResourcePaths.dip.version,$B)<0)&&(wR.engineResourcePaths.dip={version:$B,path:jB(HB+`../../dynamsoft-image-processing@${$B}/dist/`),isInternal:!0});let XB=class t{static getVersion(){const t=fR.dlr&&fR.dlr.wasm;return`4.2.10-dev-20251029130602(Worker: ${fR.dlr&&fR.dlr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadConfusableCharsData(e,i){return VB(t,zB,"m",GB).call(t,"confusable",e,i)}static async loadOverlappingCharsData(e,i){return VB(t,zB,"m",GB).call(t,"overlapping",e,i)}};var qB,ZB,JB;function KB(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let s of n.ChildFields)t=KB(s,e,i);if(void 0!==t)return t}}}function QB(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(ZB[i.MappingStatus]):ZB.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=QB(n,e);if(void 0!==t)return t}}}function tN(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(JB[i.ValidationStatus]):JB.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=tN(n,e);if(void 0!==t)return t}}}zB=XB,GB=async function(t,e,i){return await wR.loadWasm(),await new Promise((n,s)=>{let o=dR();uR[o]=async t=>{if(t.success){const e=JSON.parse(t.result);if(0!==e.errorCode){let t=new Error(e.errorString);return t.errorCode=e.errorCode,s(t)}return n(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}},i&&!i.endsWith("/")&&(i+="/");const r=wD(wR.engineResourcePaths);hR.postMessage({type:"dlr_loadData",id:o,body:{type:t,dataName:e,dataPath:i||r.dcvData+"char-resources/"}})})},mR.dlr={loadConfusableCharsData:XB.loadConfusableCharsData,loadOverlappingCharsData:XB.loadOverlappingCharsData},function(t){t[t.RTLS_LOCALIZED=0]="RTLS_LOCALIZED",t[t.RTLS_RECOGNITION_FAILED=1]="RTLS_RECOGNITION_FAILED",t[t.RTLS_RECOGNITION_SUCCEEDED=2]="RTLS_RECOGNITION_SUCCEEDED"}(qB||(qB={})),uR[-1]=async t=>{XB.onDataLoadProgressChanged&&XB.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})},function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(ZB||(ZB={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(JB||(JB={})),(async()=>{})().constructor;const eN="undefined"==typeof self,iN="function"==typeof importScripts,nN=(()=>{if(!iN){if(!eN&&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"./"}})();wR.engineResourcePaths.dcp={version:"3.2.20-dev-20251029130614",path:nN,isInternal:!0},vR.dcp={js:!0,wasm:!0,deps:[sR.MN_DYNAMSOFT_LICENSE]},mR.dcp={handleParsedResultItem:function(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:KB(e,t,"map"),t.getFieldRawValue=t=>KB(e,t,"raw"),t.getFieldMappingStatus=t=>QB(e,t),t.getFieldValidationStatus=t=>tN(e,t),delete t.fullCodeString}};const sN="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,sN)<0&&(wR.engineResourcePaths.std={version:sN,path:(t=>{if(null==t&&(t="./"),eN||iN);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(nN+`../../dynamsoft-capture-vision-std@${sN}/dist/`),isInternal:!0}),uR[-4]=async t=>{oN.onSpecLoadProgressChanged&&oN.onSpecLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let oN=class{static getVersion(){const t=fR.dcp&&fR.dcp.wasm;return`3.2.20-dev-20251029130614(Worker: ${fR.dcp&&fR.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await wR.loadWasm(),await new Promise((i,n)=>{let s=dR();uR[s]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const o=t instanceof Array?t:[t],r=wD(wR.engineResourcePaths);hR.postMessage({type:"dcp_appendResourceBuffer",id:s,body:{specificationPath:e||`${"DBR"===wR._bundleEnv?r.dbrBundle:r.dcvData}parser-resources/`,specificationNames:o}})})}};const rN="undefined"==typeof self,aN="function"==typeof importScripts,lN=(()=>{if(!aN){if(!rN&&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"./"}})(),hN=t=>{if(null==t&&(t="./"),rN||aN);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};wR.engineResourcePaths.ddn={version:"4.2.20-dev-20251029130608",path:lN,isInternal:!0},vR.ddn={js:!0,wasm:!0,deps:[sR.MN_DYNAMSOFT_LICENSE,sR.MN_DYNAMSOFT_IMAGE_PROCESSING]},mR.ddn={handleDeskewedAndEnhancedImageResultItem:function(t){let e=t,i=TD(e.imageData);e.toCanvas=()=>CD(i),e.toImage=t=>bD(t,i),e.toBlob=t=>SD(t,i)}};const cN="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,cN)<0&&(wR.engineResourcePaths.std={version:cN,path:hN(lN+`../../dynamsoft-capture-vision-std@${cN}/dist/`),isInternal:!0});const dN="3.0.10";(!wR.engineResourcePaths.dip||"string"!=typeof wR.engineResourcePaths.dip&&xD(wR.engineResourcePaths.dip.version,dN)<0)&&(wR.engineResourcePaths.dip={version:dN,path:hN(lN+`../../dynamsoft-image-processing@${dN}/dist/`),isInternal:!0});var uN;!function(t){t[t.ICM_COLOUR=0]="ICM_COLOUR",t[t.ICM_GRAYSCALE=1]="ICM_GRAYSCALE",t[t.ICM_BINARY=2]="ICM_BINARY"}(uN||(uN={}));const pN="undefined"==typeof self,gN="function"==typeof importScripts,fN=(()=>{if(!gN){if(!pN&&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"./"}})(),mN=t=>{if(null==t&&(t="./"),pN||gN);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};wR.engineResourcePaths.utility={version:"2.2.20-dev-20251029130550",path:fN,isInternal:!0},vR.utility={js:!0,wasm:!0};const vN="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,vN)<0&&(wR.engineResourcePaths.std={version:vN,path:mN(fN+`../../dynamsoft-capture-vision-std@${vN}/dist/`),isInternal:!0});const yN="3.0.10";(!wR.engineResourcePaths.dip||"string"!=typeof wR.engineResourcePaths.dip&&xD(wR.engineResourcePaths.dip.version,yN)<0)&&(wR.engineResourcePaths.dip={version:yN,path:mN(fN+`../../dynamsoft-image-processing@${yN}/dist/`),isInternal:!0});function xN(t,e,i,n){if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}"function"==typeof SuppressedError&&SuppressedError;const wN="undefined"==typeof self,CN="function"==typeof importScripts,bN=(()=>{if(!CN){if(!wN&&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"./"}})(),SN=t=>{if(null==t&&(t="./"),wN||CN);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};wR.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:bN,isInternal:!0},vR.dbr={js:!1,wasm:!0,deps:[sR.MN_DYNAMSOFT_LICENSE,sR.MN_DYNAMSOFT_IMAGE_PROCESSING]},mR.dbr={};const TN="2.0.0";"string"!=typeof wR.engineResourcePaths.std&&xD(wR.engineResourcePaths.std.version,TN)<0&&(wR.engineResourcePaths.std={version:TN,path:SN(bN+`../../dynamsoft-capture-vision-std@${TN}/dist/`),isInternal:!0});const EN="3.0.10";(!wR.engineResourcePaths.dip||"string"!=typeof wR.engineResourcePaths.dip&&xD(wR.engineResourcePaths.dip.version,EN)<0)&&(wR.engineResourcePaths.dip={version:EN,path:SN(bN+`../../dynamsoft-image-processing@${EN}/dist/`),isInternal:!0});const _N={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),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var PN,AN,IN,DN,RN;(RN=PN||(PN={}))[RN.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",RN[RN.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",RN[RN.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",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"}(AN||(AN={})),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",t[t.LM_END=4294967295]="LM_END"}(IN||(IN={})),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_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(DN||(DN={}));const kN=async t=>{let e;await new Promise((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)});const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:iD.IPF_ABGR_8888}};function MN(t,e){let i=!0;for(let r=0;r<t.length;r++){const a=(r+1)%t.length;if(n=t[r],o=e,((s=t[a]).x-n.x)*(o.y-n.y)-(s.y-n.y)*(o.x-n.x)<0){i=!1;break}}var n,s,o;return i}function LN(t,e){return Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2)}function ON(t,e){const[i,n]=t,s=i.x,o=i.y,r=n.x,a=n.y,l=e.x,h=e.y,c=(r-s)**2+(a-o)**2;if(0===c)return Math.sqrt((l-s)**2+(h-o)**2);const d=((l-s)*(r-s)+(h-o)*(a-o))/c;if(d<0)return Math.sqrt((l-s)**2+(h-o)**2);if(d>1)return Math.sqrt((l-r)**2+(h-a)**2);{const t=s+d*(r-s),e=o+d*(a-o);return Math.sqrt((l-t)**2+(h-e)**2)}}function BN(t){const e=[];for(let i=0;i<t.length;i++){const n=t[i],s=t[(i+1)%t.length];e.push([n,s])}return e}function NN(t){const[e,i]=t;return{x:(e.x+i.x)/2,y:(e.y+i.y)/2}}function UN(t,e,i,n){const s=e.x-t.x,o=e.y-t.y,r=n.x-i.x,a=n.y-i.y,l=(-o*(t.x-i.x)+s*(t.y-i.y))/(-r*o+s*a),h=(r*(t.y-i.y)-a*(t.x-i.x))/(-r*o+s*a);return l>=0&&l<=1&&h>=0&&h<=1?{x:t.x+h*s,y:t.y+h*o}:null}function FN(t){let e=0;for(let i=0;i<t.length;i++){const n=(i+1)%t.length;e+=t[i].x*t[n].y,e-=t[n].x*t[i].y}return Math.abs(e/2)}function VN(t,e,i){let n=e.x-t.x,s=e.y-t.y,o=i.x-t.x;return n*(i.y-t.y)-s*o>0}function WN(t,e){for(let i=0;i<4;i++)if(!VN(t.points[i],t.points[(i+1)%4],e))return!1;return!0}function HN(t,e,i,n){const s=t.points,o=e.points;let r=8*i;r=Math.max(r,5);const a=BN(s)[3],l=BN(s)[1],h=BN(o)[3],c=BN(o)[1];let d,u=0;if(d=Math.max(Math.abs(ON(a,e.points[0])),Math.abs(ON(a,e.points[3]))),d>u&&(u=d),d=Math.max(Math.abs(ON(l,e.points[1])),Math.abs(ON(l,e.points[2]))),d>u&&(u=d),d=Math.max(Math.abs(ON(h,t.points[0])),Math.abs(ON(h,t.points[3]))),d>u&&(u=d),d=Math.max(Math.abs(ON(c,t.points[1])),Math.abs(ON(c,t.points[2]))),d>u&&(u=d),u>r)return!1;const p=NN(BN(s)[0]),g=NN(BN(s)[2]),f=NN(BN(o)[0]),m=NN(BN(o)[2]),v=LN(p,m),y=LN(f,g),x=v>y,w=Math.min(v,y),C=LN(p,g),b=LN(f,m);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,b),!!(w<S||MN(s,x?f:m)||MN(o,x?g:p))&&(x?(n.points[0]=t.points[0],n.points[1]=t.points[1],n.points[2]=e.points[2],n.points[3]=e.points[3]):(n.points[0]=e.points[0],n.points[1]=e.points[1],n.points[2]=t.points[2],n.points[3]=t.points[3]),n.area=FN(n.points),!0)}class jN{constructor(t,e,i,n){this.overlapCount=t,this.verificationCount=e,this.crossVerificationFrame=5,this.location=n.location,this.locationArea=n.location.area,this.locationAngle=n.angle,this.format=n.format,this.text=n.text,this.isOneD=i,this.item=n,this.locationThreshold=5*n.moduleSize,this.strictLimit=Math.max(this.locationThreshold,1),this.strictLimit=Math.min(this.strictLimit,15)}getCenterPoint(t){const e={x:0,y:0};return t.forEach(({x:t,y:i})=>{e.x+=t,e.y+=i}),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let s=new Array(4).fill(0),o=new Array(4).fill(0),r=0,a=0;for(let t=0;t<4;++t)s[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,r+=s[t],o[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=o[t];r/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(s[t]-r)>this.strictLimit||Math.abs(r)>.8)return!1;if(Math.abs(o[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=r,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(WN(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(WN(this.location,e))return!0}else{for(let e=0;e<4;e++)if(WN(t,this.location.points[e]))return!0;if(WN(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 n=[this.location.points[0],this.location.points[3]],s=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],o=0===t||3===t?n:s;if(Math.abs(ON(o,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],s=this.location.points[i];if(!(Math.abs(s.x+e.x-n.x)<this.locationThreshold))return!1;if(Math.abs(s.y+e.y-n.y)>=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let s=0;s<4;s++){const o=UN(t[n],t[(n+1)%4],e[s],e[(s+1)%4]);o&&i.push(o)}return t.forEach(t=>{MN(e,t)&&i.push(t)}),e.forEach(e=>{MN(t,e)&&i.push(e)}),FN(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],n.points)>this.locationArea*t}return!0}}var zN,GN,YN,$N,XN;const qN={barcode:2,text_line:4,detected_quad:8,deskewed_image:16,enhanced_image:64},ZN=t=>Object.values(qN).includes(t)||qN.hasOwnProperty(t),JN=(t,e)=>"string"==typeof t?e[qN[t]]:e[t],KN=(t,e,i)=>{"string"==typeof t?e[qN[t]]=i:e[t]=i},QN=(t,e,i)=>{const n=[{type:zD.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:zD.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],s=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=s.length-1;t>=0;t--)s[t].type!==i||s[t].verified||s.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const s=e[t.resultName][n];e[t.resultName][n]=s.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=s.length-1;t>=0;t--)s[t].type===i&&s[t].duplicate&&s.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const s=e[t.resultName][n];e[t.resultName][n]=s.filter(t=>t.type===i&&!t.duplicate)})}};class tU{constructor(){this.verificationEnabled={[zD.CRIT_BARCODE]:!1,[zD.CRIT_TEXT_LINE]:!0,[zD.CRIT_DETECTED_QUAD]:!0,[zD.CRIT_DESKEWED_IMAGE]:!1,[zD.CRIT_ENHANCED_IMAGE]:!1},this.duplicateFilterEnabled={[zD.CRIT_BARCODE]:!1,[zD.CRIT_TEXT_LINE]:!1,[zD.CRIT_DETECTED_QUAD]:!1,[zD.CRIT_DESKEWED_IMAGE]:!1,[zD.CRIT_ENHANCED_IMAGE]:!1},this.duplicateForgetTime={[zD.CRIT_BARCODE]:3e3,[zD.CRIT_TEXT_LINE]:3e3,[zD.CRIT_DETECTED_QUAD]:3e3,[zD.CRIT_DESKEWED_IMAGE]:3e3,[zD.CRIT_ENHANCED_IMAGE]:3e3},zN.set(this,new Map),GN.set(this,new Map),YN.set(this,new Map),$N.set(this,new Map),XN.set(this,new Map),this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,this.latestOverlappingEnabled={[zD.CRIT_BARCODE]:!1,[zD.CRIT_TEXT_LINE]:!1,[zD.CRIT_DETECTED_QUAD]:!1,[zD.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[zD.CRIT_BARCODE]:this.crossVerificationFrames,[zD.CRIT_TEXT_LINE]:this.crossVerificationFrames,[zD.CRIT_DETECTED_QUAD]:this.crossVerificationFrames,[zD.CRIT_DESKEWED_IMAGE]:this.crossVerificationFrames},Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),QN(this,t,zD.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{QN(this,t,zD.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){xN(this,zN,"f").forEach((t,e)=>{KN(e,this.verificationEnabled,t)}),xN(this,GN,"f").forEach((t,e)=>{KN(e,this.duplicateFilterEnabled,t)}),xN(this,YN,"f").forEach((t,e)=>{KN(e,this.duplicateForgetTime,t)}),xN(this,$N,"f").forEach((t,e)=>{KN(e,this.latestOverlappingEnabled,t)}),xN(this,XN,"f").forEach((t,e)=>{KN(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){ZN(t)&&xN(this,zN,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!ZN(t)&&JN(t,this.verificationEnabled)}enableResultDeduplication(t,e){ZN(t)&&(e&&this.enableLatestOverlapping(t,!1),xN(this,GN,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!ZN(t)&&JN(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){ZN(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),xN(this,YN,"f").set(t,e))}getDuplicateForgetTime(t){return ZN(t)?JN(t,this.duplicateForgetTime):-1}getFilteredResultItemTypes(){let t=0;const e=[zD.CRIT_BARCODE,zD.CRIT_TEXT_LINE,zD.CRIT_DETECTED_QUAD,zD.CRIT_DESKEWED_IMAGE,zD.CRIT_ENHANCED_IMAGE];for(let i=0;i<e.length;i++)(this.verificationEnabled[e[i]]||this.duplicateFilterEnabled[e[i]])&&(t|=e[i]);return t}enableLatestOverlapping(t,e){ZN(t)&&(e&&this.enableResultDeduplication(t,!1),xN(this,$N,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!ZN(t)&&JN(t,this.latestOverlappingEnabled)}setMaxOverlappingFrames(t,e){ZN(t)&&xN(this,XN,"f").set(t,e)}getMaxOverlappingFrames(t){return ZN(t)?JN(t,this.maxOverlappingFrames):-1}latestOverlappingFilter(t){var e,i,n;const s=this.isResultCrossVerificationEnabled(zD.CRIT_BARCODE),o=this.isLatestOverlappingEnabled(zD.CRIT_BARCODE);if(o){const r=this.crossVerificationFrames,a=60,l=o?this.getMaxOverlappingFrames(zD.CRIT_BARCODE):this.crossVerificationFrames,h=t.items.length,c=null===(n=null===(i=null===(e=null==t?void 0:t.intermediateResult)||void 0===e?void 0:e[0])||void 0===i?void 0:i.intermediateResultUnits)||void 0===n?void 0:n[1].localizedBarcodes,d=c?c.length:0;let u=[];const p=[],g={x:0,y:0};let f=new Array(h).fill(-1),m=0;const v=t.items.map(t=>{if(1!==t.type){const e=(BigInt(t.format)&BigInt(_N.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(_N.BF_GS1_DATABAR))!=BigInt(0);return new jN(l,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(h).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e<h;){const i={x:0,y:0},n=new Array(h).fill(-1);let s=!1;for(;e<h;e++){if(!v[e])continue;const o=v[e].item;for(let r=0;r<this.overlapSet.length;r++){if(t[e][r]<1)continue;const a=this.overlapSet[r],l=a.item;if(o.format===l.format&&o.text===l.text){if(s=a.isProbablySameLocationWithOffset(v[e],i),s){n[e]=r,t[e][r]=0;break}}else t[e][r]=0}if(s)break}if(s){for(let s=0;s<h;s++){if(s===e||!v[s])continue;const o=v[s].item;for(let e=0;e<this.overlapSet.length;e++){if(t[s][e]<1)continue;if(n.includes(e))continue;const r=this.overlapSet[e],a=r.item;if(o.format===a.format&&o.text===a.text){if(r.isMatchedLocationWithOffset(v[s],i)){n[s]=e,t[s][e]=0;break}}else t[s][e]=0}}const s=n.filter(t=>-1!==t).length;s>m&&(m=s,f=n,g.x=i.x,g.y=i.y)}}if(0===m){for(let e=0;e<h;e++){const i=v[e].item;for(let n=0;n<this.overlapSet.length;n++){if(t[e][n]<1)continue;if(f.includes(n))continue;const s=this.overlapSet[n],o=s.item;if(i.format===o.format&&i.text===o.text){if(s.isMatchedLocationWithOffset(v[e])){f[e]=n,t[e][n]=0;break}}else t[e][n]=0}}m+=f.filter(t=>-1!=t).length}let i=this.overlapSet.length<=3?m>=1:m>=2;if(!i&&o&&d>0){let t=0;for(let e=0;e<this.overlapSet.length;e++){const i=this.overlapSet[e];for(let e=0;e<d;e++)if(i.isOverlappedLocationWithOffset(c[e],g)){t++;break}}i=this.overlapSet.length<=3?t>=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(_N.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(_N.BF_GS1_DATABAR))!=BigInt(0),o=t.confidence<a,r=new jN(l,n?1:2,n,i);s&&n&&o&&p.push(e),this.overlapSet.push(r)}});else{let e=!0;o?(Math.abs(g.x)>5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i<t.items.length;i++){const t=f[i];if(t<0&&v[i]){const t=v[i].item;let n={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}]};for(let i=0;i<4;i++)n.points[i].x=e?t.location.points[i].x-g.x:t.location.points[i].x,n.points[i].y=e?t.location.points[i].y-g.y:t.location.points[i].y;for(let s=0;s<this.overlapSet.length;s++){if(f.includes(s))continue;const o=this.overlapSet[s].item.text,r=this.overlapSet[s].item.format;if(t.format===r&&t.text===o){if(this.overlapSet[s].isOverlappedLocationWithOffset(t,g,!1)){const e=Object.assign({},t),n=(BigInt(e.format)&BigInt(_N.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(_N.BF_GS1_DATABAR))!=BigInt(0),o=n?1:2;this.overlapSet[s]=new jN(l,o,n,e),f[i]=s;break}if(v[i].isOneD){let o={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}]};for(let t=0;t<4;t++)o.points[t].x=e?this.overlapSet[s].location.points[t].x:this.overlapSet[s].location.points[t].x+g.x,o.points[t].y=e?this.overlapSet[s].location.points[t].y:this.overlapSet[s].location.points[t].y+g.y;let r={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}],area:0};if(HN(n,o,t.moduleSize,r)){t.location=r;const e=Object.assign({},t),n=(BigInt(e.format)&BigInt(_N.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(_N.BF_GS1_DATABAR))!=BigInt(0),o=n?1:2;this.overlapSet[s]=new jN(l,o,n,e),f[i]=s;break}}}}}else{if(e)v[i]&&(v[i].item.location=this.overlapSet[t].location);else{const e=Object.assign({},v[i].item),n=(BigInt(e.format)&BigInt(_N.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(_N.BF_GS1_DATABAR))!=BigInt(0),s=n?1:2;this.overlapSet[t]=new jN(l,s,n,e)}this.overlapSet[t]&&(this.overlapSet[t].overlapCount=l,this.overlapSet[t].verificationCount=2,this.overlapSet[t].crossVerificationFrame=r)}}e?this.stabilityCount<15&&this.stabilityCount++:this.stabilityCount=0;let i=!0;for(let t=0;t<this.overlapSet.length;t++){if(f.includes(t))continue;const n=this.overlapSet[t];n.overlapCount--,n.crossVerificationFrame--;const s=n.overlapCount+this.stabilityCount;if(o&&s>0){for(let t=0;t<h;t++)if(n.isOverlappedLocationWithOffset(v[t],g,!1)){i=!1;break}if(!i)break;const t=n.item;if(!e){for(let t=0;t<4;t++)n.location.points[t].x+=g.x,n.location.points[t].y+=g.y;t.location=n.location}2===n.verificationCount&&u.push(t)}}if(o&&!i){u=[];for(let t=0;t<this.overlapSet.length;t++){if(f.includes(t))continue;const e=this.overlapSet[t];e.overlapCount=0-this.stabilityCount,e.crossVerificationFrame=0,e.verificationCount=0}}for(let t=0;t<h;t++){if(-1!==f[t]||!v[t])continue;const i=v[t].item;if(e){for(let e=0;e<4;e++)v[t].location.points[e].x-=g.x,v[t].location.points[e].y-=g.y;i.location=v[t].location}let n=!1;for(let e of this.overlapSet)if(!(e.crossVerificationFrame<=0&&e.verificationCount<=0)&&(n=e.isLocationOverlap(v[t].location,v[t].locationArea),n))break;if(n){p.push(t);continue}const o=Object.assign({},i),r=(BigInt(i.format)&BigInt(_N.BF_ONED))!=BigInt(0)||(BigInt(i.format)&BigInt(_N.BF_GS1_DATABAR))!=BigInt(0),h=i.confidence<a,c=new jN(l,r?1:2,r,o);s&&r&&h?p.push(t):c.verificationCount=2,this.overlapSet.push(c)}this.overlapSet=this.overlapSet.filter(t=>!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0))}p.sort((t,e)=>e-t).forEach((e,i)=>{t.items.splice(e,1)}),u.forEach(e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))})}}}var eU,iU,nU,sU,oU;zN=new WeakMap,GN=new WeakMap,YN=new WeakMap,$N=new WeakMap,XN=new WeakMap;class rU{async readFromFile(t){return await kN(t)}async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");return(async(t,e,i)=>await new Promise(async(n,s)=>{try{const s=e.split(".");let o=s[s.length-1];const r=await SD(`image/${o}`,t);s.length<=1&&(o="png");const a=new File([r],e,{type:`image/${o}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return s()}}))(TD(t),e,i)}async readFromMemory(t){if(!xN(rU,eU,"f",iU).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=xN(rU,eU,"f",iU).get(t);return await new Promise((t,n)=>{let s=dR();uR[s]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},hR.postMessage({type:"utility_readFromMemory",id:s,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:s,stride:o,format:r}=await kN(t);return await new Promise((t,a)=>{let l=dR();uR[l]=async e=>{var i,n;if(e.success)return function(t,e,i,n,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");s?s.value=i:e.set(t,i)}(i=rU,eU,(n=xN(i,eU,"f",nU),++n),0,nU),xN(rU,eU,"f",iU).set(xN(rU,eU,"f",nU),JSON.parse(e.memery)),t(xN(rU,eU,"f",nU));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},hR.postMessage({type:"utility_saveToMemory",id:l,body:{bytes:i,width:n,height:s,stride:o,format:r,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=dR();uR[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},hR.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:s,stride:o,format:r}=await kN(t);return await new Promise((t,a)=>{let l=dR();uR[l]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},hR.postMessage({type:"utility_saveToBase64String",id:l,body:{bytes:i,width:n,height:s,stride:o,format:r,fileFormat:e}})})}}eU=rU,iU={value:new Map},nU={value:0};!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(sU||(sU={})),wR.engineResourcePaths.rootDirectory=(t=>{if(null==t&&(t="./"),CR||bR);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(SR+"../../"),wR.engineResourcePaths.dcvBundle={version:"3.2.5000",path:SR,isInternal:!0},wR.engineResourcePaths.dcvData={version:"1.1.0",path:SR,isInternal:!0},function(t){t.Scanner="scanner",t.Result="scan-result",t.Correction="correction"}(oU||(oU={}));const aU="DetectDocumentBoundaries_Default",lU="NormalizeDocument_Default";var hU,cU;function dU(t){if("string"==typeof t){const e=document.querySelector(t);if(!e)throw new Error("Element not found");return e}return t instanceof HTMLElement?t:null}function uU(t,e){pU("dds-controls-style","\n  .dds-controls {\n    display: flex;\n    height: 8rem;\n    background-color: #323234;\n    align-items: center;\n    font-size: 12px;\n    font-family: Verdana;\n    color: white;\n    width: 100%;\n  }\n\n  .dds-control-btn {\n    background-color: #323234;\n    color: white;\n    cursor: pointer;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    flex-direction: column;\n    height: 100%;\n    width: 100%;\n    gap: 0.5rem;\n    text-align: center;\n    user-select: none;\n  }\n\n  .dds-control-btn.hide {\n    display: none;\n  }\n\n  .dds-control-btn.disabled {\n    opacity: 0.4;\n    pointer-events: none;\n    cursor: default;\n  }\n\n  .dds-control-icon-wrapper {\n    flex: 0.75;\n    display: flex;\n    align-items: flex-end;\n    justify-content: center;\n    min-height: 40px;\n  }\n\n  .dds-control-icon img,\n  .dds-control-icon svg {\n    width: 32px;\n    height: 32px;\n    fill: #fe8e14;\n  }\n\n  .dds-control-text {\n    flex: 0.5;\n    display: flex;\n    align-items: flex-start;\n    justify-content: center;\n  }\n\n  @media (orientation: landscape) and (max-width: 1024px) {\n    .dds-controls {\n      flex-direction: column;\n      height: 100%;\n      width: 8rem;\n    }\n  }\n");const i=document.createElement("div");return i.className="dds-controls",t.forEach(t=>{const e=document.createElement("div");e.id=t.id,e.className=`dds-control-btn ${null==t?void 0:t.className}`;const n=document.createElement("div");if(n.className="dds-control-icon-wrapper",(s=t.icon).trim().startsWith("<svg")&&s.trim().endsWith("</svg>"))n.innerHTML=t.icon;else{const e=document.createElement("img");e.src=t.icon,e.alt=t.label,e.width=24,e.height=24,n.appendChild(e)}var s;const o=document.createElement("div");o.className="dds-control-text",o.textContent=t.label,t.isDisabled&&e.classList.add("disabled"),t.isHidden&&e.classList.add("hide"),e.appendChild(n),e.appendChild(o),t.onClick&&!t.isDisabled&&e.addEventListener("click",t.onClick),i.appendChild(e)}),i}function pU(t,e){if(!document.getElementById(t)){const i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}}!function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(hU||(hU={})),function(t){t.MANUAL="manual",t.SMART_CAPTURE="smartCapture",t.AUTO_CROP="autoCrop",t.UPLOADED_IMAGE="uploadedImage",t.STATIC_FILE="staticFile"}(cU||(cU={}));const gU=t=>!t||0===Object.keys(t).length,fU={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}},mU='\n  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="25" height="25" viewBox="0 0 25 25">\n  <defs>\n    <clipPath id="fullImageclip-path">\n      <rect id="Rectangle_2776" data-name="Rectangle 2776" width="25" height="25" fill="#fff"/>\n    </clipPath>\n  </defs>\n  <g id="full-image" transform="translate(0 0)">\n    <g id="Group_586" data-name="Group 586" transform="translate(0 0)" clip-path="url(#fullImageclip-path)">\n      <path id="Path_1528" data-name="Path 1528" d="M.621,3.618A.621.621,0,0,0,1.242,3V1.809a.569.569,0,0,1,.567-.567H3A.621.621,0,0,0,3,0H1.809A1.811,1.811,0,0,0,0,1.809V3a.621.621,0,0,0,.621.621" transform="translate(0 0)" fill="#fff"/>\n      <path id="Path_1529" data-name="Path 1529" d="M17.842,1.242H19.03a.568.568,0,0,1,.566.567V3a.621.621,0,1,0,1.242,0V1.809A1.811,1.811,0,0,0,19.03,0H17.842a.621.621,0,0,0,0,1.242" transform="translate(4.162 0)" fill="#fff"/>\n      <path id="Path_1530" data-name="Path 1530" d="M9.562,0H5.4a.621.621,0,0,0,0,1.242H9.562A.621.621,0,0,0,9.562,0" transform="translate(1.156 0)" fill="#fff"/>\n      <path id="Path_1531" data-name="Path 1531" d="M11.623,1.242h4.158a.621.621,0,0,0,0-1.242H11.623a.621.621,0,0,0,0,1.242" transform="translate(2.659 0)" fill="#fff"/>\n      <path id="Path_1532" data-name="Path 1532" d="M3,19.6H1.808a.568.568,0,0,1-.566-.567V17.841a.621.621,0,1,0-1.242,0v1.188a1.81,1.81,0,0,0,1.808,1.809H3A.621.621,0,0,0,3,19.6" transform="translate(0 4.161)" fill="#fff"/>\n      <path id="Path_1533" data-name="Path 1533" d="M9.562,19.134H5.4a.621.621,0,1,0,0,1.242H9.562a.621.621,0,1,0,0-1.242" transform="translate(1.156 4.624)" fill="#fff"/>\n      <path id="Path_1534" data-name="Path 1534" d="M.621,10.183a.621.621,0,0,0,.621-.621V5.4A.621.621,0,0,0,0,5.4V9.562a.621.621,0,0,0,.621.621" transform="translate(0 1.156)" fill="#fff"/>\n      <path id="Path_1535" data-name="Path 1535" d="M.621,16.4a.621.621,0,0,0,.621-.621V11.624a.621.621,0,1,0-1.242,0v4.157a.621.621,0,0,0,.621.621" transform="translate(0 2.659)" fill="#fff"/>\n      <path id="Path_1536" data-name="Path 1536" d="M20.376,5.4a.621.621,0,1,0-1.242,0V9.563a.621.621,0,1,0,1.242,0Z" transform="translate(4.624 1.156)" fill="#fff"/>\n      <path id="Path_1537" data-name="Path 1537" d="M20.217,17.221a.621.621,0,0,0-.621.621V19.03a.568.568,0,0,1-.567.566H17.841a.621.621,0,1,0,0,1.242h1.188a1.811,1.811,0,0,0,1.809-1.808V17.842a.621.621,0,0,0-.621-.621" transform="translate(4.162 4.162)" fill="#fff"/>\n      <path id="Path_1538" data-name="Path 1538" d="M15.781,19.134H11.623a.621.621,0,1,0,0,1.242h4.158a.621.621,0,0,0,0-1.242" transform="translate(2.659 4.624)" fill="#fff"/>\n      <path id="Path_1539" data-name="Path 1539" d="M19.755,11a.621.621,0,0,0-.621.621v4.157a.621.621,0,0,0,1.242,0V11.624A.621.621,0,0,0,19.755,11" transform="translate(4.624 2.659)" fill="#fff"/>\n      <path id="Path_1540" data-name="Path 1540" d="M7.5,18.3a.621.621,0,0,0-.621-.621H4.733l5.149-5.149A.621.621,0,0,0,9,11.656L3.855,16.806V14.579a.621.621,0,0,0-1.242,0V18.3a.611.611,0,0,0,.048.238A.606.606,0,0,0,3,18.877a.606.606,0,0,0,.238.048H6.878A.621.621,0,0,0,7.5,18.3" transform="translate(0.632 2.773)" fill="#fff"/>\n      <path id="Path_1541" data-name="Path 1541" d="M14.173,3.409a.619.619,0,0,0,.621.621h1.836L11.483,9.178a.621.621,0,0,0,.878.878l5.148-5.148V6.744a.621.621,0,1,0,1.242,0V3.41a.606.606,0,0,0-.048-.238.612.612,0,0,0-.335-.335.606.606,0,0,0-.238-.048H14.794a.621.621,0,0,0-.621.621" transform="translate(2.731 0.673)" fill="#fff"/>\n      <path id="Path_1542" data-name="Path 1542" d="M2.661,3.172a.615.615,0,0,0-.048.238V6.744a.621.621,0,0,0,1.242,0V4.908L9,10.057a.621.621,0,0,0,.878-.878L4.733,4.03H6.57a.621.621,0,1,0,0-1.242H3.235A.634.634,0,0,0,3,2.836a.624.624,0,0,0-.335.335" transform="translate(0.632 0.673)" fill="#fff"/>\n      <path id="Path_1543" data-name="Path 1543" d="M18.7,18.545a.617.617,0,0,0,.048-.24h0V14.581a.62.62,0,1,0-1.24,0v2.226l-5.148-5.15a.621.621,0,0,0-.878.878l5.147,5.149H14.4a.621.621,0,0,0-.621.621.623.623,0,0,0,.621.621h3.71a.616.616,0,0,0,.453-.18.6.6,0,0,0,.117-.175c0-.009.012-.016.016-.025" transform="translate(2.731 2.773)" fill="#fff"/>\n    </g>\n  </g>\n</svg>\n\n',vU='<svg xmlns="http://www.w3.org/2000/svg" width="25.04" height="25" viewBox="0 0 25.04 25">\n  <g id="bounds-detection" transform="translate(0.02)">\n    <g id="Group_306" data-name="Group 306" transform="translate(-0.02)">\n      <path id="Path_982" data-name="Path 982" d="M.791,8.146h.02a.468.468,0,0,0,.516-.416.455.455,0,0,0,0-.063V1.927a1,1,0,0,1,1-1H7.957A.468.468,0,0,0,8.436.492.468.468,0,0,0,7.977.013H2.247A1.913,1.913,0,0,0,.333,1.927v5.74A.468.468,0,0,0,.791,8.146Z" transform="translate(-0.293 -0.012)" fill="#fff"/>\n      <path id="Path_983" data-name="Path 983" d="M140.092,132.044a.468.468,0,0,0-.458-.478h-.02a.468.468,0,0,0-.478.458q0,.01,0,.02v5.74a1,1,0,0,1-1,1h-5.671a.5.5,0,0,0,0,1h5.711a1.913,1.913,0,0,0,1.915-1.912q0-.041,0-.081Z" transform="translate(-115.132 -114.777)" fill="#fff"/>\n      <path id="Path_984" data-name="Path 984" d="M7.665,138.7H1.955a1,1,0,0,1-1-1v-5.661a.468.468,0,0,0-.458-.478H.48a.468.468,0,0,0-.478.458q0,.01,0,.02v5.74A1.914,1.914,0,0,0,1.914,139.7H7.665a.5.5,0,1,0,0-1Z" transform="translate(-0.001 -114.777)" fill="#fff"/>\n      <path id="Path_985" data-name="Path 985" d="M138.405,0l-.081,0h-5.711a.468.468,0,0,0-.478.458q0,.01,0,.02a.468.468,0,0,0,.458.478h5.731a1,1,0,0,1,1,1v5.7a.5.5,0,0,0,1,0V1.915A1.913,1.913,0,0,0,138.405,0Z" transform="translate(-115.277)" fill="#fff"/>\n      <path id="Path_986" data-name="Path 986" d="M32.226,33.132v14.81a1.227,1.227,0,0,0,1.227,1.227H48.265a1.217,1.217,0,0,0,1.227-1.206V33.132a1.217,1.217,0,0,0-1.206-1.227H33.453A1.227,1.227,0,0,0,32.226,33.132Zm16.251-.045a.19.19,0,0,1,0,.045v14.81a.19.19,0,0,1-.179.2H33.453a.19.19,0,0,1-.211-.168.182.182,0,0,1,0-.033V33.132a.19.19,0,0,1,.212-.212H48.265A.191.191,0,0,1,48.477,33.087Z" transform="translate(-28.359 -28.076)" fill="#fff"/>\n      <path id="Path_987" data-name="Path 987" d="M59.363,95.652h9.209a.478.478,0,0,0,.478-.478.488.488,0,0,0-.478-.478H59.363a.488.488,0,0,0-.478.478A.478.478,0,0,0,59.363,95.652Z" transform="translate(-51.309 -82.838)" fill="#fff"/>\n      <path id="Path_988" data-name="Path 988" d="M59.363,128.6h9.209a.478.478,0,0,0,.478-.478.488.488,0,0,0-.478-.478H59.363a.488.488,0,0,0-.478.478A.478.478,0,0,0,59.363,128.6Z" transform="translate(-51.309 -111.663)" fill="#fff"/>\n      <path id="Path_989" data-name="Path 989" d="M59.364,64.6h4.285a.488.488,0,0,0,.478-.478.478.478,0,0,0-.478-.478H59.364a.468.468,0,0,0-.478.458q0,.01,0,.02A.478.478,0,0,0,59.364,64.6Z" transform="translate(-51.443 -55.678)" fill="#fff"/>\n    </g>\n  </g>\n</svg>\n',yU='<svg id="finish" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <clipPath id="finishclip-path">\n      <rect id="Rectangle_2775" data-name="Rectangle 2775" width="24" height="24" fill="currentColor"/>\n    </clipPath>\n  </defs>\n  <g id="Group_584" data-name="Group 584" clip-path="url(#finishclip-path)">\n    <path id="Path_1526" data-name="Path 1526" d="M17.6,6.7l-6.691,9.081L6.313,12.11a.5.5,0,0,0-.625.781l5,4a.508.508,0,0,0,.378.1.493.493,0,0,0,.337-.2l7-9.5A.5.5,0,1,0,17.6,6.7" fill="currentColor"/>\n    <path id="Path_1527" data-name="Path 1527" d="M12,0A12,12,0,1,0,24,12,12.013,12.013,0,0,0,12,0m0,23A11,11,0,1,1,23,12,11.013,11.013,0,0,1,12,23" fill="currentColor"/>\n  </g>\n</svg>\n',xU='<svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="Layer_1-2">\n    <path class="cls-1"\n      d="m17.05,14.93c-.27,0-.48.22-.48.5v5.95l-2.97-6.18c-.1-.21-.32-.32-.54-.26-.22.05-.37.25-.37.49v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-5.95l2.97,6.18c.08.17.25.28.43.28.04,0,.07,0,.11-.01.22-.05.37-.25.37-.49v-8.07c0-.28-.21-.5-.48-.5Z" />\n    <path class="cls-1"\n      d="m8.64,14.93h-1.94c-.27,0-.48.22-.48.5v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-3.53h1.46c1.34,0,2.42-1.13,2.42-2.52s-1.09-2.52-2.42-2.52Zm0,4.03h-1.46v-3.04h1.46c.81,0,1.46.68,1.46,1.52s-.66,1.52-1.46,1.52Z" />\n    <path class="cls-1"\n      d="m23.52,18.62c.27,0,.48-.22.48-.5v-.67c0-1.39-1.09-2.52-2.42-2.52s-2.42,1.13-2.42,2.52v4.03c0,1.39,1.09,2.52,2.42,2.52s2.42-1.13,2.42-2.52v-.67c0-.28-.21-.5-.48-.5h-1.29c-.27,0-.48.22-.48.5s.21.5.48.5h.81v.17c0,.84-.65,1.52-1.46,1.52s-1.46-.68-1.46-1.52v-4.03c0-.84.65-1.52,1.46-1.52s1.46.68,1.46,1.52v.67c0,.28.21.5.48.5Z" />\n    <path class="cls-1"\n      d="m3.65,22.96H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.45c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.6-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.96c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM15.58,1.28c1.86.52,3.31,1.92,3.85,3.71h-3.36c-.27,0-.49-.21-.49-.48V1.28Z" />\n    <path class="cls-1" transform="scale(1, -1) translate(0, -14)"\n      d="m10.32,7.11l-1.65,1.53v-4.58c0-.3-.26-.55-.59-.55s-.59.25-.59.55v4.58l-1.65-1.53c-.23-.21-.6-.21-.84,0s-.23.56,0,.78l2.66,2.47c.05.05.12.09.19.12.07.03.15.04.23.04s.15-.01.23-.04c.07-.03.14-.07.19-.12l2.66-2.47c.23-.21.23-.56,0-.78-.23-.21-.6-.21-.84,0Z" />\n  </g>\n</svg>\n',wU='\n<svg id="sharePng" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="sharePng">\n    <path class="cls-1"\n      d="m17.05,14.93c-.27,0-.48.22-.48.5v5.95l-2.97-6.18c-.1-.21-.32-.32-.54-.26-.22.05-.37.25-.37.49v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-5.95l2.97,6.18c.08.17.25.28.43.28.04,0,.07,0,.11-.01.22-.05.37-.25.37-.49v-8.07c0-.28-.21-.5-.48-.5Z" />\n    <path class="cls-1"\n      d="m8.64,14.93h-1.94c-.27,0-.48.22-.48.5v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-3.53h1.46c1.34,0,2.42-1.13,2.42-2.52s-1.09-2.52-2.42-2.52Zm0,4.03h-1.46v-3.04h1.46c.81,0,1.46.68,1.46,1.52s-.66,1.52-1.46,1.52Z" />\n    <path class="cls-1"\n      d="m23.52,18.62c.27,0,.48-.22.48-.5v-.67c0-1.39-1.09-2.52-2.42-2.52s-2.42,1.13-2.42,2.52v4.03c0,1.39,1.09,2.52,2.42,2.52s2.42-1.13,2.42-2.52v-.67c0-.28-.21-.5-.48-.5h-1.29c-.27,0-.48.22-.48.5s.21.5.48.5h.81v.17c0,.84-.65,1.52-1.46,1.52s-1.46-.68-1.46-1.52v-4.03c0-.84.65-1.52,1.46-1.52s1.46.68,1.46,1.52v.67c0,.28.21.5.48.5Z" />\n    <path class="cls-1"\n      d="m3.65,22.96H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.45c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.6-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.96c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM15.58,1.28c1.86.52,3.31,1.92,3.85,3.71h-3.36c-.27,0-.49-.21-.49-.48V1.28Z" />\n    <path transform="scale(0.4, -0.4) translate(8, -30)" stroke="#fff" fill="#fff" stroke-width="1px" d="M19.489,15.009h0c-.008,0-.014,0-.022,0a4.465,4.465,0,0,0-3.749,2.052l-7-3.5a4.482,4.482,0,0,0,0-3.1l7-3.5a4.466,4.466,0,0,0,3.771,2.053l.018,0A4.516,4.516,0,1,0,15.282,6.06L8.257,9.574a4.49,4.49,0,1,0-4.793,6.814,4.548,4.548,0,0,0,1.043.122,4.468,4.468,0,0,0,3.755-2.056l7.018,3.511a4.485,4.485,0,1,0,4.209-2.956M17.13,1.914a3.508,3.508,0,1,1,2.366,6.1h-.01l-.011,0a3.476,3.476,0,0,1-3.112-1.932l0-.006a3.525,3.525,0,0,1,.769-4.162M3.693,15.415a3.5,3.5,0,1,1,3.931-4.967v0a3.47,3.47,0,0,1,0,3.119l0,0a3.479,3.479,0,0,1-3.931,1.842m17.636,7.066a3.5,3.5,0,0,1-4.971-4.53l0,0a3.477,3.477,0,0,1,3.126-1.936l.011,0a3.5,3.5,0,0,1,1.831,6.472" />\n  </g>\n</svg>\n',CU='<svg id="normalize" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="19" height="24" viewBox="0 0 19 24">\n<defs>\n  <clipPath id="normalizeclip-path">\n    <rect id="Rectangle_2772" data-name="Rectangle 2772" width="19" height="24" fill="#fff"/>\n  </clipPath>\n</defs>\n<g id="Group_578" data-name="Group 578" clip-path="url(#normalizeclip-path)">\n  <path id="Path_1510" data-name="Path 1510" d="M3.483,18.987a.521.521,0,0,0,.52.522H14.9a.522.522,0,0,0,0-1.044H4a.521.521,0,0,0-.52.522" fill="#fff"/>\n  <path id="Path_1511" data-name="Path 1511" d="M4,13.52h8.75a.522.522,0,0,0,0-1.043H4A.522.522,0,0,0,4,13.52" fill="#fff"/>\n  <path id="Path_1512" data-name="Path 1512" d="M4,10.526h7.448a.522.522,0,0,0,0-1.043H4a.522.522,0,0,0,0,1.043" fill="#fff"/>\n  <path id="Path_1513" data-name="Path 1513" d="M4,7.532H9.927a.522.522,0,0,0,0-1.043H4A.522.522,0,0,0,4,7.532" fill="#fff"/>\n  <path id="Path_1514" data-name="Path 1514" d="M4.005,15.471H4a.522.522,0,0,0,0,1.043l9.79.039h0a.522.522,0,0,0,0-1.043Z" fill="#fff"/>\n  <path id="Path_1515" data-name="Path 1515" d="M9.33,1.044H11.5A.522.522,0,0,0,11.5,0H9.33a.522.522,0,0,0,0,1.043" fill="#fff"/>\n  <path id="Path_1516" data-name="Path 1516" d="M13.679,1.044h2.174a.522.522,0,0,0,0-1.043H13.679a.522.522,0,0,0,0,1.043" fill="#fff"/>\n  <path id="Path_1517" data-name="Path 1517" d="M18.48,17.548a.516.516,0,0,0-.367.152c-.572-3.035-1.506-7.61-3.012-14.546a.524.524,0,0,0-.139-.256,1.432,1.432,0,0,0-.972-.437L6.806,1.044h.349A.522.522,0,0,0,7.155,0H4.981A.522.522,0,0,0,4.46.522a.426.426,0,0,0,.013.062L3.291.351A.516.516,0,0,0,2.805,0H1.765a.515.515,0,0,0-.124.025L1.515,0A1.52,1.52,0,0,0,0,1.52V22.481A1.519,1.519,0,0,0,1.515,24H18.432a.142.142,0,0,0,.022,0,.238.238,0,0,0,.026,0,.52.52,0,0,0,.52-.521V22.435a.522.522,0,0,0-.152-.369c-.047-.358-.111-.8-.2-1.329A.516.516,0,0,0,19,20.25V18.069a.519.519,0,0,0-.52-.521M1.515,22.957a.475.475,0,0,1-.474-.476V1.52a.491.491,0,0,1,.373-.486L13.89,3.495a.468.468,0,0,1,.233.061c1.449,6.682,3.613,17.143,3.823,19.4Z" fill="#fff"/>\n  <path id="Path_1518" data-name="Path 1518" d="M18.48,4.461a.52.52,0,0,0-.52.522v2.18a.52.52,0,1,0,1.04,0V4.983a.52.52,0,0,0-.52-.522" fill="#fff"/>\n  <path id="Path_1519" data-name="Path 1519" d="M18.29.366a.521.521,0,0,0-.638.824.827.827,0,0,1,.308.653V2.8A.52.52,0,1,0,19,2.8V1.843A1.877,1.877,0,0,0,18.29.366" fill="#fff"/>\n  <path id="Path_1520" data-name="Path 1520" d="M18.48,13.185a.52.52,0,0,0-.52.522v2.181a.52.52,0,1,0,1.04,0V13.707a.52.52,0,0,0-.52-.522" fill="#fff"/>\n  <path id="Path_1521" data-name="Path 1521" d="M18.48,8.823a.52.52,0,0,0-.52.522v2.181a.52.52,0,1,0,1.04,0V9.345a.52.52,0,0,0-.52-.522" fill="#fff"/>\n</g>\n</svg>\n',bU='<svg id="re-take" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="28.761" height="23" viewBox="0 0 28.761 23">\n<defs>\n<clipPath id="retakeclip-path">\n  <rect id="Rectangle_2773" data-name="Rectangle 2773" width="28.761" height="23" fill="#fff"/>\n</clipPath>\n</defs>\n<g id="Group_580" data-name="Group 580" clip-path="url(#retakeclip-path)">\n<path id="Path_1522" data-name="Path 1522" d="M25.877,3.639H21.663a.7.7,0,0,1-.575-.288l-.575-.764C19.264.961,18.59,0,17.44,0H11.4C10.151,0,9.486.961,8.336,2.588l-.674.764a.7.7,0,0,1-.575.288H2.875C.476,3.639,0,5.077,0,6.227v13.9C0,22.041,1.051,23,2.974,23H25.787c1.914,0,2.974-.961,2.974-2.776v-14c-.008-1.147-.485-2.585-2.884-2.585m-.1,18.411H2.974c-1.339,0-2.013-.575-2.013-1.824v-14c0-.863.189-1.626,1.914-1.626H7.188a1.666,1.666,0,0,0,1.339-.674L9.1,3.162c1.15-1.626,1.536-2.2,2.2-2.2H17.34c.674,0,1.15.575,2.3,2.2l.575.764a1.562,1.562,0,0,0,1.339.674h4.313c1.725,0,1.914.764,1.914,1.626v14h.009c0,1.249-.673,1.824-2.012,1.824" fill="#fff"/>\n<path id="Path_1523" data-name="Path 1523" d="M15.978,9.16H9.462l1.745-1.743A.5.5,0,0,0,10.5,6.71l-2.6,2.6a.484.484,0,0,0-.108.162.5.5,0,0,0,0,.382.479.479,0,0,0,.108.163l2.6,2.6a.5.5,0,0,0,.708-.708L9.462,10.16h6.516a4.028,4.028,0,0,1,0,8.055H10.255a.5.5,0,1,0,0,1h5.723a5.028,5.028,0,0,0,0-10.055" fill="#fff"/>\n</g>\n</svg>\n',SU='\n<svg id="continue" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n<defs>\n<clipPath id="continueclip-path">\n  <rect id="Rectangle_2774" data-name="Rectangle 2774" width="24" height="24" fill="currentColor"/>\n</clipPath>\n</defs>\n<g id="Group_582" data-name="Group 582" clip-path="url(#continueclip-path)">\n<path id="Path_1524" data-name="Path 1524" d="M12,0A12,12,0,1,0,24,12,12.013,12.013,0,0,0,12,0m0,23A11,11,0,1,1,23,12,11.013,11.013,0,0,1,12,23" fill="currentColor"/>\n<path id="Path_1525" data-name="Path 1525" d="M19.862,12a.17.17,0,0,0,0-.024.512.512,0,0,0-.033-.168.532.532,0,0,0-.113-.17l-4.219-4.29a.5.5,0,0,0-.714,0,.51.51,0,0,0,0,.719l3.371,3.428H4.643a.509.509,0,0,0,0,1.018h13.5l-3.373,3.428a.512.512,0,0,0,0,.72.5.5,0,0,0,.714,0l4.224-4.295a.438.438,0,0,0,.056-.086.5.5,0,0,0,.051-.078A.521.521,0,0,0,19.862,12h0" fill="currentColor"/>\n</g>\n</svg>\n',TU='\n<svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">\n<defs>\n<style>\n  .cls-1 {\n    fill: #fff;\n    stroke-width: 0px;\n  }\n</style>\n</defs>\n<g id="Layer_1-2">\n<path class="cls-1"\n  d="m17.05,14.93c-.27,0-.48.22-.48.5v5.95l-2.97-6.18c-.1-.21-.32-.32-.54-.26-.22.05-.37.25-.37.49v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-5.95l2.97,6.18c.08.17.25.28.43.28.04,0,.07,0,.11-.01.22-.05.37-.25.37-.49v-8.07c0-.28-.21-.5-.48-.5Z" />\n<path class="cls-1"\n  d="m8.64,14.93h-1.94c-.27,0-.48.22-.48.5v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-3.53h1.46c1.34,0,2.42-1.13,2.42-2.52s-1.09-2.52-2.42-2.52Zm0,4.03h-1.46v-3.04h1.46c.81,0,1.46.68,1.46,1.52s-.66,1.52-1.46,1.52Z" />\n<path class="cls-1"\n  d="m23.52,18.62c.27,0,.48-.22.48-.5v-.67c0-1.39-1.09-2.52-2.42-2.52s-2.42,1.13-2.42,2.52v4.03c0,1.39,1.09,2.52,2.42,2.52s2.42-1.13,2.42-2.52v-.67c0-.28-.21-.5-.48-.5h-1.29c-.27,0-.48.22-.48.5s.21.5.48.5h.81v.17c0,.84-.65,1.52-1.46,1.52s-1.46-.68-1.46-1.52v-4.03c0-.84.65-1.52,1.46-1.52s1.46.68,1.46,1.52v.67c0,.28.21.5.48.5Z" />\n<path class="cls-1"\n  d="m3.65,22.96H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.45c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.6-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.96c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM15.58,1.28c1.86.52,3.31,1.92,3.85,3.71h-3.36c-.27,0-.49-.21-.49-.48V1.28Z" />\n<path class="cls-1"\n  d="m10.32,7.11l-1.65,1.53v-4.58c0-.3-.26-.55-.59-.55s-.59.25-.59.55v4.58l-1.65-1.53c-.23-.21-.6-.21-.84,0s-.23.56,0,.78l2.66,2.47c.05.05.12.09.19.12.07.03.15.04.23.04s.15-.01.23-.04c.07-.03.14-.07.19-.12l2.66-2.47c.23-.21.23-.56,0-.78-.23-.21-.6-.21-.84,0Z" />\n</g>\n</svg>\n';class EU{constructor(t,e,i){var n,s;this.resources=t,this.config=e,this.scannerView=i,this.imageEditorView=null,this.layer=null,this.config.utilizedTemplateNames={detect:(null===(n=e.utilizedTemplateNames)||void 0===n?void 0:n.detect)||aU,normalize:(null===(s=e.utilizedTemplateNames)||void 0===s?void 0:s.normalize)||lU}}async initialize(){if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create an Correction View Container element");pU("dds-correction-view-style",_U);const t=document.createElement("div");t.className="dds-correction-view-container";const e=document.createElement("div");Object.assign(e.style,{width:"100%",height:"100%"}),t.appendChild(e),dU(this.config.container).appendChild(t),this.imageEditorView=await IB.createInstance(e),this.layer=this.imageEditorView.createDrawingLayer(),this.imageEditorView.setOriginalImage(this.resources.result.originalImageResult),this.setupDrawingLayerStyle(),this.setupInitialDetectedQuad(),this.setupCorrectionControls(),this.setupQuadConstraints(),this.resources.result._flowType===cU.STATIC_FILE&&(document.querySelector("#dds-correction-retake").style.display="none")}setupDrawingLayerStyle(){const t=wO.createDrawingStyle({lineWidth:5,fillStyle:"transparent",strokeStyle:"#FE8E14",paintMode:"stroke"});this.layer.setDefaultStyle(t)}setupQuadConstraints(){const t=this.layer.fabricCanvas;t.defaultCursor="default",t.hoverCursor="default",t.moveCursor="default",t.on("object:scaling",e=>{const i=e.target,n=i.points,s=this.getCanvasBounds();n.forEach(t=>{t.x=Math.max(0,Math.min(s.width,t.x)),t.y=Math.max(0,Math.min(s.height,t.y))}),i.set({points:n,dirty:!0}),t.renderAll()}),t.on("object:modified",e=>{const i=e.target;if(!i)return;const n=i.points,s=this.getCanvasBounds();let o=!1;n.forEach(t=>{(t.x<0||t.x>s.width||t.y<0||t.y>s.height)&&(o=!0)}),o&&(n.forEach(t=>{t.x=Math.max(0,Math.min(s.width,t.x)),t.y=Math.max(0,Math.min(s.height,t.y))}),i.set({points:n,dirty:!0}),t.renderAll())})}getCanvasBounds(){const t=this.layer.fabricCanvas;return{width:t.getWidth(),height:t.getHeight()}}addQuadToLayer(t){var e,i;this.layer.clearDrawingItems();const n=t._getFabricObject(),s=.1*Math.min(null===(e=this.resources.result.originalImageResult)||void 0===e?void 0:e.width,null===(i=this.resources.result.originalImageResult)||void 0===i?void 0:i.height);n.cornerSize=s,n.lockMovementX=!0,n.lockMovementY=!0,n.on("mousedown",function(t){var e,i;(null===(e=t.target)||void 0===e?void 0:e.controls)&&(this.cornerColor="transparent",this.dirty=!0,null===(i=this.canvas)||void 0===i||i.renderAll())}),n.on("mouseup",function(){var t;this.cornerColor="#FE8E14",this.dirty=!0,null===(t=this.canvas)||void 0===t||t.renderAll()}),this.layer.renderAll(),this.layer.addDrawingItems([t]),this.layer.fabricCanvas.setActiveObject(n),this.layer.fabricCanvas.renderAll()}setupInitialDetectedQuad(){let t;if(this.resources.result.detectedQuadrilateral)t=new kM(this.resources.result.detectedQuadrilateral);else{const{width:e,height:i}=this.resources.result.originalImageResult;t=new kM({points:[{x:0,y:0},{x:e,y:0},{x:e,y:i},{x:0,y:i}],area:e*i})}this.addQuadToLayer(t)}createControls(){var t,e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y;const{toolbarButtonsConfig:x}=this.config;return uU([{id:"dds-correction-retake",icon:(null===(t=null==x?void 0:x.retake)||void 0===t?void 0:t.icon)||bU,label:(null===(e=null==x?void 0:x.retake)||void 0===e?void 0:e.label)||"Re-take",onClick:()=>this.handleRetake(),className:`${(null===(i=null==x?void 0:x.retake)||void 0===i?void 0:i.className)||""}`,isHidden:(null===(n=null==x?void 0:x.retake)||void 0===n?void 0:n.isHidden)||!1,isDisabled:!this.scannerView},{id:"dds-correction-fullImage",icon:(null===(s=null==x?void 0:x.fullImage)||void 0===s?void 0:s.icon)||mU,label:(null===(o=null==x?void 0:x.fullImage)||void 0===o?void 0:o.label)||"Full Image",className:`${(null===(r=null==x?void 0:x.fullImage)||void 0===r?void 0:r.className)||""}`,isHidden:(null===(a=null==x?void 0:x.fullImage)||void 0===a?void 0:a.isHidden)||!1,onClick:()=>this.setFullImageBoundary()},{id:"dds-correction-detectBorders",icon:(null===(l=null==x?void 0:x.detectBorders)||void 0===l?void 0:l.icon)||vU,label:(null===(h=null==x?void 0:x.detectBorders)||void 0===h?void 0:h.label)||"Detect Borders",className:`${(null===(c=null==x?void 0:x.detectBorders)||void 0===c?void 0:c.className)||""}`,isHidden:(null===(d=null==x?void 0:x.detectBorders)||void 0===d?void 0:d.isHidden)||!1,onClick:()=>this.setBoundaryAutomatically()},{id:"dds-correction-apply",icon:(null===(u=null==x?void 0:x.apply)||void 0===u?void 0:u.icon)||(!1===(null===(p=this.config)||void 0===p?void 0:p._showResultView)?SU:yU),label:(null===(g=null==x?void 0:x.apply)||void 0===g?void 0:g.label)||(this.resources.enableContinuousScanning&&!1===(null===(f=this.config)||void 0===f?void 0:f._showResultView)?"Keep Scan":!1===(null===(m=this.config)||void 0===m?void 0:m._showResultView)?"Done":"Apply"),className:`${(null===(v=null==x?void 0:x.apply)||void 0===v?void 0:v.className)||""}`,isHidden:(null===(y=null==x?void 0:x.apply)||void 0===y?void 0:y.isHidden)||!1,onClick:()=>this.confirmCorrection()}])}setupCorrectionControls(){try{const t=this.createControls(),e=dU(this.config.container).firstElementChild;e&&e.appendChild(t)}catch(t){throw console.error("Error setting up correction controls:",t),new Error(`Failed to setup correction controls: ${(null==t?void 0:t.message)||t}`)}}async handleRetake(){var t,e,i,n,s,o,r;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView(),this.scannerView&&(dU(this.scannerView.config.container).style.display="flex");const r=await this.scannerView.launch();if((null===(t=null==r?void 0:r.status)||void 0===t?void 0:t.code)===hU.RS_CANCELLED||(null===(e=null==r?void 0:r.status)||void 0===e?void 0:e.code)===hU.RS_FAILED)return void(null===(i=this.currentCorrectionResolver)||void 0===i||i.call(this,r));(null==r?void 0:r.status.code)===hU.RS_SUCCESS&&(null===(s=(n=this.resources).onResultUpdated)||void 0===s||s.call(n,r),null===(o=this.scannerView)||void 0===o||o.stopCapturing(),this.scannerView&&(dU(this.scannerView.config.container).style.display="none"),this.dispose(!0),await this.initialize(),dU(this.config.container).style.display="flex")}catch(t){throw console.error("Error in retake handler:",t),null===(r=this.currentCorrectionResolver)||void 0===r||r.call(this,{status:{code:hU.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}setFullImageBoundary(){if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");const{width:t,height:e}=this.resources.result.originalImageResult,i=new kM({points:[{x:0,y:0},{x:t,y:0},{x:t,y:e},{x:0,y:e}],area:t*e});this.addQuadToLayer(i)}async setBoundaryAutomatically(){var t;this.config.templateFilePath&&await this.resources.cvRouter.initSettings(this.config.templateFilePath);let e=await this.resources.cvRouter.getSimplifiedSettings(this.config.utilizedTemplateNames.detect);e.outputOriginalImage=!0,await this.resources.cvRouter.updateSettings(this.config.utilizedTemplateNames.detect,e),this.resources.cvRouter.maxImageSideLength=1/0;const i=null===(t=(await this.resources.cvRouter.capture(this.resources.result.originalImageResult,"DetectDocumentBoundaries_Default")).items.find(t=>t.type===zD.CRIT_DETECTED_QUAD))||void 0===t?void 0:t.location;i?this.addQuadToLayer(new kM(i)):this.setFullImageBoundary()}async confirmCorrection(){var t,e,i,n,s,o;const r=this.layer.getDrawingItems()[0];if(!r)throw new Error("No quad drawing item found");const a=r.getQuad(),l=await this.correctImage(null==a?void 0:a.points);if(l){const o=Object.assign(Object.assign({},this.resources.result),{correctedImageResult:l,detectedQuadrilateral:a});null===(e=(t=this.resources).onResultUpdated)||void 0===e||e.call(t,o),null===(n=null===(i=this.config)||void 0===i?void 0:i.onFinish)||void 0===n||n.call(i,o),null===(s=this.currentCorrectionResolver)||void 0===s||s.call(this,o)}else null===(o=this.currentCorrectionResolver)||void 0===o||o.call(this,this.resources.result);this.dispose(),this.hideView()}async launch(){var t,e;try{return(null===(t=this.resources.result)||void 0===t?void 0:t.correctedImageResult)?(dU(this.config.container).textContent="",await this.initialize(),dU(this.config.container).style.display="flex",new Promise(t=>{this.currentCorrectionResolver=t})):{status:{code:hU.RS_FAILED,message:"No image available for correction"}}}catch(t){let i=(null==t?void 0:t.message)||t;if(console.error(i),!(null===(e=this.resources.result)||void 0===e?void 0:e.correctedImageResult))return{status:{code:hU.RS_FAILED,message:i}}}}hideView(){dU(this.config.container).style.display="none"}async correctImage(t){var e,i;const{cvRouter:n}=this.resources;this.config.templateFilePath&&await this.resources.cvRouter.initSettings(this.config.templateFilePath);const s=await n.getSimplifiedSettings(this.config.utilizedTemplateNames.normalize);s.roiMeasuredInPercentage=!1,s.roi.points=t,await n.updateSettings(this.config.utilizedTemplateNames.normalize,s);const o=await n.capture(this.resources.result.originalImageResult,this.config.utilizedTemplateNames.normalize);if(null===(i=null===(e=null==o?void 0:o.processedDocumentResult)||void 0===e?void 0:e.deskewedImageResultItems)||void 0===i?void 0:i[0])return o.processedDocumentResult.deskewedImageResultItems[0]}dispose(t=!1){var e,i,n;null===(i=null===(e=this.imageEditorView)||void 0===e?void 0:e.dispose)||void 0===i||i.call(e),this.layer=null,(null===(n=this.config)||void 0===n?void 0:n.container)&&(dU(this.config.container).textContent=""),t||(this.currentCorrectionResolver=void 0)}}const _U="\n  .dds-correction-view-container {\n    display: flex;\n    width: 100%;\n    height: 100%;\n    background-color:#575757;\n    font-size: 12px;\n    flex-direction: column;\n    align-items: center;\n  }\n\n  @media (orientation: landscape) and (max-width: 1024px) {\n    .dds-correction-view-container {\n      flex-direction: row;\n    }\n  }\n";function PU(t,e={}){const{message:i,spinnerSize:n=32}=e,s=document.createElement("div");s.className="dds-loading-screen";const o=document.createElement("div");o.className="dds-loading";const r=document.createElement("div");r.className="dds-loading-content";const a=`\n    <svg\n      xmlns="http://www.w3.org/2000/svg"\n      viewBox="0 0 24 24"\n      fill="none"\n      stroke="white"\n      stroke-linecap="round"\n      stroke-linejoin="round"\n      width="${n}"\n      height="${n}"\n      stroke-width="0.75"\n    >\n      <path d="M12 3a9 9 0 1 0 9 9"></path>\n    </svg>\n  `;if(r.innerHTML=a,i){const t=document.createElement("div");t.className="dds-loading-message",t.textContent=i,r.appendChild(t)}return o.appendChild(r),s.appendChild(o),t.appendChild(s),{element:s,updateMessage:t=>{let e=o.querySelector(".dds-loading-message");null!==t?e?e.textContent=t:(e=document.createElement("div"),e.className="dds-loading-message",e.textContent=t,r.appendChild(e)):null==e||e.remove()},hide:()=>{(null==s?void 0:s.parentNode)&&(s.classList.add("fade-out"),setTimeout(()=>{var t;null===(t=s.parentNode)||void 0===t||t.removeChild(s)},200))}}}class AU{showScannerLoadingOverlay(t){const e=dU(this.config.container);this.loadingScreen=PU(e,{message:t}),e.style.display="block",e.style.position="relative"}hideScannerLoadingOverlay(t=!1){var e;null===(e=this.loadingScreen)||void 0===e||e.hide(),t&&(dU(this.config.container).style.display="none")}getMinVerifiedFramesForAutoCapture(){var t,e,i,n;return!(null===(t=this.config)||void 0===t?void 0:t.minVerifiedFramesForAutoCapture)||(null===(e=this.config)||void 0===e?void 0:e.minVerifiedFramesForAutoCapture)<=0||(null===(i=this.config)||void 0===i?void 0:i.minVerifiedFramesForAutoCapture)>5?2:null===(n=this.config)||void 0===n?void 0:n.minVerifiedFramesForAutoCapture}constructor(t,e){var i,n;this.resources=t,this.config=e,this.boundsDetectionEnabled=!0,this.smartCaptureEnabled=!1,this.autoCropEnabled=!1,this.isCapturing=!1,this.isClosing=!1,this.resizeTimer=null,this.lastCaptureTimestamp=0,this.CONTINUOUS_SCAN_COOLDOWN_MS=2e3,this.frameVerificationEnabled=!0,this.currentFrameId=0,this.maxClarity=0,this.maxClarityTimestamp=0,this.maxClarityImg=null,this.maxClarityFrameId=0,this.nonImprovingClarityFrameCount=0,this.clearestFrameId=0,this.clarityHistory=[],this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,closeScannerBtn:null,takePhotoBtn:null,boundsDetectionBtn:null,smartCaptureBtn:null,autoCropBtn:null,continuousScanDoneBtn:null,thumbnailPreview:null,thumbnailImg:null,floatingImage:null,floatingImageImg:null},this.loadingScreen=null,this.toastObserver=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>{this.toggleScanGuide(!0)},500)},this.config.utilizedTemplateNames={detect:(null===(i=e.utilizedTemplateNames)||void 0===i?void 0:i.detect)||aU,normalize:(null===(n=e.utilizedTemplateNames)||void 0===n?void 0:n.normalize)||lU}}async initialize(){var t,e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x,w;if(this.boundsDetectionEnabled=null===(o=null!==(n=null!==(e=null===(t=this.config)||void 0===t?void 0:t.enableBoundsDetectionMode)&&void 0!==e?e:null===(i=this.config)||void 0===i?void 0:i.enableSmartCaptureMode)&&void 0!==n?n:null===(s=this.config)||void 0===s?void 0:s.enableAutoCropMode)||void 0===o||o,this.smartCaptureEnabled=null!==(l=(null===(r=this.config)||void 0===r?void 0:r.enableSmartCaptureMode)||(null===(a=this.config)||void 0===a?void 0:a.enableAutoCropMode))&&void 0!==l&&l,this.autoCropEnabled=null!==(c=null===(h=this.config)||void 0===h?void 0:h.enableAutoCropMode)&&void 0!==c&&c,this.frameVerificationEnabled=null===(u=null===(d=this.config)||void 0===d?void 0:d.enableFrameVerification)||void 0===u||u,this.config.minVerifiedFramesForAutoCapture=this.getMinVerifiedFramesForAutoCapture(),!this.initialized){pU("dds-loading-screen-style",'\n  .dds-loading-screen {\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    background-color: #323234;\n    z-index: 998;\n    opacity: 1;\n    transition: opacity 0.2s ease-out;\n  }\n\n  .dds-loading-screen.fade-out {\n    opacity: 0;\n  }\n\n  .dds-loading {\n    position: absolute;\n    left: 50%;\n    top: 50%;\n    color: white;\n    z-index: 999;\n    transform: translate(-50%, -50%);\n  }\n\n  .dds-loading-content {\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    gap: 16px;\n  }\n\n  .dds-loading svg {\n    animation: spin 1s linear infinite;\n  }\n\n  .dds-loading-message {\n    color: white;\n    font-family: "Verdana";\n    font-size: 14px;\n    text-align: center;\n    max-width: 200px;\n    line-height: 1.4;\n    opacity: 0.9;\n  }\n\n  @keyframes spin {\n    from {\n      transform: rotate(0deg);\n    }\n    to {\n      transform: rotate(360deg);\n    }\n  }\n');try{const{cameraView:t,cameraEnhancer:e,cvRouter:i}=this.resources;t.setScanRegionMaskStyle(Object.assign(Object.assign({},t.getScanRegionMaskStyle()),{lineWidth:null!==(m=null===(f=null===(g=null===(p=this.config)||void 0===p?void 0:p.scanRegion)||void 0===g?void 0:g.style)||void 0===f?void 0:f.strokeWidth)&&void 0!==m?m:2,strokeStyle:null!==(w=null===(x=null===(y=null===(v=this.config)||void 0===v?void 0:v.scanRegion)||void 0===y?void 0:y.style)||void 0===x?void 0:x.strokeColor)&&void 0!==w?w:"transparent"})),t.setVideoFit("cover"),i.setInput(e);const n=new tU;n.enableResultCrossVerification(zD.CRIT_DETECTED_QUAD,!0),n.enableResultDeduplication(zD.CRIT_DETECTED_QUAD,!0),await i.addResultFilter(n),this.config.templateFilePath&&await i.initSettings(this.config.templateFilePath);let s=await i.getSimplifiedSettings(this.config.utilizedTemplateNames.detect);s.outputOriginalImage=!0,s.documentSettings.scaleDownThreshold=1e3,await i.updateSettings(this.config.utilizedTemplateNames.detect,s),i.maxImageSideLength=1/0;const o=new yk;o.onCapturedResultReceived=t=>this.handleBoundsDetection(t),await i.addResultReceiver(o),this.initialized=!0}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:hU.RS_FAILED,message:"DDS Init error"}};this.currentScanResolver(i)}}}async initializeElements(){var t,e;const i=dU(this.config.container),n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");this.DCE_ELEMENTS={selectCameraBtn:n.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:n.shadowRoot.querySelector(".dce-mn-upload-image-icon"),closeScannerBtn:n.shadowRoot.querySelector(".dce-mn-close"),takePhotoBtn:n.shadowRoot.querySelector(".dce-mn-take-photo"),boundsDetectionBtn:n.shadowRoot.querySelector(".dce-mn-bounds-detection"),smartCaptureBtn:n.shadowRoot.querySelector(".dce-mn-smart-capture"),autoCropBtn:n.shadowRoot.querySelector(".dce-mn-auto-crop"),continuousScanDoneBtn:n.shadowRoot.querySelector(".dce-mn-continuous-scan-done-btn"),thumbnailPreview:n.shadowRoot.querySelector(".dce-mn-thumbnail-preview"),thumbnailImg:n.shadowRoot.querySelector(".dce-mn-thumbnail-img"),floatingImage:n.shadowRoot.querySelector(".dce-mn-floating-image"),floatingImageImg:n.shadowRoot.querySelector(".dce-mn-floating-image-img")},this.assignDCEClickEvents(),this.setupSmartToastFilter(n.shadowRoot),!1===this.config._showCorrectionView&&(this.DCE_ELEMENTS.smartCaptureBtn.style.display="none"),!1===(null===(t=this.config)||void 0===t?void 0:t.showSubfooter)&&(n.shadowRoot.querySelector(".dce-subfooter").style.display="none"),!1===(null===(e=this.config)||void 0===e?void 0:e.showPoweredByDynamsoft)&&(n.shadowRoot.querySelector(".dce-mn-msg-poweredby").style.display="none"),this.resources.onThumbnailClicked&&this.DCE_ELEMENTS.thumbnailPreview&&(this.DCE_ELEMENTS.thumbnailPreview.style.border="2px solid #fe8e14",this.DCE_ELEMENTS.thumbnailPreview.style.cursor="pointer"),this.initializedDCE=!0}assignDCEClickEvents(){var t,e,i,n,s;if(![this.DCE_ELEMENTS.selectCameraBtn,this.DCE_ELEMENTS.uploadImageBtn,this.DCE_ELEMENTS.closeScannerBtn,this.DCE_ELEMENTS.takePhotoBtn,this.DCE_ELEMENTS.boundsDetectionBtn,this.DCE_ELEMENTS.smartCaptureBtn,this.DCE_ELEMENTS.autoCropBtn].every(Boolean))throw new Error("Camera control elements not found");this.takePhoto=this.takePhoto.bind(this),this.toggleBoundsDetection=this.toggleBoundsDetection.bind(this),this.toggleSmartCapture=this.toggleSmartCapture.bind(this),this.toggleAutoCrop=this.toggleAutoCrop.bind(this),this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.takePhotoBtn.onclick=this.takePhoto,this.DCE_ELEMENTS.boundsDetectionBtn.onclick=async()=>{await this.toggleBoundsDetection()},this.DCE_ELEMENTS.smartCaptureBtn.onclick=async()=>{await this.toggleSmartCapture()},this.DCE_ELEMENTS.autoCropBtn.onclick=async()=>{await this.toggleAutoCrop()},this.DCE_ELEMENTS.closeScannerBtn.onclick=async()=>{await this.handleCloseBtn()},this.DCE_ELEMENTS.selectCameraBtn.onclick=t=>{t.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>{this.uploadImage()},this.DCE_ELEMENTS.continuousScanDoneBtn&&(this.DCE_ELEMENTS.continuousScanDoneBtn.onclick=()=>{this.handleContinuousScanDone()}),null===(t=this.DCE_ELEMENTS.thumbnailPreview)||void 0===t||t.addEventListener("touchstart",t=>{t.preventDefault()},{passive:!1}),null===(e=this.DCE_ELEMENTS.thumbnailPreview)||void 0===e||e.addEventListener("touchend",t=>{t.preventDefault()},{passive:!1}),null===(i=this.DCE_ELEMENTS.thumbnailPreview)||void 0===i||i.addEventListener("dblclick",t=>{t.preventDefault()}),null===(n=this.DCE_ELEMENTS.thumbnailPreview)||void 0===n||n.addEventListener("click",async t=>{t.preventDefault(),this.resources.onThumbnailClicked&&this.resources.result&&await this.resources.onThumbnailClicked(this.resources.result)});const o=dU(this.config.container).children[dU(this.config.container).children.length-1],r=null===(s=null==o?void 0:o.shadowRoot)||void 0===s?void 0:s.querySelector(".dce-mn-torch");r&&(r.addEventListener("touchstart",t=>{t.preventDefault()},{passive:!1}),r.addEventListener("touchend",t=>{t.preventDefault()},{passive:!1}),r.addEventListener("dblclick",t=>{t.preventDefault()}))}handleContinuousScanDone(){var t;this.isCapturing||this.isClosing||(this.isClosing=!0,this.closeCamera(),null===(t=this.currentScanResolver)||void 0===t||t.call(this,{status:{code:hU.RS_CANCELLED,message:"Continuous scanning stopped by user"}}))}updateContinuousScanDoneButton(){var t;if(!this.DCE_ELEMENTS.continuousScanDoneBtn)return;this.resources.completedScansCount>0?this.DCE_ELEMENTS.continuousScanDoneBtn.style.display="block":this.DCE_ELEMENTS.continuousScanDoneBtn.style.display="none";const e=null===(t=this.DCE_ELEMENTS.continuousScanDoneBtn)||void 0===t?void 0:t.querySelector(".dce-mn-continuous-scan-done-text");e&&(e.textContent=`Done (${this.resources.completedScansCount||0})`)}updateThumbnail(t){if(!this.DCE_ELEMENTS.thumbnailPreview||!this.DCE_ELEMENTS.thumbnailImg)return;if(!this.resources.enableContinuousScanning)return;const e=t.toDataURL("image/jpeg",.8);this.DCE_ELEMENTS.thumbnailImg.src=e,this.DCE_ELEMENTS.thumbnailPreview.style.display="block"}isIOS(){return/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1}setupSmartToastFilter(t){const e=t.querySelector(".dce-mn-toast");if(!e)return;const i=()=>{var t,i;const n=(null===(t=e.textContent)||void 0===t?void 0:t.trim())||"";if("Torch Not Supported"===n){const{cameraEnhancer:n}=this.resources;if(null==n?void 0:n.isOpen())try{const t=null===(i=n.getCapabilities)||void 0===i?void 0:i.call(n);if(null==t?void 0:t.torch)return void(e.style.display="none")}catch(t){console.warn("Error checking torch capabilities:",t)}}e.style.display=n?"":"none"};this.toastObserver=new MutationObserver(()=>{i()}),this.toastObserver.observe(e,{childList:!0,characterData:!0,subtree:!0}),i()}async animateFloatingImage(t){return new Promise(e=>{if(!(this.DCE_ELEMENTS.floatingImage&&this.DCE_ELEMENTS.floatingImageImg&&this.DCE_ELEMENTS.thumbnailPreview&&this.DCE_ELEMENTS.thumbnailImg))return void e();const i=t.toDataURL("image/jpeg",.9);this.DCE_ELEMENTS.floatingImageImg.src=i,this.DCE_ELEMENTS.thumbnailImg.style.opacity="0",this.DCE_ELEMENTS.floatingImage.style.display="block",this.DCE_ELEMENTS.floatingImage.classList.remove("animating"),requestAnimationFrame(()=>{if(!this.DCE_ELEMENTS.floatingImage||!this.DCE_ELEMENTS.thumbnailPreview)return void e();const t=this.DCE_ELEMENTS.floatingImage.getBoundingClientRect(),i=this.DCE_ELEMENTS.thumbnailPreview.getBoundingClientRect(),n=t.left+t.width/2,s=t.top+t.height/2,o=i.left+i.width/2-n,r=i.top+i.height/2-s,a=Math.min(i.width/t.width,i.height/t.height);this.DCE_ELEMENTS.floatingImage.style.setProperty("--translate-x",`${o}px`),this.DCE_ELEMENTS.floatingImage.style.setProperty("--translate-y",`${r}px`),this.DCE_ELEMENTS.floatingImage.style.setProperty("--scale",`${a}`),this.DCE_ELEMENTS.floatingImage.offsetWidth,this.DCE_ELEMENTS.floatingImage.classList.add("animating"),setTimeout(()=>{this.DCE_ELEMENTS.floatingImage&&(this.DCE_ELEMENTS.floatingImage.style.display="none",this.DCE_ELEMENTS.floatingImage.classList.remove("animating")),this.DCE_ELEMENTS.thumbnailImg&&(this.DCE_ELEMENTS.thumbnailImg.style.opacity="1"),e()},500)})})}async handleCloseBtn(){var t;this.isCapturing?console.warn("Cannot close during image capture"):(this.closeCamera(),null===(t=this.currentScanResolver)||void 0===t||t.call(this,{status:{code:hU.RS_CANCELLED,message:"Cancelled"}}))}attachOptionClickListeners(){const t=dU(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...e.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...e.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach(t=>{t.onclick=()=>{var e,n;const s=t.getAttribute("data-device-id"),o=t.getAttribute("data-height"),r=t.getAttribute("data-width");s?null===(e=this.resources.cameraEnhancer)||void 0===e||e.selectCamera(s).then(()=>{this.toggleScanGuide(!0)}):o&&r&&(null===(n=this.resources.cameraEnhancer)||void 0===n||n.setResolution({width:parseInt(r),height:parseInt(o)}).then(()=>{this.toggleScanGuide(!0)})),"none"!==i.style.display&&this.toggleSelectCameraBox()}})}highlightCameraAndResolutionOption(){var t,e;const i=dU(this.config.container),n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const s=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),o=s.querySelectorAll(".dce-mn-camera-option"),r=s.querySelectorAll(".dce-mn-resolution-option"),a=null===(t=this.resources.cameraEnhancer)||void 0===t?void 0:t.getSelectedCamera(),l=null===(e=this.resources.cameraEnhancer)||void 0===e?void 0:e.getResolution();o.forEach(t=>{const e=t;e.getAttribute("data-device-id")===(null==a?void 0:a.deviceId)?e.style.border="2px solid #fe814a":e.style.border="none"});const h={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},c=function(t){const e=t.width*t.height,i=t.width/t.height;let n="480p",s=Number.MAX_VALUE;for(const[t,o]of Object.entries(fU)){const r=o.width*o.height,a=o.width/o.height,l=.7*Math.abs(r-e)+Math.abs(a-i)*r*.3;l<s&&(s=l,n=t)}return n}(l);r.forEach(t=>{const e=t,i=e.getAttribute("data-height");e.style.border=i===h[c]?"2px solid #fe814a":"none"})}toggleSelectCameraBox(){const t=dU(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),i.click(),this.toggleScanGuide(!0)}async uploadImage(){var t,e,i,n,s;const o=document.createElement("input");o.type="file",o.accept="image/png,image/jpeg",o.style.display="none",document.body.appendChild(o);try{this.showScannerLoadingOverlay("Processing image...");const r=await new Promise((t,e)=>{o.onchange=i=>{var n;const s=null===(n=i.target.files)||void 0===n?void 0:n[0];(null==s?void 0:s.type.startsWith("image/"))?t(s):e(new Error("Please select an image file"))},o.addEventListener("cancel",()=>this.hideScannerLoadingOverlay(!1)),o.click()});if(!r)return void this.hideScannerLoadingOverlay(!1);this.resources.enableContinuousScanning?this.resources.cvRouter.stopCapturing():this.closeCamera(!1);const{blob:a}=await this.fileToBlob(r);this.capturedResultItems=(await this.resources.cvRouter.capture(a,this.config.utilizedTemplateNames.detect)).items,this.originalImageData=null===(t=this.capturedResultItems[0])||void 0===t?void 0:t.imageData;let l=null;if((null===(e=this.capturedResultItems)||void 0===e?void 0:e.length)<=1){this.capturedResultItems=[];const{width:t,height:e}=this.originalImageData;l={points:[{x:0,y:0},{x:t,y:0},{x:t,y:e},{x:0,y:e}],area:e*t}}else l=null===(i=this.capturedResultItems.find(t=>t.type===zD.CRIT_DETECTED_QUAD))||void 0===i?void 0:i.location;const h=await this.normalizeImage(l.points,this.originalImageData),c={status:{code:hU.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,correctedImageResult:h,detectedQuadrilateral:l,_flowType:cU.UPLOADED_IMAGE};if(null===(s=(n=this.resources).onResultUpdated)||void 0===s||s.call(n,c),this.resources.enableContinuousScanning){if(!this.config._showCorrectionView&&!this.config._showResultView){const t=h.toCanvas();this.updateThumbnail(t),await this.animateFloatingImage(t),await this.resources.cvRouter.startCapturing(this.config.utilizedTemplateNames.detect)}this.hideScannerLoadingOverlay(!1)}else this.hideScannerLoadingOverlay(!0);this.currentScanResolver(c)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:hU.RS_FAILED,message:"Error processing uploaded image"}};this.currentScanResolver(i)}finally{document.body.removeChild(o)}}async fileToBlob(t){return new Promise((e,i)=>{const n=new Image;n.onload=()=>{const s=document.createElement("canvas");s.width=n.width,s.height=n.height;const o=s.getContext("2d");null==o||o.drawImage(n,0,0),s.toBlob(t=>{t?e({blob:t,width:n.width,height:n.height}):i(new Error("Failed to create blob"))},t.type)},n.onerror=i,n.src=URL.createObjectURL(t)})}async toggleBoundsDetection(t){const e=dU(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-bounds-detection"),s=i.shadowRoot.querySelector(".dce-mn-bounds-detection-on"),o=i.shadowRoot.querySelector(".dce-mn-bounds-detection-off");if(!s||!o)return;const r=void 0!==t?t:!this.boundsDetectionEnabled;r||(await this.toggleSmartCapture(!1),!1===this.config._showCorrectionView&&await this.toggleAutoCrop(!1));const{cvRouter:a}=this.resources;this.boundsDetectionEnabled=r,n.style.color=this.boundsDetectionEnabled?"#fe814a":"#fff",o.style.display=this.boundsDetectionEnabled?"none":"block",s.style.display=this.boundsDetectionEnabled?"block":"none",this.initialized&&this.boundsDetectionEnabled?(await a.startCapturing(this.config.utilizedTemplateNames.detect),this.toggleScanGuide(!0)):this.initialized&&!this.boundsDetectionEnabled&&this.stopCapturing()}async toggleSmartCapture(t){const e=dU(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-smart-capture"),s=i.shadowRoot.querySelector(".dce-mn-smart-capture-on"),o=i.shadowRoot.querySelector(".dce-mn-smart-capture-off");if(!s||!o)return;const r=void 0!==t?t:!this.smartCaptureEnabled;r&&!this.boundsDetectionEnabled?await this.toggleBoundsDetection(!0):r||!1===this.config._showCorrectionView||await this.toggleAutoCrop(!1),this.smartCaptureEnabled=r,n.style.color=this.smartCaptureEnabled?"#fe814a":"#fff",o.style.display=this.smartCaptureEnabled?"none":"block",s.style.display=this.smartCaptureEnabled?"block":"none",this.crossVerificationCount=0}async toggleAutoCrop(t){const e=dU(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-auto-crop"),s=i.shadowRoot.querySelector(".dce-mn-auto-crop-on"),o=i.shadowRoot.querySelector(".dce-mn-auto-crop-off");if(!s||!o)return;const r=void 0!==t?t:!this.autoCropEnabled;!r||this.boundsDetectionEnabled&&this.smartCaptureEnabled||(await this.toggleBoundsDetection(!0),await this.toggleSmartCapture(!0)),r||!1!==this.config._showCorrectionView||await this.toggleSmartCapture(!1),this.autoCropEnabled=r,n.style.color=this.autoCropEnabled?"#fe814a":"#fff",o.style.display=this.autoCropEnabled?"none":"block",s.style.display=this.autoCropEnabled?"block":"none"}toggleScanGuide(t){var e,i;t&&!gU(null===(i=null===(e=this.config)||void 0===e?void 0:e.scanRegion)||void 0===i?void 0:i.ratio)&&this.calculateScanRegion()}calculateScanRegion(){var t,e,i,n,s;const{cameraEnhancer:o,cameraView:r}=this.resources;if(!(null==o?void 0:o.isOpen()))return;const a=r.getVisibleRegionOfVideo({inPixels:!0});if(!a)return;const l=r.getVideoElement(),h=l.videoWidth,c=l.videoHeight,d=null===(e=null===(t=this.config)||void 0===t?void 0:t.scanRegion)||void 0===e?void 0:e.ratio;let u;const p=null!==(s=null===(n=null===(i=this.config)||void 0===i?void 0:i.scanRegion)||void 0===n?void 0:n.regionBottomMargin)&&void 0!==s?s:0,g=a.height-p;a.width>a.height?(u=.75*g/d.height,u*d.width>.9*a.width&&(u=.9*a.width/d.width)):(u=.9*a.width/d.width,u*d.height>.75*g&&(u=.75*g/d.height));const f=u*d.width,m=u*d.height,v=(a.width-f)/2,y=(g-m)/2,x=v,w=v+f,C=y,b=y+m,S=(a.x+x)/h*100,T=(a.x+w)/h*100,E=(a.y+C)/c*100,_=(a.y+b)/c*100,P={left:Math.round(S),right:Math.round(T),top:Math.round(E),bottom:Math.round(_),isMeasuredInPercentage:!0};null==r||r.setScanRegionMaskVisible(!0),o.setScanRegion(P)}async openCamera(){try{const{cameraEnhancer:t,cameraView:e}=this.resources,i=dU(this.config.container);if(this.resources.enableContinuousScanning&&(null==t?void 0:t.isOpen()))return i.style.display="block",this.DCE_ELEMENTS.continuousScanDoneBtn&&(this.resources.completedScansCount>0?(this.DCE_ELEMENTS.continuousScanDoneBtn.style.display="block",this.updateContinuousScanDoneButton()):this.DCE_ELEMENTS.continuousScanDoneBtn.style.display="none"),void(this.resources.cvRouter._isPauseScan&&await this.resources.cvRouter.startCapturing(this.config.utilizedTemplateNames.detect));if(this.showScannerLoadingOverlay("Initializing camera..."),i.style.display="block",null==t?void 0:t.isOpen()){if(null==t?void 0:t.isPaused())try{await t.resume()}catch(t){console.warn("Camera error (openCamera - resume after pause):",t)}}else{const n=e.getUIElement();n.parentElement||i.append(n);try{await t.open()}catch(t){const e=(null==t?void 0:t.message)||t;if(e.includes("in use")||e.includes("not available"))throw new Error("Camera is already in use by another tab or application. Please close other tabs/applications using the camera and try again.");throw t}}if(null==t?void 0:t.isOpen())try{await t.setResolution({width:2560,height:1440})}catch(t){console.warn("Camera error (openCamera - setResolution):",t)}!this.initializedDCE&&(null==t?void 0:t.isOpen())&&await this.initializeElements(),window.addEventListener("resize",this.handleResize),await this.toggleBoundsDetection(this.boundsDetectionEnabled),await this.toggleSmartCapture(this.smartCaptureEnabled),await this.toggleAutoCrop(this.autoCropEnabled),this.DCE_ELEMENTS.continuousScanDoneBtn&&(this.resources.enableContinuousScanning&&this.resources.completedScansCount>0?(this.DCE_ELEMENTS.continuousScanDoneBtn.style.display="block",this.updateContinuousScanDoneButton()):this.DCE_ELEMENTS.continuousScanDoneBtn.style.display="none")}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:hU.RS_FAILED,message:"DDS Open Camera Error"}};this.currentScanResolver(i)}finally{this.hideScannerLoadingOverlay()}}closeCamera(t=!0){var e;window.removeEventListener("resize",this.handleResize),this.resizeTimer&&window.clearTimeout(this.resizeTimer),null===(e=this.toastObserver)||void 0===e||e.disconnect();const{cameraEnhancer:i,cameraView:n}=this.resources,s=dU(this.config.container);s.style.display=t?"none":"block",n.getUIElement().parentElement&&s.removeChild(n.getUIElement());try{null==i||i.close()}catch(t){console.warn("Camera error (closeCamera):",t)}this.stopCapturing(),this.isClosing=!1}pauseCamera(){const{cameraEnhancer:t}=this.resources;try{null==t||t.pause()}catch(t){console.warn("Camera error (pauseCamera):",t)}}stopCapturing(){const{cameraView:t,cvRouter:e}=this.resources;e.stopCapturing(),t.clearAllInnerDrawingItems()}getFlowType(){return this.autoCropEnabled?cU.AUTO_CROP:this.smartCaptureEnabled?cU.SMART_CAPTURE:cU.MANUAL}trackFrameClarity(t){++this.currentFrameId;const e=t._clarity;if(!e)return;const i=Date.now();this.maxClarityTimestamp<i-3e3&&(this.maxClarity=0),e>this.maxClarity&&(this.maxClarity=e,this.maxClarityTimestamp=i,this.maxClarityImg=this.originalImageData,this.maxClarityFrameId=this.currentFrameId,this.nonImprovingClarityFrameCount=0),e<=this.clarityHistory[this.clarityHistory.length-1]?++this.nonImprovingClarityFrameCount:this.nonImprovingClarityFrameCount=0,this.clearestFrameId!=this.maxClarityFrameId&&this.maxClarityTimestamp+1e3<=i&&this.nonImprovingClarityFrameCount>=2&&(this.clearestFrameId=this.maxClarityFrameId),this.clarityHistory.push(e),this.clarityHistory.length>50&&this.clarityHistory.shift()}async takePhoto(){var t,e,i,n,s,o,r,a,l;if(!this.isCapturing){this.isCapturing=!0;try{const{cameraEnhancer:l,onResultUpdated:h}=this.resources,c=!this.boundsDetectionEnabled||this.boundsDetectionEnabled&&(null===(t=this.capturedResultItems)||void 0===t?void 0:t.length)<=1;this.frameVerificationEnabled&&this.maxClarityImg&&!c?this.originalImageData=this.maxClarityImg:this.originalImageData=c?null==l?void 0:l.fetchImage():this.originalImageData;let d=null,u=null;if(c){this.capturedResultItems=[];const{width:t,height:e}=this.originalImageData;u={points:[{x:0,y:0},{x:t,y:0},{x:t,y:e},{x:0,y:e}],area:e*t}}else u=null===(e=this.capturedResultItems.find(t=>t.type===zD.CRIT_DETECTED_QUAD))||void 0===e?void 0:e.location;gU(null===(n=null===(i=this.config)||void 0===i?void 0:i.scanRegion)||void 0===n?void 0:n.ratio)||c||(u.points=u.points.map(t=>{var e;return(null===(e=this.resources.cameraEnhancer)||void 0===e?void 0:e.convertToScanRegionCoordinates(t))||t}));const p=this.getFlowType();this.resources.enableContinuousScanning?(this.DCE_ELEMENTS.takePhotoBtn&&(this.DCE_ELEMENTS.takePhotoBtn.style.pointerEvents="none",this.DCE_ELEMENTS.takePhotoBtn.style.opacity="0.5"),this.DCE_ELEMENTS.continuousScanDoneBtn&&(this.DCE_ELEMENTS.continuousScanDoneBtn.style.pointerEvents="none",this.DCE_ELEMENTS.continuousScanDoneBtn.style.opacity="0.5")):this.showScannerLoadingOverlay("Processing image..."),this.resources.enableContinuousScanning&&(null===(s=this.resources.cameraEnhancer)||void 0===s||s.pause()),d=await this.normalizeImage(u.points,this.originalImageData),this.resources.enableContinuousScanning&&await(null===(o=this.resources.cameraEnhancer)||void 0===o?void 0:o.resume()),this.resources.enableContinuousScanning||(await this.toggleSmartCapture(!1),this.closeCamera()),this.resources.enableContinuousScanning?(this.DCE_ELEMENTS.takePhotoBtn&&(this.DCE_ELEMENTS.takePhotoBtn.style.pointerEvents="auto",this.DCE_ELEMENTS.takePhotoBtn.style.opacity="1"),this.DCE_ELEMENTS.continuousScanDoneBtn&&(this.DCE_ELEMENTS.continuousScanDoneBtn.style.pointerEvents="auto",this.DCE_ELEMENTS.continuousScanDoneBtn.style.opacity="1")):this.hideScannerLoadingOverlay(!0);const g={status:{code:hU.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,correctedImageResult:d,detectedQuadrilateral:u,_flowType:p};if(this.resources.enableContinuousScanning&&!this.config._showCorrectionView&&!this.config._showResultView){const t=d.toCanvas();this.updateThumbnail(t),null===(r=this.resources.cameraEnhancer)||void 0===r||r.pause(),await this.animateFloatingImage(t),await(null===(a=this.resources.cameraEnhancer)||void 0===a?void 0:a.resume())}null==h||h(g),this.currentScanResolver(g)}catch(t){let e=(null==t?void 0:t.message)||t;if(console.error(e),alert(e),this.resources.enableContinuousScanning){if(this.DCE_ELEMENTS.takePhotoBtn&&(this.DCE_ELEMENTS.takePhotoBtn.style.pointerEvents="auto",this.DCE_ELEMENTS.takePhotoBtn.style.opacity="1"),this.DCE_ELEMENTS.continuousScanDoneBtn&&(this.DCE_ELEMENTS.continuousScanDoneBtn.style.pointerEvents="auto",this.DCE_ELEMENTS.continuousScanDoneBtn.style.opacity="1"),null===(l=this.resources.cameraEnhancer)||void 0===l?void 0:l.isPaused())try{await this.resources.cameraEnhancer.resume()}catch(t){console.warn("Camera error (after correction/result - resume):",t)}}else this.closeCamera();const i={status:{code:hU.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(i)}finally{this.isCapturing=!1}}}async handleBoundsDetection(t){var e,i;if(this.capturedResultItems=t.items,!(null===(e=t.items)||void 0===e?void 0:e.length))return;const n=t.items.filter(t=>t.type===zD.CRIT_ORIGINAL_IMAGE);this.originalImageData=null===(i=n[0])||void 0===i?void 0:i.imageData,this.frameVerificationEnabled&&this.boundsDetectionEnabled&&this.trackFrameClarity(t),(this.smartCaptureEnabled||this.autoCropEnabled)&&this.handleAutoCaptureMode(t)}async handleAutoCaptureMode(t){var e,i,n,s;if(t.items.length<=1)this.crossVerificationCount=0;else{if(this.resources.enableContinuousScanning&&Date.now()-this.lastCaptureTimestamp<this.CONTINUOUS_SCAN_COOLDOWN_MS)return;1===(null===(n=null===(i=null===(e=t.processedDocumentResult)||void 0===e?void 0:e.detectedQuadResultItems)||void 0===i?void 0:i[0])||void 0===n?void 0:n.crossVerificationStatus)&&this.crossVerificationCount++,this.crossVerificationCount>=(null===(s=this.config)||void 0===s?void 0:s.minVerifiedFramesForAutoCapture)&&(this.crossVerificationCount=0,this.lastCaptureTimestamp=Date.now(),await this.takePhoto())}}async launch(){try{await this.initialize();const{cvRouter:t,cameraEnhancer:e}=this.resources;return new Promise(async i=>{if(this.currentScanResolver=i,await this.openCamera(),this.boundsDetectionEnabled&&await t.startCapturing(this.config.utilizedTemplateNames.detect),this.toggleScanGuide(!0),null==e?void 0:e.isOpen())try{e.setPixelFormat(iD.IPF_ABGR_8888)}catch(t){console.warn("Camera error (takePhoto - setPixelFormat):",t)}this.crossVerificationCount=0})}catch(t){let e=(null==t?void 0:t.message)||t;console.error("DDS Launch error: ",e),this.closeCamera();const i={status:{code:hU.RS_FAILED,message:"DDS Launch error"}};this.currentScanResolver(i)}}async normalizeImage(t,e){var i,n;const{cvRouter:s,cameraEnhancer:o}=this.resources,r=await s.getSimplifiedSettings(this.config.utilizedTemplateNames.normalize);r.roiMeasuredInPercentage=!1,r.roi.points=t,await s.updateSettings(this.config.utilizedTemplateNames.normalize,r);const a=await s.capture(e,this.config.utilizedTemplateNames.normalize);if(null===(n=null===(i=null==a?void 0:a.processedDocumentResult)||void 0===i?void 0:i.deskewedImageResultItems)||void 0===n?void 0:n[0])return a.processedDocumentResult.deskewedImageResultItems[0]}}class IU{constructor(t,e,i,n){this.resources=t,this.config=e,this.scannerView=i,this.correctionView=n}async launch(){try{return dU(this.config.container).textContent="",await this.initialize(),dU(this.config.container).style.display="flex",new Promise(t=>{this.currentScanResultViewResolver=t})}catch(t){let e=(null==t?void 0:t.message)||t;throw console.error(e),e}}async handleUploadAndShareBtn(t){var e;try{const{result:i}=this.resources;if(!(null==i?void 0:i.correctedImageResult))throw new Error("No image to upload");"upload"===t&&(null===(e=this.config)||void 0===e?void 0:e.onUpload)?await this.config.onUpload(i):"share"===t&&await this.handleShare()}catch(t){console.error("Error on upload/share:",t),alert("Failed")}}async handleShare(){var t,e;try{const{result:i}=this.resources;if(!(null==i?void 0:i.correctedImageResult))throw new Error("No image result provided");const n=await i.correctedImageResult.toBlob("image/png");if(!n)throw new Error("Failed to convert image to blob");const s=new File([n],`document-${Date.now()}.png`,{type:n.type});if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&navigator.share&&null!==(e=null===(t=navigator.canShare)||void 0===t?void 0:t.call(navigator,{files:[s]}))&&void 0!==e&&e)try{return await navigator.share({files:[s],title:"Dynamsoft Document Scanner Shared Image"}),!0}catch(t){if("AbortError"===t.name)return!0;"NotAllowedError"===t.name?console.log("Share permission denied, falling back to download"):"TypeError"===t.name?console.log("File type not supported for sharing, falling back to download"):"DataError"===t.name?console.log("Share target error, falling back to download"):console.warn("Share failed with unexpected error:",t)}const o=URL.createObjectURL(n),r=document.createElement("a");return r.href=o,r.download=s.name,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o),!0}catch(t){let e=(null==t?void 0:t.message)||t;console.error("Error in share/download process:",e),alert(`Error processing image: ${e}`)}}async handleCorrectImage(){var t,e,i;try{if(!this.correctionView)return void console.error("Correction View not initialized");this.hideView();const i=await this.correctionView.launch();i.correctedImageResult&&(null===(e=(t=this.resources).onResultUpdated)||void 0===e||e.call(t,Object.assign(Object.assign({},this.resources.result),{correctedImageResult:i.correctedImageResult})),this.dispose(!0),await this.initialize(),dU(this.config.container).style.display="flex")}catch(t){throw console.error("DocumentResultView - Handle Correction View Error:",t),null===(i=this.currentScanResultViewResolver)||void 0===i||i.call(this,{status:{code:hU.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}async handleRetake(){var t,e,i,n,s,o,r,a,l;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView(),this.scannerView&&(dU(this.scannerView.config.container).style.display="flex");const l=await this.scannerView.launch();if((null===(t=null==l?void 0:l.status)||void 0===t?void 0:t.code)===hU.RS_CANCELLED||(null===(e=null==l?void 0:l.status)||void 0===e?void 0:e.code)===hU.RS_FAILED)return void(null===(i=this.currentScanResultViewResolver)||void 0===i||i.call(this,l));if((null==l?void 0:l.status.code)===hU.RS_SUCCESS){if(null===(s=(n=this.resources).onResultUpdated)||void 0===s||s.call(n,l),this.scannerView&&this.scannerView.stopCapturing(),this.scannerView&&(dU(this.scannerView.config.container).style.display="none"),this.correctionView){this.dispose(!0);const t=await this.correctionView.launch();if((null===(o=null==t?void 0:t.status)||void 0===o?void 0:o.code)===hU.RS_CANCELLED||(null===(r=null==t?void 0:t.status)||void 0===r?void 0:r.code)===hU.RS_FAILED)return void(null===(a=this.currentScanResultViewResolver)||void 0===a||a.call(this,t))}this.dispose(!0),await this.initialize(),dU(this.config.container).style.display="flex"}}catch(t){throw console.error("Error in retake handler:",t),null===(l=this.currentScanResultViewResolver)||void 0===l||l.call(this,{status:{code:hU.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}async handleDone(){var t,e,i,n;try{await(null===(e=null===(t=this.config)||void 0===t?void 0:t.onDone)||void 0===e?void 0:e.call(t,this.resources.result)),null===(i=this.currentScanResultViewResolver)||void 0===i||i.call(this,this.resources.result),this.hideView(),this.dispose()}catch(t){throw console.error("Error in done handler:",t),null===(n=this.currentScanResultViewResolver)||void 0===n||n.call(this,{status:{code:hU.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}createControls(){var t,e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x;const{toolbarButtonsConfig:w,onUpload:C}=this.config,b=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),S=new Blob(["mock-png-data"],{type:"image/png"}),T=new File([S],"test.png",{type:"image/png"}),E=b&&"share"in navigator&&navigator.canShare({files:[T]});return uU([{id:"dds-scanResult-retake",icon:(null===(t=null==w?void 0:w.retake)||void 0===t?void 0:t.icon)||bU,label:(null===(e=null==w?void 0:w.retake)||void 0===e?void 0:e.label)||"Re-take",onClick:()=>this.handleRetake(),className:`${(null===(i=null==w?void 0:w.retake)||void 0===i?void 0:i.className)||""}`,isHidden:(null===(n=null==w?void 0:w.retake)||void 0===n?void 0:n.isHidden)||!1,isDisabled:!this.scannerView},{id:"dds-scanResult-correct",icon:(null===(s=null==w?void 0:w.correct)||void 0===s?void 0:s.icon)||CU,label:(null===(o=null==w?void 0:w.correct)||void 0===o?void 0:o.label)||"Correction",onClick:()=>this.handleCorrectImage(),className:`${(null===(r=null==w?void 0:w.correct)||void 0===r?void 0:r.className)||""}`,isHidden:(null===(a=null==w?void 0:w.correct)||void 0===a?void 0:a.isHidden)||!1,isDisabled:!this.correctionView},{id:"dds-scanResult-share",icon:(null===(l=null==w?void 0:w.share)||void 0===l?void 0:l.icon)||(E?wU:TU),label:(null===(h=null==w?void 0:w.share)||void 0===h?void 0:h.label)||(E?"Share":"Download"),className:`${(null===(c=null==w?void 0:w.share)||void 0===c?void 0:c.className)||""}`,isHidden:(null===(d=null==w?void 0:w.share)||void 0===d?void 0:d.isHidden)||!1,onClick:()=>this.handleUploadAndShareBtn("share")},{id:"dds-scanResult-upload",icon:(null===(u=null==w?void 0:w.upload)||void 0===u?void 0:u.icon)||xU,label:(null===(p=null==w?void 0:w.upload)||void 0===p?void 0:p.label)||"Upload",className:`${(null===(g=null==w?void 0:w.upload)||void 0===g?void 0:g.className)||""}`,isHidden:!C||(null===(f=null==w?void 0:w.upload)||void 0===f?void 0:f.isHidden)||!1,isDisabled:!C,onClick:()=>this.handleUploadAndShareBtn("upload")},{id:"dds-scanResult-done",icon:(null===(m=null==w?void 0:w.done)||void 0===m?void 0:m.icon)||SU,label:(null===(v=null==w?void 0:w.done)||void 0===v?void 0:v.label)||(this.resources.enableContinuousScanning?"Keep Scan":"Done"),className:`${(null===(y=null==w?void 0:w.done)||void 0===y?void 0:y.className)||""}`,isHidden:(null===(x=null==w?void 0:w.done)||void 0===x?void 0:x.isHidden)||!1,onClick:()=>this.handleDone()}])}async initialize(){var t;try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");pU("dds-result-view-style",DU);const e=document.createElement("div");e.className="dds-result-view-container";const i=document.createElement("div");Object.assign(i.style,{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",minHeight:"0"});const n=null===(t=this.resources.result.correctedImageResult)||void 0===t?void 0:t.toCanvas();Object.assign(n.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),i.appendChild(n),e.appendChild(i);const s=this.createControls();e.appendChild(s),dU(this.config.container).appendChild(e),this.resources.result._flowType===cU.STATIC_FILE&&(document.querySelector("#dds-scanResult-retake").style.display="none")}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e)}}hideView(){dU(this.config.container).style.display="none"}dispose(t=!1){dU(this.config.container).textContent="",t||(this.currentScanResultViewResolver=void 0)}}const DU="\n  .dds-result-view-container {\n    display: flex;\n    width: 100%;\n    height: 100%;\n    background-color:#575757;\n    font-size: 12px;\n    flex-direction: column;\n    align-items: center;\n  }\n\n  @media (orientation: landscape) and (max-width: 1024px) {\n    .dds-result-view-container {\n      flex-direction: row;\n    }\n  }\n",RU={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class kU{showScannerLoadingOverlay(t){const e=dU(this.config.scannerViewConfig.container);this.loadingScreen=PU(e,{message:t}),e.style.display="block",e.style.position="relative"}hideScannerLoadingOverlay(t=!1){var e;null===(e=this.loadingScreen)||void 0===e||e.hide(),t&&(dU(this.config.scannerViewConfig.container).style.display="none")}constructor(t){this.config=t,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.shouldStopContinuousScanning=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,correctionView:this.correctionView,scanResultView:this.scanResultView}};try{this.initializeDDSConfig(),await this.initializeDCVResources(),this.resources.onResultUpdated=t=>{this.resources.result=t},this.resources.enableContinuousScanning=this.config.enableContinuousScanning||!1,this.resources.completedScansCount=0,this.resources.onThumbnailClicked=this.config.onThumbnailClicked;const t={};return this.config.scannerViewConfig&&(this.scannerView=new AU(this.resources,this.config.scannerViewConfig),t.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.correctionViewConfig&&(this.correctionView=new EU(this.resources,this.config.correctionViewConfig,this.scannerView),t.correctionView=this.correctionView),this.config.resultViewConfig&&(this.scanResultView=new IU(this.resources,this.config.resultViewConfig,this.scannerView,this.correctionView),t.scanResultView=this.scanResultView),this.isInitialized=!0,{resources:this.resources,components:t}}catch(t){this.isInitialized=!1;let e=(null==t?void 0:t.message)||t;throw new Error(`Initialization Failed: ${e}`)}}async initializeDCVResources(){var t,e,i;try{wR.engineResourcePaths=gU(null===(t=this.config)||void 0===t?void 0:t.engineResourcePaths)?RU:this.config.engineResourcePaths,Vk._onAuthMessage=t=>t.replace("(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)","(https://www.dynamsoft.com/customer/license/trialLicense?product=mwc&deploymenttype=web)"),Vk.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",!0),wR.loadWasm(),this.resources.cameraView=await _O.createInstance(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath),this.resources.cameraEnhancer=await xB.createInstance(this.resources.cameraView),this.resources.cvRouter=await vk.createInstance()}catch(t){let e=(null==t?void 0:t.message)||t;throw new Error(`Resource Initialization Failed: ${e}`)}}shouldCreateDefaultContainer(){var t,e,i;const n=!this.config.container,s=!((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)||(null===(i=this.config.correctionViewConfig)||void 0===i?void 0:i.container));return n&&s}createDefaultDDSContainer(){const t=document.createElement("div");return t.className="dds-main-container",Object.assign(t.style,{display:"none",height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(t),t}checkForTemporaryLicense(t){return!(null==t?void 0:t.length)||(null==t?void 0:t.startsWith("A"))||(null==t?void 0:t.startsWith("L"))||(null==t?void 0:t.startsWith("P"))||(null==t?void 0:t.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":t}validateViewConfigs(){var t,e;if(!this.config.container&&!this.shouldCreateDefaultContainer()){if(this.config.showCorrectionView&&!(null===(t=this.config.correctionViewConfig)||void 0===t?void 0:t.container))throw new Error("CorrectionView container is required when showCorrectionView is true and no main container is provided");if(this.config.showResultView&&!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container))throw new Error("ResultView container is required when showResultView is true and no main container is provided")}}showCorrectionView(){var t,e;return!1!==this.config.showCorrectionView&&(this.config.container?!(void 0!==this.config.showCorrectionView||!(null===(t=this.config.correctionViewConfig)||void 0===t?void 0:t.container)&&!this.config.container)||!!this.config.showCorrectionView:this.config.showCorrectionView&&!!(null===(e=this.config.correctionViewConfig)||void 0===e?void 0:e.container))}showResultView(){var t,e;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container))}initializeDDSConfig(){var t,e,i,n,s,o,r;this.validateViewConfigs(),this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultDDSContainer():this.config.container&&(this.config.container=dU(this.config.container));const a=this.config.container?this.createViewContainers(dU(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:{detect:(null===(t=this.config.utilizedTemplateNames)||void 0===t?void 0:t.detect)||aU,normalize:(null===(e=this.config.utilizedTemplateNames)||void 0===e?void 0:e.normalize)||lU},templateFilePath:(null===(i=this.config)||void 0===i?void 0:i.templateFilePath)||null},h=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:a[oU.Scanner]||(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||null,cameraEnhancerUIPath:(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-document-scanner@1.4.2/dist/document-scanner.ui.xml",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,_showCorrectionView:this.showCorrectionView(),_showResultView:this.showResultView(),enableFrameVerification:!1!==this.config.enableFrameVerification}),c=this.showCorrectionView()?Object.assign(Object.assign({},this.config.correctionViewConfig),{container:a[oU.Correction]||(null===(o=this.config.correctionViewConfig)||void 0===o?void 0:o.container)||null,templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,_showResultView:this.showResultView()}):void 0,d=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:a[oU.Result]||(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)||null}):void 0;Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:h,correctionViewConfig:c,resultViewConfig:d}))}createViewContainers(t){t.textContent="";const e=[oU.Scanner];return this.showCorrectionView()&&e.push(oU.Correction),this.showResultView()&&e.push(oU.Result),e.reduce((e,i)=>{const n=document.createElement("div");return n.className=`dds-${i}-view-container`,Object.assign(n.style,{height:"100%",width:"100%",display:"none",position:"relative",userSelect:"none"}),t.append(n),e[i]=n,e},{})}stopContinuousScanning(){this.shouldStopContinuousScanning=!0}dispose(){var t,e,i,n,s,o,r,a;null===(t=this.scanResultView)||void 0===t||t.dispose(),null===(e=this.correctionView)||void 0===e||e.dispose(),this.scannerView=null,null===(i=this.resources.cameraEnhancer)||void 0===i||i.dispose(),null===(n=this.resources.cameraView)||void 0===n||n.dispose(),null===(s=this.resources.cvRouter)||void 0===s||s.dispose(),this.resources.result=null,this.resources.onResultUpdated=null;const l=t=>{const e=dU(t);e&&(e.style.display="none",e.textContent="")};l(this.config.container),l(null===(o=this.config.scannerViewConfig)||void 0===o?void 0:o.container),l(null===(r=this.config.correctionViewConfig)||void 0===r?void 0:r.container),l(null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container),this.isInitialized=!1}async processFileToBlob(t){return new Promise((e,i)=>{if(!t.type.startsWith("image/"))return void i(new Error("Please select an image file"));const n=new Image;n.onload=()=>{const s=document.createElement("canvas");s.width=n.width,s.height=n.height;const o=s.getContext("2d");null==o||o.drawImage(n,0,0),s.toBlob(t=>{t?e({blob:t,width:n.width,height:n.height}):i(new Error("Failed to create blob from image"))},t.type)},n.onerror=()=>i(new Error("Failed to load image")),n.src=URL.createObjectURL(t)})}async processUploadedFile(t){var e,i,n,s,o,r;try{this.showScannerLoadingOverlay("Processing image...");const{blob:a}=await this.processFileToBlob(t),l=(await this.resources.cvRouter.capture(a,this.config.utilizedTemplateNames.detect)).items,h=null===(e=l[0])||void 0===e?void 0:e.imageData;if(!h)throw new Error("Failed to extract image data");let c;if(l.length<=1){const{width:t,height:e}=h;c={points:[{x:0,y:0},{x:t,y:0},{x:t,y:e},{x:0,y:e}],area:e*t}}else c=null===(i=l.find(t=>t.type===zD.CRIT_DETECTED_QUAD))||void 0===i?void 0:i.location;const d=await this.resources.cvRouter.getSimplifiedSettings(this.config.utilizedTemplateNames.normalize);d.roiMeasuredInPercentage=!1,d.roi.points=c.points,await this.resources.cvRouter.updateSettings(this.config.utilizedTemplateNames.normalize,d);const u=await this.resources.cvRouter.capture(h,this.config.utilizedTemplateNames.normalize),p=null===(s=null===(n=null==u?void 0:u.processedDocumentResult)||void 0===n?void 0:n.deskewedImageResultItems)||void 0===s?void 0:s[0],g={status:{code:hU.RS_SUCCESS,message:"Success"},originalImageResult:h,correctedImageResult:p,detectedQuadrilateral:c,_flowType:cU.STATIC_FILE};null===(r=(o=this.resources).onResultUpdated)||void 0===r||r.call(o,g),this.hideScannerLoadingOverlay(!0)}catch(t){return console.error("Failed to process uploaded file:",t),{status:{code:hU.RS_FAILED,message:`Failed to process image: ${(null==t?void 0:t.message)||t}`}}}}async performSingleScan(t){var e;const{components:i}=await this.initialize();if(this.config.container&&(dU(this.config.container).style.display="block"),t&&(i.scannerView=null,await this.processUploadedFile(t)),!i.scannerView&&this.resources.result){if(i.correctionView&&!i.scanResultView)return await i.correctionView.launch();if(i.scanResultView&&!i.correctionView)return await i.scanResultView.launch();if(i.scanResultView&&i.correctionView)return await i.correctionView.launch(),await i.scanResultView.launch()}if(!i.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(i.scannerView){const t=await i.scannerView.launch();if((null==t?void 0:t.status.code)!==hU.RS_SUCCESS)return{status:{code:null==t?void 0:t.status.code,message:(null==t?void 0:t.status.message)||"Failed to capture image"}};if(i.scannerView&&(i.scannerView.stopCapturing(),(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&(dU(this.config.scannerViewConfig.container).style.display="none")),i.correctionView&&i.scanResultView&&(n=t._flowType,[cU.SMART_CAPTURE,cU.UPLOADED_IMAGE,cU.MANUAL].includes(n)))return await i.correctionView.launch(),await i.scanResultView.launch();if(i.correctionView&&!i.scanResultView)return await i.correctionView.launch();if(i.scanResultView)return await i.scanResultView.launch()}var n;return this.resources.result}async launch(t){var e,i,n,s;if(this.isCapturing)throw new Error("Capture session already in progress");try{if(this.isCapturing=!0,document.body.style.overflow="hidden",this.config.enableContinuousScanning){for(this.shouldStopContinuousScanning=!1;!this.shouldStopContinuousScanning;){const n=await this.performSingleScan(t);if(n.status.code===hU.RS_CANCELLED)break;if(n.status.code===hU.RS_FAILED)return n;n.status.code!==hU.RS_SUCCESS||(this.resources.completedScansCount++,await(null===(i=(e=this.config).onDocumentScanned)||void 0===i?void 0:i.call(e,n)))}return this.resources.result||{status:{code:hU.RS_CANCELLED,message:"Continuous scanning stopped"}}}const o=await this.performSingleScan(t);return o.status.code===hU.RS_SUCCESS&&await(null===(s=(n=this.config).onDocumentScanned)||void 0===s?void 0:s.call(n,o)),o}catch(t){return console.error("Document capture flow failed:",(null==t?void 0:t.message)||t),{status:{code:hU.RS_FAILED,message:`Document capture flow failed. ${(null==t?void 0:t.message)||t}`}}}finally{this.isCapturing=!1,document.body.style.overflow="",this.dispose()}}}const MU={DocumentScanner:kU,DocumentNormalizerView:EU,DocumentScannerView:AU,DocumentResultView:IU,EnumResultStatus:hU,EnumFlowType:cU,EnumDDSViews:oU};var LU=Object.freeze({__proto__:null,CameraEnhancer:xB,CameraEnhancerModule:class{static getVersion(){return"4.3.3-dev-20251029130621"}},CameraManager:IO,CameraView:_O,CaptureVisionRouter:vk,CaptureVisionRouterModule:WR,CapturedResultReceiver:yk,CoreModule:wR,DDS:MU,DocumentNormalizerModule:class{static getVersion(){const t=fR.ddn&&fR.ddn.wasm;return`4.2.20-dev-20251029130608(Worker: ${fR.ddn&&fR.ddn.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},DocumentNormalizerView:EU,DocumentResultView:IU,DocumentScanner:kU,DocumentScannerView:AU,get EnumBufferOverflowProtectionMode(){return tD},get EnumCapturedResultItemType(){return zD},get EnumErrorCode(){return YD},get EnumImagePixelFormat(){return iD},get EnumResultStatus(){return hU},ImageDrawer:class{async drawOnImage(t,e,i,n=4294901760,s=1,o="test.png",r){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await kN(t);else if("string"==typeof t){let e=await yD(t,"blob");a=await kN(e)}else dD(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,l)=>{let h=dR();uR[h]=async e=>{if(e.success)return r&&(new rU).saveToFile(e.image,o,r),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},hR.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:s,type:i}})})}},ImageIO:rU,ImageProcessor:class{async cropImage(t,e){const{bytes:i,width:n,height:s,stride:o,format:r}=await kN(t);return await new Promise((t,a)=>{let l=dR();uR[l]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},hR.postMessage({type:"utility_cropImage",id:l,body:{type:"Rect",bytes:i,width:n,height:s,stride:o,format:r,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:s,stride:o,format:r}=await kN(t);return await new Promise((t,a)=>{let l=dR();uR[l]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},hR.postMessage({type:"utility_adjustBrightness",id:l,body:{bytes:i,width:n,height:s,stride:o,format:r,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:s,stride:o,format:r}=await kN(t);return await new Promise((t,a)=>{let l=dR();uR[l]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},hR.postMessage({type:"utility_adjustContrast",id:l,body:{bytes:i,width:n,height:s,stride:o,format:r,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:s,stride:o,format:r}=await kN(t);return await new Promise((t,a)=>{let l=dR();uR[l]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},hR.postMessage({type:"utility_filterImage",id:l,body:{bytes:i,width:n,height:s,stride:o,format:r,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:s,width:o,height:r,stride:a,format:l}=await kN(t);return await new Promise((t,h)=>{let c=dR();uR[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},hR.postMessage({type:"utility_convertToGray",id:c,body:{bytes:s,width:o,height:r,stride:a,format:l,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:s,height:o,stride:r,format:a}=await kN(t);return await new Promise((t,l)=>{let h=dR();uR[h]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},hR.postMessage({type:"utility_convertToBinaryGlobal",id:h,body:{bytes:n,width:s,height:o,stride:r,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:s,width:o,height:r,stride:a,format:l}=await kN(t);return await new Promise((t,h)=>{let c=dR();uR[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},hR.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:s,width:o,height:r,stride:a,format:l,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:s,stride:o,format:r}=await kN(t);return await new Promise((t,a)=>{let l=dR();uR[l]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},hR.postMessage({type:"utility_cropAndDeskewImage",id:l,body:{bytes:i,width:n,height:s,stride:o,format:r,roi:e}})})}},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=QD.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.onScaledColourImageUnitReceived=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}},LicenseManager:Vk,LicenseModule:class{static getVersion(){return`4.2.20-dev-20251029130543(Worker: ${fR.license&&fR.license.worker||"Not Loaded"}, Wasm: ${fR.license&&fR.license.wasm||"Not Loaded"})`}},MultiFrameResultCrossFilter:tU,UtilityModule:class{static getVersion(){return`2.2.20-dev-20251029130550(Worker: ${fR.utility&&fR.utility.worker||"Not Loaded"}, Wasm: ${fR.utility&&fR.utility.wasm||"Not Loaded"})`}},handleEngineResourcePaths:wD,innerVersions:fR,isDSImageData:dD,isDSRect:uD,isPoint:gD,isQuad:mD});const OU={cameraCapture:'\n  <svg id="camera-capture" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="28" height="24" viewBox="0 0 28 24">\n    <defs>\n      <clipPath id="cameraCaptureclip-path">\n        <rect id="Rectangle_2738" data-name="Rectangle 2738" width="28" height="24" fill="#fff"/>\n      </clipPath>\n    </defs>\n    <g id="Group_529" data-name="Group 529" clip-path="url(#cameraCaptureclip-path)">\n      <path id="Path_1455" data-name="Path 1455" d="M24.37,4.174H21.287a1.672,1.672,0,0,1-1.224-.635L18.387,1.066A2.726,2.726,0,0,0,16.356,0H11.615A2.725,2.725,0,0,0,9.6,1.09L7.5,4.174l-3.927,0A3.978,3.978,0,0,0,0,8.206V20.348A3.645,3.645,0,0,0,3.63,24H24.37A3.645,3.645,0,0,0,28,20.348V8.212a3.99,3.99,0,0,0-3.63-4.038m2.593,16.174a2.6,2.6,0,0,1-2.593,2.609H3.63a2.6,2.6,0,0,1-2.592-2.609V8.2A2.935,2.935,0,0,1,3.63,5.218H7.778a.521.521,0,0,0,.429-.228L10.436,1.7a1.663,1.663,0,0,1,1.208-.657h4.683a1.665,1.665,0,0,1,1.221.635l1.676,2.474a2.735,2.735,0,0,0,2.033,1.066l3.06,0a2.946,2.946,0,0,1,2.646,2.991Z" fill="#fff"/>\n      <path id="Path_1456" data-name="Path 1456" d="M14,8.348a5.739,5.739,0,1,0,5.7,5.739A5.729,5.729,0,0,0,14,8.348m0,10.435a4.7,4.7,0,1,1,4.667-4.7A4.687,4.687,0,0,1,14,18.783" fill="#fff"/>\n    </g>\n  </svg>\n  ',galleryImport:'\n  <svg id="gallery-import" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n    <defs>\n      <clipPath id="galleryImportclip-path">\n        <rect id="Rectangle_2739" data-name="Rectangle 2739" width="24" height="24" fill="#fff"/>\n      </clipPath>\n    </defs>\n    <g id="Group_531" data-name="Group 531" clip-path="url(#galleryImportclip-path)">\n      <path id="Path_1457" data-name="Path 1457" d="M19.7,18.1V1.6A1.6,1.6,0,0,0,18.1,0H1.6A1.6,1.6,0,0,0,0,1.6V18.1a1.6,1.6,0,0,0,1.6,1.6H18.1a1.6,1.6,0,0,0,1.6-1.6M1.6,1H18.1a.6.6,0,0,1,.6.6V15.4H16.236L13.472,8.489c-.258-.659-.695-.74-.872-.745a1.019,1.019,0,0,0-.911.7L9.722,12.768l-1.5-1.8A1.236,1.236,0,0,0,7.1,10.427a1.211,1.211,0,0,0-1,.659L3.516,15.4H1V1.6A.6.6,0,0,1,1.6,1M15.159,15.4H4.682l2.3-3.842a.236.236,0,0,1,.194-.134.273.273,0,0,1,.241.142L9.464,14.02a.5.5,0,0,0,.839-.113L12.57,8.924ZM1,18.1V16.4H18.7v1.7a.6.6,0,0,1-.6.6H1.6a.6.6,0,0,1-.6-.6" fill="#fff"/>\n      <path id="Path_1458" data-name="Path 1458" d="M22.55,6.571l-1.1-.1a.5.5,0,0,0-.091,1l1.1.1a.6.6,0,0,1,.541.65l-1.3,14.24a.6.6,0,0,1-.653.54L5.714,21.6a.5.5,0,0,0-.09,1l15.332,1.4A1.414,1.414,0,0,0,21.1,24a1.606,1.606,0,0,0,1.593-1.45l1.3-14.243A1.606,1.606,0,0,0,22.55,6.571" fill="#fff"/>\n      <path id="Path_1459" data-name="Path 1459" d="M5.449,7.6A2.15,2.15,0,1,0,3.3,5.45,2.152,2.152,0,0,0,5.449,7.6m0-3.3A1.15,1.15,0,1,1,4.3,5.45,1.151,1.151,0,0,1,5.449,4.3" fill="#fff"/>\n    </g>\n  </svg>\n  ',fileOperations:'\n  <svg id="file-operations" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n    <defs>\n      <clipPath id="fileOpclip-path">\n        <rect id="Rectangle_2763" data-name="Rectangle 2763" width="24" height="24" fill="#fff"/>\n      </clipPath>\n    </defs>\n    <g id="Group_558" data-name="Group 558" clip-path="url(#fileOpclip-path)">\n      <path id="Path_1490" data-name="Path 1490" d="M13.5,19H9.949A3.494,3.494,0,0,0,6.5,16H1v-.5a.5.5,0,0,0-1,0v8a.5.5,0,0,0,1,0V23H16.5a.5.5,0,0,0,.5-.5A3.5,3.5,0,0,0,13.5,19M1,22V17H6.5a2.5,2.5,0,0,1,2.449,2H5.5a.5.5,0,0,0,0,1h8a2.5,2.5,0,0,1,2.45,2Z" fill="#fff"/>\n      <path id="Path_1491" data-name="Path 1491" d="M23.56,3.854,20.146.44A1.492,1.492,0,0,0,19.085,0H8.5A1.5,1.5,0,0,0,7,1.5v12a.5.5,0,0,0,1,0V1.5A.5.5,0,0,1,8.5,1H19.085a.5.5,0,0,1,.354.147l3.414,3.414A.5.5,0,0,1,23,4.915V19.5a.5.5,0,0,1-.5.5H19a.5.5,0,1,0,0,1h3.5A1.5,1.5,0,0,0,24,19.5V4.915a1.491,1.491,0,0,0-.439-1.061" fill="#fff"/>\n    </g>\n  </svg>  \n  ',copyTo:'\n  <svg id="copy-to" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="24" viewBox="0 0 20 24">\n    <defs>\n      <clipPath id="copyToclip-path">\n        <rect id="Rectangle_2765" data-name="Rectangle 2765" width="20" height="24" fill="#fff"/>\n      </clipPath>\n    </defs>\n    <g id="Group_562" data-name="Group 562" clip-path="url(#copyToclip-path)">\n      <path id="Path_1504" data-name="Path 1504" d="M19.561,3.854,16.146.439A1.49,1.49,0,0,0,15.086,0H4.5A1.5,1.5,0,0,0,3,1.5V3H1.5A1.5,1.5,0,0,0,0,4.5v18A1.5,1.5,0,0,0,1.5,24h14A1.5,1.5,0,0,0,17,22.5V21h1.5A1.5,1.5,0,0,0,20,19.5V4.914a1.49,1.49,0,0,0-.439-1.06M16,22.5a.5.5,0,0,1-.5.5H1.5a.5.5,0,0,1-.5-.5V4.5A.5.5,0,0,1,1.5,4H3V19.5A1.5,1.5,0,0,0,4.5,21H16Zm3-3a.5.5,0,0,1-.5.5H4.5a.5.5,0,0,1-.5-.5V1.5A.5.5,0,0,1,4.5,1H15.086a.5.5,0,0,1,.353.146l3.415,3.415A.5.5,0,0,1,19,4.914Z" fill="#fff"/>\n      <path id="Path_1505" data-name="Path 1505" d="M14.842,10.141l0-.007L12.6,7.885a.5.5,0,0,0-.719.695l.012.012,1.4,1.4h-4.8a.5.5,0,0,0,0,1h4.793l-1.4,1.4a.5.5,0,1,0,.707.707l2.249-2.25a.5.5,0,0,0,.109-.545.53.53,0,0,0-.109-.163" fill="#fff"/>\n    </g>\n  </svg>\n  ',moveTo:'\n  <svg id="move-to" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n    <defs>\n      <clipPath id="moveToclip-path">\n        <rect id="Rectangle_2764" data-name="Rectangle 2764" width="24" height="24" fill="#fff"/>\n      </clipPath>\n    </defs>\n    <g id="Group_560" data-name="Group 560" clip-path="url(#moveToclip-path)">\n      <path id="Path_1492" data-name="Path 1492" d="M13.71,12.528l-1.147,1.146a.5.5,0,0,0,.708.708l2-2a.5.5,0,0,0,0-.708l-2-2a.5.5,0,0,0-.708.708l1.147,1.146H5.917c-.552,0-1.1,1,0,1Z" fill="#fff"/>\n      <path id="Path_1493" data-name="Path 1493" d="M.5,13.241a.5.5,0,0,0-.5.5v1.87a1.6,1.6,0,0,0,.01.17A.474.474,0,0,0,.5,16.2a.375.375,0,0,0,.067,0A.522.522,0,0,0,1,15.611v-1.87a.5.5,0,0,0-.5-.5" fill="#fff"/>\n      <path id="Path_1494" data-name="Path 1494" d="M.5,9.282a.5.5,0,0,0-.5.5v1.979a.5.5,0,0,0,1,0V9.782a.5.5,0,0,0-.5-.5" fill="#fff"/>\n      <path id="Path_1495" data-name="Path 1495" d="M12.385,3.258a.4.4,0,0,1,.115.277v.958a.5.5,0,0,0,1,0V3.535a1.389,1.389,0,0,0-.407-.983l-.229-.229a.5.5,0,0,0-.707.707Z" fill="#fff"/>\n      <path id="Path_1496" data-name="Path 1496" d="M9.415,1h.549a.4.4,0,0,1,.276.113l.517.517a.5.5,0,0,0,.719-.695L11.464.923,10.946.405A1.386,1.386,0,0,0,9.964,0H9.415a.5.5,0,0,0,0,1" fill="#fff"/>\n      <path id="Path_1497" data-name="Path 1497" d="M.5,5.323a.5.5,0,0,0-.5.5V7.8a.5.5,0,0,0,1,0V5.823a.5.5,0,0,0-.5-.5" fill="#fff"/>\n      <path id="Path_1498" data-name="Path 1498" d="M8.021,16H6.042a.5.5,0,0,0,0,1H8.021a.5.5,0,0,0,0-1" fill="#fff"/>\n      <path id="Path_1499" data-name="Path 1499" d="M7.436,1a.5.5,0,0,0,0-1H5.457a.5.5,0,0,0,0,1Z" fill="#fff"/>\n      <path id="Path_1500" data-name="Path 1500" d="M.5,1.364a.5.5,0,0,0-.5.5V3.843a.5.5,0,0,0,1,0V1.864a.5.5,0,0,0-.5-.5" fill="#fff"/>\n      <path id="Path_1501" data-name="Path 1501" d="M4.062,16H2.082a.5.5,0,0,0,0,1h1.98a.5.5,0,0,0,0-1" fill="#fff"/>\n      <path id="Path_1502" data-name="Path 1502" d="M3.977.5a.5.5,0,0,0-.5-.5H1.5a.5.5,0,0,0,0,1H3.477a.5.5,0,0,0,.5-.5" fill="#fff"/>\n      <path id="Path_1503" data-name="Path 1503" d="M23.594,9.552,21.447,7.405A1.385,1.385,0,0,0,20.465,7H13.5V6.5a.5.5,0,0,0-1,0v1A.5.5,0,0,0,13,8h7.465a.4.4,0,0,1,.276.113l2.145,2.145a.4.4,0,0,1,.114.276V22.611a.39.39,0,0,1-.389.389H11.889a.39.39,0,0,1-.389-.389V16.5A.5.5,0,0,0,11,16H10a.5.5,0,0,0,0,1h.5v5.611A1.39,1.39,0,0,0,11.889,24H22.611A1.39,1.39,0,0,0,24,22.611V10.534a1.381,1.381,0,0,0-.406-.982" fill="#fff"/>\n    </g>\n  </svg>\n  ',downloadPDF:'\n <svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="Layer_1-2">\n    <path class="cls-1"\n      d="m3.64,22.95H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.44c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.59-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.95c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM19.41,4.99h-3.35c-.27,0-.49-.21-.49-.48V1.28c1.86.52,3.31,1.92,3.85,3.71Z" />\n    <path class="cls-1"\n      d="m8.82,14.97h-2.07c-.3,0-.54.23-.54.52v7.98c0,.29.24.52.54.52s.54-.23.54-.52v-3.47h1.53c1.44,0,2.61-1.13,2.61-2.52s-1.17-2.52-2.61-2.52Zm0,3.99h-1.53v-2.95h1.53c.84,0,1.53.66,1.53,1.47s-.69,1.47-1.53,1.47Z" />\n    <path class="cls-1"\n      d="m23.46,15h-2.69c-1.19,0-2.15.9-2.15,2.01v6.47c0,.29.24.52.54.52s.54-.23.54-.52v-3.31h2.05c.3,0,.54-.23.54-.52s-.24-.52-.54-.52h-2.05v-2.11c0-.53.48-.97,1.07-.97h2.69c.3,0,.54-.23.54-.52s-.24-.52-.54-.52Z" />\n    <path class="cls-1"\n      d="m12.95,14.97c-.3,0-.54.23-.54.52v7.98c0,.29.24.52.54.52,2.58,0,4.68-2.02,4.68-4.51s-2.1-4.51-4.68-4.51Zm.54,7.94v-6.86c1.73.25,3.06,1.69,3.06,3.43s-1.33,3.18-3.06,3.43Z" />\n    <path class="cls-1"\n      d="m7.86,10.46c.07.03.15.04.23.04s.15-.01.23-.04c.07-.03.14-.07.19-.12l2.66-2.47c.23-.21.23-.56,0-.78s-.6-.21-.84,0l-1.65,1.53v-4.58c0-.3-.26-.55-.59-.55s-.59.25-.59.55v4.58l-1.65-1.53c-.23-.21-.6-.21-.84,0s-.23.56,0,.78l2.66,2.47c.05.05.12.09.19.12Z" />\n  </g>\n</svg>\n  ',downloadPNG:'\n    <svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" width="24" height="24"  viewBox="0 0 24 24">\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="Layer_1-2">\n    <path class="cls-1"\n      d="m17.05,14.93c-.27,0-.48.22-.48.5v5.95l-2.97-6.18c-.1-.21-.32-.32-.54-.26-.22.05-.37.25-.37.49v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-5.95l2.97,6.18c.08.17.25.28.43.28.04,0,.07,0,.11-.01.22-.05.37-.25.37-.49v-8.07c0-.28-.21-.5-.48-.5Z" />\n    <path class="cls-1"\n      d="m8.64,14.93h-1.94c-.27,0-.48.22-.48.5v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-3.53h1.46c1.34,0,2.42-1.13,2.42-2.52s-1.09-2.52-2.42-2.52Zm0,4.03h-1.46v-3.04h1.46c.81,0,1.46.68,1.46,1.52s-.66,1.52-1.46,1.52Z" />\n    <path class="cls-1"\n      d="m23.52,18.62c.27,0,.48-.22.48-.5v-.67c0-1.39-1.09-2.52-2.42-2.52s-2.42,1.13-2.42,2.52v4.03c0,1.39,1.09,2.52,2.42,2.52s2.42-1.13,2.42-2.52v-.67c0-.28-.21-.5-.48-.5h-1.29c-.27,0-.48.22-.48.5s.21.5.48.5h.81v.17c0,.84-.65,1.52-1.46,1.52s-1.46-.68-1.46-1.52v-4.03c0-.84.65-1.52,1.46-1.52s1.46.68,1.46,1.52v.67c0,.28.21.5.48.5Z" />\n    <path class="cls-1"\n      d="m3.65,22.96H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.45c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.6-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.96c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM15.58,1.28c1.86.52,3.31,1.92,3.85,3.71h-3.36c-.27,0-.49-.21-.49-.48V1.28Z" />\n    <path class="cls-1"\n      d="m10.32,7.11l-1.65,1.53v-4.58c0-.3-.26-.55-.59-.55s-.59.25-.59.55v4.58l-1.65-1.53c-.23-.21-.6-.21-.84,0s-.23.56,0,.78l2.66,2.47c.05.05.12.09.19.12.07.03.15.04.23.04s.15-.01.23-.04c.07-.03.14-.07.19-.12l2.66-2.47c.23-.21.23-.56,0-.78-.23-.21-.6-.21-.84,0Z" />\n  </g>\n</svg>\n  ',delete:'\n  <svg id="delete" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n    <defs>\n      <clipPath id="deleteclip-path">\n        <rect id="Rectangle_2735" data-name="Rectangle 2735" width="24" height="24" fill="#fff"/>\n      </clipPath>\n    </defs>\n    <g id="Group_523" data-name="Group 523" clip-path="url(#deleteclip-path)">\n      <path id="Path_1447" data-name="Path 1447" d="M23.5,4H17V1.5A1.5,1.5,0,0,0,15.5,0h-7A1.5,1.5,0,0,0,7,1.5V4H.5a.5.5,0,0,0,0,1H2.55L4.314,21.761A2.494,2.494,0,0,0,6.8,24H17.2a2.494,2.494,0,0,0,2.485-2.239L21.45,5H23.5a.5.5,0,0,0,0-1M8,1.5A.5.5,0,0,1,8.5,1h7a.5.5,0,0,1,.5.5V4H8ZM18.691,21.657A1.5,1.5,0,0,1,17.2,23H6.8a1.5,1.5,0,0,1-1.492-1.343L3.555,5h16.89Z" fill="#fff"/>\n      <path id="Path_1448" data-name="Path 1448" d="M12,8.5a.5.5,0,0,0-.5.5V19.5a.5.5,0,0,0,1,0V9a.5.5,0,0,0-.5-.5" fill="#fff"/>\n      <path id="Path_1449" data-name="Path 1449" d="M16,8.976l-.5,10.5a.5.5,0,0,0,.476.523H16a.5.5,0,0,0,.5-.476l.5-10.5a.5.5,0,1,0-1-.048" fill="#fff"/>\n      <path id="Path_1450" data-name="Path 1450" d="M7.476,8.5A.5.5,0,0,0,7,9.024l.5,10.5A.5.5,0,0,0,8,20h.025a.5.5,0,0,0,.475-.523L8,8.977A.5.5,0,0,0,7.476,8.5" fill="#fff"/>\n    </g>\n  </svg>\n  ',back:'\n  <svg id="back" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n    <defs>\n      <clipPath id="backclip-path">\n        <rect id="Rectangle_2781" data-name="Rectangle 2781" width="24" height="24" fill="#fff"/>\n      </clipPath>\n    </defs>\n    <g id="Group_597" data-name="Group 597" clip-path="url(#backclip-path)">\n      <path id="Path_1555" data-name="Path 1555" d="M0,12A12,12,0,1,0,12,0,12.013,12.013,0,0,0,0,12m1,0A11,11,0,1,1,12,23,11.013,11.013,0,0,1,1,12" fill="#fff"/>\n      <path id="Path_1556" data-name="Path 1556" d="M4.138,12a.17.17,0,0,1,.005-.024.512.512,0,0,1,.033-.168.532.532,0,0,1,.113-.17l4.219-4.29a.5.5,0,0,1,.714,0,.51.51,0,0,1,0,.719L5.855,11.491h13.5a.509.509,0,0,1,0,1.018H5.853l3.373,3.428a.512.512,0,0,1,0,.72.5.5,0,0,1-.714,0L4.284,12.359a.438.438,0,0,1-.056-.086.5.5,0,0,1-.051-.078A.521.521,0,0,1,4.138,12h0" fill="#fff"/>\n    </g>\n  </svg>\n  ',emptyLibrary:'\n  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="291.648" height="257.641" viewBox="0 0 291.648 257.641">\n    <defs>\n      <clipPath id="emptyLibraryclip-path">\n        <rect id="Rectangle_2706" data-name="Rectangle 2706" width="291.648" height="257.641" transform="translate(12.66)" fill="none"/>\n      </clipPath>\n    </defs>\n    <g id="image-empty" transform="translate(-12.66)">\n      <g id="Group_471" data-name="Group 471" clip-path="url(#emptyLibraryclip-path)">\n        <path id="Path_1418" data-name="Path 1418" d="M160.751,255.727c-66.485,0-118.227-5.845-142.606-73.507-24.415-67.766,19.034-164.7,91.047-166.173,48.757-1,31.942,48.623,74.131,72.638,32.339,18.408,117.378-36.39,113.723,42.777-3.321,71.951-64.267,124.265-136.3,124.265" transform="translate(1.351 1.915)" fill="#f8f8f8"/>\n        <path id="Path_1419" data-name="Path 1419" d="M18.1,93.9a9.048,9.048,0,1,1-9.048-9.048A9.048,9.048,0,0,1,18.1,93.9" transform="translate(12.66 5.997)" fill="#e0e0e0"/>\n        <path id="Path_1420" data-name="Path 1420" d="M230.481,202.978a9.048,9.048,0,1,1-9.048-9.048,9.048,9.048,0,0,1,9.048,9.048" transform="translate(25.364 23.16)" fill="#e0e0e0"/>\n        <path id="Path_1421" data-name="Path 1421" d="M34.644,204.233a5.928,5.928,0,1,1-5.928-5.928,5.928,5.928,0,0,1,5.928,5.928" transform="translate(2.721 23.683)" fill="#e0e0e0"/>\n        <path id="Path_1422" data-name="Path 1422" d="M190.8,199.7c0,1.208-25.187,7.8-54.651,7.8S84.1,200.906,84.1,199.7s22.064-4.679,51.527-4.679S190.8,198.493,190.8,199.7" transform="translate(10.044 23.29)" fill="#e0e0e0"/>\n        <path id="Path_1423" data-name="Path 1423" d="M278.22,131.008a13.14,13.14,0,1,1-13.141-13.14A13.142,13.142,0,0,1,278.22,131.008Z" transform="translate(23.088 14.076)" fill="none" stroke="#e0e0e0" stroke-miterlimit="10" stroke-width="2"/>\n        <path id="Path_1424" data-name="Path 1424" d="M137.744,113.388V195.23L58.638,161.4V84.531s79.6,29.354,79.106,28.857" transform="translate(7.003 10.095)" fill="#fff4eb"/>\n        <path id="Path_1425" data-name="Path 1425" d="M137.744,113.388V195.23L58.638,161.4V84.531S138.241,113.885,137.744,113.388Z" transform="translate(7.003 10.095)" fill="none" stroke="#f4cba2" stroke-miterlimit="10" stroke-width="1"/>\n        <path id="Path_1426" data-name="Path 1426" d="M129.224,113.388V195.23L208.331,161.4V84.531s-79.6,29.354-79.106,28.857" transform="translate(15.432 10.095)" fill="#fff4eb"/>\n        <path id="Path_1427" data-name="Path 1427" d="M129.224,113.388V195.23L208.331,161.4V84.531S128.727,113.885,129.224,113.388Z" transform="translate(15.432 10.095)" fill="none" stroke="#f4cba2" stroke-miterlimit="10" stroke-width="1"/>\n        <path id="Path_1428" data-name="Path 1428" d="M136.187,63.156,58.139,86.447,137.649,116.3l79.6-29.7Z" transform="translate(6.943 7.542)" fill="#f2c097"/>\n        <path id="Path_1429" data-name="Path 1429" d="M40.67,110.107l19.994-25.58L139.1,112.942l-22.392,26.6Z" transform="translate(4.857 10.095)" fill="#f9dec2"/>\n        <path id="Path_1430" data-name="Path 1430" d="M60.952,85.263l77.3,28-21.618,25.681L41.672,109.928Zm-.382-1.329L39.861,110.427l77.116,29.851,23.165-27.519Z" transform="translate(4.76 10.024)" fill="#f4cba2"/>\n        <path id="Path_1431" data-name="Path 1431" d="M129.194,113.529l23.321,27.861,75.561-30.038-19.4-26.836Z" transform="translate(15.429 10.093)" fill="#f9dec2"/>\n        <path id="Path_1432" data-name="Path 1432" d="M129.194,113.529l23.321,27.861,75.561-30.038-19.4-26.836Z" transform="translate(15.429 10.093)" fill="none" stroke="#f4cba2" stroke-miterlimit="10" stroke-width="1"/>\n        <line id="Line_79" data-name="Line 79" x1="29.852" y1="30.847" transform="translate(46.611 39.852)" fill="none" stroke="#e5e5e5" stroke-miterlimit="10" stroke-width="3"/>\n        <line id="Line_80" data-name="Line 80" x1="13.433" y1="29.852" transform="translate(95.866 25.921)" fill="none" stroke="#e5e5e5" stroke-miterlimit="10" stroke-width="3"/>\n        <line id="Line_81" data-name="Line 81" y1="49.255" x2="1.492" transform="translate(141.638 0.05)" fill="none" stroke="#e5e5e5" stroke-miterlimit="10" stroke-width="3"/>\n        <line id="Line_82" data-name="Line 82" y1="30.847" x2="13.433" transform="translate(172.982 25.424)" fill="none" stroke="#e5e5e5" stroke-miterlimit="10" stroke-width="3"/>\n        <line id="Line_83" data-name="Line 83" y1="30.847" x2="32.339" transform="translate(205.818 39.354)" fill="none" stroke="#e5e5e5" stroke-miterlimit="10" stroke-width="3"/>\n      </g>\n    </g>\n  </svg>\n    ',newDoc:'\n    <svg id="add-new-doc" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n      <defs>\n        <clipPath id="newDocclip-path">\n          <rect id="Rectangle_2737" data-name="Rectangle 2737" width="24" height="24" fill="#fff"/>\n        </clipPath>\n      </defs>\n      <g id="Group_527" data-name="Group 527" clip-path="url(#newDocclip-path)">\n        <path id="Path_1453" data-name="Path 1453" d="M12,0A12,12,0,1,0,24,12,12.013,12.013,0,0,0,12,0m0,22.957A10.957,10.957,0,1,1,22.957,12,10.97,10.97,0,0,1,12,22.957" fill="#fff"/>\n        <path id="Path_1454" data-name="Path 1454" d="M17.739,11.478H12.522V6.261a.522.522,0,0,0-1.044,0v5.217H6.261a.522.522,0,1,0,0,1.043h5.217v5.218a.522.522,0,0,0,1.044,0V12.521h5.217a.522.522,0,1,0,0-1.043" fill="#fff"/>\n      </g>\n    </svg>\n    ',uploadedFiles:'\n    <svg id="uploaded-files" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n      <defs>\n        <clipPath id="uploadedFilesclip-path">\n          <rect id="Rectangle_2740" data-name="Rectangle 2740" width="24" height="24" fill="#fff"/>\n        </clipPath>\n      </defs>\n      <g id="Group_533" data-name="Group 533" clip-path="url(#uploadedFilesclip-path)">\n        <path id="Path_1460" data-name="Path 1460" d="M10,12c-5.3,0-9-1.845-9-3.5V6.482C2.6,7.984,5.986,9,10,9s7.4-1.016,9-2.518V9a.5.5,0,0,0,1,0V4.5C20,1.977,15.611,0,10,0S0,1.977,0,4.5v13c0,2.365,3.777,4.248,8.98,4.478H9a.5.5,0,0,0,.022-1C4.068,20.762,1,19,1,17.5V15.014c1.376,1.287,4.072,2.209,7.468,2.434H8.5a.5.5,0,0,0,.033-1C4.31,16.17,1,14.655,1,13V10.482C2.6,11.984,5.986,13,10,13a.5.5,0,0,0,0-1M10,1c5.305,0,9,1.845,9,3.5S15.307,8,10,8,1,6.155,1,4.5,4.7,1,10,1" fill="#fff"/>\n        <path id="Path_1461" data-name="Path 1461" d="M17.5,11A6.5,6.5,0,1,0,24,17.5,6.508,6.508,0,0,0,17.5,11m0,12A5.5,5.5,0,1,1,23,17.5,5.507,5.507,0,0,1,17.5,23" fill="#fff"/>\n        <path id="Path_1462" data-name="Path 1462" d="M19.5,17H18V14.5a.5.5,0,0,0-1,0v3a.5.5,0,0,0,.5.5h2a.5.5,0,0,0,0-1" fill="#fff"/>\n      </g>\n    </svg>  \n    ',print:'\n    <svg id="print" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n      <defs>\n        <clipPath id="printclip-path">\n          <rect id="Rectangle_2742" data-name="Rectangle 2742" width="24" height="24" fill="#fff"/>\n        </clipPath>\n      </defs>\n      <g id="Group_537" data-name="Group 537" clip-path="url(#printclip-path)">\n        <path id="Path_1465" data-name="Path 1465" d="M16.5,19h-9a.5.5,0,0,0,0,1h9a.5.5,0,0,0,0-1" fill="#fff"/>\n        <path id="Path_1466" data-name="Path 1466" d="M16.5,16h-9a.5.5,0,0,0,0,1h9a.5.5,0,0,0,0-1" fill="#fff"/>\n        <path id="Path_1467" data-name="Path 1467" d="M21.5,6H2.5A2.512,2.512,0,0,0,0,8.5v6A2.511,2.511,0,0,0,2.5,17H5v5.5A1.5,1.5,0,0,0,6.5,24h11A1.5,1.5,0,0,0,19,22.5V17h2.5A2.51,2.51,0,0,0,24,14.5v-6A2.511,2.511,0,0,0,21.5,6M18,22.5a.5.5,0,0,1-.5.5H6.5a.5.5,0,0,1-.5-.5V14H18Zm5-8A1.509,1.509,0,0,1,21.5,16H19V13.5a.5.5,0,0,0-.5-.5H5.5a.5.5,0,0,0-.5.5V16H2.5A1.509,1.509,0,0,1,1,14.5v-6A1.509,1.509,0,0,1,2.5,7h19A1.509,1.509,0,0,1,23,8.5Z" fill="#fff"/>\n        <path id="Path_1468" data-name="Path 1468" d="M5.5,5A.5.5,0,0,0,6,4.5V1h8V4.5a.5.5,0,0,0,.5.5h4a.5.5,0,0,0,.5-.5V3.913a1.49,1.49,0,0,0-.439-1.059L16.147.44A1.488,1.488,0,0,0,15.086,0H5.5A.5.5,0,0,0,5,.5v4a.5.5,0,0,0,.5.5m9.94-3.854,2.414,2.415A.5.5,0,0,1,18,3.913V4H15V1h.086a.508.508,0,0,1,.354.146" fill="#fff"/>\n        <path id="Path_1469" data-name="Path 1469" d="M3.5,8A1.5,1.5,0,1,0,5,9.5,1.5,1.5,0,0,0,3.5,8m0,2A.5.5,0,1,1,4,9.5a.5.5,0,0,1-.5.5" fill="#fff"/>\n      </g>\n    </svg>\n    ',uploadPDF:'\n     <svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" >\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="Layer_1-2">\n    <path class="cls-1 "\n      d="m3.64,22.95H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.44c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.59-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.95c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM19.41,4.99h-3.35c-.27,0-.49-.21-.49-.48V1.28c1.86.52,3.31,1.92,3.85,3.71Z" />\n    <path class="cls-1 "\n      d="m8.82,14.97h-2.07c-.3,0-.54.23-.54.52v7.98c0,.29.24.52.54.52s.54-.23.54-.52v-3.47h1.53c1.44,0,2.61-1.13,2.61-2.52s-1.17-2.52-2.61-2.52Zm0,3.99h-1.53v-2.95h1.53c.84,0,1.53.66,1.53,1.47s-.69,1.47-1.53,1.47Z" />\n    <path class="cls-1 "\n      d="m23.46,15h-2.69c-1.19,0-2.15.9-2.15,2.01v6.47c0,.29.24.52.54.52s.54-.23.54-.52v-3.31h2.05c.3,0,.54-.23.54-.52s-.24-.52-.54-.52h-2.05v-2.11c0-.53.48-.97,1.07-.97h2.69c.3,0,.54-.23.54-.52s-.24-.52-.54-.52Z" />\n    <path class="cls-1 "\n      d="m12.95,14.97c-.3,0-.54.23-.54.52v7.98c0,.29.24.52.54.52,2.58,0,4.68-2.02,4.68-4.51s-2.1-4.51-4.68-4.51Zm.54,7.94v-6.86c1.73.25,3.06,1.69,3.06,3.43s-1.33,3.18-3.06,3.43Z" />\n    <path class="cls-1" transform="scale(1, -1) translate(0, -14)"\n      d="m7.86,10.46c.07.03.15.04.23.04s.15-.01.23-.04c.07-.03.14-.07.19-.12l2.66-2.47c.23-.21.23-.56,0-.78s-.6-.21-.84,0l-1.65,1.53v-4.58c0-.3-.26-.55-.59-.55s-.59.25-.59.55v4.58l-1.65-1.53c-.23-.21-.6-.21-.84,0s-.23.56,0,.78l2.66,2.47c.05.05.12.09.19.12Z" />\n  </g>\n</svg>\n    ',uploadPNG:'\n<svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" >\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="Layer_1-2">\n    <path class="cls-1"\n      d="m17.05,14.93c-.27,0-.48.22-.48.5v5.95l-2.97-6.18c-.1-.21-.32-.32-.54-.26-.22.05-.37.25-.37.49v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-5.95l2.97,6.18c.08.17.25.28.43.28.04,0,.07,0,.11-.01.22-.05.37-.25.37-.49v-8.07c0-.28-.21-.5-.48-.5Z" />\n    <path class="cls-1"\n      d="m8.64,14.93h-1.94c-.27,0-.48.22-.48.5v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-3.53h1.46c1.34,0,2.42-1.13,2.42-2.52s-1.09-2.52-2.42-2.52Zm0,4.03h-1.46v-3.04h1.46c.81,0,1.46.68,1.46,1.52s-.66,1.52-1.46,1.52Z" />\n    <path class="cls-1"\n      d="m23.52,18.62c.27,0,.48-.22.48-.5v-.67c0-1.39-1.09-2.52-2.42-2.52s-2.42,1.13-2.42,2.52v4.03c0,1.39,1.09,2.52,2.42,2.52s2.42-1.13,2.42-2.52v-.67c0-.28-.21-.5-.48-.5h-1.29c-.27,0-.48.22-.48.5s.21.5.48.5h.81v.17c0,.84-.65,1.52-1.46,1.52s-1.46-.68-1.46-1.52v-4.03c0-.84.65-1.52,1.46-1.52s1.46.68,1.46,1.52v.67c0,.28.21.5.48.5Z" />\n    <path class="cls-1"\n      d="m3.65,22.96H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.45c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.6-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.96c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM15.58,1.28c1.86.52,3.31,1.92,3.85,3.71h-3.36c-.27,0-.49-.21-.49-.48V1.28Z" />\n    <path class="cls-1" transform="scale(1, -1) translate(0, -14)"\n      d="m10.32,7.11l-1.65,1.53v-4.58c0-.3-.26-.55-.59-.55s-.59.25-.59.55v4.58l-1.65-1.53c-.23-.21-.6-.21-.84,0s-.23.56,0,.78l2.66,2.47c.05.05.12.09.19.12.07.03.15.04.23.04s.15-.01.23-.04c.07-.03.14-.07.19-.12l2.66-2.47c.23-.21.23-.56,0-.78-.23-.21-.6-.21-.84,0Z" />\n  </g>\n</svg>\n    ',sharePDF:'\n <svg id="sharePdf" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" >\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="sharePdf">\n    <path class="cls-1"\n      d="m3.64,22.95H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.44c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.59-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.95c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM19.41,4.99h-3.35c-.27,0-.49-.21-.49-.48V1.28c1.86.52,3.31,1.92,3.85,3.71Z" />\n    <path class="cls-1"\n      d="m8.82,14.97h-2.07c-.3,0-.54.23-.54.52v7.98c0,.29.24.52.54.52s.54-.23.54-.52v-3.47h1.53c1.44,0,2.61-1.13,2.61-2.52s-1.17-2.52-2.61-2.52Zm0,3.99h-1.53v-2.95h1.53c.84,0,1.53.66,1.53,1.47s-.69,1.47-1.53,1.47Z" />\n    <path class="cls-1"\n      d="m23.46,15h-2.69c-1.19,0-2.15.9-2.15,2.01v6.47c0,.29.24.52.54.52s.54-.23.54-.52v-3.31h2.05c.3,0,.54-.23.54-.52s-.24-.52-.54-.52h-2.05v-2.11c0-.53.48-.97,1.07-.97h2.69c.3,0,.54-.23.54-.52s-.24-.52-.54-.52Z" />\n    <path class="cls-1"\n      d="m12.95,14.97c-.3,0-.54.23-.54.52v7.98c0,.29.24.52.54.52,2.58,0,4.68-2.02,4.68-4.51s-2.1-4.51-4.68-4.51Zm.54,7.94v-6.86c1.73.25,3.06,1.69,3.06,3.43s-1.33,3.18-3.06,3.43Z" />\n    <path transform="scale(0.4, -0.4) translate(8, -30)" stroke="#fff" fill="#fff" stroke-width="1px" d="M19.489,15.009h0c-.008,0-.014,0-.022,0a4.465,4.465,0,0,0-3.749,2.052l-7-3.5a4.482,4.482,0,0,0,0-3.1l7-3.5a4.466,4.466,0,0,0,3.771,2.053l.018,0A4.516,4.516,0,1,0,15.282,6.06L8.257,9.574a4.49,4.49,0,1,0-4.793,6.814,4.548,4.548,0,0,0,1.043.122,4.468,4.468,0,0,0,3.755-2.056l7.018,3.511a4.485,4.485,0,1,0,4.209-2.956M17.13,1.914a3.508,3.508,0,1,1,2.366,6.1h-.01l-.011,0a3.476,3.476,0,0,1-3.112-1.932l0-.006a3.525,3.525,0,0,1,.769-4.162M3.693,15.415a3.5,3.5,0,1,1,3.931-4.967v0a3.47,3.47,0,0,1,0,3.119l0,0a3.479,3.479,0,0,1-3.931,1.842m17.636,7.066a3.5,3.5,0,0,1-4.971-4.53l0,0a3.477,3.477,0,0,1,3.126-1.936l.011,0a3.5,3.5,0,0,1,1.831,6.472" />\n  </g>\n</svg>\n  ',sharePNG:'\n<svg id="sharePng" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" >\n  <defs>\n    <style>\n      .cls-1 {\n        fill: #fff;\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="sharePng">\n    <path class="cls-1"\n      d="m17.05,14.93c-.27,0-.48.22-.48.5v5.95l-2.97-6.18c-.1-.21-.32-.32-.54-.26-.22.05-.37.25-.37.49v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-5.95l2.97,6.18c.08.17.25.28.43.28.04,0,.07,0,.11-.01.22-.05.37-.25.37-.49v-8.07c0-.28-.21-.5-.48-.5Z" />\n    <path class="cls-1"\n      d="m8.64,14.93h-1.94c-.27,0-.48.22-.48.5v8.07c0,.28.21.5.48.5s.48-.22.48-.5v-3.53h1.46c1.34,0,2.42-1.13,2.42-2.52s-1.09-2.52-2.42-2.52Zm0,4.03h-1.46v-3.04h1.46c.81,0,1.46.68,1.46,1.52s-.66,1.52-1.46,1.52Z" />\n    <path class="cls-1"\n      d="m23.52,18.62c.27,0,.48-.22.48-.5v-.67c0-1.39-1.09-2.52-2.42-2.52s-2.42,1.13-2.42,2.52v4.03c0,1.39,1.09,2.52,2.42,2.52s2.42-1.13,2.42-2.52v-.67c0-.28-.21-.5-.48-.5h-1.29c-.27,0-.48.22-.48.5s.21.5.48.5h.81v.17c0,.84-.65,1.52-1.46,1.52s-1.46-.68-1.46-1.52v-4.03c0-.84.65-1.52,1.46-1.52s1.46.68,1.46,1.52v.67c0,.28.21.5.48.5Z" />\n    <path class="cls-1"\n      d="m3.65,22.96H1.58c-.27,0-.49-.21-.49-.48V1.52c0-.26.22-.48.49-.48h12.45c.16,0,.31.03.47.05v3.42c0,.84.71,1.52,1.58,1.52h3.55c.01.15.05.3.05.45v6.01c0,.29.24.52.54.52s.54-.23.54-.52v-6.01c0-.33-.03-.65-.08-.97,0,0,0,0,0,0,0,0,0-.02,0-.02-.45-2.77-2.72-4.97-5.6-5.4-.01,0-.02,0-.03,0,0,0,0,0,0,0-.33-.05-.66-.08-1-.08H1.58C.71,0,0,.68,0,1.52v20.96c0,.84.71,1.52,1.58,1.52h2.07c.3,0,.54-.23.54-.52s-.24-.52-.54-.52ZM15.58,1.28c1.86.52,3.31,1.92,3.85,3.71h-3.36c-.27,0-.49-.21-.49-.48V1.28Z" />\n    <path transform="scale(0.4, -0.4) translate(8, -30)" stroke="#fff" fill="#fff" stroke-width="1px" d="M19.489,15.009h0c-.008,0-.014,0-.022,0a4.465,4.465,0,0,0-3.749,2.052l-7-3.5a4.482,4.482,0,0,0,0-3.1l7-3.5a4.466,4.466,0,0,0,3.771,2.053l.018,0A4.516,4.516,0,1,0,15.282,6.06L8.257,9.574a4.49,4.49,0,1,0-4.793,6.814,4.548,4.548,0,0,0,1.043.122,4.468,4.468,0,0,0,3.755-2.056l7.018,3.511a4.485,4.485,0,1,0,4.209-2.956M17.13,1.914a3.508,3.508,0,1,1,2.366,6.1h-.01l-.011,0a3.476,3.476,0,0,1-3.112-1.932l0-.006a3.525,3.525,0,0,1,.769-4.162M3.693,15.415a3.5,3.5,0,1,1,3.931-4.967v0a3.47,3.47,0,0,1,0,3.119l0,0a3.479,3.479,0,0,1-3.931,1.842m17.636,7.066a3.5,3.5,0,0,1-4.971-4.53l0,0a3.477,3.477,0,0,1,3.126-1.936l.011,0a3.5,3.5,0,0,1,1.831,6.472" />\n  </g>\n</svg>\n  ',done:'<svg id="done" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <clipPath id="done-path">\n      <rect id="Rectangle_2775" data-name="Rectangle 2775" width="24" height="24" fill="#fe8e14"/>\n    </clipPath>\n  </defs>\n  <g id="Group_584" data-name="Group 584" clip-path="url(#doneclip-path)">\n    <path id="Path_1526" data-name="Path 1526" d="M17.6,6.7l-6.691,9.081L6.313,12.11a.5.5,0,0,0-.625.781l5,4a.508.508,0,0,0,.378.1.493.493,0,0,0,.337-.2l7-9.5A.5.5,0,1,0,17.6,6.7" fill="#fe8e14"/>\n    <path id="Path_1527" data-name="Path 1527" d="M12,0A12,12,0,1,0,24,12,12.013,12.013,0,0,0,12,0m0,23A11,11,0,1,1,23,12,11.013,11.013,0,0,1,12,23" fill="#fe8e14"/>\n  </g>\n</svg>\n',captureAnother:'\n<svg id="capture-another" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="28.761" height="23" viewBox="0 0 28.761 23">\n  <defs>\n    <clipPath id="captureAnotherclip-path">\n      <rect id="Rectangle_2777" data-name="Rectangle 2777" width="28.761" height="23" fill="#fff"/>\n    </clipPath>\n  </defs>\n  <g id="Group_589" data-name="Group 589" clip-path="url(#captureAnotherclip-path)">\n    <path id="Path_1544" data-name="Path 1544" d="M25.877,3.639H21.663a.7.7,0,0,1-.575-.288l-.575-.764C19.264.961,18.59,0,17.44,0H11.4C10.151,0,9.486.961,8.336,2.588l-.674.764a.7.7,0,0,1-.575.288H2.875C.476,3.639,0,5.077,0,6.227v13.9C0,22.041,1.051,23,2.974,23H25.787c1.914,0,2.974-.961,2.974-2.776v-14c-.008-1.147-.485-2.585-2.884-2.585m-.1,18.411H2.974c-1.339,0-2.013-.575-2.013-1.824v-14c0-.863.189-1.626,1.914-1.626H7.188a1.666,1.666,0,0,0,1.339-.674L9.1,3.162c1.15-1.626,1.536-2.2,2.2-2.2H17.34c.674,0,1.15.575,2.3,2.2l.575.764a1.562,1.562,0,0,0,1.339.674h4.313c1.725,0,1.914.764,1.914,1.626v14h.009c0,1.249-.673,1.824-2.012,1.824" fill="#fff"/>\n    <path id="Path_1545" data-name="Path 1545" d="M14.38,6.194a6.5,6.5,0,1,0,6.5,6.5,6.508,6.508,0,0,0-6.5-6.5m0,12a5.5,5.5,0,1,1,5.5-5.5,5.507,5.507,0,0,1-5.5,5.5" fill="#fff"/>\n    <path id="Path_1546" data-name="Path 1546" d="M17.381,12.194h-2.5v-2.5a.5.5,0,0,0-1,0v2.5h-2.5a.5.5,0,0,0,0,1h2.5v2.5a.5.5,0,1,0,1,0v-2.5h2.5a.5.5,0,0,0,0-1" fill="#fff"/>\n  </g>\n</svg>\n',edit:'\n<svg id="edit" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24.002" height="24" viewBox="0 0 24.002 24">\n  <defs>\n    <clipPath id="editclip-path">\n      <rect id="Rectangle_2778" data-name="Rectangle 2778" width="24.002" height="24" fill="none" stroke="currentColor" stroke-width="1"/>\n    </clipPath>\n  </defs>\n  <g id="Group_591" data-name="Group 591" clip-path="url(#editclip-path)">\n    <path id="Path_1547" data-name="Path 1547" d="M21.5,13.5v9a1,1,0,0,1-1,1H1.5a1,1,0,0,1-1-1V3.5a1,1,0,0,1,1-1h11" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"/>\n    <path id="Path_1548" data-name="Path 1548" d="M9.824,17.007l-3.99,1.049L7,14.177,20.674.5,23.5,3.328Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"/>\n  </g>\n</svg>\n',crop:'\n<svg id="crop" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <clipPath id="cropclip-path">\n      <rect id="Rectangle_2787" data-name="Rectangle 2787" width="24" height="24" fill="currentColor"/>\n    </clipPath>\n  </defs>\n  <g id="Group_609" data-name="Group 609" clip-path="url(#cropclip-path)">\n    <path id="Path_1569" data-name="Path 1569" d="M18.95,5.05a.745.745,0,0,1,.243.536V18.2h.974V5.586a1.681,1.681,0,0,0-.521-1.232,1.681,1.681,0,0,0-1.232-.521H5.8v.974h12.61a.745.745,0,0,1,.536.243" fill="currentColor"/>\n    <path id="Path_1570" data-name="Path 1570" d="M5.609,19.17a.789.789,0,0,1-.779-.779V0H3.856V3.833H0v.974H3.856V18.391a1.748,1.748,0,0,0,1.753,1.753H19.193V24h.974V20.144H24V19.17Z" fill="currentColor"/>\n  </g>\n</svg>\n',rotate:'\n<svg id="rotate" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <clipPath id="rotateclip-path">\n      <rect id="Rectangle_2786" data-name="Rectangle 2786" width="24" height="24" fill="#fff"/>\n    </clipPath>\n  </defs>\n  <g id="Group_607" data-name="Group 607" clip-path="url(#rotateclip-path)">\n    <path id="Path_1567" data-name="Path 1567" d="M15.557,11H1.5A1.5,1.5,0,0,0,0,12.5v10A1.5,1.5,0,0,0,1.5,24H15.557a1.5,1.5,0,0,0,1.5-1.5v-10a1.5,1.5,0,0,0-1.5-1.5m.5,11.5a.5.5,0,0,1-.5.5H1.5a.5.5,0,0,1-.5-.5v-10a.5.5,0,0,1,.5-.5H15.557a.5.5,0,0,1,.5.5Z" fill="#fff"/>\n    <path id="Path_1568" data-name="Path 1568" d="M21.022,6.667A9.785,9.785,0,0,0,13.845,3.69h-2.2l2.9-2.876L13.83,0,9.624,4.181,13.83,8.387l.717-.814-2.9-2.9h2.2a8.825,8.825,0,0,1,6.5,2.69,8.859,8.859,0,0,1,2.677,6.483l.982,0a9.777,9.777,0,0,0-2.978-7.175" fill="#fff"/>\n  </g>\n</svg>\n',annotate:'\n<svg id="annotate" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <clipPath id="annotateclip-path">\n      <rect id="Rectangle_2785" data-name="Rectangle 2785" width="24" height="24" fill="currentColor"/>\n    </clipPath>\n  </defs>\n  <g id="Group_605" data-name="Group 605" clip-path="url(#annotateclip-path)">\n    <path id="Path_1561" data-name="Path 1561" d="M9.575,21H4.934A2.5,2.5,0,0,0,2.99,19.051V4.949A2.5,2.5,0,0,0,4.934,3H18.993a2.5,2.5,0,0,0,1.943,1.949V11.11a.5.5,0,1,0,1,0V4.949A2.5,2.5,0,1,0,18.993,2H4.934A2.493,2.493,0,1,0,2,4.949v14.1A2.5,2.5,0,1,0,4.934,22H9.575a.5.5,0,0,0,0-1M21.435,1a1.5,1.5,0,1,1-1.5,1.5,1.5,1.5,0,0,1,1.5-1.5M1,2.5A1.495,1.495,0,1,1,2.493,4,1.5,1.5,0,0,1,1,2.5M2.493,23a1.5,1.5,0,1,1,1.494-1.5A1.5,1.5,0,0,1,2.493,23" fill="currentColor"/>\n    <path id="Path_1562" data-name="Path 1562" d="M23.561,14.718l-.908-.912a1.483,1.483,0,0,0-1.944-.149l-4.539,3.35-2.563,2.571a.5.5,0,0,0,0,.707l.277.278-1.791,1.711A1,1,0,0,0,12.779,24h2.883a.5.5,0,0,0,.333-.128l.626-.563.509.511a.5.5,0,0,0,.7,0l2.613-2.627,3.264-4.534a1.5,1.5,0,0,0-.151-1.941M15.471,23H12.779l1.81-1.73L15.915,22.6Zm7.434-6.928-3.214,4.475-2.208,2.212-2.82-2.829,2.155-2.167,4.482-3.3a.5.5,0,0,1,.647.05h0l.907.912a.5.5,0,0,1,.05.647" fill="currentColor"/>\n    <path id="Path_1563" data-name="Path 1563" d="M5.082,10.014a4.479,4.479,0,0,0,.738,2.46c.007.012.007.025.015.036l.009.009a4.5,4.5,0,1,0-.762-2.505M9.07,6.565V9.746L6.428,11.512A3.464,3.464,0,0,1,9.07,6.565m3.988,3.449a3.474,3.474,0,0,1-6.075,2.329L9.845,10.43a.5.5,0,0,0,.222-.416V6.565a3.491,3.491,0,0,1,2.991,3.449" fill="currentColor"/>\n    <path id="Path_1564" data-name="Path 1564" d="M18.542,6.534H16.049a.5.5,0,0,0,0,1h2.493a.5.5,0,0,0,0-1" fill="currentColor"/>\n    <path id="Path_1565" data-name="Path 1565" d="M18.542,9.534H16.049a.5.5,0,0,0,0,1h2.493a.5.5,0,0,0,0-1" fill="currentColor"/>\n    <path id="Path_1566" data-name="Path 1566" d="M18.542,12.534H16.049a.5.5,0,0,0,0,1h2.493a.5.5,0,0,0,0-1" fill="currentColor"/>\n  </g>\n</svg>\n',defaultDocument:'\n<svg id="document" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="24" viewBox="0 0 20 24">\n  <defs>\n    <clipPath id="documentclip-path">\n      <rect id="Rectangle_2779" data-name="Rectangle 2779" width="20" height="24" fill="#9AA0A6"/>\n    </clipPath>\n  </defs>\n  <g id="Group_593" data-name="Group 593" clip-path="url(#documentclip-path)">\n    <path id="Path_1549" data-name="Path 1549" d="M19.56,3.85,16.15.44A1.52,1.52,0,0,0,15.09,0H4.5A1.5,1.5,0,0,0,3,1.5V3H1.5A1.5,1.5,0,0,0,0,4.5v18A1.5,1.5,0,0,0,1.5,24h14A1.5,1.5,0,0,0,17,22.5V21h1.5A1.5,1.5,0,0,0,20,19.5V4.91a1.52,1.52,0,0,0-.44-1.06M16,22.5a.5.5,0,0,1-.5.5H1.5a.5.5,0,0,1-.5-.5V4.5A.5.5,0,0,1,1.5,4H3V19.5A1.5,1.5,0,0,0,4.5,21H16Zm3-3a.5.5,0,0,1-.5.5H4.5a.5.5,0,0,1-.5-.5V1.5A.5.5,0,0,1,4.5,1H15.09a.492.492,0,0,1,.35.15l3.41,3.41a.468.468,0,0,1,.15.35Z" fill="#9AA0A6"/>\n    <path id="Path_1550" data-name="Path 1550" d="M7.66,6.4h5.18a.5.5,0,0,0,0-1H7.66a.5.5,0,0,0,0,1" fill="#9AA0A6"/>\n    <path id="Path_1551" data-name="Path 1551" d="M15.5,9.08h-8a.5.5,0,1,0,0,1h8a.5.5,0,1,0,0-1" fill="#9AA0A6"/>\n    <path id="Path_1552" data-name="Path 1552" d="M15.5,13.08h-8a.5.5,0,1,0,0,1h8a.5.5,0,0,0,0-1" fill="#9AA0A6"/>\n  </g>\n</svg>\n',selectedCircle:'\n<svg id="selected-circle" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <clipPath id="selected-circleclip-path">\n      <rect id="Rectangle_2751" data-name="Rectangle 2751" width="24" height="24" fill="none"/>\n    </clipPath>\n  </defs>\n  <g id="Group_547" data-name="Group 547" clip-path="url(#selected-circleclip-path)">\n    <path id="Path_1478" data-name="Path 1478" d="M24,12A12,12,0,1,1,12,0,12,12,0,0,1,24,12" fill="#fe8e14"/>\n    <path id="Path_1479" data-name="Path 1479" d="M10.52,17.174a2.517,2.517,0,0,1-1.757-.725L5.757,13.442a1,1,0,0,1,1.414-1.414l3,3a.49.49,0,0,0,.387.144.511.511,0,0,0,.373-.2l5.8-7.742a1,1,0,0,1,1.6,1.2l-5.81,7.748a2.514,2.514,0,0,1-1.83.994c-.059,0-.117.006-.176.006" fill="#fff"/>\n  </g>\n</svg>\n',filter:'\n<svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 24" width="25" height="24" >\n  <defs>\n    <style>\n      .cls-1 {\n        stroke-width: 0px;\n      }\n    </style>\n  </defs>\n  <g id="Layer_1-2">\n    <path class="cls-1"\n      d="m20.27,8.85c.04-.31.06-.62.06-.95,0-4.36-3.51-7.9-7.83-7.9s-7.83,3.54-7.83,7.9c0,.32.02.63.06.94C1.95,10.06,0,12.85,0,16.1c0,4.36,3.51,7.9,7.83,7.9,1.75,0,3.37-.59,4.67-1.58,1.31.99,2.92,1.58,4.67,1.58,4.32,0,7.83-3.54,7.83-7.9,0-3.25-1.95-6.04-4.73-7.25Zm-3.09,14.1c-1.43,0-2.76-.45-3.86-1.22-.29-.2-.56-.43-.81-.67-1.3-1.25-2.11-3-2.11-4.95,0-.2.01-.4.03-.59.03-.36.09-.7.17-1.04-.34-.1-.66-.23-.98-.38-.09.35-.16.7-.21,1.07-.04.31-.06.62-.06.95,0,2.2.9,4.19,2.34,5.62-1.1.77-2.43,1.22-3.86,1.22-3.74,0-6.78-3.07-6.78-6.85,0-2.73,1.6-5.09,3.9-6.19.31-.15.64-.28.98-.38.61-.18,1.24-.28,1.91-.28,1.43,0,2.76.45,3.86,1.22.29.2.56.43.81.67.25-.24.53-.47.81-.67-.25-.25-.53-.48-.81-.7-1.31-.99-2.92-1.58-4.67-1.58-.72,0-1.42.11-2.08.29-.02-.2-.03-.39-.03-.59,0-3.78,3.04-6.85,6.78-6.85s6.78,3.07,6.78,6.85c0,.2-.01.4-.03.59-.03.36-.09.7-.17,1.04-.49,2.02-1.87,3.68-3.69,4.55-.31.15-.64.28-.98.38.08.34.14.69.17,1.04.35-.1.69-.21,1.01-.35,2.19-.95,3.85-2.88,4.47-5.24,2.3,1.1,3.9,3.45,3.9,6.19,0,3.78-3.04,6.85-6.78,6.85Z" />\n  </g>\n</svg>\n  ',close:'\n            <svg\n            xmlns="http://www.w3.org/2000/svg"\n            viewBox="0 0 24 24"\n            fill="none"\n            stroke="currentColor"\n            stroke-linecap="round"\n            stroke-linejoin="round"\n            width="24"\n            height="24"\n            stroke-width="2"\n          >\n            <path d="M18 6l-12 12"></path>\n            <path d="M6 6l12 12"></path>\n          </svg>\n'};function BU(){return"ontouchstart"in document.documentElement}function NU(t){return"string"==typeof t?document.querySelector(t):t instanceof HTMLElement?t:null}function UU(t){if(!t)return`Doc-${Date.now()}`;const e=t.lastIndexOf(".");return-1!==e?t.substring(0,e):t}function FU(t,e){if(!document.getElementById(t)){const i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}}class VU{constructor(t){this.config=t,this.checked=!1,this.isSelectMode=!1,this.createUI(),this.bindEvents()}createUI(){FU("mwc-document-item-style",WU);const t=$I.documentManager.getDocument(this.config.docId),e=t.pages.length;this.dom=document.createElement("div"),this.dom.className="mwc-document-item",this.dom.innerHTML=`\n      <div class="mwc-document-info-container">\n        <div class="mwc-document-thumbnail">\n          ${OU.defaultDocument}\n        </div>\n        <div class="mwc-document-info">\n          <div class="mwc-document-name-container">\n            <div class="mwc-document-name">${t.name}</div>\n            <button type="button" class="mwc-document-rename-btn">\n              ${OU.edit}\n            </button>\n          </div>\n          <div class="mwc-document-pages">${e} pages</div>\n        </div>\n      </div>\n      <input type="checkbox" class="mwc-document-checkbox">\n    `,this.checkbox=this.dom.querySelector(".mwc-document-checkbox"),this.renameBtn=this.dom.querySelector(".mwc-document-rename-btn"),this.updateThumbnail(t)}async updateThumbnail(t){const e=this.dom.querySelector(".mwc-document-thumbnail");if(e.textContent="",t.pages[0]){const i=t.getPageData(t.pages[0]),n=await i.display(),s=URL.createObjectURL(n.data),o=document.createElement("img");o.className="mwc-image-thumbnail",o.alt="mwc-image-thumbnail",o.src=s,e.append(o)}else e.innerHTML=OU.defaultDocument}bindEvents(){this.dom.addEventListener("click",t=>{var e,i;t.target!==this.checkbox&&(this.isSelectMode?this.toggleCheck():null===(i=(e=this.config).onDocumentClick)||void 0===i||i.call(e,this.config.docId))}),this.checkbox.addEventListener("click",t=>{t.stopPropagation(),this.toggleCheck()}),this.renameBtn.addEventListener("click",t=>{var e,i;t.stopPropagation(),null===(i=(e=this.config).onRename)||void 0===i||i.call(e,this.config.docId)})}setSelectMode(t){this.isSelectMode=t,t||this.toggleCheck(!1)}toggleCheck(t){var e,i;this.checked=null!=t?t:!this.checked,this.checkbox.checked=this.checked,this.dom.classList.toggle("selected",this.checked),null===(i=(e=this.config).onCheckedChange)||void 0===i||i.call(e,this.config.docId,this.checked)}getDom(){return this.dom}getUid(){return this.config.docId}update(){const t=$I.documentManager.getDocument(this.config.docId);if(!t)return;const e=this.dom.querySelector(".mwc-document-name"),i=this.dom.querySelector(".mwc-document-pages");e.textContent=t.name,i.textContent=1===t.pages.length?"1 page":`${t.pages.length} pages`,this.updateThumbnail(t)}dispose(){this.dom.remove()}}const WU="\n.mwc-document-item {\n  display: grid;\n  grid-template-columns: 90% 10%;\n  background-color: #EFEFEF;\n  cursor: pointer;\n  font-family: Verdana;\n  padding: 15px;\n  align-items: center;\n  border: 2px solid transparent;\n}\n\n.mwc-document-item.selected {\n  border: 2px solid #FE8E14;\n}\n\n.mwc-document-info-container {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n}\n\n.mwc-document-info {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  padding-right: 1rem;\n}\n\n.mwc-document-item .mwc-document-name-container {\n  display: grid;\n  grid-template-columns: 90% 10%;\n}\n\n.mwc-document-item .mwc-document-name-container .mwc-document-name {\n  font-size: 16px;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n\n.mwc-document-item .mwc-document-name-container .mwc-document-rename-btn{\n  background: none;\n  border: none;\n  cursor: pointer;\n}\n\n.mwc-document-item .mwc-document-name-container .mwc-document-rename-btn svg {\n  width: 16px;\n  height: 16px;\n  stroke: black;\n}\n\n.mwc-document-item .mwc-document-pages {\n  color: #888888;\n}\n\n.mwc-document-thumbnail {\n  width: 70px;\n  height: 70px;\n  background-color: #DADCE0;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  flex-shrink: 0;\n}\n\n.mwc-document-thumbnail svg {\n  width: 48px;\n  height: 48px;\n  padding: 1rem;\n}\n\n.mwc-image-thumbnail {\n  width: 100%;\n  height: 100%;\n  object-fit: contain;\n}\n\n.mwc-document-checkbox {\n  cursor: pointer;\n  accent-color: #FE8E14;\n  width: 24px;\n  height: 24px;\n  justify-self: end;\n}\n";var HU,jU,zU,GU;!function(t){t.Library="library",t.Page="page",t.Document="document",t.Transfer="transfer",t.History="history",t.Scanner="Scanner"}(HU||(HU={})),function(t){t.Library="library",t.Page="page",t.Document="document",t.Transfer="transfer",t.History="history",t.Scanner="scanner",t.Correction="correction",t.ScanResult="scan-result"}(jU||(jU={})),function(t){t.CONFIRM="confirm",t.INPUT="input",t.TOAST="toast"}(zU||(zU={})),function(t){t.WARNING="warning",t.ERROR="error",t.SUCCESS="success"}(GU||(GU={}));const YU={[GU.WARNING]:'\n    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="24" height="24" fill="currentColor" class="modal-icon warning">\n  <path width="24" height="24" fill="currentColor"\n    d="M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm0 319.91a20 20 0 1120-20 20 20 0 01-20 20zm21.72-201.15l-5.74 122a16 16 0 01-32 0l-5.74-121.94v-.05a21.74 21.74 0 1143.44 0z" />\n</svg>\n  ',[GU.ERROR]:'\n    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="modal-icon error">\n      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />\n    </svg>\n  ',[GU.SUCCESS]:'\n  <svg id="selected-circle" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="modal-icon " width="24" height="24" viewBox="0 0 24 24">\n  <defs>\n    <clipPath id="selected-circleclip-path">\n      <rect id="Rectangle_2751" data-name="Rectangle 2751" width="24" height="24" fill="none"/>\n    </clipPath>\n  </defs>\n  <g id="Group_547" data-name="Group 547" clip-path="url(#selected-circleclip-path)">\n    <path id="Path_1478" data-name="Path 1478" d="M24,12A12,12,0,1,1,12,0,12,12,0,0,1,24,12" fill="#fe8e14"/>\n    <path id="Path_1479" data-name="Path 1479" d="M10.52,17.174a2.517,2.517,0,0,1-1.757-.725L5.757,13.442a1,1,0,0,1,1.414-1.414l3,3a.49.49,0,0,0,.387.144.511.511,0,0,0,.373-.2l5.8-7.742a1,1,0,0,1,1.6,1.2l-5.81,7.748a2.514,2.514,0,0,1-1.83.994c-.059,0-.117.006-.176.006" fill="#fff"/>\n  </g>\n</svg>'};async function $U(t,e,i=GU.SUCCESS,n=1500){return await XU({container:t,type:zU.TOAST,title:e,variant:i,duration:n})}function XU({container:t,type:e=zU.CONFIRM,variant:i=GU.SUCCESS,title:n,message:s,placeholder:o,initialValue:r="",confirmText:a="OK",cancelText:l="CANCEL",validation:h,duration:c,showCloseBtn:d}){if(!document.getElementById("modal-styles")){const t=document.createElement("style");t.id="modal-styles",t.textContent=qU,document.head.appendChild(t)}const u=t.style.position;t.style.position||(t.style.position="relative");const p=document.createElement("div");p.className="modal-overlay";const g=e===zU.INPUT?`\n        <div class="modal-input-container">\n          <input \n            type="text" \n            class="modal-input" \n            placeholder="${o||""}"\n            value="${r}"\n            maxlength="100"\n          >\n          <div class="modal-error"></div>\n        </div>\n        `:"",f=s?`\n      <div class="modal-message">\n        ${s}\n      </div>\n      `:"";if(e===zU.TOAST)return p.classList.add("toast"),p.innerHTML=`\n        <div class="modal-toast">\n          ${YU[i]||""}\n          <div class="modal-title">${n}</div>\n        </div>\n      `,t.appendChild(p),new Promise(t=>{const e=p.querySelector(".modal-toast");setTimeout(()=>{e.classList.add("fade-out"),p.remove(),t(null)},c)});p.innerHTML=`\n  <div class="modal">\n    ${e===zU.CONFIRM?d?`<button type="button" class="close-btn">${OU.close}</button>`:YU[i]||"":""}\n    <div class="modal-title">${n}</div>\n    ${f}\n    ${g}\n    <div class="modal-actions">\n      <button class="modal-btn cancel">${l}</button>\n      <button class="modal-btn confirm ${i}">${a}</button>\n    </div>\n  </div>\n`,t.appendChild(p);const m=p.querySelector(".modal-input"),v=p.querySelector(".modal-error"),y=p.querySelector(".confirm"),x=p.querySelector(".cancel"),w=p.querySelector(".close-btn");return m&&(m.selectionStart=m.value.length,m.focus()),new Promise(i=>{const n=()=>{if(e===zU.INPUT){const t=m.value.trim();if(h){const e=h(t);if(e)return void o(e)}i(t)}else i(!0);s()},s=()=>{p.classList.add("fade-out"),setTimeout(()=>{p.remove(),t.style.position=u},200)},o=t=>{v.textContent=t,v.style.opacity="1",v.style.height="auto",m.classList.add("error"),m.classList.add("shake"),setTimeout(()=>m.classList.remove("shake"),500)};null==y||y.addEventListener("click",n),null==x||x.addEventListener("click",()=>{i(!1),s()}),null==w||w.addEventListener("click",()=>{i(null),s()}),m&&(m.addEventListener("input",t=>{let e=t.target.value;e=e.replace(/[\x00-\x1F\x7F]/g,""),e.startsWith(" ")&&(e=e.trimStart()),t.target.value=e,v&&(v.style.opacity="0",v.style.height="0px",null==m||m.classList.remove("error")),y.classList.toggle("disabled",!e.trim())}),m.addEventListener("keyup",t=>{"Enter"===t.key?n():"Escape"===t.key&&(i(!1),s())}),y.classList.toggle("disabled",!m.value.trim())),p.addEventListener("click",t=>{t.target===p&&(i(null),s())}),document.addEventListener("keyup",function t(e){"Escape"===e.key&&(document.removeEventListener("keyup",t),i(!1),s())})})}const qU="\n.modal-overlay {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.5);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 1000;\n  animation: fadeIn 0.2s ease-out;\n}\n\n.modal-overlay.toast {\n  background-color: transparent;\n  pointer-events: none;\n}\n\n.modal-toast {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  background-color: rgba(0, 0, 0, 0.8);\n  color: white;\n  padding: 1rem;\n  border-radius: 8px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-direction: column;\n  gap: 0.5rem;\n  width: 80px;\n  height: 80px;\n  z-index: 1001;\n  opacity: 1;\n  animation: toastIn 0.2s ease-out;\n}\n\n.modal-toast.fade-out {\n  animation: toastOut 0.2s ease-out forwards;\n}\n\n\n.modal-toast .modal-icon {\n  width: 24px;\n  height: 24px;\n}\n\n.modal-overlay:not(.toast) {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.5);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 1000;\n  animation: fadeIn 0.2s ease-out;\n}\n\n.modal-overlay.fade-out {\n  animation: fadeOut 0.2s ease-out;\n}\n\n.modal {\n  background-color: white;\n  padding: 1rem;\n  border-radius: 8px;\n  width: 90%;\n  max-width: 320px;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 0.5rem;\n  position: relative;\n}\n\n.modal-icon {\n  width: 48px;\n  height: 48px;\n  margin: 0 auto;\n}\n\n.modal-icon.warning {\n  color: #f59e0b;\n}\n\n.modal-icon.error {\n  stroke: #ef4444;\n}\n\n.modal-title {\n  font-size: 16px;\n  font-family: Verdana;\n  text-align: center;\n  padding-bottom: 1rem;\n}\n\n.modal-toast .modal-title {\n  color: white;\n  padding-bottom: 0;\n  text-align: center;\n}\n\n.modal .close-btn {\n  position: absolute;\n  right: 1rem;\n  top: 1rem;\n  border: none;\n  padding: 0;\n  margin: 0;\n  background-color: transparent;\n  cursor: pointer;\n}\n\n.modal .close-btn svg {\n  color: #858585;\n}\n\n.modal-message {\n  font-size: 14px;\n  font-family: Verdana;\n  color: #666;\n  text-align: center;\n}\n\n.modal-input-container {\n  display: flex;\n  flex-direction: column;\n}\n\n.modal-input {\n  padding: 8px 12px;\n  border: 1px solid #ccc;\n  border-radius: 4px;\n  font-size: 16px;\n  font-family: Verdana;\n  transition: border-color 0.2s;\n}\n\n.modal-input.error {\n  border-color: #ef4444;\n}\n\n.modal-input.shake {\n  animation: shake 0.5s;\n}\n\n.modal-error {\n  color: #ef4444;\n  font-size: 12px;\n  min-height: 0;\n  opacity: 0;\n  transition: opacity 0.2s, height 0.2s;\n}\n\n.modal-actions {\n  display: flex;\n  justify-content: flex-end;\n  gap: 12px;\n  margin-top: 8px;\n}\n\n.modal-btn {\n  padding: 8px 16px;\n  border: none;\n  border-radius: 4px;\n  font-family: Verdana;\n  font-size: 14px;\n  cursor: pointer;\n  transition: opacity 0.2s;\n}\n\n.modal-btn:hover {\n  opacity: 0.9;\n}\n\n.modal-btn.cancel {\n  background-color: #e6e6e6;\n  color: #333;\n}\n\n.modal-btn.confirm {\n background-color: #fe8e14;\n  color: white;\n}\n\n.modal-btn.confirm.warning {\n  background-color: #FE8E14;\n}\n\n.modal-btn.confirm.error {\n  background-color: #ef4444;\n}\n\n.modal-btn.confirm.info {\n  background-color: #FE8E14;\n}\n\n.modal-btn.confirm.disabled {\n  opacity: 0.4;\n  cursor: not-allowed;\n  pointer-events: none;\n}\n\n@keyframes fadeIn {\n  from { opacity: 0; }\n  to { opacity: 1; }\n}\n\n@keyframes fadeOut {\n  from { opacity: 1; }\n  to { opacity: 0; }\n}\n\n@keyframes toastIn {\n  0% { \n    opacity: 0;\n    transform: translate(-50%, calc(-50% + 20px));\n  }\n  100% { \n    opacity: 1;\n    transform: translate(-50%, -50%);\n  }\n}\n\n@keyframes toastOut {\n  0% { \n    opacity: 1;\n    transform: translate(-50%, -50%);\n  }\n  100% { \n    opacity: 0;\n    transform: translate(-50%, calc(-50% - 20px));\n  }\n}\n\n@keyframes shake {\n  0%, 100% { transform: translateX(0); }\n  10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }\n  20%, 40%, 60%, 80% { transform: translateX(2px); }\n}\n";class ZU{constructor(t){this.config=t,this.MWCViewElements={headerContainer:null,contentContainer:null,emptyContentContainer:null,toolbarContainer:null,selectedToolbarContainer:null},this.isSelectionMode=!1}initialize(){if(!this.config.container)throw new Error("Create a container element");this.createMWCView()}createMWCView(){this.config.container.textContent="",FU("mwc-views-style",JU),this.createHeader(),this.createContent(),this.createEmptyContent(),this.createToolbars()}createHeader(t=!0){t&&(this.MWCViewElements.headerContainer=document.createElement("div"),this.MWCViewElements.headerContainer.className="mwc-view-header",this.config.container.appendChild(this.MWCViewElements.headerContainer))}createContent(){this.MWCViewElements.contentContainer=document.createElement("div"),this.MWCViewElements.contentContainer.className="mwc-view-content",this.config.container.appendChild(this.MWCViewElements.contentContainer)}createEmptyContent(){this.MWCViewElements.emptyContentContainer=document.createElement("div"),this.MWCViewElements.emptyContentContainer.className="mwc-view-content-empty",this.config.container.appendChild(this.MWCViewElements.emptyContentContainer)}async setEmptyContent(t){const e=this.MWCViewElements.emptyContentContainer;e.textContent="";try{if("object"==typeof t&&"templatePath"in t){const i=await fetch(t.templatePath);if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);const n=await i.text();e.innerHTML=n;const s=e.querySelector("template");s&&(e.innerHTML=s.innerHTML),e.style.display="flex",e.style.height="100%",e.style.alignItems="center",e.style.justifyContent="center"}else if(t instanceof HTMLTemplateElement){const i=document.importNode(t.content,!0);e.appendChild(i)}else if(t instanceof HTMLElement)e.appendChild(t);else if("string"==typeof t)if(t.trim().startsWith("<template")){const i=document.createElement("template");i.innerHTML=t;const n=document.importNode(i.content,!0);e.appendChild(n)}else e.innerHTML=t}catch(t){console.error("Error setting empty content:",t),e.innerHTML="<div>No content available</div>"}}createToolbars(){this.MWCViewElements.toolbarContainer=document.createElement("div"),this.MWCViewElements.toolbarContainer.className="mwc-view-controls-container",this.config.container.appendChild(this.MWCViewElements.toolbarContainer),this.MWCViewElements.selectedToolbarContainer=document.createElement("div"),this.MWCViewElements.selectedToolbarContainer.className="mwc-view-controls-container",this.MWCViewElements.selectedToolbarContainer.style.display="none",this.config.container.appendChild(this.MWCViewElements.selectedToolbarContainer)}createToolbarButton(t){const e=document.createElement("div");if(e.className=`mwc-view-controls-btn ${(null==t?void 0:t.className)||""}`,!t)return e.classList.add("disabled"),e.innerHTML="<div></div>",e;const i=document.createElement("div");if(i.className="icon",(n=t.icon).trim().startsWith("<svg")&&n.trim().endsWith("</svg>"))i.innerHTML=t.icon;else{const e=document.createElement("img");e.src=t.icon,e.alt=t.label,e.width=24,e.height=24,i.appendChild(e)}var n;const s=document.createElement("div");return s.className="label",s.textContent=t.label,!0===t.isDisabled&&e.classList.add("disabled"),!0===t.isHidden&&e.classList.add("hide"),e.appendChild(i),e.appendChild(s),t.onClick&&e.addEventListener("click",t.onClick),e}setVisible(t,e){this.config.container.style.display=t?"flex":"none"}showContent(t){this.MWCViewElements.contentContainer.style.display=t?"flex":"none",this.MWCViewElements.emptyContentContainer.style.display=t?"none":"flex"}toggleSelectionMode(t){this.isSelectionMode=t,this.updateToolbarState()}updateToolbarState(){this.MWCViewElements.toolbarContainer.style.display=this.isSelectionMode?"none":"flex",this.MWCViewElements.selectedToolbarContainer.style.display=this.isSelectionMode?"flex":"none"}}const JU="\n  .mwc-view-container {\n    display: flex;\n    flex-direction: column;\n    position: relative;\n    width: 100%;\n    height: 100%;\n    background-color: white;\n    font-family: Verdana;\n    color: black;\n  }\n\n  .mwc-view-container .mwc-view-header {\n    display: flex;\n    font-family: Verdana;\n    height: 3rem;\n    font-size: 24px;\n    align-items: center;\n    justify-content: center;\n    background-color: #e6e6e6;\n    flex: 0 1 3rem;\n    padding: 0.5rem;\n    user-select: none;\n        color: black;\n  }\n\n  .mwc-view-container .mwc-view-header .mwc-view-header-title {\n    white-space: nowrap;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    max-width: 100%;\n        color: black;\n  }\n\n  .mwc-library-header-btn:hover {\n    text-decoration: underline;\n  }\n\n  .mwc-view-container .mwc-view-content {\n    flex: 1 1 auto;\n    overflow-y: auto;\n    display: none;\n    flex-direction: column;\n    justify-content: start;\n    padding: 1rem;\n    gap: 1rem;\n    padding-bottom: 2rem;\n  }\n\n  .mwc-view-container .mwc-view-content-empty {\n    flex: 1 1 auto;\n    overflow-y: auto;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    padding: 1rem;\n    user-select: none;\n    font-family: Verdana;\n  }\n\n  .mwc-view-container .mwc-view-content-empty {\n    flex: 1 1 auto;\n    overflow-y: auto;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    padding: 1rem;\n    user-select: none;\n    font-family: Verdana;\n  }\n\n  .mwc-view-container .mwc-view-controls-container {\n    display: flex;\n    height: 6rem;\n    background-color: #323234;\n    align-items: center;\n    font-size: 12px;\n    font-family: Verdana;\n    color: white;\n    width: 100%;\n    flex: 0 1 65px;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn {\n    color: white;\n    cursor: pointer;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    flex-direction: column;\n    height: 100%;\n    width: 100%;\n    gap: 0.5rem;\n    text-align: center;\n    user-select: none;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn >div:first-child {\n    padding-top: 1rem;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn >div:last-child {\n    padding-bottom: 1rem;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn.selected{\n    background-color: #E36605;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn.disabled {\n    pointer-events: none;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn.disabled >div {\n    opacity: 0.4;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn.hide {\n    display: none;\n  }\n\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn .icon img,\n  .mwc-view-container .mwc-view-controls-container .mwc-view-controls-btn .icon svg {\n    width: 24px;\n    height: 24px;\n  }\n";class KU{constructor(t){this.config=t,this.checked=!1,this.createUI(),this.bindEvents(),this.toggleCheck(!1)}createUI(){this.createStylesheet();const t=$I.documentManager.getDocument(this.config.docId),e=t.pages.length;this.dom=document.createElement("div"),this.dom.className="mwc-document-item",this.dom.innerHTML=`\n      <div class="mwc-transfer-info-container">\n        <div class="mwc-transfer-thumbnail">\n          ${OU.defaultDocument}\n        </div>\n        <div class="mwc-transfer-info">\n          <div class="mwc-transfer-name-container">\n            ${t.name}           \n          </div>\n          <div class="mwc-transfer-pages">${e} pages</div>\n        </div>\n      </div>\n      <div class="mwc-transfer-check-icon">\n        ${OU.selectedCircle}\n      </div>\n    `,this.selectedIcon=this.dom.querySelector(".mwc-transfer-check-icon"),this.updateThumbnail(t)}createStylesheet(){const t=document.createElement("style");t.textContent=QU,document.head.appendChild(t)}async updateThumbnail(t){const e=this.dom.querySelector(".mwc-transfer-thumbnail");if(e.textContent="",t.pages[0]){const i=t.getPageData(t.pages[0]),n=await i.display(),s=URL.createObjectURL(n.data),o=document.createElement("img");o.className="mwc-image-thumbnail",o.alt="mwc-image-thumbnail",o.src=s,e.append(o)}else e.innerHTML=OU.defaultDocument}bindEvents(){this.dom.addEventListener("click",t=>{this.toggleCheck()})}toggleCheck(t){var e,i;this.checked=null!=t?t:!this.checked,this.selectedIcon.style.display=this.checked?"flex":"none",this.dom.style.border=this.checked?"2px solid #FE8E14":"2px solid transparent",null===(i=(e=this.config).onCheckedChange)||void 0===i||i.call(e,this.config.docId,this.checked)}getDom(){return this.dom}dispose(){this.dom.remove()}}const QU="\n.mwc-transfer-item {\n  display: grid;\n  grid-template-columns: 90% 10%;\n  background-color: #EFEFEF;\n  cursor: pointer;\n  font-family: Verdana;\n  padding: 15px;\n  align-items: center\n}\n\n.mwc-transfer-info-container {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n}\n\n.mwc-transfer-info {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  padding-right: 1rem;\n  overflow: hidden;\n}\n\n.mwc-transfer-info .mwc-transfer-name-container  {\n  font-size: 16px;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n\n\n.mwc-transfer-info .mwc-transfer-pages {\n  color: #888888;\n}\n\n.mwc-transfer-thumbnail {\n  width: 70px;\n  height: 70px;\n  background-color: #DADCE0;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n\n.mwc-transfer-thumbnail svg {\n  width: 48px;\n  height: 48px;\n  padding: 1rem;\n}\n\n.mwc-image-thumbnail {\n  width: 100%;\n  height: 100%;\n  object-fit: contain;\n}\n";var tF;!function(t){t.Copy="copy",t.Move="move"}(tF||(tF={}));class eF extends ZU{constructor(t){super(t),this.config=t,this.transferMode=tF.Copy,this.checkedDocUids=[],this.docItems=[],this.toolbarBtn={action:null,cancel:null},this.headerTitle=null}initialize(){super.initialize(),FU("mwc-transfer-view-style",iF),this.updateEmptyContentHTML(),this.setVisible(!1)}createHeader(){super.createHeader(),this.MWCViewElements.headerContainer.innerHTML='\n      <div class="mwc-transfer-view-header-title">Transfer Page</div>\n    ',this.headerTitle=this.MWCViewElements.headerContainer.querySelector(".mwc-transfer-view-header-title")}createContent(){this.MWCViewElements.contentContainer=document.createElement("div"),this.MWCViewElements.contentContainer.className="mwc-view-content",this.config.container.appendChild(this.MWCViewElements.contentContainer)}updateEmptyContentHTML(){this.MWCViewElements.emptyContentContainer.innerHTML='\n      <div class="title">\n        No other documents to move the pages!\n      </div>\n      <div class="desc">\n        Please create another document!\n      </div>\n    '}createToolbars(){super.createToolbars();[{id:"mwc-transfer-cancel",icon:OU.back,label:"Cancel",onClick:()=>this.handleCancelButton()},{id:"mwc-transfer-action",icon:OU.done,label:"Action",className:"action-btn",onClick:()=>{}}].forEach(t=>{const e=this.createToolbarButton(t);"mwc-transfer-cancel"===t.id?this.toolbarBtn.cancel=e:"mwc-transfer-action"===t.id&&(this.toolbarBtn.action=e),this.MWCViewElements.toolbarContainer.appendChild(e)})}updateHeaderAndAction(){switch(this.transferMode){case tF.Copy:this.headerTitle.textContent="Copy Selected Pages to",this.toolbarBtn.action.children[1].textContent="Paste";break;case tF.Move:this.headerTitle.textContent="Move Selected Pages to",this.toolbarBtn.action.children[1].textContent="Confirm"}}setVisible(t,e){if(super.setVisible(t),t&&e){this.MWCViewElements.contentContainer.textContent="",this.transferMode=e.mode,this.updateHeaderAndAction(),this.updateToolbarStyle(),this.toolbarBtn.action.onclick=()=>this.handleActionClick(e.docId,e.selectedIdx);const t=$I.documentManager.getAllDocuments().filter(t=>this.transferMode!==tF.Move||t.uid!==e.docId),i=t.length>0;this.showContent(i),i&&this.loadDocuments(t)}}loadDocuments(t){t.forEach(t=>{const e=new KU({docId:t.uid,onCheckedChange:(t,e)=>this.handleDocumentChecked(t,e)});this.docItems.unshift(e),this.MWCViewElements.contentContainer.firstChild?this.MWCViewElements.contentContainer.insertBefore(e.getDom(),this.MWCViewElements.contentContainer.firstChild):this.MWCViewElements.contentContainer.appendChild(e.getDom())})}handleDocumentChecked(t,e){var i;e?this.checkedDocUids.push(t):this.checkedDocUids=null===(i=this.checkedDocUids)||void 0===i?void 0:i.filter(e=>e!==t),this.updateToolbarStyle()}updateToolbarStyle(){const t=this.transferMode===tF.Move?1!==this.checkedDocUids.length:this.checkedDocUids.length<1;this.toolbarBtn.action.classList.toggle("disabled",t)}handleCancelButton(){var t,e;this.checkedDocUids=[],this.docItems.forEach(t=>{t.toggleCheck(!1),t.dispose()}),this.docItems=[],null===(e=(t=this.config).onCancelTransfer)||void 0===e||e.call(t)}handleActionClick(t,e){var i,n;this.toolbarBtn.action.classList.contains("disabled")||(this.transferMode===tF.Copy?this.checkedDocUids.forEach(i=>{$I.documentManager.copyPagesToDocument(t,i,{sourceIndices:[...e]})}):this.transferMode===tF.Move&&$I.documentManager.movePagesToDocument(t,this.checkedDocUids[0],{sourceIndices:[...e]}),null===(n=(i=this.config).onConfirmTransfer)||void 0===n||n.call(i,this.transferMode),this.handleCancelButton())}dispose(){this.docItems.forEach(t=>t.dispose()),this.docItems=[],this.checkedDocUids=[],this.config.container&&(this.config.container.style.display="none")}}const iF="\n  .mwc-view-controls-btn.action-btn .label {\n    color: #fe8e14;\n  }\n";class nF extends ZU{constructor(t){super(t),this.config=t,this.documentTitle=null,this.headerRenameTitleBtn=null,this.toolbarBtn={backToLibrary:null,capture:null,import:null,shareDocument:null,uploadDocument:null,manage:null,copyTo:null,moveTo:null,deleteImage:null,shareImage:null,uploadImage:null,back:null},this.headerTitle=null,this.headerActionBtn={close:null,cancel:null,selectAll:null},this.browseViewer=null,this.isDragged=!1}bindBrowseViewerEvents(){this.browseViewer.on("selectedPagesChanged",t=>{var e;if(!this.isSelectionMode)return;(null===(e=this.browseViewer)||void 0===e?void 0:e.currentDocument)&&this.handlePageChecked()}),this.browseViewer.on("click",t=>{if(!this.isSelectionMode){if(!BU()&&this.isDragged)return void(this.isDragged=!1);if(t.index>-1){const e=this.browseViewer.currentDocument;this.config.onPageClick&&this.config.onPageClick(e.uid,t.index)}}}),this.browseViewer.on("pagesDragged",()=>{this.isDragged=!0})}initialize(){FU("mwc-document-view-style",sF),super.initialize(),this.createBrowseViewer(),this.bindBrowseViewerEvents(),this.updateEmptyContentHTML(),this.setVisible(!1)}setVisible(t){super.setVisible(t);const e=this.browseViewer.currentDocument;if(t){const t=e&&e.pages.length>0;this.updateHeaderActionBtnStyle(),this.showContent(t),this.updateToolbarBtnStates()}}createBrowseViewer(){var t;this.browseViewer=new $I.BrowseViewer({container:this.MWCViewElements.contentContainer,uiConfig:{type:$I.Elements.Layout,style:{border:"none"},children:[$I.Elements.MainView]},groupUid:null===(t=this.config)||void 0===t?void 0:t.groupUid,viewerConfig:{canvasStyle:{background:"white"},checkboxStyle:{borderRadius:"1px",left:"6px",top:"6px",width:"24px",height:"24px",visibility:"hidden"},currentPageStyle:{border:"2px solid #FE8E14"},pageStyle:{background:"#e6e6e6"}}}),this.browseViewer.setRowAndColumn(2,2)}createHeader(){var t;super.createHeader(),this.MWCViewElements.headerContainer.innerHTML=`\n    <div class="mwc-document-view-header">\n      <div class="mwc-document-view-header-container">\n        <div class="mwc-document-view-header-doc-name">Document Name</div>\n        <button type="button" class="mwc-document-view-header-btn rename">\n          ${OU.edit}\n        </button>\n      </div>\n      <div class="mwc-document-view-header-actions">\n        <button type="button" class="mwc-document-view-header-btn selectAll">Select All</button>\n        <button type="button" class="mwc-document-view-header-btn cancel">Cancel</button>\n        <button type="button" class="mwc-document-view-header-btn close" style="display: ${this.config.showLibraryView?"none":"flex"}">\n          ${OU.close}\n        </button>\n      </div>\n    </div>\n    `,this.documentTitle=this.MWCViewElements.headerContainer.querySelector(".mwc-document-view-header-doc-name"),this.headerRenameTitleBtn=this.MWCViewElements.headerContainer.querySelector(".mwc-document-view-header-btn.rename"),null===(t=this.headerRenameTitleBtn)||void 0===t||t.addEventListener("click",()=>this.handleRename()),this.headerActionBtn.close=this.MWCViewElements.headerContainer.querySelector(".close"),this.headerActionBtn.close.addEventListener("click",()=>this.handleClose()),this.headerActionBtn.selectAll=this.MWCViewElements.headerContainer.querySelector(".selectAll"),this.headerActionBtn.selectAll.addEventListener("click",()=>this.handleSelectAll()),this.headerActionBtn.cancel=this.MWCViewElements.headerContainer.querySelector(".cancel"),this.headerActionBtn.cancel.addEventListener("click",()=>this.handleSelectAll()),this.updateHeaderActionBtnStyle()}updateHeaderActionBtnStyle(){if(this.isSelectionMode){this.documentTitle.textContent="Select Pages",this.headerRenameTitleBtn.style.display="none",this.headerActionBtn.close.style.display="none";const t=this.browseViewer.getSelectedPageIndices().length===this.browseViewer.currentDocument.pages.length;this.headerActionBtn.selectAll.style.display=t?"none":"flex",this.headerActionBtn.cancel.style.display=t?"flex":"none"}else this.updateHeaderTitle(),this.headerRenameTitleBtn.style.display="flex",this.headerActionBtn.close.style.display=this.config.showLibraryView?"none":"flex",this.headerActionBtn.selectAll.style.display="none",this.headerActionBtn.cancel.style.display="none"}updateHeaderTitle(){var t;const e=null===(t=this.browseViewer)||void 0===t?void 0:t.currentDocument;this.documentTitle.textContent=(null==e?void 0:e.name)||"Document Name"}async handleRename(){const t=this.browseViewer.currentDocument;if(!t)return;const e=await XU({container:this.config.container,type:zU.INPUT,title:"Rename Document",placeholder:"Enter document name",initialValue:t.name,confirmText:"Rename",validation:t=>t.length<1?"Name can't be empty":null});e&&(t.rename(e),this.updateHeaderTitle(),await $U(this.config.container,"Renamed"))}dispose(){var t;null===(t=this.browseViewer)||void 0===t||t.destroy(),this.browseViewer=null,$I.documentManager.deleteAllDocuments(),this.config.container&&(this.config.container.style.display="none")}handleClose(){var t;if(!this.config.showLibraryView)try{null===(t=this.config)||void 0===t||t.onClose()}catch(t){console.error("Failed to close library view:",t)}}updateEmptyContentHTML(){const t=`\n    <div class="mwc-default-empty-document">\n      ${OU.emptyLibrary}\n      <div class="title">Add your first page!</div>\n      <div class="desc">\n        <div>Option 1: Click "<b>Capture</b>" for live images</div>\n        <div>Option 2: Click "<b>Import</b>" for existing images</div>\n      </div>\n    </div>`;super.setEmptyContent(this.config.emptyContentConfig||t)}createToolbars(){var t,e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x,w,C,b,S,T,E,_,P,A,I,D,R,k,M,L,O,B,N,U,F,V,W,H,j,z,G,Y,$,X;super.createToolbars();const{toolbarButtonsConfig:q,exportConfig:Z,showLibraryView:J}=this.config,K=!!(null==Z?void 0:Z.uploadToServer),Q=new File([""],"test.pdf",{type:"application/pdf"}),tt="share"in navigator&&navigator.canShare({files:[Q]}),et=()=>{tt?this.handleShareDoc():nF.handleDownloadDoc(this.browseViewer.currentDocument,this.config.container)},it=()=>{tt?this.handleShareImage():this.handleDownloadImage()};[{id:"mwc-document-backToLibrary",icon:null!==(e=null===(t=null==q?void 0:q.backToLibrary)||void 0===t?void 0:t.icon)&&void 0!==e?e:OU.back,label:(null===(i=null==q?void 0:q.backToLibrary)||void 0===i?void 0:i.label)||"Back",isHidden:(null===(n=null==q?void 0:q.backToLibrary)||void 0===n?void 0:n.isHidden)||!this.config.showLibraryView||!1,className:`${(null===(s=null==q?void 0:q.backToLibrary)||void 0===s?void 0:s.className)||""}`,onClick:()=>{var t,e;return null===(e=(t=this.config).onBackToLibrary)||void 0===e?void 0:e.call(t)}},{id:"mwc-document-capture",icon:(null===(o=null==q?void 0:q.capture)||void 0===o?void 0:o.icon)||OU.cameraCapture,label:(null===(r=null==q?void 0:q.capture)||void 0===r?void 0:r.label)||"Capture",isHidden:(null===(a=null==q?void 0:q.capture)||void 0===a?void 0:a.isHidden)||!1,className:`${(null===(l=null==q?void 0:q.capture)||void 0===l?void 0:l.className)||""}`,onClick:()=>{var t,e;return null===(e=(t=this.config).onCameraCapture)||void 0===e?void 0:e.call(t)}},{id:"mwc-document-import",icon:(null===(h=null==q?void 0:q.import)||void 0===h?void 0:h.icon)||OU.galleryImport,label:(null===(c=null==q?void 0:q.import)||void 0===c?void 0:c.label)||"Import",isHidden:(null===(d=null==q?void 0:q.import)||void 0===d?void 0:d.isHidden)||!1,className:`${(null===(u=null==q?void 0:q.import)||void 0===u?void 0:u.className)||""}`,onClick:()=>{var t,e;return null===(e=(t=this.config).onGalleryImport)||void 0===e?void 0:e.call(t)}},{id:"mwc-document-shareDocument",icon:(null===(p=null==q?void 0:q.shareDocument)||void 0===p?void 0:p.icon)||(tt?OU.sharePDF:OU.downloadPDF),label:(null===(g=null==q?void 0:q.shareDocument)||void 0===g?void 0:g.label)||(tt?"Share":"Download"),className:`${(null===(f=null==q?void 0:q.shareDocument)||void 0===f?void 0:f.className)||""}`,isHidden:(null===(m=null==q?void 0:q.shareDocument)||void 0===m?void 0:m.isHidden)||!1,onClick:()=>et()},{id:"mwc-document-uploadDocument",icon:(null===(v=null==q?void 0:q.uploadDocument)||void 0===v?void 0:v.icon)||OU.uploadPDF,label:(null===(y=null==q?void 0:q.uploadDocument)||void 0===y?void 0:y.label)||"Upload",className:`${(null===(x=null==q?void 0:q.uploadDocument)||void 0===x?void 0:x.className)||""}`,isHidden:(null===(w=null==q?void 0:q.uploadDocument)||void 0===w?void 0:w.isHidden)||!K,onClick:()=>this.handleUploadDocument()},{id:"mwc-document-manage",icon:(null===(C=null==q?void 0:q.manage)||void 0===C?void 0:C.icon)||OU.fileOperations,label:(null===(b=null==q?void 0:q.manage)||void 0===b?void 0:b.label)||"Manage",isHidden:(null===(S=null==q?void 0:q.manage)||void 0===S?void 0:S.isHidden)||!1,className:`${(null===(T=null==q?void 0:q.manage)||void 0===T?void 0:T.className)||""}`,onClick:()=>this.handleManagePages()}].forEach(t=>{const e=this.createToolbarButton(t);this.toolbarBtn[`${t.id.split("-").pop()}`]=e,this.MWCViewElements.toolbarContainer.appendChild(e)});[{id:"mwc-document-select-copyTo",icon:(null===(E=null==q?void 0:q.copyTo)||void 0===E?void 0:E.icon)||OU.copyTo,label:(null===(_=null==q?void 0:q.copyTo)||void 0===_?void 0:_.label)||"Copy To",className:`selected ${(null===(P=null==q?void 0:q.copyTo)||void 0===P?void 0:P.className)||""}`,isHidden:(null===(A=null==q?void 0:q.copyTo)||void 0===A?void 0:A.isHidden)||!J,onClick:()=>this.handleTransferPage(tF.Copy)},{id:"mwc-document-select-moveTo",icon:(null===(I=null==q?void 0:q.moveTo)||void 0===I?void 0:I.icon)||OU.moveTo,label:(null===(D=null==q?void 0:q.moveTo)||void 0===D?void 0:D.label)||"Move To",className:`selected ${(null===(R=null==q?void 0:q.moveTo)||void 0===R?void 0:R.className)||""}`,isHidden:(null===(k=null==q?void 0:q.moveTo)||void 0===k?void 0:k.isHidden)||!J,onClick:()=>this.handleTransferPage(tF.Move)},{id:"mwc-library-select-deleteImage",icon:(null===(M=null==q?void 0:q.deleteImage)||void 0===M?void 0:M.icon)||OU.delete,label:(null===(L=null==q?void 0:q.deleteImage)||void 0===L?void 0:L.label)||"Delete",className:`selected ${(null===(O=null==q?void 0:q.deleteImage)||void 0===O?void 0:O.className)||""}`,isHidden:null===(B=null==q?void 0:q.deleteImage)||void 0===B?void 0:B.isHidden,onClick:()=>this.handleDeleteImage()},{id:"mwc-document-select-shareImage",icon:(null===(N=null==q?void 0:q.shareImage)||void 0===N?void 0:N.icon)||(tt?OU.sharePNG:OU.downloadPNG),label:(null===(U=null==q?void 0:q.shareImage)||void 0===U?void 0:U.label)||(tt?"Share":"Download"),isHidden:null===(F=null==q?void 0:q.shareImage)||void 0===F?void 0:F.isHidden,className:`selected ${(null===(V=null==q?void 0:q.shareImage)||void 0===V?void 0:V.className)||""}`,onClick:()=>it()},{id:"mwc-document-uploadImage",icon:(null===(W=null==q?void 0:q.uploadImage)||void 0===W?void 0:W.icon)||OU.uploadPNG,label:(null===(H=null==q?void 0:q.uploadImage)||void 0===H?void 0:H.label)||"Upload",className:`selected ${(null===(j=null==q?void 0:q.uploadImage)||void 0===j?void 0:j.className)||""}`,isHidden:(null===(z=null==q?void 0:q.uploadImage)||void 0===z?void 0:z.isHidden)||!K,onClick:()=>this.handleUploadImage()},{id:"mwc-library-select-back",icon:(null===(G=null==q?void 0:q.back)||void 0===G?void 0:G.icon)||OU.back,label:(null===(Y=null==q?void 0:q.back)||void 0===Y?void 0:Y.label)||"Back",className:`selected ${(null===($=null==q?void 0:q.back)||void 0===$?void 0:$.className)||""}`,isHidden:null===(X=null==q?void 0:q.back)||void 0===X?void 0:X.isHidden,onClick:()=>this.handleSelectedBack()}].forEach(t=>{const e=this.createToolbarButton(t);this.toolbarBtn[`${t.id.split("-").pop()}`]=e,this.MWCViewElements.selectedToolbarContainer.appendChild(e)})}async handleShareDoc(){const t=[],e=this.browseViewer.currentDocument;if(e.pages.length){const i=await e.saveToPdf({mimeType:"application/octet-stream",saveAnnotation:"annotation",quality:100});t.push(new File([i],`${e.name}.pdf`,{type:"application/pdf"}))}if(navigator.canShare&&navigator.canShare({files:t}))try{await navigator.share({files:t,title:"PDF Files"})}catch(t){"AbortError"!==t.name&&await $U(this.config.container,"Failed to share files",GU.ERROR)}else await $U(this.config.container,"Your system doesn't support sharing PDF files",GU.WARNING)}static async handleDownloadDoc(t,e){var i;(null===(i=null==t?void 0:t.pages)||void 0===i?void 0:i.length)?t.saveToPdf({mimeType:"application/octet-stream",saveAnnotation:"annotation",quality:100}).then(e=>{const i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=`${t.name}.pdf`,n.click(),n.remove()}):(console.warn("Failed to download. Document contains no pages"),await $U(e,"Document contains no pages!",GU.WARNING))}async handleUploadDocument(){var t,e,i,n,s,o,r,a,l,h;if(null===(e=null===(t=this.config)||void 0===t?void 0:t.exportConfig)||void 0===e?void 0:e.uploadToServer)try{const t=this.browseViewer.currentDocument;if(null===(i=null==t?void 0:t.pages)||void 0===i?void 0:i.length){const e=await t.saveToPdf({mimeType:"application/pdf",saveAnnotation:"annotation",quality:100}),i=`${t.name}.pdf`,c=await(null===(s=null===(n=this.config)||void 0===n?void 0:n.exportConfig)||void 0===s?void 0:s.uploadToServer(i,e));if("success"===(null==c?void 0:c.status)){const t=this.config.getUploadedDocuments();t.push(c),this.config.updateUploadedDocuments(t);if(await(null===(r=null===(o=this.config.exportConfig)||void 0===o?void 0:o.onUploadSuccess)||void 0===r?void 0:r.call(o,i,"pdf",HU.Page,e)))return void(null===(a=this.config)||void 0===a||a.onClose());await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.SUCCESS,title:"Upload Successful",confirmText:"View in Uploads",cancelText:"Continue"})&&(null===(h=(l=this.config).onViewUploadsHistory)||void 0===h||h.call(l))}}else console.warn(`Upload failed: ${t.name} contains no pages`),await $U(this.config.container,"Document contains no pages!",GU.WARNING)}catch(t){let e=(null==t?void 0:t.message)||t;console.error("Upload failed:",e),await $U(this.config.container,"Upload Failed!",GU.ERROR)}else console.warn("No upload function configured")}handleManagePages(){this.toggleSelectionMode(!0)}handleSelectAll(){this.browseViewer.getSelectedPageIndices().length===this.browseViewer.currentDocument.pages.length?this.browseViewer.selectPages([]):this.browseViewer.selectAllPages(),this.updateToolbarBtnStates()}toggleSelectionMode(t){if(this.isSelectionMode!==t){if(super.toggleSelectionMode(t),this.browseViewer.multiselectMode=t,this.updateHeaderActionBtnStyle(),t){const t=this.browseViewer.getCurrentPageIndex();t>=0&&this.browseViewer.selectPages([t])}else this.browseViewer.selectPages([]);this.browseViewer.updateStyle("checkboxStyle",{visibility:t?"visible":"hidden",border:"1px solid #707070"})}}handlePageChecked(){this.updateToolbarBtnStates(),this.updateHeaderActionBtnStyle()}updateToolbarBtnStates(){var t;const e=this.browseViewer.currentDocument,i=!(null===(t=null==e?void 0:e.pages)||void 0===t?void 0:t.length),n=this.browseViewer.getSelectedPageIndices().length>0;this.browseViewer.getSelectedPageIndices().length,this.browseViewer.currentDocument.pages.length,this.toolbarBtn.manage.classList.toggle("disabled",i),this.toolbarBtn.shareDocument.classList.toggle("disabled",i),this.toolbarBtn.uploadDocument.classList.toggle("disabled",i),this.toolbarBtn.copyTo.classList.toggle("disabled",!n),this.toolbarBtn.moveTo.classList.toggle("disabled",!n),this.toolbarBtn.shareImage.classList.toggle("disabled",!n),this.toolbarBtn.deleteImage.classList.toggle("disabled",!n),this.toolbarBtn.uploadImage.classList.toggle("disabled",!n)}handleTransferPage(t){if(t===tF.Copy&&this.toolbarBtn.copyTo.classList.contains("disabled"))return;if(t===tF.Move&&this.toolbarBtn.moveTo.classList.contains("disabled"))return;const e=this.browseViewer.currentDocument,i=this.browseViewer.getSelectedPageIndices();this.config.onTransferPages(t,e.uid,i)}async handleDeleteImage(){if(this.toolbarBtn.deleteImage.classList.contains("disabled"))return;const t=this.browseViewer.getSelectedPageIndices();if(t.length>0){await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.WARNING,title:"Delete Pages",message:`Are you sure you want to delete ${1===t.length?"1 page":`${t.length} pages`}?`,confirmText:"Delete",cancelText:"Cancel",showCloseBtn:!0})&&(this.browseViewer.currentDocument.deletePages(t),this.showContent(0!==this.browseViewer.currentDocument.pages.length),this.updateToolbarBtnStates(),this.handleSelectedBack(),await $U(this.config.container,"Deleted",GU.SUCCESS))}}async handleShareImage(){try{const t=this.browseViewer.currentDocument,e=this.browseViewer.getSelectedPageIndices(),i=(await Promise.all(e.map(e=>t.saveToPng(e,{saveAnnotation:!0})))).map((i,n)=>new File([i],`${t.name}-${e[n]}-${Date.now()}.png`,{type:i.type}));if(navigator.canShare&&navigator.canShare({files:i}))try{await navigator.share({files:i,title:"Image Files"})}catch(t){"AbortError"!==t.name&&await $U(this.config.container,"Failed to share files",GU.ERROR)}else await $U(this.config.container,"Failed to share",GU.WARNING)}catch(t){await $U(this.config.container,"Error processing files",GU.ERROR)}}async handleDownloadImage(){const t=this.browseViewer.currentDocument,e=this.browseViewer.getSelectedPageIndices();try{e.forEach(async(i,n)=>{const s=await t.saveToPng(i,{saveAnnotation:!0}),o=URL.createObjectURL(s),r=document.createElement("a");r.href=o,r.download=`${t.name}-${e[n]}-${Date.now()}.png`,r.click(),r.remove(),URL.revokeObjectURL(o)}),await $U(this.config.container,"Downloaded",GU.SUCCESS)}catch(t){const e=(null==t?void 0:t.message)||t;console.warn("Download failed:",e),await $U(this.config.container,"Failed to download page",GU.ERROR)}}async handleUploadImage(){var t,e,i,n;if(null===(e=null===(t=this.config)||void 0===t?void 0:t.exportConfig)||void 0===e?void 0:e.uploadToServer)try{const t=this.browseViewer.currentDocument,e=this.browseViewer.getSelectedPageIndices(),s=e.map(async(i,n)=>{var s,o,r,a,l;const h=await t.saveToPng(i,{saveAnnotation:!0}),c=`${t.name}-${e[n]}-${Date.now()}.png`,d=new Blob([h],{type:"image/png"}),u=await(null===(o=null===(s=this.config)||void 0===s?void 0:s.exportConfig)||void 0===o?void 0:o.uploadToServer(c,d));if("success"===(null==u?void 0:u.status)){const t=this.config.getUploadedDocuments();t.push(u),this.config.updateUploadedDocuments(t);if(await(null===(a=null===(r=this.config.exportConfig)||void 0===r?void 0:r.onUploadSuccess)||void 0===a?void 0:a.call(r,c,"png",HU.Document,d)))return void(null===(l=this.config)||void 0===l||l.onClose())}return u}),o=await Promise.all(s),r=null==o?void 0:o.filter(t=>"success"===(null==t?void 0:t.status));if(r.length){await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.SUCCESS,title:"Upload Successful",confirmText:"View in Uploads",cancelText:"Continue"})&&(null===(n=(i=this.config).onViewUploadsHistory)||void 0===n||n.call(i))}}catch(t){let e=(null==t?void 0:t.message)||t;console.error("Upload failed:",e),await $U(this.config.container,"Upload Failed!",GU.ERROR)}else console.warn("No upload function configured")}handleSelectedBack(){this.toggleSelectionMode(!1)}}const sF="\n  .mwc-document-view-header {\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n    width: 100%;\n    color: black;\n  }\n\n  .mwc-document-view-header-btn {\n    border: none;\n    background: transparent;\n    display: flex;\n    align-content: center;\n    cursor: pointer;\n  }\n\n  .mwc-document-view-header-btn.rename{\n    width: 30px;\n    height: 30px;\n  }\n\n  .mwc-document-view-header-container {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    flex: 1;\n    max-width: calc(100% - 4rem);\n    padding-left: 1rem;\n  }\n\n  .mwc-document-view-header-container .mwc-document-view-header-doc-name {\n    font-family: Verdana;\n    font-size: 18px;\n    white-space: nowrap;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    user-select: none;\n  }\n\n  .mwc-document-view-header-actions {\n    display: flex;\n    align-items: center;\n    padding-right: 1rem;\n  }\n\n  .mwc-document-view-header-actions .mwc-document-view-header-btn.selectAll,\n  .mwc-document-view-header-actions .mwc-document-view-header-btn.cancel {\n    background: none;\n    border: none;\n    color: #FE8E14;\n    font-size: 14px;\n    cursor: pointer;\n    padding: 4px 8px;\n    align-content: end;\n  }\n\n  .mwc-default-empty-document {\n    display: flex;\n    flex-direction: column;\n    justify-content:center;\n    align-items: center;\n    gap: 1rem;\n  }\n\n  .mwc-default-empty-document svg {\n    width: 200px;\n    height: auto;\n  }\n\n  .mwc-default-empty-document .title {\n    margin-top: 2rem;\n    font-size: 24px;\n    color: black;\n  }\n\n  .mwc-default-empty-document .desc {\n    font-size: 16px;\n    color: black;\n  }\n";class oF extends ZU{constructor(t){super(t),this.config=t,this.headerTitle=null,this.headerActionBtn={close:null,cancel:null,selectAll:null},this.toolbarBtn={newDoc:null,capture:null,import:null,uploads:null,delete:null,print:null,share:null,upload:null,back:null},this.checkedDocUids=[],this.docItems=[]}bindDocumentManagerEvents(){$I.documentManager.on("documentCreated",t=>{const e=new VU({docId:t.docUid,onCheckedChange:()=>this.handleDocumentChecked(),onDocumentClick:t=>{this.isSelectionMode||this.handleDocumentClick(t)},onRename:t=>this.handleRename(t)});this.docItems.unshift(e),this.MWCViewElements.contentContainer.firstChild?this.MWCViewElements.contentContainer.insertBefore(e.getDom(),this.MWCViewElements.contentContainer.firstChild):this.MWCViewElements.contentContainer.appendChild(e.getDom())}),$I.documentManager.on("documentDeleted",t=>{this.docItems.forEach((e,i)=>{e.getUid()===t.docUid&&(e.dispose(),this.docItems.splice(i,1))})})}initialize(){FU("mwc-library-view-style",rF),super.initialize(),this.bindDocumentManagerEvents(),this.updateEmptyContentHTML(),this.setVisible(!1)}setVisible(t){if(super.setVisible(t),this.updateToolbarState(),t&&t){const t=$I.documentManager.getAllDocuments().length;this.showContent(!!t),t&&this.docItems.forEach(t=>{t.update()})}}createHeader(){super.createHeader(),this.MWCViewElements.headerContainer.innerHTML=`\n      <div class="mwc-view-header-title">Library</div>\n      <div class="mwc-view-header-actions">\n        <button type="button" class="mwc-library-header-btn selectAll">Select All</button>\n        <button type="button" class="mwc-library-header-btn cancel">Cancel</button>\n        <button type="button" class="mwc-library-header-btn close">\n          ${OU.close}\n        </button>\n      </div>\n    `,this.headerTitle=this.MWCViewElements.headerContainer.querySelector(".mwc-view-header-title"),this.headerActionBtn.close=this.MWCViewElements.headerContainer.querySelector(".close"),this.headerActionBtn.close.addEventListener("click",()=>this.handleClose()),this.headerActionBtn.cancel=this.MWCViewElements.headerContainer.querySelector(".cancel"),this.headerActionBtn.cancel.addEventListener("click",()=>this.handleSelectAllOrCancel(!0)),this.headerActionBtn.selectAll=this.MWCViewElements.headerContainer.querySelector(".selectAll"),this.headerActionBtn.selectAll.addEventListener("click",()=>this.handleSelectAllOrCancel(!1)),this.updateHeaderActionBtnStyle()}updateHeaderActionBtnStyle(){if(this.isSelectionMode){this.headerTitle.textContent="Select Items",this.headerActionBtn.close.style.display="none";const t=this.docItems.every(t=>t.checked);this.headerActionBtn.selectAll.style.display=t?"none":"flex",this.headerActionBtn.cancel.style.display=t?"flex":"none"}else this.headerTitle.textContent="Library",this.headerActionBtn.close.style.display="block",this.headerActionBtn.selectAll.style.display="none",this.headerActionBtn.cancel.style.display="none"}updateEmptyContentHTML(){const t=`\n    <div class="mwc-default-empty-library">\n      ${OU.emptyLibrary}\n      <div class="title">\n        Create your first document!\n      </div>\n      <div class="desc">\n        <div>\n          Option 1: Click "<b>New</b>" to create a blank document\n        </div>\n        <div>\n          Option 2: Click "<b>Capture</b>" or "<b>Import</b>" to use images\n        </div>\n      </div>\n    </div>\n    `;super.setEmptyContent(this.config.emptyContentConfig||t)}handleClose(){try{this.config.onClose()}catch(t){console.error("Failed to close library view:",t)}}dispose(){this.docItems.forEach(t=>t.dispose()),this.docItems=[],$I.documentManager.deleteAllDocuments()}toggleSelectionMode(t){this.isSelectionMode!==t&&(super.toggleSelectionMode(t),this.updateHeaderActionBtnStyle(),this.docItems.forEach(t=>t.setSelectMode(this.isSelectionMode)))}handleSelectAllOrCancel(t){if(t)return this.docItems.forEach(t=>t.toggleCheck(!1)),this.checkedDocUids=[],void this.toggleSelectionMode(!1);this.docItems.forEach(t=>{t.toggleCheck(!0)}),this.updateHeaderActionBtnStyle()}handleDocumentChecked(){var t,e,i;this.checkedDocUids=this.docItems.filter(t=>t.checked).map(t=>t.getUid());const n=this.checkedDocUids.length>0;this.toggleSelectionMode(n),this.updateHeaderActionBtnStyle();const s=this.checkedDocUids.some(t=>{var e;const i=$I.documentManager.getDocument(t);return!(null===(e=null==i?void 0:i.pages)||void 0===e?void 0:e.length)}),o=1===this.checkedDocUids.length;null===(t=this.toolbarBtn.print)||void 0===t||t.classList.toggle("disabled",!o||s),null===(e=this.toolbarBtn.upload)||void 0===e||e.classList.toggle("disabled",s),null===(i=this.toolbarBtn.share)||void 0===i||i.classList.toggle("disabled",s)}handleDocumentClick(t){var e,i;null===(i=(e=this.config).onDocumentClick)||void 0===i||i.call(e,t)}handleRename(t){const e=$I.documentManager.getDocument(t);e&&XU({container:this.config.container,type:zU.INPUT,title:"Rename Document",placeholder:"Enter document name",initialValue:e.name,confirmText:"Rename",validation:t=>t.length<1?"Name can't be empty":null}).then(async i=>{if(i){e.rename(i);const n=this.docItems.find(e=>e.getUid()===t);null==n||n.update(),await $U(this.config.container,"Renamed",GU.SUCCESS)}})}createToolbars(){var t,e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x,w,C,b,S,T,E,_,P,A,I,D,R,k,M,L,O;super.createToolbars();const{toolbarButtonsConfig:B,exportConfig:N}=this.config,U=new File([""],"test.pdf",{type:"application/pdf"}),F="share"in navigator&&navigator.canShare({files:[U]}),V=()=>{F?this.handleShare():this.handleDownload()},W=!!(null==N?void 0:N.uploadToServer);[{id:"mwc-lbrary-newDoc",icon:(null===(t=null==B?void 0:B.newDoc)||void 0===t?void 0:t.icon)||OU.newDoc,label:(null===(e=null==B?void 0:B.newDoc)||void 0===e?void 0:e.label)||"New",className:(null===(i=null==B?void 0:B.newDoc)||void 0===i?void 0:i.className)||"",isHidden:null===(n=null==B?void 0:B.newDoc)||void 0===n?void 0:n.isHidden,onClick:()=>this.handleNewDocument()},{id:"mwc-lbrary-capture",icon:(null===(s=null==B?void 0:B.capture)||void 0===s?void 0:s.icon)||OU.cameraCapture,label:(null===(o=null==B?void 0:B.capture)||void 0===o?void 0:o.label)||"Capture",className:(null===(r=null==B?void 0:B.capture)||void 0===r?void 0:r.className)||"",isHidden:null===(a=null==B?void 0:B.capture)||void 0===a?void 0:a.isHidden,onClick:()=>this.handleCameraCapture()},{id:"mwc-lbrary-import",icon:(null===(l=null==B?void 0:B.import)||void 0===l?void 0:l.icon)||OU.galleryImport,label:(null===(h=null==B?void 0:B.import)||void 0===h?void 0:h.label)||"Import",className:(null===(c=null==B?void 0:B.import)||void 0===c?void 0:c.className)||"",isHidden:null===(d=null==B?void 0:B.import)||void 0===d?void 0:d.isHidden,onClick:()=>this.handleGalleryImport()},{id:"mwc-lbrary-uploads",icon:(null===(u=null==B?void 0:B.uploads)||void 0===u?void 0:u.icon)||OU.uploadedFiles,label:(null===(p=null==B?void 0:B.uploads)||void 0===p?void 0:p.label)||"Uploads",className:(null===(g=null==B?void 0:B.uploads)||void 0===g?void 0:g.className)||"",isHidden:(null===(f=null==B?void 0:B.uploads)||void 0===f?void 0:f.isHidden)||!W,onClick:()=>this.handleViewUploadsHistory()}].forEach(t=>{const e=this.createToolbarButton(t);this.toolbarBtn[`${t.id.split("-").pop()}`]=e,this.MWCViewElements.toolbarContainer.appendChild(e)});[{id:"mwc-library-select-delete",icon:(null===(m=null==B?void 0:B.delete)||void 0===m?void 0:m.icon)||OU.delete,label:(null===(v=null==B?void 0:B.delete)||void 0===v?void 0:v.label)||"Delete",className:`selected ${(null===(y=null==B?void 0:B.delete)||void 0===y?void 0:y.className)||""}`,isHidden:null===(x=null==B?void 0:B.delete)||void 0===x?void 0:x.isHidden,onClick:()=>this.handleDelete()},{id:"mwc-library-select-print",icon:(null===(w=null==B?void 0:B.print)||void 0===w?void 0:w.icon)||OU.print,label:(null===(C=null==B?void 0:B.print)||void 0===C?void 0:C.label)||"Print",className:`selected ${(null===(b=null==B?void 0:B.print)||void 0===b?void 0:b.className)||""}`,isHidden:null===(S=null==B?void 0:B.print)||void 0===S?void 0:S.isHidden,onClick:()=>this.handlePrint()},{id:"mwc-library-select-share",icon:(null===(T=null==B?void 0:B.share)||void 0===T?void 0:T.icon)||(F?OU.sharePDF:OU.downloadPDF),label:(null===(E=null==B?void 0:B.share)||void 0===E?void 0:E.label)||(F?"Share":"Download"),className:`selected ${(null===(_=null==B?void 0:B.share)||void 0===_?void 0:_.className)||""}`,isHidden:null===(P=null==B?void 0:B.share)||void 0===P?void 0:P.isHidden,onClick:()=>V()},{id:"mwc-library-select-upload",icon:(null===(A=null==B?void 0:B.upload)||void 0===A?void 0:A.icon)||OU.uploadPDF,label:(null===(I=null==B?void 0:B.upload)||void 0===I?void 0:I.label)||"Upload",className:`selected ${(null===(D=null==B?void 0:B.upload)||void 0===D?void 0:D.className)||""}`,isHidden:(null===(R=null==B?void 0:B.upload)||void 0===R?void 0:R.isHidden)||!W,onClick:()=>this.handleUploadDocuments()},{id:"mwc-library-select-back",icon:(null===(k=null==B?void 0:B.back)||void 0===k?void 0:k.icon)||OU.back,label:(null===(M=null==B?void 0:B.back)||void 0===M?void 0:M.label)||"Back",className:`selected ${(null===(L=null==B?void 0:B.back)||void 0===L?void 0:L.className)||""}`,isHidden:null===(O=null==B?void 0:B.back)||void 0===O?void 0:O.isHidden,onClick:()=>this.handleSelectedBack()}].forEach(t=>{const e=this.createToolbarButton(t);this.toolbarBtn[`${t.id.split("-").pop()}`]=e,this.MWCViewElements.selectedToolbarContainer.appendChild(e)})}async handleNewDocument(){const t=await XU({container:this.config.container,type:zU.INPUT,title:"New Document",placeholder:"Enter document name",confirmText:"Create"});if(t){await this.createAndLoadDocument(t||`Doc-${Date.now()}`)&&(this.setVisible(!0),await $U(this.config.container,"Created",GU.SUCCESS))}}async createAndLoadDocument(t,e){try{const i=$I.documentManager.createDocument({name:t||`Doc-${Date.now()}`});return e&&await i.loadSource(e),i}catch(t){let e=t.message||t;alert(`Failed to create and load document: ${e}`),console.error("Failed to create and load document: ",e)}}async handleCameraCapture(){await this.config.onCameraCapture()}async handleGalleryImport(){await this.config.onGalleryImport()}async handleViewUploadsHistory(){var t;null===(t=this.config)||void 0===t||t.onViewUploadsHistory()}async handleDelete(){await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.WARNING,title:"Delete Documents",message:`Are you sure you want to delete ${this.checkedDocUids.length} document(s)?`,confirmText:"Delete",cancelText:"Cancel",showCloseBtn:!0})&&($I.documentManager.deleteDocuments([...this.checkedDocUids]),this.setVisible(!0),this.toggleSelectionMode(!1),await $U(this.config.container,"Deleted",GU.SUCCESS))}async handlePrint(){var t,e;if(this.checkedDocUids.length>1||(null===(t=this.toolbarBtn.print)||void 0===t?void 0:t.classList.contains("disabled")))return void console.warn("Please select 1 document to print");const i=this.checkedDocUids[0],n=$I.documentManager.getDocument(i);(null===(e=null==n?void 0:n.pages)||void 0===e?void 0:e.length)&&n.print()}async handleShare(){const t=[];for(let e=0;e<this.checkedDocUids.length;e++){const i=$I.documentManager.getDocument(this.checkedDocUids[e]);if(i.pages.length){const e=await i.saveToPdf({mimeType:"application/octet-stream",saveAnnotation:"annotation",quality:100});t.push(new File([e],`${i.name}.pdf`,{type:"application/pdf"}))}}if(navigator.canShare&&navigator.canShare({files:t}))try{await navigator.share({files:t,title:"PDF Files"})}catch(t){"AbortError"!==t.name&&await $U(this.config.container,"Failed to share files",GU.ERROR)}else await $U(this.config.container,"Your system doesn't support sharing PDF files",GU.WARNING)}async handleDownload(){this.checkedDocUids.forEach(async t=>{var e;const i=$I.documentManager.getDocument(t);(null===(e=null==i?void 0:i.pages)||void 0===e?void 0:e.length)&&await nF.handleDownloadDoc(i,this.config.container)})}async handleUploadDocuments(){var t,e;if(null===(e=null===(t=this.config)||void 0===t?void 0:t.exportConfig)||void 0===e?void 0:e.uploadToServer)try{const t=this.checkedDocUids.map(async t=>{var e,i,n,s,o,r;const a=$I.documentManager.getDocument(t);if(null===(e=null==a?void 0:a.pages)||void 0===e?void 0:e.length){const t=await a.saveToPdf({mimeType:"application/pdf",saveAnnotation:"annotation",quality:100}),e=`${a.name}.pdf`,l=await(null===(n=null===(i=this.config)||void 0===i?void 0:i.exportConfig)||void 0===n?void 0:n.uploadToServer(e,t));if("success"===(null==l?void 0:l.status)){const i=this.config.getUploadedDocuments();i.push(l),this.config.updateUploadedDocuments(i);if(await(null===(o=null===(s=this.config.exportConfig)||void 0===s?void 0:s.onUploadSuccess)||void 0===o?void 0:o.call(s,e,"pdf",HU.Library,t)))return void(null===(r=this.config)||void 0===r||r.onClose())}return l}await $U(this.config.container,"Document contains no pages!",GU.WARNING)}),e=await Promise.all(t),i=null==e?void 0:e.filter(t=>"success"===(null==t?void 0:t.status));if(i.length){this.handleSelectAllOrCancel(!0);await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.SUCCESS,title:"Upload Successful",confirmText:"View in Uploads",cancelText:"Continue"})&&this.handleViewUploadsHistory()}}catch(t){let e=(null==t?void 0:t.message)||t;console.error("Uploads failed:",e);await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.ERROR,title:"Uploads Failed",confirmText:"View Uploaded Files",cancelText:"Continue"})&&this.handleViewUploadsHistory()}else await $U(this.config.container,"No upload function configured",GU.WARNING)}async handleSelectedBack(){this.handleSelectAllOrCancel(!0)}}const rF="\n  .mwc-view-header-actions {\n    position: absolute;\n    right: 1rem;\n    font-family: Verdana;\n    color: black;\n  }\n\n  .mwc-view-header-actions .mwc-library-header-btn {\n    border: none;\n    background: transparent;\n    display: flex;\n    align-content: center;\n    cursor: pointer;\n  }\n\n  .mwc-view-header-actions .mwc-library-header-btn.selectAll,\n  .mwc-view-header-actions .mwc-library-header-btn.cancel{\n    background: none;\n    border: none;\n    color: #FE8E14;\n    font-size: 14px;\n    cursor: pointer;\n    padding: 4px 8px;\n    align-content: end;\n  }\n\n  .mwc-default-empty-library {\n    display: flex;\n    flex-direction: column;\n    justify-content:center;\n    align-items: center;\n    gap: 1rem;\n  }\n\n  .mwc-default-empty-library svg {\n    width: 200px;\n    height: auto;\n  }\n\n  .mwc-default-empty-library .title {\n    margin-top: 2rem;\n    font-size: 24px;\n    color: black;\n  }\n\n  .mwc-default-empty-library .desc {\n    font-size: 16px;\n    color: black;\n  }\n",aF={base:{type:$I.Elements.Layout,className:"ddv-edit-viewer-header-mobile",children:[{type:$I.Elements.Layout,children:[$I.Elements.Download,$I.Elements.Pagination,$I.Elements.Print]}]},edit:{type:$I.Elements.Layout,className:"ddv-edit-viewer-header-mobile",children:[{type:$I.Elements.Layout,children:[$I.Elements.Undo,$I.Elements.Pagination,$I.Elements.Redo]}]}},lF={type:$I.Elements.Layout,flexDirection:"column",className:"ddv-edit-viewer-mobile",children:[aF.base,$I.Elements.MainView,{type:$I.Elements.Layout,className:"ddv-edit-viewer-footer-mobile",children:[{type:$I.Elements.DeleteCurrent,events:{click:"showDocumentPageByDelete"}},$I.Elements.Crop,$I.Elements.Filter,{type:$I.Elements.AnnotationSet,className:"mwc-annotation-set",pullDownBox:{className:"mwc-annotation-mode-bar"}}]}]};class hF extends ZU{constructor(t){super(t),this.config=t,this.editViewer=null,this.toolbarBtn={back:null,delete:null,addPage:null,upload:null,share:null,edit:null,crop:null,rotate:null,filter:null,annotate:null,done:null},this.editToolbarContainer={},this.ddvAnnotationsToolbarLabel={Undo:"Undo",Redo:"Redo",SelectAnnotation:"Select",EraseAnnotation:"Eraser",RectAnnotation:"Rect",EllipseAnnotation:"Ellipse",PolygonAnnotation:"Polygon",PolylineAnnotation:"Polyline",LineAnnotation:"Line",InkAnnotation:"Ink",TextBoxAnnotation:"Textbox",TextTypewriterAnnotation:"Text",StampIconAnnotation:"Stamp",StampImageAnnotation:"Image",BringForward:"Up",BringToFront:"Top",SendBackward:"Down",SendToBack:"Bottom"},this.isCroppingMode=!1,this.isAnnotatingMode=!1,this.isFilterMode=!1}initialize(){FU("mwc-page-view-style",cF),super.initialize(),$I.Elements.setDisplayTextConfig({...this.ddvAnnotationsToolbarLabel,...this.config.annotationToolbarLabelConfig}),this.editViewer=new $I.EditViewer({container:this.MWCViewElements.contentContainer,viewerConfig:{scrollToLatest:!0},uiConfig:lF}),this.editViewer.displayMode="single",this.MWCViewElements.contentContainer.style.padding="0px",this.bindPageViewEvents(),this.setVisible(!1)}bindPageViewEvents(){this.editViewer.on("showDocumentPageByDelete",async()=>{this.editViewer.currentDocument.pages.length||this.handleBack(),await $U(this.config.container,"Deleted",GU.SUCCESS)}),this.bindAnnotationEvents(),this.bindToolModeEvents()}bindAnnotationEvents(){let t=!1;const e=document.querySelector(".mwc-annotation-set");!BU()&&e&&e.addEventListener("click",()=>{const e=document.querySelector(".ddv-annotation-mode-box");if(!t){t=!0;let i=!1;e.addEventListener("mousedown",t=>{let e=t.target;t.target instanceof HTMLSpanElement&&(e=t.target.parentElement),e.classList.contains("ddv-button-focused")&&(i=!0)}),e.addEventListener("click",()=>{i&&(this.editViewer.toolMode="pan",i=!1)})}})}bindToolModeEvents(){this.editViewer.on("toolModeChanged",t=>{"crop"===t.oldToolMode&&(this.toolbarBtn.crop.classList.remove("selected"),this.enableAllEditButtons(),this.toggleDDVHeaderButtons(!0),this.isCroppingMode=!1)})}createHeader(){super.createHeader(!1)}updateEmptyContentHTML(){const t=`\n      <div class="mwc-default-empty-page">\n        ${OU.emptyLibrary}\n        <div class="title">No page to display!</div>\n      </div>\n    `;this.MWCViewElements.emptyContentContainer.innerHTML=t}createToolbars(){var t,e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x,w,C,b,S,T,E,_,P,A,I,D,R,k,M,L,O,B,N,U,F,V,W,H,j;super.createToolbars();const{toolbarButtonsConfig:z,exportConfig:G}=this.config,Y=new File([""],"test.pdf",{type:"application/pdf"}),$="share"in navigator&&navigator.canShare({files:[Y]}),X=()=>{$?this.handleShare():this.handleDownload()},q=!!(null==G?void 0:G.uploadToServer);[{id:"mwc-page-back",icon:(null===(t=null==z?void 0:z.back)||void 0===t?void 0:t.icon)||OU.back,label:(null===(e=null==z?void 0:z.back)||void 0===e?void 0:e.label)||"Back",isHidden:null===(i=null==z?void 0:z.back)||void 0===i?void 0:i.isHidden,className:`${(null===(n=null==z?void 0:z.back)||void 0===n?void 0:n.className)||""}`,onClick:()=>this.handleBack()},{id:"mwc-page-delete",icon:(null===(s=null==z?void 0:z.delete)||void 0===s?void 0:s.icon)||OU.delete,label:(null===(o=null==z?void 0:z.delete)||void 0===o?void 0:o.label)||"Delete",isHidden:null===(r=null==z?void 0:z.delete)||void 0===r?void 0:r.isHidden,className:`${(null===(a=null==z?void 0:z.delete)||void 0===a?void 0:a.className)||""}`,onClick:()=>this.handleDeletePage()},{id:"mwc-page-addPage",icon:(null===(l=null==z?void 0:z.addPage)||void 0===l?void 0:l.icon)||OU.captureAnother,label:(null===(h=null==z?void 0:z.addPage)||void 0===h?void 0:h.label)||"Add Page",isHidden:null===(c=null==z?void 0:z.addPage)||void 0===c?void 0:c.isHidden,className:`${(null===(d=null==z?void 0:z.addPage)||void 0===d?void 0:d.className)||""}`,onClick:()=>this.handleAddPage()},{id:"mwc-page-share",icon:(null===(u=null==z?void 0:z.share)||void 0===u?void 0:u.icon)||($?OU.sharePNG:OU.downloadPNG),label:(null===(p=null==z?void 0:z.share)||void 0===p?void 0:p.label)||($?"Share":"Download"),isHidden:null===(g=null==z?void 0:z.share)||void 0===g?void 0:g.isHidden,className:`${(null===(f=null==z?void 0:z.share)||void 0===f?void 0:f.className)||""}`,onClick:()=>X()},{id:"mwc-page-upload",icon:(null===(m=null==z?void 0:z.upload)||void 0===m?void 0:m.icon)||OU.uploadPNG,label:(null===(v=null==z?void 0:z.upload)||void 0===v?void 0:v.label)||"Upload",isHidden:(null===(y=null==z?void 0:z.upload)||void 0===y?void 0:y.isHidden)||!q,className:`${(null===(x=null==z?void 0:z.upload)||void 0===x?void 0:x.className)||""}`,onClick:()=>this.handleUpload()},{id:"mwc-page-edit",icon:(null===(w=null==z?void 0:z.edit)||void 0===w?void 0:w.icon)||OU.edit,label:(null===(C=null==z?void 0:z.edit)||void 0===C?void 0:C.label)||"Edit",isHidden:null===(b=null==z?void 0:z.edit)||void 0===b?void 0:b.isHidden,className:`${(null===(S=null==z?void 0:z.edit)||void 0===S?void 0:S.className)||""}`,onClick:()=>this.handleEditMode()}].forEach(t=>{const e=this.createToolbarButton(t);this.toolbarBtn[t.id.split("-").pop()]=e,this.MWCViewElements.toolbarContainer.appendChild(e)});[{id:"mwc-page-crop",icon:(null===(T=null==z?void 0:z.crop)||void 0===T?void 0:T.icon)||OU.crop,label:(null===(E=null==z?void 0:z.crop)||void 0===E?void 0:E.label)||"Crop",isHidden:null===(_=null==z?void 0:z.crop)||void 0===_?void 0:_.isHidden,className:`${(null===(P=null==z?void 0:z.crop)||void 0===P?void 0:P.className)||""}`,onClick:()=>this.handleCrop()},{id:"mwc-page-rotate",icon:(null===(A=null==z?void 0:z.rotate)||void 0===A?void 0:A.icon)||OU.rotate,label:(null===(I=null==z?void 0:z.rotate)||void 0===I?void 0:I.label)||"Rotate",isHidden:null===(D=null==z?void 0:z.rotate)||void 0===D?void 0:D.isHidden,className:`${(null===(R=null==z?void 0:z.rotate)||void 0===R?void 0:R.className)||""}`,onClick:()=>this.handleRotate()},{id:"mwc-page-filter",icon:(null===(k=null==z?void 0:z.filter)||void 0===k?void 0:k.icon)||OU.filter,label:(null===(M=null==z?void 0:z.filter)||void 0===M?void 0:M.label)||"Filter",isHidden:null===(L=null==z?void 0:z.filter)||void 0===L?void 0:L.isHidden,className:`${(null===(O=null==z?void 0:z.filter)||void 0===O?void 0:O.className)||""}`,onClick:()=>this.handleFilter()},{id:"mwc-page-annotate",icon:(null===(B=null==z?void 0:z.annotate)||void 0===B?void 0:B.icon)||OU.annotate,label:(null===(N=null==z?void 0:z.annotate)||void 0===N?void 0:N.label)||"Annotate",isHidden:null===(U=null==z?void 0:z.annotate)||void 0===U?void 0:U.isHidden,className:`${(null===(F=null==z?void 0:z.annotate)||void 0===F?void 0:F.className)||""}`,onClick:()=>this.handleAnnotate()},{id:"mwc-page-done",icon:(null===(V=null==z?void 0:z.done)||void 0===V?void 0:V.icon)||OU.done,label:(null===(W=null==z?void 0:z.done)||void 0===W?void 0:W.label)||"Done",isHidden:null===(H=null==z?void 0:z.done)||void 0===H?void 0:H.isHidden,className:`done ${(null===(j=null==z?void 0:z.done)||void 0===j?void 0:j.className)||""}`,onClick:()=>this.handleDoneBtn()}].forEach(t=>{const e=this.createToolbarButton(t);this.toolbarBtn[t.id.split("-").pop()]=e,this.MWCViewElements.selectedToolbarContainer.appendChild(e)})}setVisible(t){var e,i;super.setVisible(t),t?(this.showContent(!0),null===(e=this.editViewer)||void 0===e||e.show()):null===(i=this.editViewer)||void 0===i||i.hide()}openPage(t,e){this.editViewer.openDocument(t),this.editViewer.goToPage(e),this.editViewer.show()}handleBack(){var t,e;null===(e=(t=this.config).onDocumentClick)||void 0===e||e.call(t)}async handleDeletePage(){await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.WARNING,title:"Delete Page",message:"Are you sure you want to delete this page?",confirmText:"Delete",cancelText:"Cancel",showCloseBtn:!0})&&this.config.container.querySelector(".ddv-delete-current").click()}handleAddPage(){const t=this.toolbarBtn.addPage;let e=t.querySelector(".mwc-add-page-menu");if(e)e.classList.toggle("show");else{FU("mwc-add-page-dropdown-style",dF),e=document.createElement("div"),e.className="mwc-add-page-menu",e.innerHTML=`\n        <button class="mwc-add-page-option capture">\n          ${OU.cameraCapture}\n          <span>Capture</span>\n        </button>\n        <button class="mwc-add-page-option import">\n          ${OU.galleryImport}\n          <span>Import</span>\n        </button>\n      `;e.querySelector(".capture").addEventListener("click",async t=>{var i,n;e.classList.contains("show")&&e.classList.remove("show"),await(null===(n=(i=this.config).onCameraCapture)||void 0===n?void 0:n.call(i)),t.stopPropagation()});e.querySelector(".import").addEventListener("click",async t=>{var i,n;e.classList.contains("show")&&e.classList.remove("show"),await(null===(n=(i=this.config).onGalleryImport)||void 0===n?void 0:n.call(i)),t.stopPropagation()}),document.addEventListener("click",i=>{!t.contains(i.target)&&e.classList.contains("show")&&e.classList.remove("show")}),t.querySelector(".icon").prepend(e),e.classList.toggle("show")}}async handleShare(){try{const t=this.editViewer.currentDocument,e=this.editViewer.getCurrentPageIndex(),i=await t.saveToPng(e,{saveAnnotation:!0}),n=[new File([i],`${t.name}-${Date.now()}.png`,{type:i.type})];if(navigator.canShare&&navigator.canShare({files:n}))try{await navigator.share({files:n,title:"Image Files"})}catch(t){"AbortError"!==t.name&&await $U(this.config.container,"Failed to share files",GU.ERROR)}else await $U(this.config.container,"Failed to share",GU.WARNING)}catch(t){await $U(this.config.container,"Error processing files",GU.ERROR)}}async handleDownload(){try{const t=this.editViewer.currentDocument,e=this.editViewer.getCurrentPageIndex(),i=await t.saveToPng(e,{saveAnnotation:!0}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=`${t.name}.png`,s.click(),s.remove(),URL.revokeObjectURL(n),await $U(this.config.container,"Downloaded",GU.SUCCESS)}catch(t){const e=(null==t?void 0:t.message)||t;console.warn("Download failed:",e),await $U(this.config.container,"Failed to download page",GU.ERROR)}}async handleUpload(){var t,e,i,n,s,o,r,a,l;if(null===(e=null===(t=this.config)||void 0===t?void 0:t.exportConfig)||void 0===e?void 0:e.uploadToServer)try{const t=this.editViewer.currentDocument,e=this.editViewer.getCurrentPageIndex(),h=await t.saveToPng(e,{saveAnnotation:!0}),c=`${t.name}-${e}.png`,d=await(null===(n=null===(i=this.config)||void 0===i?void 0:i.exportConfig)||void 0===n?void 0:n.uploadToServer(c,h));if("success"===(null==d?void 0:d.status)){if(await(null===(o=null===(s=this.config.exportConfig)||void 0===s?void 0:s.onUploadSuccess)||void 0===o?void 0:o.call(s,c,"png",HU.Page,h)))return void(null===(r=this.config)||void 0===r||r.onClose());const t=this.config.getUploadedDocuments();t.push(d),this.config.updateUploadedDocuments(t);await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.SUCCESS,title:"Upload Successful",confirmText:"View in Uploads",cancelText:"Continue"})&&(null===(l=(a=this.config).onViewUploadsHistory)||void 0===l||l.call(a))}}catch(t){const e=(null==t?void 0:t.message)||t;console.error("Upload failed:",e),await $U(this.config.container,"Failed to upload page",GU.ERROR)}else await $U(this.config.container,"No upload function configured",GU.WARNING)}async handleEditMode(){try{if(!this.updateEditViewTopbar("edit"))throw new Error("Failed to update edit viewer");this.toggleSelectionMode(!0)}catch(t){await $U(this.config.container,"Failed to enter edit mode",GU.ERROR),console.error(t)}}updateEditViewTopbar(t){const e=this.editViewer.getUiConfig();return e.children[0]=aF[t],this.editViewer.updateUiConfig(e)}toggleDDVHeaderButtons(t){const e=this.config.container.querySelector(".ddv-edit-viewer-header-mobile"),i=t?"remove":"add";e.childNodes.forEach(t=>t.classList[i]("ddv-disable-button"))}disableOtherEditButtons(t){this.config.container.querySelectorAll(".mwc-view-controls-container")[1].childNodes.forEach(e=>{e!==t&&e!==this.toolbarBtn.done&&e.classList.add("ddv-disable-button")})}enableAllEditButtons(){this.config.container.querySelectorAll(".mwc-view-controls-container")[1].childNodes.forEach(t=>{t.classList.remove("ddv-disable-button")})}handleCrop(){this.config.container.querySelector(".ddv-button.ddv-crop").click(),this.disableOtherEditButtons(this.toolbarBtn.crop),this.toolbarBtn.crop.classList.add("selected"),this.toggleDDVHeaderButtons(!1)}handleRotate(){this.editViewer.rotate(-90)}handleFilter(){const t=this.config.container.querySelector(".ddv-filter");null==t||t.click(),this.isFilterMode?(this.isFilterMode=!1,this.toolbarBtn.filter.classList.remove("selected"),this.enableAllEditButtons()):(this.isFilterMode=!0,this.isAnnotatingMode=!1,this.disableOtherEditButtons(this.toolbarBtn.filter),this.toolbarBtn.filter.classList.add("selected"),this.toolbarBtn.annotate.classList.remove("selected"))}handleAnnotate(){const t=this.config.container.querySelector(".mwc-annotation-set");null==t||t.click(),this.isAnnotatingMode?(this.isAnnotatingMode=!1,this.toolbarBtn.annotate.classList.remove("selected"),this.enableAllEditButtons()):(this.isAnnotatingMode=!0,this.isFilterMode=!1,this.disableOtherEditButtons(this.toolbarBtn.annotate),this.toolbarBtn.annotate.classList.add("selected"),this.toolbarBtn.filter.classList.remove("selected"))}async handleDoneBtn(){try{const t=await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.WARNING,title:"Exit Edit Mode",message:"You might have unsaved changes. Do you want to save before exiting?",confirmText:"Save & Exit",cancelText:"Discard",showCloseBtn:!0});if(null===t)return;if(t)this.editViewer.saveOperations();else{for(;this.editViewer.undo(););this.editViewer.saveOperations()}this.isAnnotatingMode=!1,this.isFilterMode=!1,this.toolbarBtn.annotate.classList.remove("selected"),this.toolbarBtn.filter.classList.remove("selected"),"pan"!==this.editViewer.toolMode&&(this.editViewer.toolMode="pan");if(!this.updateEditViewTopbar("base"))throw new Error("Failed to update edit viewer");this.toggleSelectionMode(!1),this.enableAllEditButtons()}catch(t){await $U(this.config.container,"Failed to exit edit mode",GU.ERROR),console.error(t)}}dispose(){var t;null===(t=this.editViewer)||void 0===t||t.destroy(),this.editViewer=null,this.config.container&&(this.config.container.style.display="none")}}const cF="\n.done .label {\n  color: #fe8e14\n}\n\n.ddv-edit-viewer-footer-mobile{\n  height: 0;\n  display: none;\n}\n\n.ddv-annotation-mode-box,\n.ddv-crop-box,\n.ddv-filter-list {\n  top: unset !important;\n  bottom: 0;\n}\n\n.ddv-disable-button {\n  opacity: 0.3;\n  pointer-events: none;\n}\n\n.mwc-annotation-mode-bar {\n  overflow-y: hidden;\n  height: 70px;\n\n  scrollbar-width: thin;\n  scrollbar-color: rgb(193,193,193) rgb(241,241,241);\n}\n.mwc-annotation-mode-bar > .ddv-button {\n  height: 50px;\n  width: 50px;\n}\n\n.mwc-annotation-mode-bar::-webkit-scrollbar {\n  width: 5px;\n  height: 5px;\n  border-radius: 0px;\n}\n\n.mwc-annotation-mode-bar::-webkit-scrollbar-thumb {\n  border-radius: 0px;\n  background-color: rgb(193,193,193);\n}\n\n.mwc-annotation-mode-bar::-webkit-scrollbar-track {\n  border-radius: 0px;\n  background-color: rgb(241,241,241);\n}\n\n.ddv-undo-page, .ddv-redo-page {\n  flex-direction: column;\n}\n\n/* Top bar layout adjustments */\n.ddv-edit-viewer-header-mobile {\n  min-height: 60px;\n  height: 60px;\n}\n\n.ddv-edit-viewer-header-mobile .ddv-pagination {\n  flex: 0 0 auto;\n}\n",dF="\n  .mwc-view-controls-btn {\n    position: relative; /* Add this to make the absolute positioning work relative to button */\n  }\n\n  .mwc-add-page-menu {\n    position: absolute;\n    bottom: 6rem;\n    transform: translate(-50%);\n    left: 50%;\n    right: 50%;\n    width: max-content;\n    background-color: #323234;\n    border-radius: 0.5rem;\n    overflow: visible;\n    display: none;\n    margin-bottom: 0.5px; /* Add some spacing between menu and button */\n    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2); /* Add shadow for better visibility */\n  }\n\n  .mwc-add-page-menu::after {\n    content: '';\n    position: absolute;\n    bottom: -8px; /* Triangle */\n    left: 50%;\n    right: 50%;\n    transform: translateX(-50%);\n    width: 0;\n    height: 0;\n    border-left: 8px solid transparent;\n    border-right: 8px solid transparent;\n    border-top: 8px solid #323234; /* Same color as menu background */\n  }\n\n  \n  .mwc-add-page-menu.show {\n    display: block;\n  }\n  \n  .mwc-add-page-option {\n    display: flex;\n    align-items: center;\n    gap: 1rem;\n    padding: 1rem;\n    color: white;\n    background: none;\n    border: none;\n    cursor: pointer;\n    font-family: Verdana;\n    font-size: 14px;\n    width: 100%;\n    box-sizing: border-box;\n  }\n\n  .mwc-add-page-option svg {\n    width: 24px;\n    height: 24px;\n  }\n\n  .mwc-add-page-option span {\n    cursor: pointer;\n  }\n  \n  .mwc-add-page-option:hover {\n    background-color: rgba(255, 255, 255, 0.1);\n  }\n\n  .mwc-add-page-option:not(:last-child) {\n    border-bottom: 1px solid rgba(255, 255, 255, 0.1);\n  }\n";class uF{constructor(t){this.config=t,this.createUI(),this.bindEvents()}createUI(){FU("mwc-history-item-style",pF),this.dom=document.createElement("div"),this.dom.className="mwc-library-view-history-item",this.dom.innerHTML=`\n      <div class="mwc-library-view-history-name">${this.config.doc.fileName}</div>\n      <div class="mwc-library-view-history-time">${function(t){if(!t)return"";const e=(Number(t)-621355968e9)/1e4,i=6e4*new Date(e).getTimezoneOffset();return new Date(e+i).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}(this.config.doc.uploadTime)||""}</div>\n      <div class="mwc-library-view-history-actions">\n        <button class="mwc-library-view-history-action-btn delete">Delete</button>\n        <span class="mwc-library-view-history-separator">|</span>\n        <button class="mwc-library-view-history-action-btn download">Download</button>\n      </div>\n    `}bindEvents(){const t=this.dom.querySelector(".delete"),e=this.dom.querySelector(".download");null==t||t.addEventListener("click",()=>this.handleDelete()),null==e||e.addEventListener("click",()=>this.handleDownload())}async handleDelete(){var t,e;await XU({container:this.config.container,type:zU.CONFIRM,variant:GU.WARNING,title:"Delete Document",message:"Are you sure you want to delete this document from the server?",confirmText:"Delete",cancelText:"Cancel",showCloseBtn:!0})&&(await(null===(e=null===(t=this.config)||void 0===t?void 0:t.onDeleteDocument)||void 0===e?void 0:e.call(t,this.config.doc)),this.dispose(),await $U(this.config.container,"Deleted",GU.SUCCESS))}async handleDownload(){var t,e;await(null===(e=null===(t=this.config)||void 0===t?void 0:t.onDownloadDocument)||void 0===e?void 0:e.call(t,this.config.doc))}getDom(){return this.dom}dispose(){this.dom.remove()}}const pF="\n.mwc-library-view-history-item {\n  display: flex;\n  flex-direction: column;\n  font-family: Verdana;\n  padding: 16px;\n  border-bottom: 1px solid #e6e6e6;\n}\n\n.mwc-library-view-history-item:last-child {\n  border-bottom: none;\n}\n\n.mwc-library-view-history-name {\n  font-size: 16px;\n}\n\n.mwc-library-view-history-time {\n  color: #888888;\n  font-size: 16px;\n}\n\n.mwc-library-view-history-actions {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.mwc-library-view-history-action-btn {\n  color: #FE8E14;\n  cursor: pointer;\n  background: none;\n  border: none;\n  font-family: Verdana;\n  padding: 0;\n  font-size: 16px;\n}\n\n.mwc-library-view-history-action-btn:hover {\n  text-decoration: underline;\n}\n\n.mwc-library-view-history-separator {\n  color: #E0E0E0;\n}\n";class gF extends ZU{constructor(t){super(t),this.config=t,this.currentCaller=HU.Library,this.toolbarBtn={back:null}}initialize(){FU("mwc-history-view-style",fF),super.initialize(),this.updateEmptyContentHTML(),this.setVisible(!1)}setVisible(t,e){var i;super.setVisible(t),t&&(this.currentCaller=e.caller,this.showContent(!!(null===(i=this.config.getUploadedDocuments())||void 0===i?void 0:i.length)),this.loadUploadedFiles())}createHeader(){super.createHeader(),this.MWCViewElements.headerContainer.innerHTML='\n      <div class="mwc-view-header-title">Upload History</div>\n    '}updateEmptyContentHTML(){const t=`\n    <div class="mwc-default-empty-history">\n      ${OU.emptyLibrary}\n      <div class="title">\n        No uploaded files found!\n      </div>\n    </div>\n    `;super.setEmptyContent(this.config.emptyContentConfig||t)}createToolbars(){var t,e,i,n;super.createToolbars();const{toolbarButtonsConfig:s}=this.config;[null,null,null,{id:"mwc-history-back",icon:(null===(t=null==s?void 0:s.back)||void 0===t?void 0:t.icon)||OU.back,label:(null===(e=null==s?void 0:s.back)||void 0===e?void 0:e.label)||"Back",className:(null===(i=null==s?void 0:s.back)||void 0===i?void 0:i.className)||"",isHidden:null===(n=null==s?void 0:s.back)||void 0===n?void 0:n.isHidden,onClick:()=>{var t,e;return null===(e=(t=this.config).onBack)||void 0===e?void 0:e.call(t,this.currentCaller)}}].forEach(t=>{const e=this.createToolbarButton(t);t&&(this.toolbarBtn[t.id.split("-").pop()]=e),this.MWCViewElements.toolbarContainer.appendChild(e)})}loadUploadedFiles(){var t;this.MWCViewElements.contentContainer.textContent="",null===(t=this.config.getUploadedDocuments())||void 0===t||t.forEach(t=>{const e=new uF({container:this.config.container,doc:t,onDeleteDocument:()=>this.handleHistoryDelete(t),onDownloadDocument:()=>this.handleHistoryDownload(t)});this.MWCViewElements.contentContainer.append(e.getDom())})}handleHistoryDelete(t){var e,i;t&&(null===(i=null===(e=this.config)||void 0===e?void 0:e.exportConfig)||void 0===i||i.deleteFromServer(t).then(async()=>{var e,i;const n=null===(e=this.config.getUploadedDocuments())||void 0===e?void 0:e.filter(e=>e.uploadTime!==t.uploadTime);this.config.updateUploadedDocuments(n),this.showContent(!!(null===(i=this.config.getUploadedDocuments())||void 0===i?void 0:i.length)),await $U(this.config.container,"Deleted",GU.SUCCESS)}).catch(async()=>{await $U(this.config.container,"Failed",GU.ERROR)}))}handleHistoryDownload(t){var e,i;null===(i=null===(e=this.config)||void 0===e?void 0:e.exportConfig)||void 0===i||i.downloadFromServer(t).then(async()=>{await $U(this.config.container,"Downloaded",GU.SUCCESS)}).catch(async()=>{await $U(this.config.container,"Failed",GU.ERROR)})}dispose(){this.config.container&&(this.config.container.style.display="none",this.MWCViewElements.contentContainer.textContent="")}}const fF="\n  .mwc-default-empty-history {\n    display: flex;\n    flex-direction: column;\n    justify-content: center;\n    align-items: center;\n    gap: 1rem;\n  }\n\n  .mwc-default-empty-history svg {\n    width: 200px;\n    height: auto;\n  }\n\n  .mwc-default-empty-history .title {\n    margin-top: 2rem;\n    font-size: 24px;\n        color: black;\n  }\n\n  .mwc-default-empty-history .desc {\n    font-size: 16px;\n        color: black;\n  }\n",mF="mwc-ddv-css",vF="https://cdn.jsdelivr.net/npm/dynamsoft-document-viewer@3.2.0/dist";class yF{showMWCLoadingOverlay(t){const e=NU(this.config.container);this.loadingScreen=function(t,e={}){const{message:i,spinnerSize:n=32}=e,s=document.createElement("div");s.className="mwc-loading-screen";const o=document.createElement("div");o.className="mwc-loading";const r=document.createElement("div");r.className="mwc-loading-content";const a=`\n    <svg \n      xmlns="http://www.w3.org/2000/svg" \n      viewBox="0 0 24 24" \n      fill="none" \n      stroke="white" \n      stroke-linecap="round" \n      stroke-linejoin="round" \n      width="${n}" \n      height="${n}" \n      stroke-width="0.75"\n    > \n      <path d="M12 3a9 9 0 1 0 9 9"></path> \n    </svg>\n  `;if(r.innerHTML=a,i){const t=document.createElement("div");t.className="mwc-loading-message",t.textContent=i,r.appendChild(t)}return o.appendChild(r),s.appendChild(o),t.appendChild(s),{element:s,updateMessage:t=>{let e=o.querySelector(".dds-loading-message");null!==t?e?e.textContent=t:(e=document.createElement("div"),e.className="mwc-loading-message",e.textContent=t,r.appendChild(e)):null==e||e.remove()},hide:()=>{s&&s.parentNode&&(s.classList.add("fade-out"),setTimeout(()=>{var t;null===(t=s.parentNode)||void 0===t||t.removeChild(s)},200))}}}(e,{message:t})}hideMWCLoadingOverlay(){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null)}constructor(t){this.config=t,this.currentView=null,this.uploadedFiles=[],this.isInitialized=!1,this.isUsingDefaultContainer=!1,this.hasLaunched=!1,this.loadingScreen=null,this.updateUploadedDocuments=t=>{this.uploadedFiles=t}}async initialize(){var t;if(!this.isInitialized)try{this.setupMWCViews(),FU("mwc-loading-screen-style",'\n  .mwc-loading-screen {\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    background-color: #323234;\n    z-index: 998;\n    opacity: 1;\n    transition: opacity 0.2s ease-out;\n  }\n\n  .mwc-loading-screen.fade-out {\n    opacity: 0;\n  }\n\n  .mwc-loading {\n    position: absolute;\n    left: 50%;\n    top: 50%;\n    color: white;\n    z-index: 999;\n    transform: translate(-50%, -50%);\n  }\n\n  .mwc-loading-content {\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    gap: 16px;\n  }\n\n  .mwc-loading svg {\n    animation: spin 1s linear infinite;\n  }\n\n  .mwc-loading-message {\n    color: white;\n    font-family: "Verdana";\n    font-size: 14px;\n    text-align: center;\n    max-width: 200px;\n    line-height: 1.4;\n    opacity: 0.9;\n  }\n\n  @keyframes spin {\n    from {\n      transform: rotate(0deg);\n    }\n    to {\n      transform: rotate(360deg);\n    }\n  }\n'),this.showMWCLoadingOverlay("Initializing"),this.scanner&&await this.scanner.initialize(),await this.loadDDVcss(),$I.Core.license=this.config.license,$I.Core.engineResourcePath=`${(null===(t=this.config)||void 0===t?void 0:t.ddvResourcePath)||vF}/engine`,await this.initializeDDV(),this.initializeMWCViews(),this.isInitialized=!0}catch(t){this.isInitialized=!1;const e=(null==t?void 0:t.message)||t;throw console.error(e),new Error(e)}finally{this.hideMWCLoadingOverlay()}}async launch(t,e){try{if(this.hasLaunched)throw new Error("Failed to launch this MobileWebCapture instance as it is already running");if(this.hasLaunched=!0,this.isInitialized||await this.initialize(),t)return void(t instanceof File?e===HU.Library&&this.config.showLibraryView?await this.createDocumentFromFile(t,HU.Library):await this.createDocumentFromFile(t,HU.Document):"string"==typeof t&&(e===HU.Library&&this.config.showLibraryView?await this.createDocumentFromName(t,HU.Library):await this.createDocumentFromName(t,HU.Document)));t||(e===HU.Library?await this.handleDefaultLaunch(HU.Library):e===HU.Document?await this.createDocumentFromName(`Doc-${Date.now()}`,HU.Document):this.config.showLibraryView?await this.handleDefaultLaunch(HU.Library):await this.createDocumentFromName(`Doc-${Date.now()}`,HU.Document))}catch(t){const e=(null==t?void 0:t.message)||t;throw this.dispose(),new Error(`Launch MWC Failed: ${e}`)}}async createDocumentFromFile(t,e){const i=UU(null==t?void 0:t.name),n=[{convertMode:"cm/auto",fileData:new Blob([t],{type:t.type}),renderOptions:{renderAnnotations:"loadAnnotations"}}];if(this.config.showLibraryView){const t=await this.mwcViews.library.instance.createAndLoadDocument(i,n);e===HU.Document?this.handleDocumentClick(t.uid):this.switchView(e||HU.Library)}else{const t=$I.documentManager.createDocument({name:i});await t.loadSource(n),this.handleDocumentClick(t.uid)}}async createDocumentFromName(t,e){const i=UU(t);if(this.config.showLibraryView){const t=await this.mwcViews.library.instance.createAndLoadDocument(i);e===HU.Document?this.handleDocumentClick(t.uid):this.switchView(e||HU.Library)}else{const t=$I.documentManager.createDocument({name:i});this.handleDocumentClick(t.uid)}}async handleDefaultLaunch(t){if(this.config.showLibraryView)this.switchView(t||HU.Library);else try{const t=$I.documentManager.createDocument({name:`Doc-${Date.now()}`});this.mwcViews[HU.Document].instance.browseViewer.openDocument(t.uid),this.switchView(HU.Document),await $U(this.mwcViews[HU.Document].config.container,"Document Created",GU.SUCCESS)}catch(t){throw new Error(`Failed to create empty document: ${t.message}`)}}setupMWCViews(){var t,e,i,n,s,o,r,a,l,h,c,d,u,p,g,f,m,v,y,x,w;const{license:C,exportConfig:b,showLibraryView:S}=this.config;this.config.license=this.checkForTemporaryLicense(C),this.config.container?(this.config.container=NU(this.config.container),this.config.container.style.position="absolute"!==(null===(e=null===(t=this.config.container)||void 0===t?void 0:t.style)||void 0===e?void 0:e.position)&&"fixed"!==(null===(n=null===(i=this.config.container)||void 0===i?void 0:i.style)||void 0===n?void 0:n.position)?"relative":null===(o=null===(s=this.config.container)||void 0===s?void 0:s.style)||void 0===o?void 0:o.position):this.config.container=this.createDefaultMWCContainer();const T=this.createMWCViewContainers(this.config.container);this.config.libraryViewConfig={...this.config.libraryViewConfig,container:T[jU.Library]},this.config.documentViewConfig={...this.config.documentViewConfig,container:T[jU.Document]},this.config.pageViewConfig={...this.config.pageViewConfig,container:T[jU.Page]},this.config.transferViewConfig={...this.config.transferViewConfig,container:T[jU.Transfer]},this.config.historyViewConfig={...this.config.historyViewConfig,container:T[jU.History]},this.config.scanner?this.scanner=this.config.scanner||null:(this.config.documentScannerConfig={...this.config.documentScannerConfig,scannerViewConfig:{...null===(r=this.config.documentScannerConfig)||void 0===r?void 0:r.scannerViewConfig,container:T[jU.Scanner]},...!1!==(null===(a=this.config.documentScannerConfig)||void 0===a?void 0:a.showResultView)&&{resultViewConfig:{...null===(l=this.config.documentScannerConfig)||void 0===l?void 0:l.resultViewConfig,container:T[jU.ScanResult]}},...!1!==(null===(h=this.config.documentScannerConfig)||void 0===h?void 0:h.showCorrectionView)&&{correctionViewConfig:{...null===(c=this.config.documentScannerConfig)||void 0===c?void 0:c.correctionViewConfig,container:T[jU.Correction]}},correctionViewConfig:{...null===(d=this.config.documentScannerConfig)||void 0===d?void 0:d.scannerViewConfig,container:T[jU.Correction]}},this.scanner=new kU({license:this.config.license,...this.config.documentScannerConfig,scannerViewConfig:null===(u=this.config.documentScannerConfig)||void 0===u?void 0:u.scannerViewConfig,resultViewConfig:!1===(null===(p=this.config.documentScannerConfig)||void 0===p?void 0:p.showResultView)||null===(g=this.config.documentScannerConfig)||void 0===g?void 0:g.resultViewConfig,correctionViewConfig:!1===(null===(f=this.config.documentScannerConfig)||void 0===f?void 0:f.showCorrectionView)||null===(m=this.config.documentScannerConfig)||void 0===m?void 0:m.correctionViewConfig,showResultView:null===(y=null===(v=this.config.documentScannerConfig)||void 0===v?void 0:v.showResultView)||void 0===y||y,showCorrectionView:null===(w=null===(x=this.config.documentScannerConfig)||void 0===x?void 0:x.showCorrectionView)||void 0===w||w})),this.mwcViews={[HU.Library]:{config:{...this.config.libraryViewConfig,container:this.config.libraryViewConfig.container,onCameraCapture:()=>this.handleCameraCapture(HU.Library),onGalleryImport:()=>this.handleGalleryImport(HU.Library),onDocumentClick:t=>this.handleDocumentClick(t),onViewUploadsHistory:()=>this.switchView(HU.History,{caller:HU.Library}),onClose:()=>this.dispose(),exportConfig:b,getUploadedDocuments:()=>this.getUploadedDocuments(),updateUploadedDocuments:t=>this.updateUploadedDocuments(t)}},[HU.Document]:{config:{...this.config.documentViewConfig,container:this.config.documentViewConfig.container,onBackToLibrary:()=>this.switchView(HU.Library),onCameraCapture:()=>this.handleCameraCapture(HU.Document),onGalleryImport:()=>this.handleGalleryImport(HU.Document),onPageClick:(t,e)=>this.handlePageClick(t,e),onViewUploadsHistory:()=>this.switchView(HU.History,{caller:HU.Document}),onClose:()=>this.dispose(),exportConfig:b,getUploadedDocuments:()=>this.getUploadedDocuments(),updateUploadedDocuments:t=>this.updateUploadedDocuments(t),onTransferPages:(t,e,i)=>this.handleTransferPage(t,e,i),showLibraryView:S}},[HU.Page]:{config:{...this.config.pageViewConfig,container:this.config.pageViewConfig.container,onDocumentClick:()=>this.switchView(HU.Document),onCameraCapture:()=>this.handleCameraCapture(HU.Page),onGalleryImport:()=>this.handleGalleryImport(HU.Page),onViewUploadsHistory:()=>this.switchView(HU.History,{caller:HU.Page}),onClose:()=>this.dispose(),exportConfig:b,getUploadedDocuments:()=>this.getUploadedDocuments(),updateUploadedDocuments:t=>this.updateUploadedDocuments(t),showLibraryView:S}},[HU.Transfer]:{config:{...this.config.transferViewConfig,container:this.config.transferViewConfig.container,onConfirmTransfer:t=>this.handleTransferPageConfirm(t),onCancelTransfer:()=>this.handleTransferPageCancel()}},[HU.History]:{config:{...this.config.historyViewConfig,container:this.config.historyViewConfig.container,exportConfig:b,getUploadedDocuments:()=>this.getUploadedDocuments(),updateUploadedDocuments:t=>this.updateUploadedDocuments(t),onBack:t=>this.handleHistoryBack(t)}},[HU.Scanner]:{config:{}}}}getDDSViewsToCreate(){var t,e,i,n;const s=null===(e=null===(t=this.config.documentScannerConfig)||void 0===t?void 0:t.showResultView)||void 0===e||e,o=null===(n=null===(i=this.config.documentScannerConfig)||void 0===i?void 0:i.showCorrectionView)||void 0===n||n,r=[jU.Scanner];return s&&r.push(jU.ScanResult),o&&r.push(jU.Correction),r}createMWCViewContainers(t){const e=this.getDDSViewsToCreate(),i=Object.values(HU),n=(t,e)=>{const i=document.createElement("div");return i.className=`mwc-view-container mwc-${t}-view-container`,Object.assign(i.style,e),i};return{...e.reduce((e,i)=>{const s=n(i,{position:"absolute",height:"100%",width:"100%",top:"0",left:"0",zIndex:"1000",display:"none"});return t.append(s),e[i]=s,e},{}),...i.reduce((e,i)=>{const s=n(i,{position:"relative",height:"100%",width:"100%",display:"none"});return t.append(s),e[i]=s,e},{})}}createDefaultMWCContainer(){const t=document.createElement("div");return t.className="mwc-main-container",Object.assign(t.style,{height:"100dvh",width:"100%",position:"absolute",left:0,top:0,display:"none"}),document.body.append(t),this.isUsingDefaultContainer=!0,t}checkForTemporaryLicense(t){return!(null==t?void 0:t.length)||(null==t?void 0:t.startsWith("A"))||(null==t?void 0:t.startsWith("L"))||(null==t?void 0:t.startsWith("P"))||(null==t?void 0:t.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":t}loadDDVcss(){var t;if(document.getElementById(mF))return;const e=(null===(t=this.config)||void 0===t?void 0:t.ddvResourcePath)||vF;return new Promise((t,i)=>{const n=document.createElement("link");n.rel="stylesheet",n.href=`${e}/ddv.css`,n.id=mF,n.onload=()=>t(),n.onerror=()=>i(new Error(`Failed to load CSS from ${e}`)),document.head.appendChild(n)})}removeDDVcss(){const t=document.getElementById(mF);t&&t.remove()}async initializeDDV(){await $I.Core.loadWasm(),await $I.Core.init(),$I.setProcessingHandler("imageFilter",new $I.ImageFilter)}initializeMWCViews(){const{Library:t,Document:e,Page:i,Transfer:n,History:s}=HU;this.mwcViews[t].instance=new oF(this.mwcViews[t].config),this.mwcViews[e].instance=new nF(this.mwcViews[e].config),this.mwcViews[i].instance=new hF(this.mwcViews[i].config),this.mwcViews[n].instance=new eF(this.mwcViews[n].config),this.mwcViews[s].instance=new gF(this.mwcViews[s].config),this.mwcViews[t].instance.initialize(),this.mwcViews[e].instance.initialize(),this.mwcViews[i].instance.initialize(),this.mwcViews[n].instance.initialize(),this.mwcViews[s].instance.initialize()}switchView(t,e){var i,n,s,o,r,a,l;if("none"===(null===(i=this.config.container)||void 0===i?void 0:i.style.display)&&(this.config.container.style.display="block"),t===this.currentView)return void(null===(s=null===(n=this.mwcViews[t].instance)||void 0===n?void 0:n.setVisible)||void 0===s||s.call(n,!0,e));if(this.currentView){null===(r=null===(o=this.mwcViews[this.currentView].instance)||void 0===o?void 0:o.setVisible)||void 0===r||r.call(o,!1,e)}null===(l=null===(a=this.mwcViews[t].instance)||void 0===a?void 0:a.setVisible)||void 0===l||l.call(a,!0,e),this.currentView=t}async processScanResult(t){var e;const i=[];try{if(Array.isArray(t)){const e=t.map(async t=>{var e;const n=null==t?void 0:t._imageData;if((null==n?void 0:n.toBlob)&&(null===(e=null==t?void 0:t.status)||void 0===e?void 0:e.code)===hU.RS_SUCCESS){const t=await n.toBlob("image/png");i.push(t)}});await Promise.all(e)}else if(((null==t?void 0:t.correctedImageResult)||(null==t?void 0:t.imageData))&&(null===(e=null==t?void 0:t.status)||void 0===e?void 0:e.code)===hU.RS_SUCCESS){const e=(null==t?void 0:t.correctedImageResult)||(null==t?void 0:t._imageData);if(null==e?void 0:e.toBlob){const t=await e.toBlob("image/png");i.push(t)}}else if(t&&"object"==typeof t&&((n=t)&&0!==Object.keys(n).length)){const e=Object.values(t).map(async t=>{var e;const n=null==t?void 0:t._imageData;if((null==n?void 0:n.toBlob)&&(null===(e=null==t?void 0:t.status)||void 0===e?void 0:e.code)===hU.RS_SUCCESS){const t=await n.toBlob("image/png");i.push(t)}});await Promise.all(e)}}catch(t){let e=`Error processing scan result: ${(null==t?void 0:t.message)||t}`;throw console.error(e),new Error(e)}var n;return i}async handleCameraCapture(t){var e,i,n,s;null===(i=null===(e=this.mwcViews[this.currentView].instance)||void 0===e?void 0:e.setVisible)||void 0===i||i.call(e,!1);try{const e=await this.scanner.launch(),i=await this.processScanResult(e);if(0===i.length)return;if(t===HU.Library){const t=i.map(t=>({convertMode:"cm/auto",fileData:t})),e=await this.mwcViews.library.instance.createAndLoadDocument(`Doc-${Date.now()}`,t);this.handleDocumentClick(e.uid)}else if(t===HU.Document||t===HU.Page){const t=this.mwcViews[HU.Document].instance.browseViewer.currentDocument,e=i.map(t=>({convertMode:"cm/auto",fileData:t}));t&&await t.loadSource(e)}}catch(t){throw console.error("Camera capture failed:",t),new Error(t)}finally{null===(s=null===(n=this.mwcViews[this.currentView].instance)||void 0===n?void 0:n.setVisible)||void 0===s||s.call(n,!0)}}async handleGalleryImport(t){const e=document.createElement("input");e.type="file",e.accept="image/png,image/jpeg,image/bmp,image/tiff,application/pdf",e.multiple=!0,e.onchange=async()=>{var i;const n=Array.from(e.files||[]),s=n.length,o=[];for(let t=0;t<s;t++)o.push({convertMode:"cm/auto",fileData:new Blob([n[t]],{type:n[t].type}),renderOptions:{renderAnnotations:"loadAnnotations"}});if(o.length>0)if(t===HU.Library){const t=UU(null===(i=n[0])||void 0===i?void 0:i.name),e=await this.mwcViews.library.instance.createAndLoadDocument(t,o);this.handleDocumentClick(e.uid)}else if(t===HU.Document||t===HU.Page){const e=this.mwcViews[HU.Document].instance.browseViewer.currentDocument;e&&(await e.loadSource(o),this.switchView(t))}},e.click()}handleDocumentClick(t){this.mwcViews[HU.Document].instance.browseViewer.openDocument(t),this.switchView(HU.Document)}handlePageClick(t,e){this.mwcViews[HU.Page].instance.openPage(t,e),this.switchView(HU.Page)}handleTransferPage(t,e,i){this.switchView(HU.Transfer,{mode:t,docId:e,selectedIdx:i})}async handleTransferPageConfirm(t){this.mwcViews.document.instance.handleSelectedBack(),await $U(this.mwcViews.document.config.container,"copy"===t?"Pasted":"move"===t?"Moved":"")}handleTransferPageCancel(){this.switchView(HU.Document)}handleHistoryBack(t){this.switchView(t)}getUploadedDocuments(){return this.uploadedFiles}dispose(){var t,e;return Object.values(this.mwcViews).forEach(t=>{var e;(null===(e=t.instance)||void 0===e?void 0:e.dispose)&&t.instance.dispose()}),this.scanner.dispose(),$I.documentManager.deleteAllDocuments(),this.config.container instanceof HTMLElement&&(this.config.container.textContent=""),this.isUsingDefaultContainer&&NU(this.config.container).remove(),this.removeDDVcss(),this.currentView=null,this.uploadedFiles=[],this.mwcViews=null,this.scanner=null,this.isInitialized=!1,(null===(t=this.config)||void 0===t?void 0:t.onClose)&&(null===(e=this.config)||void 0===e||e.onClose()),this.hasLaunched=!1,Promise.resolve()}}const xF={MobileWebCapture:yF,LibraryView:oF,DocumentView:nF,PageView:hF,TransferView:eF};t.DDS=LU,t.DDV=XI,t.DocumentView=nF,t.LibraryView=oF,t.MWC=xF,t.MobileWebCapture=yF,t.PageView=hF,t.TransferView=eF});
