@component-hook/pdf-canvas 0.1.6 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,509 +0,0 @@
1
- (function(nt,q){typeof exports=="object"&&typeof module<"u"?q(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],q):(nt=typeof globalThis<"u"?globalThis:nt||self,q(nt["pdf-canvas"]={},nt.Vue))})(this,function(nt,q){"use strict";var gS=Object.defineProperty;var Z0=nt=>{throw TypeError(nt)};var fS=(nt,q,Ot)=>q in nt?gS(nt,q,{enumerable:!0,configurable:!0,writable:!0,value:Ot}):nt[q]=Ot;var Q=(nt,q,Ot)=>fS(nt,typeof q!="symbol"?q+"":q,Ot),Jg=(nt,q,Ot)=>q.has(nt)||Z0("Cannot "+Ot);var c=(nt,q,Ot)=>(Jg(nt,q,"read from private field"),Ot?Ot.call(nt):q.get(nt)),w=(nt,q,Ot)=>q.has(nt)?Z0("Cannot add the same private member more than once"):q instanceof WeakSet?q.add(nt):q.set(nt,Ot),b=(nt,q,Ot,A)=>(Jg(nt,q,"write to private field"),A?A.call(nt,Ot):q.set(nt,Ot),Ot),y=(nt,q,Ot)=>(Jg(nt,q,"access private method"),Ot);var Pe=(nt,q,Ot,A)=>({set _(ql){b(nt,q,ql,Ot)},get _(){return c(nt,q,A)}});var Ei,Ld,Zg,mh,ur,gr,Gs,ki,me,pd,fr,W,we,La,Ra,Rd,Fa,tb,tf,Ia,Il,jl,ef,Nl,pn,pr,As,mr,bh,vh,md,eb,Me,sb,ib,Fd,nb,sf,yh,br,vr,mn,rb,ob,ab,bd,Fo,_h,be,Io,Id,Zt,bn,wh,te,vd,hb,jo,$e,$t,re,No,Oi,Bo,Ts,vn,Ho,yr,Us,Es,_r,xh,Sh,Wo,Ch,Ys,yn,zo,_n,qs,_d,wn,Ah,xn,wr,Th,Eh,ee,pt,Di,xr,kh,Mh,Sn,$s,Pi,Oh,ls,N,jd,nf,lb,cb,Nd,db,ub,gb,rf,fb,of,af,pb,Le,Vn,mb,bb,hf,vb,Bl,lf,se,Ks,ks,Qs,Ke,Vo,Js,Be,Li,Sr,Zs,Go,ti,Bd,Hd,Cr,Ms,Et,Uo,Ar,oe,Tr,Cn,Dh,Er,An,Ph,kr,Ri,ei,Yo,qo,cs,Lh,wd,et,cf,Rh,df,uf,yb,_b,gf,ff,pf,wb,mf,xb,Sb,Cb,bf,Hl,Mr,Or,ne,xd,Ab,Fh,$o,Tn,vf,yf,Ih,jh,si,Tb,Eb,Wd,Dr,Nh,Bh,Hh,Wh,Ko,En,mt,Qo,Jo,zh,_f,J0,kn,He,Xh,Vh,Pr,Fi,Gh,Uh,Lr,Zo,ta,Mn,ea,Yh,sa,Rr,qh,$h,Fr,Ir,Kh,On,ia,Ii,kb,Mb,wf,Qe,zd,xf,Ob,Db,Cd,Dn,ji,ds,ja,Xd,jr,Td,Ed,Nr,Br,na,Vd,ra,Gd,Ni,ii,oa,aa,ni,Hr,Wl,Os,Qh,Sf,Pn,Ln,Wr,Xr,ha,la,Jh,Cf,Je,go,Pb,Lb,ca,kd,Md,da,Vr,Pt,Bi,ua,Zh,tl,ga,Hi,Ds,Wi,el,zi,sl,Gr,Ur,bt,Ud,Af,Rb,Fb,Ib,jb,Yd,qd,Tf,il,nl,rl,ol,al,hl,ll,Ef,cl,Yr,qr,dl,$r,Nb,kf,Ps,Ze,ul,Kr,ts,Xt,Bb,Hb,Wb,$d,Xi,Kd,Qd,zb,Mf,Xb,gl,Rn,Ls,Oe,Vb,Jd,Gb,Ub,Of,fl,fa,ri,Vi,pa,ma,oi,ot,Qr,Jr,pl,ml,ba,va,Fn,bl,Od,Dd,vl,Df,ya,Zr,Ui,yl,es,_l,Nt,We,zl,Xl,Yb,wl,xl,Rs,to,_a,Qt,Sl,wa,Cl,Al,Fs,xa,Tl,vt,Pf,Lf,qb,fo,$b,Gn,Sa,El,Yi,eo,Ca,us,kl,Ml,so,Is,ve,Xe,Aa,qi,Jt,Ta,gs,Ol,Z,Rf,Zd,Kb,Qb,Jb,Ff,po,fs,Na,Zb,tu,Vl,tv,ev,sv,iv,nv,io,no,ai,$i,ps,ro,oo,ao,Ki,Ea,ho,lo,In,I,rv,ov,av,hv,If,lv,jf,cv,dv,uv,gv,fv,mo,Nf,Bf,Hf,eu,su,Ba,Wf,iu,Qi,pv,zf,mv,bv,Xf,nu,Gl,Mt,ae,jn,Ji,Nn,ka,hi,Zi,li,ss,Ma,it,Ul,Yl,ru,Vf,vv,ou,Gf,au,yv,_v,co,Oa,ci,Bn,tn,is,Hn,Da,Pa,ye,en,U,Wn,he,wv,Uf,Yf,qf,hu,di,Pl,Vt,zn,Ll,$f,uo,Kf,xv;var Ot=typeof document<"u"?document.currentScript:null;function A(a,t,e){return(t=function(s){var i=function(n,r){if(typeof n!="object"||!n)return n;var o=n[Symbol.toPrimitive];if(o!==void 0){var h=o.call(n,r||"default");if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)}(s,"string");return typeof i=="symbol"?i:i+""}(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function ql(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),e.push.apply(e,s)}return e}function T(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?ql(Object(e),!0).forEach(function(s){A(a,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):ql(Object(e)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(e,s))})}return a}function xt(a,t){if(a==null)return{};var e,s,i=function(r,o){if(r==null)return{};var h={};for(var l in r)if({}.hasOwnProperty.call(r,l)){if(o.indexOf(l)>=0)continue;h[l]=r[l]}return h}(a,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(a);for(s=0;s<n.length;s++)e=n[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(a,e)&&(i[e]=a[e])}return i}function sn(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class Qf{constructor(){A(this,"browserShadowBlurConstant",1),A(this,"DPI",96),A(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),A(this,"perfLimitSizeTotal",2097152),A(this,"maxCacheSideLimit",4096),A(this,"minCacheSideLimit",256),A(this,"disableStyleCopyPaste",!1),A(this,"enableGLFiltering",!0),A(this,"textureSize",4096),A(this,"forceGLPutImageData",!1),A(this,"cachesBoundsOfCurve",!1),A(this,"fontPaths",{}),A(this,"NUM_FRACTION_DIGITS",4)}}const at=new class extends Qf{constructor(a){super(),this.configure(a)}configure(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,a)}addFonts(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths=T(T({},this.fontPaths),a)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(a=>{delete this.fontPaths[a]})}clearFonts(){this.fontPaths={}}restoreDefaults(a){const t=new Qf,e=(a==null?void 0:a.reduce((s,i)=>(s[i]=t[i],s),{}))||t;this.configure(e)}},ui=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return console[a]("fabric",...e)};class Ns extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class lu extends Ns{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class Sv{}class Cv extends Sv{testPrecision(t,e){const s="precision ".concat(e,` float;
2
- void main(){}`),i=t.createShader(t.FRAGMENT_SHADER);return!!i&&(t.shaderSource(i,s),t.compileShader(i),!!t.getShaderParameter(i,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find(s=>this.testPrecision(e,s)),e.getExtension("WEBGL_lose_context").loseContext(),ui("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Av={};let Jf;const Bs=()=>Jf||(Jf={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Cv,dispose(){},copyPasteData:Av}),bo=()=>Bs().document,$l=()=>Bs().window,Zf=()=>{var a;return Math.max((a=at.devicePixelRatio)!==null&&a!==void 0?a:$l().devicePixelRatio,1)},Ha=new class{constructor(){A(this,"charWidthsCache",{}),A(this,"boundsOfCurveCache",{})}getFontCache(a){let{fontFamily:t,fontStyle:e,fontWeight:s}=a;t=t.toLowerCase(),this.charWidthsCache[t]||(this.charWidthsCache[t]={});const i=this.charWidthsCache[t],n="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return i[n]||(i[n]={}),i[n]}clearFontCache(a){(a=(a||"").toLowerCase())?this.charWidthsCache[a]&&delete this.charWidthsCache[a]:this.charWidthsCache={}}limitDimsByArea(a){const{perfLimitSizeTotal:t}=at,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},cu="6.4.3";function Un(){}const nn=Math.PI/2,gi=2*Math.PI,du=Math.PI/180,xe=Object.freeze([1,0,0,1,0,0]),uu=16,rn=.4477152502,J="center",ut="left",Re="top",gu="bottom",Lt="right",Se="none",fu=/\r?\n/,tp="moving",Kl="scaling",ep="rotating",pu="rotate",sp="skewing",Wa="resizing",Tv="modifyPoly",Ev="modifyPath",Ql="changed",Jl="scale",Ce="scaleX",Ge="scaleY",vo="skewX",yo="skewY",Rt="fill",Ae="stroke",Zl="modified",_o="json",mu="svg",z=new class{constructor(){this[_o]=new Map,this[mu]=new Map}has(a){return this[_o].has(a)}getClass(a){const t=this[_o].get(a);if(!t)throw new Ns("No class registered for ".concat(a));return t}setClass(a,t){t?this[_o].set(t,a):(this[_o].set(a.type,a),this[_o].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[mu].get(a)}setSVGClass(a,t){this[mu].set(t??a.type.toLowerCase(),a)}},tc=new class extends Array{remove(a){const t=this.indexOf(a);t>-1&&this.splice(t,1)}cancelAll(){const a=this.splice(0);return a.forEach(t=>t.abort()),a}cancelByCanvas(a){if(!a)return[];const t=this.filter(e=>{var s;return e.target===a||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===a});return t.forEach(e=>e.abort()),t}cancelByTarget(a){if(!a)return[];const t=this.filter(e=>e.target===a);return t.forEach(e=>e.abort()),t}};class kv{constructor(){A(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach(s=>{let[i,n]=s;this.on(i,n)}),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach(i=>{let[n,r]=i;s.push(this.once(n,r))}),()=>s.forEach(i=>i())}if(e){const s=this.on(t,function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()});return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach(s=>{let[i,n]=s;this._removeEventListener(i,n)}):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const Yn=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},ms=a=>{if(a===0)return 1;switch(Math.abs(a)/nn){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},bs=a=>{if(a===0)return 0;const t=a/nn,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class M{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;typeof t=="object"?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new M(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new M(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new M(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new M(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new M(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new M(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new M(this.x/t.x,this.y/t.y)}scalarDivide(t){return new M(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.x<t.x&&this.y<t.y}lte(t){return this.x<=t.x&&this.y<=t.y}gt(t){return this.x>t.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new M(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}midPointFrom(t){return this.lerp(t)}min(t){return new M(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new M(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new M(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:bu;const s=bs(t),i=ms(t),n=this.subtract(e);return new M(n.x*i-n.y*s,n.x*s+n.y*i).add(e)}transform(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new M(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}const bu=new M(0,0),ec=a=>!!a&&Array.isArray(a._objects);function ip(a){class t extends a{constructor(){super(...arguments),A(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach(o=>this._onObjectAdded(o)),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach(o=>this._onObjectAdded(o)),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return r.forEach(h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),i.push(h),this._onObjectRemoved(h))}),i}forEachObject(s){this.getObjects().forEach((i,n,r)=>s(i,n,r))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter(r=>r.isType(...i))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some(n=>n instanceof t&&n.contains(s,!0))}complexity(){return this._objects.reduce((s,i)=>s+=i.complexity?i.complexity():0,0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(Yn(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Yn(this._objects,s),this._objects.push(s),this._onStackOrderChanged(s),!0)}sendObjectBackwards(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==0){const r=this.findNewLowerIndex(s,n,i);return Yn(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}bringObjectForward(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==this._objects.length-1){const r=this.findNewUpperIndex(s,n,i);return Yn(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Yn(this._objects,s),this._objects.splice(i,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,i,n){let r;if(n){r=i;for(let o=i-1;o>=0;--o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let o=i+1;o<this._objects.length;++o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:o}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const l=[],d=new M(i,n),u=d.add(new M(r,o));for(let g=this._objects.length-1;g>=0;g--){const f=this._objects[g];f.selectable&&f.visible&&(h&&f.intersectsWithRect(d,u)||f.isContainedWithinRect(d,u)||h&&f.containsPoint(d)||h&&f.containsPoint(u))&&l.push(f)}return l}}return t}class np extends kv{_setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};for(const e in t)this.set(e,t[e])}_setObject(t){for(const e in t)this._set(e,t[e])}set(t,e){return typeof t=="object"?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return typeof e=="boolean"&&this.set(t,!e),this}get(t){return this[t]}}function za(a){return $l().requestAnimationFrame(a)}function rp(a){return $l().cancelAnimationFrame(a)}let Mv=0;const on=()=>Mv++,Ft=()=>{const a=bo().createElement("canvas");if(!a||a.getContext===void 0)throw new Ns("Failed to create `canvas` element");return a},op=()=>bo().createElement("img"),vu=(a,t,e)=>a.toDataURL("image/".concat(t),e),Dt=a=>a*du,an=a=>a/du,ap=a=>a.every((t,e)=>t===xe[e]),ce=(a,t,e)=>new M(a).transform(t,e),Fe=a=>{const t=1/(a[0]*a[3]-a[1]*a[2]),e=[t*a[3],-t*a[1],-t*a[2],t*a[0],0,0],{x:s,y:i}=new M(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},It=(a,t,e)=>[a[0]*t[0]+a[2]*t[1],a[1]*t[0]+a[3]*t[1],a[0]*t[2]+a[2]*t[3],a[1]*t[2]+a[3]*t[3],e?0:a[0]*t[4]+a[2]*t[5]+a[4],e?0:a[1]*t[4]+a[3]*t[5]+a[5]],sc=(a,t)=>a.reduceRight((e,s)=>s&&e?It(s,e,t):s||e,void 0)||xe.concat(),hp=a=>{let[t,e]=a;return Math.atan2(e,t)},qn=a=>{const t=hp(a),e=Math.pow(a[0],2)+Math.pow(a[1],2),s=Math.sqrt(e),i=(a[0]*a[3]-a[2]*a[1])/s,n=Math.atan2(a[0]*a[2]+a[1]*a[3],e);return{angle:an(t),scaleX:s,scaleY:i,skewX:an(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},wo=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function xo(){let{angle:a=0}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{x:t=0,y:e=0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=Dt(a),i=ms(s),n=bs(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const ic=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},lp=a=>Math.tan(Dt(a)),yu=a=>[1,0,lp(a),1,0,0],_u=a=>[1,lp(a),0,1,0,0],Xa=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=ic(s?-t:t,i?-e:e);return n&&(o=It(o,yu(n),!0)),r&&(o=It(o,_u(r),!0)),o},cp=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=wo(t,e);s&&(i=It(i,xo({angle:s})));const n=Xa(a);return ap(n)||(i=It(i,n)),i},Va=function(a){let{signal:t,crossOrigin:e=null}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(s,i){if(t&&t.aborted)return i(new lu("loadImage"));const n=op();let r;t&&(r=function(h){n.src="",i(h)},t.addEventListener("abort",r,{once:!0}));const o=function(){n.onload=n.onerror=null,r&&(t==null||t.removeEventListener("abort",r)),s(n)};a?(n.onload=o,n.onerror=function(){r&&(t==null||t.removeEventListener("abort",r)),i(new Ns("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()})},So=function(a){let{signal:t,reviver:e=Un}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((s,i)=>{const n=[];t&&t.addEventListener("abort",i,{once:!0}),Promise.all(a.map(r=>z.getClass(r.type).fromObject(r,{signal:t}).then(o=>(e(r,o),n.push(o),o)))).then(s).catch(r=>{n.forEach(o=>{o.dispose&&o.dispose()}),i(r)}).finally(()=>{t&&t.removeEventListener("abort",i)})})},Ga=function(a){let{signal:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((e,s)=>{const i=[];t&&t.addEventListener("abort",s,{once:!0});const n=Object.values(a).map(o=>o&&o.type&&z.has(o.type)?So([o],{signal:t}).then(h=>{let[l]=h;return i.push(l),l}):o),r=Object.keys(a);Promise.all(n).then(o=>o.reduce((h,l,d)=>(h[r[d]]=l,h),{})).then(e).catch(o=>{i.forEach(h=>{h.dispose&&h.dispose()}),s(o)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},$n=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in a&&(t[e]=a[e]),t),{})},wu=(a,t)=>Object.keys(a).reduce((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e),{}),dp={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#0FF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000",blanchedalmond:"#FFEBCD",blue:"#00F",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#0FF",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:"#F0F",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:"#789",lightslategrey:"#789",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#0F0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#F0F",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:"#639",red:"#F00",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:"#FFF",whitesmoke:"#F5F5F5",yellow:"#FF0",yellowgreen:"#9ACD32"},xu=(a,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?a+6*(t-a)*e:e<.5?t:e<2/3?a+(t-a)*(2/3-e)*6:a),up=(a,t,e,s)=>{a/=255,t/=255,e/=255;const i=Math.max(a,t,e),n=Math.min(a,t,e);let r,o;const h=(i+n)/2;if(i===n)r=o=0;else{const l=i-n;switch(o=h>.5?l/(2-i-n):l/(i+n),i){case a:r=(t-e)/l+(t<e?6:0);break;case t:r=(e-a)/l+2;break;case e:r=(a-t)/l+4}r/=6}return[Math.round(360*r),Math.round(100*o),Math.round(100*h),s]},gp=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},nc=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),fp=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class ft{constructor(t){if(A(this,"isUnrecognised",!1),t)if(t instanceof ft)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,s,i,n=1]=t;this.setSource([e,s,i,n])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return t in dp&&(t=dp[t]),t==="transparent"?[255,255,255,0]:ft.sourceFromHex(t)||ft.sourceFromRgb(t)||ft.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=up(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=up(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(i,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return"".concat(nc(t)).concat(nc(e)).concat(nc(s)).concat(nc(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(fp(this.getSource())),this}toBlackWhite(t){const[e,,,s]=fp(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof ft||(t=new ft(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map((o,h)=>Math.round(.5*o+.5*s[h]));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return ft.fromRgba(t)}static fromRgba(t){return new ft(ft.sourceFromRgb(t))}static sourceFromRgb(t){const e=t.match(/^rgba?\(\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d{0,3}(?:\.\d+)?%?)\s*)?\)$/i);if(e){const[s,i,n]=e.slice(1,4).map(r=>{const o=parseFloat(r);return r.endsWith("%")?Math.round(2.55*o):o});return[s,i,n,gp(e[4])]}}static fromHsl(t){return ft.fromHsla(t)}static fromHsla(t){return new ft(ft.sourceFromHsl(t))}static sourceFromHsl(t){const e=t.match(/^hsla?\(\s*([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d*(?:\.\d+)?%?)\s*)?\)$/i);if(!e)return;const s=(ft.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,o,h;if(i===0)r=o=h=n;else{const l=n<=.5?n*(i+1):n+i-n*i,d=2*n-l;r=xu(d,l,s+1/3),o=xu(d,l,s),h=xu(d,l,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),gp(e[4])]}static fromHex(t){return new ft(ft.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map(h=>h+h):e.match(/.{2}/g);const[i,n,r,o=255]=s.map(h=>parseInt(h,16));return[i,n,r,o/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?an(s):e.includes("turn")?360*s:s}}const St=(a,t)=>parseFloat(Number(a).toFixed(t)),Te=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:uu;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=at.DPI;switch(e==null?void 0:e[0]){case"mm":return s*i/25.4;case"cm":return s*i/2.54;case"in":return s*i;case"pt":return s*i/72;case"pc":return s*i/72*12;case"em":return s*t;default:return s}},Su=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==Se?[n.slice(1,4),n.slice(5,8)]:n===Se?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},Ua=a=>"matrix("+a.map(t=>St(t,at.NUM_FRACTION_DIGITS)).join(" ")+")",Ya=function(a,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const n=new ft(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(a,": ").concat(e,"; ").concat(s?"".concat(a,"-opacity: ").concat(s,"; "):""):"".concat(a,'="').concat(e,'" ').concat(s?"".concat(a,'-opacity="').concat(s,'" '):"")},ns=a=>!!a&&a.toLive!==void 0,pp=a=>!!a&&typeof a.toObject=="function",mp=a=>!!a&&a.offsetX!==void 0&&"source"in a,bp=a=>!!a&&typeof a._renderText=="function",Kn=a=>!!a&&"multiSelectionStacking"in a;function vp(a){const t=a&&vs(a);let e=0,s=0;if(!a||!t)return{left:e,top:s};let i=a;const n=t.documentElement,r=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(e=r.scrollLeft||n.scrollLeft||0,s=r.scrollTop||n.scrollTop||0):(e+=i.scrollLeft||0,s+=i.scrollTop||0),i.nodeType!==1||i.style.position!=="fixed"););return{left:e,top:s}}const vs=a=>a.ownerDocument||null,yp=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},_p=function(a,t,e){let{width:s,height:i}=e,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;a.width=s,a.height=i,n>1&&(a.setAttribute("width",(s*n).toString()),a.setAttribute("height",(i*n).toString()),t.scale(n,n))},Cu=(a,t)=>{let{width:e,height:s}=t;e&&(a.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(a.style.height=typeof s=="number"?"".concat(s,"px"):s)};function wp(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=Se,a}class xp{constructor(t){A(this,"_originalCanvasStyle",void 0),A(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&bo().getElementById(t)||Ft();var s;if(e.hasAttribute("data-fabric"))throw new Ns("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width","".concat(e)),i.setAttribute("height","".concat(s)),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;_p(s,i,t,e)}setCSSDimensions(t){Cu(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&vs(t),i={left:0,top:0};if(!s)return i;const n=((e=yp(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};i.left+=parseInt(n.borderLeftWidth,10)||0,i.top+=parseInt(n.borderTopWidth,10)||0,i.left+=parseInt(n.paddingLeft,10)||0,i.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const o=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const h=vp(t);return{left:r.left+h.left-(o.clientLeft||0)+i.left,top:r.top+h.top-(o.clientTop||0)+i.top}}(this.lower.el)}dispose(){Bs().dispose(this.lower.el),delete this.lower}}const Ov={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...xe]};class qa extends ip(np){get lowerCanvasEl(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.el}get contextContainer(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.ctx}static getDefaults(){return qa.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new xp(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(ui("warn",`Canvas is trying to add an object that belongs to a different canvas.
3
- Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?Zf():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const i=T({width:this.width,height:this.height},t);this.elements.setDimensions(i,this.getRetinaScaling()),this.hasLostContext=!0,this.width=i.width,this.height=i.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,i=[...this.viewportTransform],n=ce(t,Fe(i));i[0]=e,i[3]=e;const r=ce(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new M(0,0),t)}absolutePan(t){const e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new M(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(t){t.clearRect(0,0,this.width,this.height)}getContext(){return this.elements.lower.ctx}clear(){this.remove(...this.getObjects()),this.backgroundImage=void 0,this.overlayImage=void 0,this.backgroundColor="",this.overlayColor="",this.clearContext(this.getContext()),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll()}renderAll(){this.cancelRequestedRender(),this.destroyed||this.renderCanvas(this.getContext(),this._objects)}renderAndReset(){this.nextRenderHandle=0,this.renderAll()}requestRenderAll(){this.nextRenderHandle||this.disposed||this.destroyed||(this.nextRenderHandle=za(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Fe(this.viewportTransform),i=ce({x:0,y:0},s),n=ce({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new M(o.x,r.y),bl:new M(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(rp(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const s=this.viewportTransform,i=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),i&&(i._set("canvas",this),i.shouldCache(),i._transformDone=!0,i.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,i)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const s=this.viewportTransform;t.save(),t.transform(...s),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let s=0,i=e.length;s<i;++s)e[s]&&e[s].render(t)}_renderBackgroundOrOverlay(t,e){const s=this["".concat(e,"Color")],i=this["".concat(e,"Image")],n=this.viewportTransform,r=this["".concat(e,"Vpt")];if(!s&&!i)return;const o=ns(s);if(s){if(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=o?s.toLive(t):s,r&&t.transform(...n),o){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const h=s.gradientTransform||s.patternTransform;h&&t.transform(...h)}t.fill(),t.restore()}if(i){t.save();const{skipOffscreen:h}=this;this.skipOffscreen=r,r&&t.transform(...n),i.render(t),this.skipOffscreen=h,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenter(){return{top:this.height/2,left:this.width/2}}getCenterPoint(){return new M(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new M(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new M(t.getCenterPoint().x,this.getCenterPoint().y))}centerObject(t){return this._centerObject(t,this.getCenterPoint())}viewportCenterObject(t){return this._centerObject(t,this.getVpCenter())}viewportCenterObjectH(t){return this._centerObject(t,new M(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new M(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return ce(this.getCenterPoint(),Fe(this.viewportTransform))}_centerObject(t,e){t.setXY(e,J,J),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(t){return this.toDatalessObject(t)}toObject(t){return this._toObjectMethod("toObject",t)}toJSON(){return this.toObject()}toDatalessObject(t){return this._toObjectMethod("toDatalessObject",t)}_toObjectMethod(t,e){const s=this.clipPath,i=s&&!s.excludeFromExport?this._toObject(s,t,e):null;return T(T(T({version:cu},$n(this,e)),{},{objects:this._objects.filter(n=>!n.excludeFromExport).map(n=>this._toObject(n,t,e))},this.__serializeBgOverlay(t,e)),i?{clipPath:i}:null)}_toObject(t,e,s){let i;this.includeDefaultValues||(i=t.includeDefaultValues,t.includeDefaultValues=!1);const n=t[e](s);return this.includeDefaultValues||(t.includeDefaultValues=!!i),n}__serializeBgOverlay(t,e){const s={},i=this.backgroundImage,n=this.overlayImage,r=this.backgroundColor,o=this.overlayColor;return ns(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),ns(o)?o.excludeFromExport||(s.overlay=o.toObject(e)):o&&(s.overlay=o),i&&!i.excludeFromExport&&(s.backgroundImage=this._toObject(i,t,e)),n&&!n.excludeFromExport&&(s.overlayImage=this._toObject(n,t,e)),s}toSVG(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const s=[];return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push('<g clip-path="url(#'.concat(this.clipPath.clipPathId,`)" >
4
- `)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
5
- `),this._setSVGBgOverlayColor(s,"overlay"),this._setSVGBgOverlayImage(s,"overlayImage",e),s.push("</svg>"),s.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",`" standalone="no" ?>
6
- `,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
7
- `)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=at.NUM_FRACTION_DIGITS,r=e.viewBox;let o;if(r)o='viewBox="'.concat(r.x," ").concat(r.y," ").concat(r.width," ").concat(r.height,'" ');else if(this.svgViewportTransformation){const h=this.viewportTransform;o='viewBox="'.concat(St(-h[4]/h[0],n)," ").concat(St(-h[5]/h[3],n)," ").concat(St(this.width/h[0],n)," ").concat(St(this.height/h[3],n),'" ')}else o='viewBox="0 0 '.concat(this.width," ").concat(this.height,'" ');t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',i,'" ',o,`xml:space="preserve">
8
- `,"<desc>Created with Fabric.js ",cu,`</desc>
9
- `,`<defs>
10
- `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
11
- `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(on()),'<clipPath id="'.concat(e.clipPathId,`" >
12
- `).concat(e.toClipPathSVG(t.reviver),`</clipPath>
13
- `)):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this["".concat(t,"Color")];if(ns(e)){const s=this["".concat(t,"Vpt")],i=this.viewportTransform,n={isType:()=>!1,width:this.width/(s?i[0]:1),height:this.height/(s?i[3]:1)};return e.toSVG(n,{additionalTransform:s?Ua(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=at.fontPaths;this._objects.forEach(function n(r){t.push(r),ec(r)&&r._objects.forEach(n)}),t.forEach(n=>{if(!bp(n))return;const{styles:r,fontFamily:o}=n;!e[o]&&s[o]&&(e[o]=!0,r&&Object.values(r).forEach(h=>{Object.values(h).forEach(l=>{let{fontFamily:d=""}=l;!e[d]&&s[d]&&(e[d]=!0)})}))});const i=Object.keys(e).map(n=>` @font-face {
14
- font-family: '`.concat(n,`';
15
- src: url('`).concat(s[n],`');
16
- }
17
- `)).join("");return i?` <style type="text/css"><![CDATA[
18
- `.concat(i,`]]></style>
19
- `):""}_setSVGObjects(t,e){this.forEachObject(s=>{s.excludeFromExport||this._setSVGObject(t,s,e)})}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const i=this[e];i&&!i.excludeFromExport&&i.toSVG&&t.push(i.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(ns(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?Ua(Fe(this.viewportTransform)):"";t.push('<rect transform="'.concat(o," translate(").concat(n/2,",").concat(r/2,')" x="').concat(s.offsetX-n/2,'" y="').concat(s.offsetY-r/2,'" width="').concat(i!=="repeat-y"&&i!=="no-repeat"||!mp(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!mp(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
20
- `))}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',s,'"',`></rect>
21
- `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new Ns("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[],backgroundImage:r,background:o,overlayImage:h,overlay:l,clipPath:d}=i,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([So(n,{reviver:e,signal:s}),Ga({backgroundImage:r,backgroundColor:o,overlayImage:h,overlayColor:l,clipPath:d},{signal:s})]).then(g=>{let[f,p]=g;return this.clear(),this.add(...f),this.set(i),this.set(p),this.renderOnAddRemove=u,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=Ft();return t.width=this.width,t.height=this.height,new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return vu(this.toCanvasElement(r,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:i,top:n,filter:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const o=(e||this.width)*t,h=(s||this.height)*t,l=this.getZoom(),d=this.width,u=this.height,g=this.skipControlsDrawing,f=l*t,p=this.viewportTransform,m=[f,0,0,f,(p[4]-(i||0))*t,(p[5]-(n||0))*t],_=this.enableRetinaScaling,v=Ft(),x=r?this._objects.filter(S=>r(S)):this._objects;return v.width=o,v.height=h,this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(v.getContext("2d"),x),this.viewportTransform=p,this.width=d,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=_,this.skipControlsDrawing=g,v}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),tc.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}A(qa,"ownDefaults",Ov);const Dv=["touchstart","touchmove","touchend"],Sp=a=>{const t=vp(a.target),e=function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s}(a);return new M(e.clientX+t.left,e.clientY+t.top)},rc=a=>Dv.includes(a.type)||a.pointerType==="touch",Au=a=>{a.preventDefault(),a.stopPropagation()},Hs=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:h}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},Pv=["translateX","translateY","scaleX","scaleY"],Cp=(a,t)=>Co(a,It(t,a.calcOwnMatrix())),Co=(a,t)=>{const e=qn(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=xt(e,Pv),h=new M(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,J,J)},Ap=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},Tu=a=>({scaleX:a.scaleX,scaleY:a.scaleY,skewX:a.skewX,skewY:a.skewY,angle:a.angle,left:a.left,flipX:a.flipX,flipY:a.flipY,top:a.top}),oc=(a,t,e)=>{const s=a/2,i=t/2,n=[new M(-s,-i),new M(s,-i),new M(-s,i),new M(s,i)].map(o=>o.transform(e)),r=Hs(n);return new M(r.width,r.height)},$a=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xe;return It(Fe(arguments.length>1&&arguments[1]!==void 0?arguments[1]:xe),a)},Qn=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:xe,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:xe;return a.transform($a(t,e))},Tp=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:xe,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:xe;return a.transform($a(t,e),!0)},Eu=(a,t,e)=>{const s=$a(t,e);return Co(a,It(s,a.calcOwnMatrix())),s},Ep=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),T(T({},t),{},{target:s})),s.fire(a,t)},Lv={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Ht=a=>typeof a=="string"?Lv[a]:a-.5,ac="not-allowed";function kp(a){return Ht(a.originX)===Ht(J)&&Ht(a.originY)===Ht(J)}function Mp(a){return .5-Ht(a)}const ys=(a,t)=>a[t],Op=(a,t,e,s)=>({e:a,transform:t,pointer:new M(e,s)});function Dp(a,t){const e=a.getTotalAngle()+an(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function ku(a,t,e,s,i){var n;let{target:r,corner:o}=a;const h=r.controls[o],l=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,d=r.padding/l,u=function(g,f,p,m){const _=g.getRelativeCenterPoint(),v=p!==void 0&&m!==void 0?g.translateToGivenOrigin(_,J,J,p,m):new M(g.left,g.top);return(g.angle?f.rotate(-Dt(g.angle),_):f).subtract(v)}(r,new M(s,i),t,e);return u.x>=d&&(u.x-=d),u.x<=-d&&(u.x+=d),u.y>=d&&(u.y-=d),u.y<=d&&(u.y+=d),u.x-=h.offsetX,u.y-=h.offsetY,u}const Rv=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!ys(i,"lockMovementX")&&i.left!==o,d=!ys(i,"lockMovementY")&&i.top!==h;return l&&i.set(ut,o),d&&i.set(Re,h),(l||d)&&Ep(tp,Op(a,t,e,s)),l||d};class Pp{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):Se,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=this.opacity!==void 0?this.opacity:"1",d=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),g=Ya(Rt,this.fill);return[Ya(Ae,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",h,"; ",g,"fill-rule: ",e,"; ","opacity: ",l,";",u,d].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),i='transform="'.concat(Ua(s));return"".concat(i).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=i,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:i,additionalTransform:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=e?"":'style="'.concat(this.getSvgStyles(),'" '),o=i?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",d=h&&h.absolutePositioned,u=this.stroke,g=this.fill,f=this.shadow,p=[],m=t.indexOf("COMMON_PARTS");let _;h&&(h.clipPathId="CLIPPATH_".concat(on()),_='<clipPath id="'.concat(h.clipPathId,`" >
22
- `).concat(h.toClipPathSVG(s),`</clipPath>
23
- `)),d&&p.push("<g ",o,this.getSvgCommons(),` >
24
- `),p.push("<g ",this.getSvgTransform(!1),d?"":o+this.getSvgCommons(),` >
25
- `);const v=[r,l,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[m]=v,ns(g)&&p.push(g.toSVG(this)),ns(u)&&p.push(u.toSVG(this)),f&&p.push(f.toSVG(this)),h&&p.push(_),p.push(t.join("")),p.push(`</g>
26
- `),d&&p.push(`</g>
27
- `),s?s(p.join("")):p.join("")}addPaintOrder(){return this.paintFirst!==Rt?' paint-order="'.concat(this.paintFirst,'" '):""}}function hc(a){return new RegExp("^("+a.join("|")+")\\b","i")}var Lp;const _s=String.raw(Lp||(Lp=sn(["(?:[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?)"],["(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)"]))),Mu="http://www.w3.org/2000/svg",Fv=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+_s+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+_s+"))?\\s+(.*)"),Iv={cx:ut,x:ut,r:"radius",cy:Re,y:Re,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"},Ou="font-size",Du="clip-path",jv=hc(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Nv=hc(["symbol","image","marker","pattern","view","svg"]),Rp=hc(["symbol","g","a","svg","clipPath","defs"]),Fp=new RegExp("^\\s*("+_s+"+)\\s*,?\\s*("+_s+"+)\\s*,?\\s*("+_s+"+)\\s*,?\\s*("+_s+"+)\\s*$"),Bv=new M(1,0),Ip=new M,Pu=(a,t)=>a.rotate(t),lc=(a,t)=>new M(t).subtract(a),cc=a=>a.distanceFrom(Ip),dc=(a,t)=>Math.atan2(Ao(a,t),Np(a,t)),jp=a=>dc(Bv,a),uc=a=>a.eq(Ip)?a:a.scalarDivide(cc(a)),Lu=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return uc(new M(-a.y,a.x).scalarMultiply(t?1:-1))},Ao=(a,t)=>a.x*t.y-a.y*t.x,Np=(a,t)=>a.x*t.x+a.y*t.y,Ru=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=Ao(t,e),i=Ao(t,a),n=Ao(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},Bp="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Hp=new RegExp("(?:\\s|^)"+Bp+Bp+"("+_s+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class fi{constructor(t){const e=typeof t=="string"?fi.parseShadow(t):t;Object.assign(this,fi.ownDefaults,e),this.id=on()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Hp.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(Hp,"")||"rgb(0,0,0)").trim(),offsetX:s,offsetY:i,blur:n}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const e=Pu(new M(this.offsetX,this.offsetY),Dt(-t.angle)),s=new ft(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*St((Math.abs(e.x)+this.blur)/t.width,at.NUM_FRACTION_DIGITS)+20,n=100*St((Math.abs(e.y)+this.blur)/t.height,at.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(n,'%" height="').concat(100+2*n,'%" x="-').concat(i,'%" width="').concat(100+2*i,`%" >
28
- <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(St(this.blur?this.blur/2:0,at.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
29
- <feOffset dx="`).concat(St(e.x,at.NUM_FRACTION_DIGITS),'" dy="').concat(St(e.y,at.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
30
- <feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
31
- <feComposite in2="oBlur" operator="in" />
32
- <feMerge>
33
- <feMergeNode></feMergeNode>
34
- <feMergeNode in="SourceGraphic"></feMergeNode>
35
- </feMerge>
36
- </filter>
37
- `)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=fi.ownDefaults;return this.includeDefaultValues?t:wu(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}A(fi,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),A(fi,"type","shadow"),z.setClass(fi,"shadow");const Jn=(a,t,e)=>Math.max(a,Math.min(t,e)),Hv=[Re,ut,Ce,Ge,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",vo,yo],pi=[Rt,Ae,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Wv={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:ut,originY:Re,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:Rt,fill:"rgb(0,0,0)",fillRule:"nonzero",stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,globalCompositeOperation:"source-over",backgroundColor:"",shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},Fu=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/gi*Math.asin(1):e/gi*Math.asin(t/a),{a,c:t,p:e,s}),Wp=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*gi/e),zp=(a,t,e,s)=>-e*Math.cos(a/s*nn)+e+t,Iu=(a,t,e,s)=>(a/=s)<1/2.75?e*(7.5625*a*a)+t:a<2/2.75?e*(7.5625*(a-=1.5/2.75)*a+.75)+t:a<2.5/2.75?e*(7.5625*(a-=2.25/2.75)*a+.9375)+t:e*(7.5625*(a-=2.625/2.75)*a+.984375)+t,Xp=(a,t,e,s)=>e-Iu(s-a,0,e,s)+t;var zv=Object.freeze({__proto__:null,defaultEasing:zp,easeInBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*(a/=s)*a*((i+1)*a-i)+t},easeInBounce:Xp,easeInCirc:(a,t,e,s)=>-e*(Math.sqrt(1-(a/=s)*a)-1)+t,easeInCubic:(a,t,e,s)=>e*(a/s)**3+t,easeInElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h}=Fu(i,e,n,1.70158);return-Wp(r,o,h,a,s)+t},easeInExpo:(a,t,e,s)=>a===0?t:e*2**(10*(a/s-1))+t,easeInOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(a/=s/2)<1?e/2*(a*a*((1+(i*=1.525))*a-i))+t:e/2*((a-=2)*a*((1+(i*=1.525))*a+i)+2)+t},easeInOutBounce:(a,t,e,s)=>a<s/2?.5*Xp(2*a,0,e,s)+t:.5*Iu(2*a-s,0,e,s)+.5*e+t,easeInOutCirc:(a,t,e,s)=>(a/=s/2)<1?-e/2*(Math.sqrt(1-a**2)-1)+t:e/2*(Math.sqrt(1-(a-=2)*a)+1)+t,easeInOutCubic:(a,t,e,s)=>(a/=s/2)<1?e/2*a**3+t:e/2*((a-2)**3+2)+t,easeInOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:o,p:h,c:l}=Fu(i,e,n,1.70158);return a<1?-.5*Wp(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*gi/h)*.5+l+t},easeInOutExpo:(a,t,e,s)=>a===0?t:a===s?t+e:(a/=s/2)<1?e/2*2**(10*(a-1))+t:e/2*-(2**(-10*--a)+2)+t,easeInOutQuad:(a,t,e,s)=>(a/=s/2)<1?e/2*a**2+t:-e/2*(--a*(a-2)-1)+t,easeInOutQuart:(a,t,e,s)=>(a/=s/2)<1?e/2*a**4+t:-e/2*((a-=2)*a**3-2)+t,easeInOutQuint:(a,t,e,s)=>(a/=s/2)<1?e/2*a**5+t:e/2*((a-2)**5+2)+t,easeInOutSine:(a,t,e,s)=>-e/2*(Math.cos(Math.PI*a/s)-1)+t,easeInQuad:(a,t,e,s)=>e*(a/=s)*a+t,easeInQuart:(a,t,e,s)=>e*(a/=s)*a**3+t,easeInQuint:(a,t,e,s)=>e*(a/s)**5+t,easeInSine:(a,t,e,s)=>-e*Math.cos(a/s*nn)+e+t,easeOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*((a=a/s-1)*a*((i+1)*a+i)+1)+t},easeOutBounce:Iu,easeOutCirc:(a,t,e,s)=>e*Math.sqrt(1-(a=a/s-1)*a)+t,easeOutCubic:(a,t,e,s)=>e*((a/s-1)**3+1)+t,easeOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h,c:l}=Fu(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*gi/h)+l+t},easeOutExpo:(a,t,e,s)=>a===s?t+e:e*-(2**(-10*a/s)+1)+t,easeOutQuad:(a,t,e,s)=>-e*(a/=s)*(a-2)+t,easeOutQuart:(a,t,e,s)=>-e*((a=a/s-1)*a**3-1)+t,easeOutQuint:(a,t,e,s)=>e*((a/s-1)**5+1)+t,easeOutSine:(a,t,e,s)=>e*Math.sin(a/s*nn)+t});const Xv=()=>!1;class ju{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=zp,onStart:o=Un,onChange:h=Un,onComplete:l=Un,abort:d=Xv,target:u}=t;A(this,"_state","pending"),A(this,"durationProgress",0),A(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=o,this._onChange=h,this._onComplete=l,this._abort=d,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>za(t),this.delay):za(t)}tick(t){const e=(t||+new Date)-this.startTime,s=Math.min(e,this.duration);this.durationProgress=s/this.duration;const{value:i,valueProgress:n}=this.calculate(s);this.value=Object.freeze(i),this.valueProgress=n,this._state!=="aborted"&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),za(this.tick)))}register(){tc.push(this)}unregister(){tc.remove(this)}abort(){this._state="aborted",this.unregister()}}const Vv=["startValue","endValue"];class Gv extends ju{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(T(T({},xt(t,Vv)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const Uv=["startValue","endValue"];class Yv extends ju{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(T(T({},xt(t,Uv)),{},{startValue:e,byValue:s.map((i,n)=>i-e[n])}))}calculate(t){const e=this.startValue.map((s,i)=>this.easing(t,s,this.byValue[i],this.duration,i));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const qv=["startValue","endValue","easing","onChange","onComplete","abort"],$v=(a,t,e,s)=>t+e*(1-Math.cos(a/s*nn)),Nu=a=>a&&((t,e,s)=>a(new ft(t).toRgba(),e,s));class Kv extends ju{constructor(t){let{startValue:e,endValue:s,easing:i=$v,onChange:n,onComplete:r,abort:o}=t,h=xt(t,qv);const l=new ft(e).getSource(),d=new ft(s).getSource();super(T(T({},h),{},{startValue:l,byValue:d.map((u,g)=>u-l[g]),easing:i,onChange:Nu(n),onComplete:Nu(r),abort:Nu(o)}))}calculate(t){const[e,s,i,n]=this.startValue.map((o,h)=>this.easing(t,o,this.byValue[h],this.duration,h)),r=[...[e,s,i].map(Math.round),Jn(0,n,1)];return{value:r,valueProgress:r.map((o,h)=>this.byValue[h]!==0?Math.abs((o-this.startValue[h])/this.byValue[h]):0).find(o=>o!==0)||0}}}function Bu(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new Yv(a):new Gv(a);return t.start(),t}function Vp(a){const t=new Kv(a);return t.start(),t}class At{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter(i=>!this.includes(i))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=lc(e,s),r=lc(e,t).divide(n);return i?Math.abs(r.x)===Math.abs(r.y):r.x===r.y&&r.x>=0&&r.x<=1}}static isPointInPolygon(t,e){const s=new M(t).setX(Math.min(t.x-1,...e.map(n=>n.x)));let i=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,s);if(r.includes(t))return!0;i+=+(r.status==="Intersection")}return i%2==1}static intersectLineLine(t,e,s,i){let n=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const o=e.x-t.x,h=e.y-t.y,l=i.x-s.x,d=i.y-s.y,u=t.x-s.x,g=t.y-s.y,f=l*g-d*u,p=o*g-h*u,m=d*o-l*h;if(m!==0){const _=f/m,v=p/m;return(n||0<=_&&_<=1)&&(r||0<=v&&v<=1)?new At("Intersection").append(new M(t.x+_*o,t.y+_*h)):new At}if(f===0||p===0){const _=n||r||At.isPointContained(t,s,i)||At.isPointContained(e,s,i)||At.isPointContained(s,t,e)||At.isPointContained(i,t,e);return new At(_?"Coincident":void 0)}return new At("Parallel")}static intersectSegmentLine(t,e,s,i){return At.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return At.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new At,r=s.length;for(let o,h,l,d=0;d<r;d++){if(o=s[d],h=s[(d+1)%r],l=At.intersectLineLine(t,e,o,h,i,!1),l.status==="Coincident")return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return At.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new At,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=At.intersectSegmentPolygon(o,h,e);l.status==="Coincident"?(n.push(l),s.append(o,h)):s.append(...l.points)}return n.length>0&&n.length===t.length?new At("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new M(n.x,i.y),o=new M(i.x,n.y);return At.intersectPolygonPolygon(t,[i,r,n,o])}}class Qv extends np{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?ce(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=ce(t,Fe(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new M(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:i}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,s,i];if(this.group){const r=this.group.calcTransformMatrix();return n.map(o=>ce(o,r))}return n}intersectsWithRect(t,e){return At.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=At.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return At.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every(s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Hs(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Ce,t),this._set(Ge,t),this.setCoords()}scaleToWidth(t){const e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){const e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?an(hp(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||xe.concat()}calcACoords(){const t=xo({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=wo(e,s),n=It(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:ce({x:-o,y:-h},n),tr:ce({x:o,y:-h},n),bl:ce({x:-o,y:h},n),br:ce({x:o,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,Ht(this.originX),Ht(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),i=this.matrixCache;return i&&i.key.every((n,r)=>n===s[r])?i.value:(this.group&&(e=It(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),i={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=cp(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new M(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=T({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,o=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new M(r*e.scaleX,o*e.scaleY):oc(r,o,Xa(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=Ht(i)-Ht(e),l=Ht(n)-Ht(s);if(h||l){const d=this._getTransformedDimensions();r+=h*d.x,o+=l*d.y}return new M(r,o)}translateToCenterPoint(t,e,s){if(e===J&&s===J)return t;const i=this.translateToGivenOrigin(t,e,s,J,J);return this.angle?i.rotate(Dt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,J,J,e,s);return this.angle?i.rotate(Dt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?ce(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new M(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const i=this.translateToCenterPoint(t,e,s),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),ut,Re)}}const Jv=["type"],Zv=["extraParam"];let mi=class Pd extends Qv{static getDefaults(){return Pd.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){ui("warn","Setting type has no effect",t)}constructor(t){super(),A(this,"_cacheContext",null),Object.assign(this,Pd.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Ft(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=at.maxCacheSideLimit,n=at.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=at.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=Ha.limitDimsByArea(r),l=Jn(n,o,i),d=Jn(n,h,i);return e>l&&(t.zoomX/=e/l,t.width=l,t.capped=!0),s>d&&(t.zoomY/=s/d,t.height=d,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,i=e.y*t.y/this.scaleY;return{width:s+2,height:i+2,zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,s=this._limitCacheSize(this._getCacheCanvasDimensions()),i=at.minCacheSideLimit,n=s.width,r=s.height,o=s.zoomX,h=s.zoomY,l=n!==t.width||r!==t.height,d=this.zoomX!==o||this.zoomY!==h;if(!t||!e)return!1;let u,g,f=l||d,p=0,m=0,_=!1;if(l){const v=this._cacheCanvas.width,x=this._cacheCanvas.height,S=n>v||r>x;_=S||(n<.9*v||r<.9*x)&&v>i&&x>i,S&&!s.capped&&(n>i||r>i)&&(p=.1*n,m=.1*r)}return bp(this)&&this.path&&(f=!0,_=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!f&&(_?(t.width=Math.ceil(n+p),t.height=Math.ceil(r+m)):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height)),u=s.x/2,g=s.y/2,this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-g)+g,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(o,h),this.zoomX=o,this.zoomY=h,!0)}setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,s=this.calcTransformMatrix(!e);t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}getObjectScaling(){if(!this.group)return new M(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=qn(this.calcTransformMatrix());return new M(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),s=this.getCanvasRetinaScaling();return t.scalarMultiply(e*s)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t===0?1e-4:t}_set(t,e){t!==Ce&&t!==Ge||(e=this._constrainScale(e)),t===Ce&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof fi||(e=new fi(e));const s=this[t]!==e;return this[t]=e,s&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||s&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(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.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext&&(this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return this.stroke&&this.stroke!=="transparent"&&this.strokeWidth!==0}hasFill(){return this.fill&&this.fill!=="transparent"}needsItsOwnCache(){return!!(this.paintFirst===Ae&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.parent||!this.parent.isOnACache()),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e){if(t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",e.absolutePositioned){const s=Fe(this.calcTransformMatrix());t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}drawObject(t,e){const s=this.fill,i=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=s,this.stroke=i}_drawClipPath(t,e){e&&(e._set("canvas",this.canvas),e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,s=this._cacheContext;return!(!e||!s||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&s&&!t&&(s.save(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),s.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;const e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){const s=e.stroke;s&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,ns(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?this._applyPatternForTransformedGradient(t,s):(t.strokeStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:s}=e;s&&(ns(s)?(t.fillStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.fillStyle=s)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&e.length!==0&&(1&e.length&&e.push(...e),t.setLineDash(e))}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,i=this.getCanvasRetinaScaling(),[n,,,r]=(s==null?void 0:s.viewportTransform)||xe,o=n*i,h=r*i,l=e.nonScaling?new M(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*at.browserShadowBlurConstant*(o+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!ns(e))return{offsetX:0,offsetY:0};const s=e.gradientTransform||e.patternTransform,i=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return e.gradientUnits==="percentage"?t.transform(this.width,0,0,this.height,i,n):t.transform(1,0,0,1,i,n),s&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),{offsetX:i,offsetY:n}}_renderPaintInOrder(t){this.paintFirst===Ae?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const i=this._limitCacheSize(this._getCacheCanvasDimensions()),n=Ft(),r=this.getCanvasRetinaScaling(),o=i.x/this.scaleX/r,h=i.y/this.scaleY/r;n.width=Math.ceil(o),n.height=Math.ceil(h);const l=n.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(o,0),l.lineTo(o,h),l.lineTo(0,h),l.closePath(),l.translate(o/2,h/2),l.scale(i.zoomX/this.scaleX/r,i.zoomY/this.scaleY/r),this._applyPatternGradientTransform(l,e),l.fillStyle=e.toLive(t),l.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(r*this.scaleX/i.zoomX,r*this.scaleY/i.zoomY),t.strokeStyle=(s=l.createPattern(n,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new M(this.left+this.width/2,this.top+this.height/2)}clone(t){const e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){const e=this.toCanvasElement(t);return new(z.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Tu(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?Zf():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(x=>new qa(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Ap(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Eu(this,this.getViewportTransform()),this.setCoords();const l=Ft(),d=this.getBoundingRect(),u=this.shadow,g=new M;if(u){const x=u.blur,S=u.nonScaling?new M(1,1):this.getObjectScaling();g.x=2*Math.round(n(u.offsetX)+x)*n(S.x),g.y=2*Math.round(n(u.offsetY)+x)*n(S.y)}const f=d.width+g.x,p=d.height+g.y;l.width=Math.ceil(f),l.height=Math.ceil(p);const m=h(l);t.format==="jpeg"&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new M(m.width/2,m.height/2),J,J);const _=this.canvas;m._objects=[this],this.set("canvas",m),this.setCoords();const v=m.toCanvasElement(o||1,t);return this.set("canvas",_),this.shadow=i,s&&(this.group=s),this.set(e),this.setCoords(),m._objects=[],m.destroy(),v}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return vu(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:s,originY:i}=this;if(e){const{x:n,y:r}=this.getRelativeCenterPoint();this.originX=J,this.originY=J,this.left=n,this.top=r}if(this.set("angle",t),e){const{x:n,y:r}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){tc.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Bs().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s},{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:o,onChange:h,onComplete:l}=s,d=T(T({},s),{},{target:this,startValue:o??i.reduce((u,g)=>u[g],this),endValue:e,abort:r==null?void 0:r.bind(this),onChange:(u,g,f)=>{i.reduce((p,m,_)=>(_===i.length-1&&(p[m]=u),p[m]),this),h&&h(u,g,f)},onComplete:(u,g,f)=>{this.setCoords(),l&&l(u,g,f)}});return n?Vp(d):Bu(d)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let i,n=0;n<e.length;n++){if(i=e[n],i===t)return{fork:[this,...e.slice(0,n)],otherFork:[],common:e.slice(n)};for(let r=0;r<s.length;r++){if(this===s[r])return{fork:[],otherFork:[t,...s.slice(0,r)],common:[this,...e]};if(i===s[r])return{fork:[this,...e.slice(0,n)],otherFork:[t,...s.slice(0,r)],common:e.slice(n)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const i=e.fork.pop(),n=e.otherFork.pop(),r=s._objects.indexOf(i),o=s._objects.indexOf(n);return r>-1&&r>o}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Pd.customProperties,this.constructor.customProperties||[]);let e;const s=at.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:l,top:d,originX:u,originY:g,width:f,height:p,strokeWidth:m,strokeLineCap:_,strokeDashOffset:v,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:C,scaleX:E,scaleY:k,angle:P,flipX:D,flipY:F,opacity:B,visible:O,backgroundColor:R,fillRule:L,paintFirst:j,globalCompositeOperation:G,skewX:Y,skewY:X}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const H=dt=>St(dt,s),_t=T(T({},$n(this,t)),{},{type:this.constructor.type,version:cu,originX:u,originY:g,left:H(l),top:H(d),width:H(f),height:H(p),fill:pp(n)?n.toObject():n,stroke:pp(r)?r.toObject():r,strokeWidth:H(m),strokeDashArray:h&&h.concat(),strokeLineCap:_,strokeDashOffset:v,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:H(C),scaleX:H(E),scaleY:H(k),angle:H(P),flipX:D,flipY:F,opacity:H(B),shadow:o&&o.toObject(),visible:O,backgroundColor:R,fillRule:L,paintFirst:j,globalCompositeOperation:G,skewX:H(Y),skewY:H(X)},e?{clipPath:e}:null);return this.includeDefaultValues?_t:this._removeDefaultValues(_t)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return wu(t,(i,n)=>{if(n===ut||n===Re||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=xt(t,Jv),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=xt(s,Zv);return Ga(e,n).then(r=>i?(delete r[i],new this(e[i],r)):new this(r))}static fromObject(t,e){return this._fromObject(t,e)}};A(mi,"stateProperties",Hv),A(mi,"cacheProperties",pi),A(mi,"ownDefaults",Wv),A(mi,"type","FabricObject"),A(mi,"colorProperties",[Rt,Ae,"backgroundColor"]),A(mi,"customProperties",[]),z.setClass(mi),z.setClass(mi,"object");const To=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Ep(a,T(T({},Op(s,i,n,r)),e)),o};function Eo(a){return(t,e,s,i)=>{const{target:n,originX:r,originY:o}=e,h=n.getRelativeCenterPoint(),l=n.translateToOriginPoint(h,r,o),d=a(t,e,s,i);return n.setPositionByOrigin(l,e.originX,e.originY),d}}const Gp=To(Wa,Eo((a,t,e,s)=>{const i=ku(t,t.originX,t.originY,e,s);if(Ht(t.originX)===Ht(J)||Ht(t.originX)===Ht(Lt)&&i.x<0||Ht(t.originX)===Ht(ut)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=kp(t)?2:1,h=n.width,l=Math.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(l,1)),h!==n.width}return!1}));function ty(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?Ae:Rt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor);let d,u=t,g=e;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(d=n,a.scale(1,r/n),g=e*n/r):r>n?(d=r,a.scale(n/r,1),u=t*r/n):d=n,a.lineWidth=1,a.beginPath(),a.arc(u,g,d/2,0,gi,!1),a[h](),l&&a.stroke(),a.restore()}function ey(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?Ae:Rt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor),d=n/2,u=r/2;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",a.lineWidth=1,a.translate(t,e);const g=i.getTotalAngle();a.rotate(Dt(g)),a["".concat(h,"Rect")](-d,-u,n,r),l&&a.strokeRect(-d,-u,n,r),a.restore()}class ws{constructor(t){A(this,"visible",!0),A(this,"actionName",Jl),A(this,"angle",0),A(this,"x",0),A(this,"y",0),A(this,"offsetX",0),A(this,"offsetY",0),A(this,"sizeX",0),A(this,"sizeY",0),A(this,"touchSizeX",0),A(this,"touchSizeY",0),A(this,"cursorStyle","crosshair"),A(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:l}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&At.isPointInPolygon(s,[r,o,h,l])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new M(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=sc([wo(s,i),xo({angle:t}),ic((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new M(-.5,-.5).transform(o),tr:new M(.5,-.5).transform(o),br:new M(.5,.5).transform(o),bl:new M(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?ty.call(this,t,e,s,i,n):ey.call(this,t,e,s,i,n)}}const sy=(a,t,e)=>e.lockRotation?ac:t.cursorStyle,iy=To(ep,Eo((a,t,e,s)=>{let{target:i,ex:n,ey:r,theta:o,originX:h,originY:l}=t;const d=i.translateToOriginPoint(i.getRelativeCenterPoint(),h,l);if(ys(i,"lockRotation"))return!1;const u=Math.atan2(r-d.y,n-d.x),g=Math.atan2(s-d.y,e-d.x);let f=an(g-u+o);if(i.snapAngle&&i.snapAngle>0){const m=i.snapAngle,_=i.snapThreshold||m,v=Math.ceil(f/m)*m,x=Math.floor(f/m)*m;Math.abs(f-x)<_?f=x:Math.abs(f-v)<_&&(f=v)}f<0&&(f=360+f),f%=360;const p=i.angle!==f;return i.angle=f,p}));function Up(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Yp(a,t,e){const s=ys(a,"lockScalingX"),i=ys(a,"lockScalingY");if(s&&i||!t&&(s||i)&&e||s&&t==="x"||i&&t==="y")return!0;const{width:n,height:r,strokeWidth:o}=a;return n===0&&o===0&&t!=="y"||r===0&&o===0&&t!=="x"}const ny=["e","se","s","sw","w","nw","n","ne","e"],Ka=(a,t,e)=>{const s=Up(a,e);if(Yp(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return ac;const i=Dp(e,t);return"".concat(ny[i],"-resize")};function Hu(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Up(a,n);let h,l,d,u,g,f;if(Yp(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,d=t.scaleY*t.gestureScale;else{if(h=ku(t,t.originX,t.originY,e,s),g=r!=="y"?Math.sign(h.x||t.signX||1):1,f=r!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=g),t.signY||(t.signY=f),ys(n,"lockScalingFlip")&&(t.signX!==g||t.signY!==f))return!1;if(u=n._getTransformedDimensions(),o&&!r){const _=Math.abs(h.x)+Math.abs(h.y),{original:v}=t,x=_/(Math.abs(u.x*v.scaleX/n.scaleX)+Math.abs(u.y*v.scaleY/n.scaleY));l=v.scaleX*x,d=v.scaleY*x}else l=Math.abs(h.x*n.scaleX/u.x),d=Math.abs(h.y*n.scaleY/u.y);kp(t)&&(l*=2,d*=2),t.signX!==g&&r!=="y"&&(t.originX=Mp(t.originX),l*=-1,t.signX=g),t.signY!==f&&r!=="x"&&(t.originY=Mp(t.originY),d*=-1,t.signY=f)}const p=n.scaleX,m=n.scaleY;return r?(r==="x"&&n.set(Ce,l),r==="y"&&n.set(Ge,d)):(!ys(n,"lockScalingX")&&n.set(Ce,l),!ys(n,"lockScalingY")&&n.set(Ge,d)),p!==n.scaleX||m!==n.scaleY}const gc=To(Kl,Eo((a,t,e,s)=>Hu(a,t,e,s))),ry=To(Kl,Eo((a,t,e,s)=>Hu(a,t,e,s,{by:"x"}))),oy=To(Kl,Eo((a,t,e,s)=>Hu(a,t,e,s,{by:"y"}))),ay=["target","ex","ey","skewingSide"],Wu={x:{counterAxis:"y",scale:Ce,skew:vo,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Ge,skew:yo,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},hy=["ns","nesw","ew","nwse"],ly=(a,t,e)=>{if(t.x!==0&&ys(e,"lockSkewingY")||t.y!==0&&ys(e,"lockSkewingX"))return ac;const s=Dp(e,t)%4;return"".concat(hy[s],"-resize")};function qp(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:d}=Wu[a];if(ys(n,h))return!1;const{origin:u,flip:g}=Wu[r],f=Ht(e[u])*(n[g]?-1:1),p=-Math.sign(f)*(n[d]?-1:1),m=.5*-((n[l]===0&&ku(e,J,J,s,i)[a]>0||n[l]>0?1:-1)*p)+.5;return To(sp,Eo((v,x,S,C)=>function(E,k,P){let{target:D,ex:F,ey:B,skewingSide:O}=k,R=xt(k,ay);const{skew:L}=Wu[E],j=P.subtract(new M(F,B)).divide(new M(D.scaleX,D.scaleY))[E],G=D[L],Y=R[L],X=Math.tan(Dt(Y)),H=E==="y"?D._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:D._getTransformedDimensions({scaleX:1,scaleY:1}).y,_t=2*j*O/Math.max(H,1)+X,dt=an(Math.atan(_t));D.set(L,dt);const _e=G!==D[L];if(_e&&E==="y"){const{skewX:Bt,scaleX:wt}=D,De=D._getTransformedDimensions({skewY:G}),Ve=D._getTransformedDimensions(),Gt=Bt!==0?De.x/Ve.x:1;Gt!==1&&D.set(Ce,Gt*wt)}return _e}(a,x,new M(S,C))))(t,T(T({},e),{},{[o]:m,skewingSide:p}),s,i)}const cy=(a,t,e,s)=>qp("x",a,t,e,s),dy=(a,t,e,s)=>qp("y",a,t,e,s);function fc(a,t){return a[t.canvas.altActionKey]}const pc=(a,t,e)=>{const s=fc(a,e);return t.x===0?s?vo:Ge:t.y===0?s?yo:Ce:""},ko=(a,t,e)=>fc(a,e)?ly(0,t,e):Ka(a,t,e),$p=(a,t,e,s)=>fc(a,t.target)?dy(a,t,e,s):ry(a,t,e,s),Kp=(a,t,e,s)=>fc(a,t.target)?cy(a,t,e,s):oy(a,t,e,s),Qp=()=>({ml:new ws({x:-.5,y:0,cursorStyleHandler:ko,actionHandler:$p,getActionName:pc}),mr:new ws({x:.5,y:0,cursorStyleHandler:ko,actionHandler:$p,getActionName:pc}),mb:new ws({x:0,y:.5,cursorStyleHandler:ko,actionHandler:Kp,getActionName:pc}),mt:new ws({x:0,y:-.5,cursorStyleHandler:ko,actionHandler:Kp,getActionName:pc}),tl:new ws({x:-.5,y:-.5,cursorStyleHandler:Ka,actionHandler:gc}),tr:new ws({x:.5,y:-.5,cursorStyleHandler:Ka,actionHandler:gc}),bl:new ws({x:-.5,y:.5,cursorStyleHandler:Ka,actionHandler:gc}),br:new ws({x:.5,y:.5,cursorStyleHandler:Ka,actionHandler:gc}),mtr:new ws({x:0,y:-.5,actionHandler:iy,cursorStyleHandler:sy,offsetY:-40,withConnection:!0,actionName:pu})}),uy=()=>({mr:new ws({x:.5,y:0,actionHandler:Gp,cursorStyleHandler:ko,actionName:Wa}),ml:new ws({x:-.5,y:0,actionHandler:Gp,cursorStyleHandler:ko,actionName:Wa})}),gy=()=>T(T({},Qp()),uy());class Qa extends mi{static getDefaults(){return T(T({},super.getDefaults()),Qa.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),Qa.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Qp()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,s=e.target,i=e.action;if(this===s&&i&&i.startsWith(Jl))return!1}return super._updateCacheCanvas()}getActiveControl(){const t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const s=Object.entries(this.oCoords);for(let i=s.length-1;i>=0;i--){const[n,r]=s[i],o=this.controls[n];if(o.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:o,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=wo(e.x,e.y),i=xo({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=It(s,i),r=It(t,n),o=It(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?qn(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const l=this._calculateCurrentDimensions(h),d={};return this.forEachControl((u,g)=>{const f=u.positionHandler(l,o,this,u);d[g]=Object.assign(f,this._calcCornerCoords(u,f))}),d}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),i=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/i[0],1/i[3]),t.rotate(Dt(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=T({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=i.borderColor,this._setLineDash(t,i.borderDashArray),this.strokeBorders(t,e),i.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:i}=this,n=T({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=It(r,this.calcTransformMatrix()),d=qn(l);t.save(),t.translate(d.translateX,d.translateY),t.lineWidth=1*this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(d.angle-=180),t.rotate(Dt(this.group?d.angle:this.angle)),o&&this.drawBorders(t,d,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=oc(this.width,this.height,Xa(e)),r=this.isStrokeAccountedForInDimensions()?bu:(this.strokeUniform?new M().scalarAdd(this.canvas?this.canvas.getZoom():1):new M(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);i=n.add(r).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else i=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,i,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl((i,n)=>{i.withConnection&&i.getVisibility(this,n)&&(s=!0,t.moveTo(i.x*e.x,i.y*e.y),t.lineTo(i.x*e.x+i.offsetX,i.y*e.y+i.offsetY))}),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:i,cornerDashArray:n,cornerColor:r}=this,o=T({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl((h,l)=>{if(h.getVisibility(this,l)){const d=this.oCoords[l];h.render(t,d.x,d.y,o,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,i]=e;return this.setControlVisible(s,i)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const i=this.width+4,n=this.height+4;return e.clearRect(-i/2,-n/2,i,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function Jp(a,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(a.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),a}A(Qa,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class de extends Qa{}Jp(de,[Pp]),z.setClass(de),z.setClass(de,"object");const Zp=(a,t,e,s)=>{const i=2*(s=Math.round(s))+1,{data:n}=a.getImageData(t-s,e-s,i,i);for(let r=3;r<n.length;r+=4)if(n[r]>0)return!1;return!0};class tm{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new M(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new M(1/this.options.scaleX,1/this.options.scaleY):new M(1,1)}createSideVector(t,e){const s=lc(t,e);return this.options.strokeUniform?s.multiply(this.scale):s}projectOrthogonally(t,e,s){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,s)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(t){const e=new M(t);return e.y+=e.x*Math.tan(Dt(this.options.skewY)),e.x+=e.y*Math.tan(Dt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const fy=new M;class Mo extends tm{static getOrthogonalRotationFactor(t,e){const s=e?dc(t,e):jp(t);return Math.abs(s)<nn?-1:1}constructor(t,e,s,i){super(i),A(this,"AB",void 0),A(this,"AC",void 0),A(this,"alpha",void 0),A(this,"bisector",void 0),this.A=new M(t),this.B=new M(e),this.C=new M(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=dc(this.AB,this.AC),this.bisector=uc(Pu(this.AB.eq(fy)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e),n=Lu(i),r=Mo.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%gi==0?[this.B]:[this.B,this.C]).forEach(e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))}),t}projectMiter(){const t=[],e=Math.abs(this.alpha),s=1/Math.sin(e/2),i=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*s),n=this.options.strokeUniform?cc(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return cc(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new M(Mo.getOrthogonalRotationFactor(this.bisector),Mo.getOrthogonalRotationFactor(new M(this.bisector.y,this.bisector.x)));return[new M(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new M(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{Ru(n,t,e)&&s.push(this.A.add(n))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:o,strokeUniform:h}=this.options,l=new M(Math.tan(Dt(i)),Math.tan(Dt(n))),d=this.strokeProjectionMagnitude,u=h?d/o/Math.sqrt(1/o**2+1/r**2*l.y**2):d/Math.sqrt(1+l.y**2),g=new M(Math.sqrt(Math.max(d**2-u**2,0)),u),f=h?d/Math.sqrt(1+l.x**2*(1/o)**2/(1/r+1/r*l.x*l.y)**2):d/Math.sqrt(1+l.x**2/(1+l.x*l.y)**2),p=new M(f,Math.sqrt(Math.max(d**2-f**2,0)));return[p,p.scalarMultiply(-1),g,g.scalarMultiply(-1)].map(m=>this.applySkew(h?m.multiply(this.strokeUniformScalar):m)).forEach(m=>{Ru(m,t,e)&&s.push(this.applySkew(this.A).add(m))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%gi==0,s=this.applySkew(this.A),i=t[e?0:2].subtract(s),n=t[e?1:0].subtract(s),r=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),o=Ao(i,r)>0,h=o?i:n,l=o?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,l)):t.push(...this.projectRoundNoSkew(h,l)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class em extends tm{constructor(t,e,s){super(s),this.A=new M(t),this.T=new M(e)}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e);return this.scaleUnitVector(Lu(i),s)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){const t=[];if(!this.isSkewed()&&this.A.eq(this.T)){const e=new M(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.applySkew(this.A.add(e)),this.applySkew(this.A.subtract(e)))}else t.push(...new Mo(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new M(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{const e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),s=this.scaleUnitVector(uc(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),i=this.A.add(s);t.push(i.add(e),i.subtract(e))}return t.map(e=>this.applySkew(e))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}const sm=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(a.length===0)return s;const i=a.reduce((n,r)=>(n[n.length-1].eq(r)||n.push(new M(r)),n),[new M(a[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((o,h)=>{for(let l=o.length-1;l>=0;l--)if(h(o[l],l,o))return l;return-1})(i,o=>!o.eq(n));i.splice(r+1)}return i.forEach((n,r,o)=>{let h,l;r===0?(l=o[1],h=e?n:o[o.length-1]):r===o.length-1?(h=o[r-1],l=e?n:o[0]):(h=o[r-1],l=o[r+1]),e&&o.length===1?s.push(...new em(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Mo(n,h,l,t).project()):s.push(...new em(n,r===0?l:h,t).project())}),s},zu=a=>{const t={};return Object.keys(a).forEach(e=>{t[e]={},Object.keys(a[e]).forEach(s=>{t[e][s]=T({},a[e][s])})}),t},im=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),mc=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=py(a,s))!==!1&&t.push(e);return t},py=(a,t)=>{const e=a.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return a.charAt(t);if(55296<=e&&e<=56319){if(a.length<=t+1)throw"High surrogate without following low surrogate";const i=a.charCodeAt(t+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return a.charAt(t)+a.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=a.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var my=Object.freeze({__proto__:null,capitalize:function(a){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(a.charAt(0).toUpperCase()).concat(t?a.slice(1):a.slice(1).toLowerCase())},escapeXml:im,graphemeSplit:mc});const bc=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return a.fill!==t.fill||a.stroke!==t.stroke||a.strokeWidth!==t.strokeWidth||a.fontSize!==t.fontSize||a.fontFamily!==t.fontFamily||a.fontWeight!==t.fontWeight||a.fontStyle!==t.fontStyle||a.textBackgroundColor!==t.textBackgroundColor||a.deltaY!==t.deltaY||e&&(a.overline!==t.overline||a.underline!==t.underline||a.linethrough!==t.linethrough)},nm=(a,t)=>{const e=t.split(`
38
- `),s=[];let i=-1,n={};a=zu(a);for(let r=0;r<e.length;r++){const o=mc(e[r]);if(a[r])for(let h=0;h<o.length;h++){i++;const l=a[r][h];l&&Object.keys(l).length>0&&(bc(n,l,!0)?s.push({start:i,end:i+1,style:l}):s[s.length-1].end++),n=l||{}}else i+=o.length,n={}}return s},rm=(a,t)=>{if(!Array.isArray(a))return zu(a);const e=t.split(fu),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=mc(e[r]);for(let h=0;h<o.length;h++)i++,a[n]&&a[n].start<=i&&i<a[n].end&&(s[r]=s[r]||{},s[r][h]=T({},a[n].style),i===a[n].end-1&&n++)}return s},hn=["display","transform",Rt,"fill-opacity","fill-rule","opacity",Ae,"stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"];function om(a,t){const e=a.nodeName,s=a.getAttribute("class"),i=a.getAttribute("id"),n="(?![a-zA-Z\\-]+)";let r;if(r=new RegExp("^"+e,"i"),t=t.replace(r,""),i&&t.length&&(r=new RegExp("#"+i+n,"i"),t=t.replace(r,"")),s&&t.length){const o=s.split(" ");for(let h=o.length;h--;)r=new RegExp("\\."+o[h]+n,"i"),t=t.replace(r,"")}return t.length===0}function by(a,t){let e=!0;const s=om(a,t.pop());return s&&t.length&&(e=function(i,n){let r,o=!0;for(;i.parentElement&&i.parentElement.nodeType===1&&n.length;)o&&(r=n.pop()),o=om(i=i.parentElement,r);return n.length===0}(a,t)),s&&e&&t.length===0}const vy=a=>{var t;return(t=Iv[a])!==null&&t!==void 0?t:a},yy=new RegExp("(".concat(_s,")"),"gi"),_y=a=>a.replace(yy," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var am,hm,lm,cm,dm,um,gm;const Ee="(".concat(_s,")"),wy=String.raw(am||(am=sn(["(skewX)(",")"],["(skewX)\\(","\\)"])),Ee),xy=String.raw(hm||(hm=sn(["(skewY)(",")"],["(skewY)\\(","\\)"])),Ee),Sy=String.raw(lm||(lm=sn(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Ee,Ee,Ee),Cy=String.raw(cm||(cm=sn(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Ee,Ee),Ay=String.raw(dm||(dm=sn(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Ee,Ee),Ty=String.raw(um||(um=sn(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Ee,Ee,Ee,Ee,Ee,Ee),Xu="(?:".concat(Ty,"|").concat(Ay,"|").concat(Sy,"|").concat(Cy,"|").concat(wy,"|").concat(xy,")"),Ey="(?:".concat(Xu,"*)"),ky=String.raw(gm||(gm=sn(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),Ey),My=new RegExp(ky),Oy=new RegExp(Xu),Dy=new RegExp(Xu,"g");function vc(a){const t=[];if(!(a=_y(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!My.test(a))return[...xe];for(const e of a.matchAll(Dy)){const s=Oy.exec(e[0]);if(!s)continue;let i=xe;const n=s.filter(p=>!!p),[,r,...o]=n,[h,l,d,u,g,f]=o.map(p=>parseFloat(p));switch(r){case"translate":i=wo(h,l);break;case pu:i=xo({angle:h},{x:l,y:d});break;case Jl:i=ic(h,l);break;case vo:i=yu(h);break;case yo:i=_u(h);break;case"matrix":i=[h,l,d,u,g,f]}t.push(i)}return sc(t)}function Py(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==Rt&&a!==Ae||t!==Se){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===Se?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?It(e.transformMatrix,vc(t)):vc(t);else if(a==="visible")r=t!==Se&&t!=="hidden",e&&e.visible===!1&&(r=!1);else if(a==="opacity")r=parseFloat(t),e&&e.opacity!==void 0&&(r*=e.opacity);else if(a==="textAnchor")r=t==="start"?ut:t==="end"?Lt:J;else if(a==="charSpacing")n=Te(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(Rt),h=t.indexOf(Ae);r=Rt,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=Ae)}else{if(a==="href"||a==="xlink:href"||a==="font"||a==="id")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(Te):Te(t,s)}}else r="";return!i&&isNaN(n)?r:n}function Ly(a,t){const e=a.match(Fv);if(!e)return;const s=e[1],i=e[3],n=e[4],r=e[5],o=e[6];s&&(t.fontStyle=s),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),n&&(t.fontSize=Te(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function Vu(a,t){a.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function Ry(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?Vu(e,t):function(s,i){Object.entries(s).forEach(n=>{let[r,o]=n;o!==void 0&&(i[r.toLowerCase()]=o)})}(e,t)),t}const Fy={stroke:"strokeOpacity",fill:"fillOpacity"};function bi(a,t,e){if(!a)return{};let s,i={},n=uu;a.parentNode&&Rp.test(a.parentNode.nodeName)&&(i=bi(a.parentElement,t,e),i.fontSize&&(s=n=Te(i.fontSize)));const r=T(T(T({},t.reduce((l,d)=>{const u=a.getAttribute(d);return u&&(l[d]=u),l},{})),function(l){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const g in d)by(l,g.split(" "))&&(u=T(T({},u),d[g]));return u}(a,e)),Ry(a));r[Du]&&a.setAttribute(Du,r[Du]),r[Ou]&&(s=Te(r[Ou],n),r[Ou]="".concat(s));const o={};for(const l in r){const d=vy(l),u=Py(d,r[l],i,s);o[d]=u}o&&o.font&&Ly(o.font,o);const h=T(T({},i),o);return Rp.test(a.nodeName)?h:function(l){const d=de.getDefaults();return Object.entries(Fy).forEach(u=>{let[g,f]=u;if(l[f]===void 0||l[g]==="")return;if(l[g]===void 0){if(!d[g])return;l[g]=d[g]}if(l[g].indexOf("url(")===0)return;const p=new ft(l[g]);l[g]=p.setAlpha(St(p.getAlpha()*l[f],2)).toRgba()}),l}(h)}const Iy=["left","top","width","height","visible"],fm=["rx","ry"];class Ws extends de{static getDefaults(){return T(T({},super.getDefaults()),Ws.ownDefaults)}constructor(t){super(),Object.assign(this,Ws.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){const{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){const{width:e,height:s}=this,i=-e/2,n=-s/2,r=this.rx?Math.min(this.rx,e/2):0,o=this.ry?Math.min(this.ry,s/2):0,h=r!==0||o!==0;t.beginPath(),t.moveTo(i+r,n),t.lineTo(i+e-r,n),h&&t.bezierCurveTo(i+e-rn*r,n,i+e,n+rn*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-rn*o,i+e-rn*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+rn*r,n+s,i,n+s-rn*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+rn*o,i+rn*r,n,i+r,n),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...fm,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:i}=this;return["<rect ","COMMON_PARTS",'x="'.concat(-t/2,'" y="').concat(-e/2,'" rx="').concat(s,'" ry="').concat(i,'" width="').concat(t,'" height="').concat(e,`" />
39
- `)]}static async fromElement(t,e,s){const i=bi(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,d=xt(i,Iy);return new this(T(T(T({},e),d),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}A(Ws,"type","Rect"),A(Ws,"cacheProperties",[...pi,...fm]),A(Ws,"ownDefaults",{rx:0,ry:0}),A(Ws,"ATTRIBUTE_NAMES",[...hn,"x","y","rx","ry","width","height"]),z.setClass(Ws),z.setSVGClass(Ws);const vi="initialization",yc="added",Gu="removed",_c="imperative",pm=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?$a(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),d=e&&l?Tp(new M(s,s),void 0,a.calcTransformMatrix()):bu,u=!e&&l?s:0,g=oc(i+u,n+u,sc([o,t.calcOwnMatrix()],!0)).add(d).scalarDivide(2);return[h.subtract(g),h.add(g)]};class wc{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===vi||e===_c||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==vi&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===_c&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Hs(t.map(u=>pm(i,u)).reduce((u,g)=>u.concat(g),[])),l=new M(o,h),d=new M(n,r).add(l.scalarDivide(2));if(s===vi){const u=this.getInitialSize(e,{size:l,center:d});return{center:d,relativeCorrection:new M(0,0),size:u}}return{center:d.transform(i.calcOwnMatrix()),size:l}}}A(wc,"type","strategy");class Uu extends wc{shouldPerformLayout(t){return!0}}A(Uu,"type","fit-content"),z.setClass(Uu);const jy=["strategy"],Ny=["target","strategy","bubbles","prevStrategy"],mm="layoutManager";class Ja{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Uu;A(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=T(T({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[Zl,tp,Wa,ep,Kl,sp,Ql,Tv,Ev].map(i=>t.on(i,n=>this.performLayout(i===Zl?{type:"object_modified",trigger:i,e:n,target:s}:{type:"object_modifying",trigger:i,e:n,target:s})))}subscribe(t,e){this.unsubscribe(t,e);const s=this.attachHandlers(t,e);this._subscriptions.set(t,s)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(s=>s()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){const{target:e,type:s}=t,{canvas:i}=e;if(s===vi||s===yc?this.subscribeTargets(t):s===Gu&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===_c&&t.deep){const n=xt(t,jy);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(T(T({},n),{},{bubbles:!1,target:r})))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===vi?new M:e.getRelativeCenterPoint(),{center:o,correction:h=new M,relativeCorrection:l=new M}=n,d=r.subtract(o).add(h).transform(i===vi?xe:Fe(e.calcOwnMatrix()),!0).add(l);return{result:n,prevCenter:r,nextCenter:o,offset:d}}commitLayout(t,e){const{target:s}=t,{result:{size:i},nextCenter:n}=e;var r,o;s.set({width:i.x,height:i.y}),this.layoutObjects(t,e),t.type===vi?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*Ht(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*Ht(s.originY)}):(s.setPositionByOrigin(n,J,J),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject(i=>{i.group===s&&this.layoutObject(t,e,i)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:i}=e;s.set({left:s.left+i.x,top:s.top+i.y})}onAfterLayout(t,e){const{target:s,strategy:i,bubbles:n,prevStrategy:r}=t,o=xt(t,Ny),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;n&&l!=null&&l.layoutManager&&((o.path||(o.path=[])).push(s),l.layoutManager.performLayout(T(T({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:mm,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}z.setClass(Ja,mm);const By=["type","objects","layoutManager"];class Hy extends Ja{performLayout(){}}class zs extends ip(de){static getDefaults(){return T(T({},super.getDefaults()),zs.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),A(this,"_activeObjects",[]),A(this,"__objectSelectionTracker",void 0),A(this,"__objectSelectionDisposer",void 0),Object.assign(this,zs.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var s;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(i=>{this.enterGroup(i,!1)}),this.layoutManager=(s=e.layoutManager)!==null&&s!==void 0?s:new Ja,this.layoutManager.performLayout({type:vi,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(ui("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(ui("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((e,s,i)=>this.canEnterGroup(e)&&i.indexOf(e)===s)}add(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];const i=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...i);return this._onAfterObjectsChange(yc,i),n}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=this._filterObjectsBeforeEnteringGroup(s),r=super.insertAt(t,...n);return this._onAfterObjectsChange(yc,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Gu,t),t}_onObjectAdded(t){this.enterGroup(t,!0),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t,e){this.exitGroup(t,e),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onAfterObjectsChange(t,e){this.layoutManager.performLayout({type:t,targets:e,target:this})}_onStackOrderChanged(){this._set("dirty",!0)}_set(t,e){const s=this[t];return super._set(t,e),t==="canvas"&&s!==e&&(this._objects||[]).forEach(i=>{i._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:s}=e;const i=this._activeObjects;if(t)i.push(s),this._set("dirty",!0);else if(i.length>0){const n=i.indexOf(s);n>-1&&(i.splice(n,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&Co(t,It(Fe(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const s=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();s&&(s===t||t.isDescendantOf(s))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(Co(t,It(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=de.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t){this._renderBackground(t);for(let s=0;s<this._objects.length;s++){var e;(e=this.canvas)!==null&&e!==void 0&&e.preserveObjectStacking&&this._objects[s].group!==this?(t.save(),t.transform(...Fe(this.calcTransformMatrix())),this._objects[s].render(t),t.restore()):this._objects[s].group===this&&this._objects[s].render(t)}this._drawClipPath(t,this.clipPath)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(T({target:this,type:_c},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter(function(i){return!i.excludeFromExport}).map(function(i){const n=i.includeDefaultValues;i.includeDefaultValues=s;const r=i[t||"toObject"](e);return i.includeDefaultValues=n,r})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return T(T(T({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Ws.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const i=e.join("");return t?t(i):i}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
40
- `],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toSVG(t));return e.push(`</g>
41
- `),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:i=[],layoutManager:n}=t,r=xt(t,By);return Promise.all([So(i,e),Ga(r,e)]).then(o=>{let[h,l]=o;const d=new this(h,T(T(T({},r),l),{},{layoutManager:new Hy}));if(n){const u=z.getClass(n.type),g=z.getClass(n.strategy);d.layoutManager=new u(new g)}else d.layoutManager=new Ja;return d.layoutManager.subscribeTargets({type:vi,target:d,targets:d.getObjects()}),d.setCoords(),d})}}A(zs,"type","Group"),A(zs,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),z.setClass(zs);const bm=(a,t)=>Math.min(t.width/a.width,t.height/a.height),vm=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Yu="\\s*,?\\s*",Za="".concat(Yu,"(").concat(_s,")"),Wy="".concat(Za).concat(Za).concat(Za).concat(Yu,"([01])").concat(Yu,"([01])").concat(Za).concat(Za),zy={m:"l",M:"L"},Xy=(a,t,e,s,i,n,r,o,h,l,d)=>{const u=ms(a),g=bs(a),f=ms(t),p=bs(t),m=e*i*f-s*n*p+r,_=s*i*f+e*n*p+o;return["C",l+h*(-e*i*g-s*n*u),d+h*(-s*i*g+e*n*u),m+h*(e*i*p+s*n*f),_+h*(s*i*p-e*n*f),m,_]},ym=(a,t,e,s)=>{const i=Math.atan2(t,a),n=Math.atan2(s,e);return n>=i?n-i:2*Math.PI-(i-n)};function qu(a,t,e,s,i,n,r,o){let h;if(at.cachesBoundsOfCurve&&(h=[...arguments].join(),Ha.boundsOfCurveCache[h]))return Ha.boundsOfCurveCache[h];const l=Math.sqrt,d=Math.abs,u=[],g=[[0,0],[0,0]];let f=6*a-12*e+6*i,p=-3*a+9*e-9*i+3*r,m=3*e-3*a;for(let C=0;C<2;++C){if(C>0&&(f=6*t-12*s+6*n,p=-3*t+9*s-9*n+3*o,m=3*s-3*t),d(p)<1e-12){if(d(f)<1e-12)continue;const F=-m/f;0<F&&F<1&&u.push(F);continue}const E=f*f-4*m*p;if(E<0)continue;const k=l(E),P=(-f+k)/(2*p);0<P&&P<1&&u.push(P);const D=(-f-k)/(2*p);0<D&&D<1&&u.push(D)}let _=u.length;const v=_,x=wm(a,t,e,s,i,n,r,o);for(;_--;){const{x:C,y:E}=x(u[_]);g[0][_]=C,g[1][_]=E}g[0][v]=a,g[1][v]=t,g[0][v+1]=r,g[1][v+1]=o;const S=[new M(Math.min(...g[0]),Math.min(...g[1])),new M(Math.max(...g[0]),Math.max(...g[1]))];return at.cachesBoundsOfCurve&&(Ha.boundsOfCurveCache[h]=S),S}const Vy=(a,t,e)=>{let[s,i,n,r,o,h,l,d]=e;const u=((g,f,p,m,_,v,x)=>{if(p===0||m===0)return[];let S=0,C=0,E=0;const k=Math.PI,P=x*du,D=bs(P),F=ms(P),B=.5*(-F*g-D*f),O=.5*(-F*f+D*g),R=p**2,L=m**2,j=O**2,G=B**2,Y=R*L-R*j-L*G;let X=Math.abs(p),H=Math.abs(m);if(Y<0){const Xn=Math.sqrt(1-Y/(R*L));X*=Xn,H*=Xn}else E=(_===v?-1:1)*Math.sqrt(Y/(R*j+L*G));const _t=E*X*O/H,dt=-E*H*B/X,_e=F*_t-D*dt+.5*g,Bt=D*_t+F*dt+.5*f;let wt=ym(1,0,(B-_t)/X,(O-dt)/H),De=ym((B-_t)/X,(O-dt)/H,(-B-_t)/X,(-O-dt)/H);v===0&&De>0?De-=2*k:v===1&&De<0&&(De+=2*k);const Ve=Math.ceil(Math.abs(De/k*2)),Gt=[],ht=De/Ve,Rl=8/3*Math.sin(ht/4)*Math.sin(ht/4)/Math.sin(ht/2);let Fl=wt+ht;for(let Xn=0;Xn<Ve;Xn++)Gt[Xn]=Xy(wt,Fl,F,D,X,H,_e,Bt,Rl,S,C),S=Gt[Xn][5],C=Gt[Xn][6],wt=Fl,Fl+=ht;return Gt})(l-a,d-t,i,n,o,h,r);for(let g=0,f=u.length;g<f;g++)u[g][1]+=a,u[g][2]+=t,u[g][3]+=a,u[g][4]+=t,u[g][5]+=a,u[g][6]+=t;return u},_m=a=>{let t=0,e=0,s=0,i=0;const n=[];let r,o=0,h=0;for(const l of a){const d=[...l];let u;switch(d[0]){case"l":d[1]+=t,d[2]+=e;case"L":t=d[1],e=d[2],u=["L",t,e];break;case"h":d[1]+=t;case"H":t=d[1],u=["L",t,e];break;case"v":d[1]+=e;case"V":e=d[1],u=["L",t,e];break;case"m":d[1]+=t,d[2]+=e;case"M":t=d[1],e=d[2],s=d[1],i=d[2],u=["M",t,e];break;case"c":d[1]+=t,d[2]+=e,d[3]+=t,d[4]+=e,d[5]+=t,d[6]+=e;case"C":o=d[3],h=d[4],t=d[5],e=d[6],u=["C",d[1],d[2],o,h,t,e];break;case"s":d[1]+=t,d[2]+=e,d[3]+=t,d[4]+=e;case"S":r==="C"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=d[3],e=d[4],u=["C",o,h,d[1],d[2],t,e],o=u[3],h=u[4];break;case"q":d[1]+=t,d[2]+=e,d[3]+=t,d[4]+=e;case"Q":o=d[1],h=d[2],t=d[3],e=d[4],u=["Q",o,h,t,e];break;case"t":d[1]+=t,d[2]+=e;case"T":r==="Q"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=d[1],e=d[2],u=["Q",o,h,t,e];break;case"a":d[6]+=t,d[7]+=e;case"A":Vy(t,e,d).forEach(g=>n.push(g)),t=d[6],e=d[7];break;case"z":case"Z":t=s,e=i,u=["Z"]}u?(n.push(u),r=u[0]):r=""}return n},xc=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),wm=(a,t,e,s,i,n,r,o)=>h=>{const l=h**3,d=(f=>3*f**2*(1-f))(h),u=(f=>3*f*(1-f)**2)(h),g=(f=>(1-f)**3)(h);return new M(r*l+i*d+e*u+a*g,o*l+n*d+s*u+t*g)},xm=a=>a**2,Sm=a=>2*a*(1-a),Cm=a=>(1-a)**2,Gy=(a,t,e,s,i,n,r,o)=>h=>{const l=xm(h),d=Sm(h),u=Cm(h),g=3*(u*(e-a)+d*(i-e)+l*(r-i)),f=3*(u*(s-t)+d*(n-s)+l*(o-n));return Math.atan2(f,g)},Uy=(a,t,e,s,i,n)=>r=>{const o=xm(r),h=Sm(r),l=Cm(r);return new M(i*o+e*h+a*l,n*o+s*h+t*l)},Yy=(a,t,e,s,i,n)=>r=>{const o=1-r,h=2*(o*(e-a)+r*(i-e)),l=2*(o*(s-t)+r*(n-s));return Math.atan2(l,h)},Am=(a,t,e)=>{let s=new M(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=xc(s.x,s.y,r.x,r.y),s=r}return i},qy=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=T({},n),o=.01,h=0;const l=a.iterator,d=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=xc(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return T(T({},r),{},{angle:d(h)})},$u=a=>{let t,e,s=0,i=0,n=0,r=0,o=0;const h=[];for(const l of a){const d={x:i,y:n,command:l[0],length:0};switch(l[0]){case"M":e=d,e.x=r=i=l[1],e.y=o=n=l[2];break;case"L":e=d,e.length=xc(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=wm(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=d,e.iterator=t,e.angleFinder=Gy(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=Am(t,i,n),i=l[5],n=l[6];break;case"Q":t=Uy(i,n,l[1],l[2],l[3],l[4]),e=d,e.iterator=t,e.angleFinder=Yy(i,n,l[1],l[2],l[3],l[4]),e.length=Am(t,i,n),i=l[3],n=l[4];break;case"Z":e=d,e.destX=r,e.destY=o,e.length=xc(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},Tm=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:$u(a),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const i=e[s],n=t/i.length,r=a[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return T(T({},new M(i.x,i.y).lerp(new M(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return T(T({},new M(i.x,i.y).lerp(new M(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return qy(i,t)}},$y=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Em=new RegExp(Wy,"g"),Ky=new RegExp(_s,"gi"),Qy={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},km=a=>{var t;const e=[],s=(t=a.match($y))!==null&&t!==void 0?t:[];for(const i of s){const n=i[0];if(n==="z"||n==="Z"){e.push([n]);continue}const r=Qy[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){Em.lastIndex=0;for(let h=null;h=Em.exec(i);)o.push(...h.slice(1))}else o=i.match(Ky)||[];for(let h=0;h<o.length;h+=r){const l=new Array(r),d=zy[n];l[0]=h>0&&d?d:n;for(let u=0;u<r;u++)l[u+1]=parseFloat(o[h+u]);e.push(l)}}return e},Jy=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new M(a[0]),s=new M(a[1]),i=1,n=0;const r=[],o=a.length,h=o>2;let l;for(h&&(i=a[2].x<s.x?-1:a[2].x===s.x?0:1,n=a[2].y<s.y?-1:a[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),l=1;l<o;l++){if(!e.eq(s)){const d=e.midPointFrom(s);r.push(["Q",e.x,e.y,d.x,d.y])}e=a[l],l+1<a.length&&(s=a[l+1])}return h&&(i=e.x>a[l-2].x?1:e.x===a[l-2].x?0:-1,n=e.y>a[l-2].y?1:e.y===a[l-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},Mm=(a,t)=>a.map(e=>e.map((s,i)=>i===0||t===void 0?s:St(s,t)).join(" ")).join(" ");function Sc(a,t){const e=a.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const Zy=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function Om(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||Un,s=new($l()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=Un};if(i&&i.aborted)throw new lu("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=Un)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const Cc=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=qn(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Ce,i),s.set(Ge,n),s.angle=r,s.skewX=o,s.skewY=0}})(a),e=e.transform(a.transformMatrix)),delete a.transformMatrix,t&&(a.scaleX*=t.scaleX,a.scaleY*=t.scaleY,a.cropX=t.cropX,a.cropY=t.cropY,e.x+=t.offsetLeft,e.y+=t.offsetTop,a.width=t.width,a.height=t.height),a.setPositionByOrigin(e,J,J)};var t_=Object.freeze({__proto__:null,addTransformToObject:Cp,animate:Bu,animateColor:Vp,applyTransformToObject:Co,calcAngleBetweenVectors:dc,calcDimensionsMatrix:Xa,calcPlaneChangeMatrix:$a,calcVectorRotation:jp,cancelAnimFrame:rp,capValue:Jn,composeMatrix:cp,copyCanvasElement:a=>{var t;const e=Ft();return e.width=a.width,e.height=a.height,(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:ms,createCanvasElement:Ft,createImage:op,createRotateMatrix:xo,createScaleMatrix:ic,createSkewXMatrix:yu,createSkewYMatrix:_u,createTranslateMatrix:wo,createVector:lc,crossProduct:Ao,degreesToRadians:Dt,dotProduct:Np,ease:zv,enlivenObjectEnlivables:Ga,enlivenObjects:So,findScaleToCover:vm,findScaleToFit:bm,getBoundsOfCurve:qu,getOrthonormalVector:Lu,getPathSegmentsInfo:$u,getPointOnPath:Tm,getPointer:Sp,getRandomInt:Zy,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-nn;a%2==0&&(s+=e/2);const i=new Array(a+1);for(let n=0;n<a;n++){const r=n*e+s,{x:o,y:h}=new M(ms(r),bs(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:Jy,getSvgAttributes:a=>{const t=["instantiated_by_use","style","id","class"];switch(a){case"linearGradient":return t.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return t.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return t.concat(["offset","stop-color","stop-opacity"])}return t},getUnitVector:uc,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new zs(a,t),hasStyleChanged:bc,invertTransform:Fe,isBetweenVectors:Ru,isIdentityMatrix:ap,isTouchEvent:rc,isTransparent:Zp,joinPath:Mm,loadImage:Va,magnitude:cc,makeBoundingBoxFromPoints:Hs,makePathSimpler:_m,matrixToSVG:Ua,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),Eu(i,(e=i.group)===null||e===void 0?void 0:e.calcTransformMatrix(),s.calcTransformMatrix());const n=s.inverted&&i.inverted;return n&&(s.inverted=i.inverted=!1),new zs([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:It,multiplyTransformMatrixArray:sc,parsePath:km,parsePreserveAspectRatioAttribute:Su,parseUnit:Te,pick:$n,projectStrokeOnPoints:sm,qrDecompose:qn,radiansToDegrees:an,removeFromArray:Yn,removeTransformFromObject:(a,t)=>{const e=Fe(t),s=It(e,a.calcOwnMatrix());Co(a,s)},removeTransformMatrixForSvgParsing:Cc,request:Om,requestAnimFrame:za,resetObjectTransform:Ap,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:Pu,saveObjectTransform:Tu,sendObjectToPlane:Eu,sendPointToPlane:Qn,sendVectorToPlane:Tp,setStyle:Sc,sin:bs,sizeAfterTransform:oc,string:my,stylesFromArray:rm,stylesToArray:nm,toDataURL:vu,toFixed:St,transformPath:(a,t,e)=>(e&&(t=It(t,[1,0,0,1,-e.x,-e.y])),a.map(s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:o}=ce({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i})),transformPoint:ce});class e_ extends xp{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),A(this,"upper",void 0),A(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(s),i.parentNode&&i.parentNode.replaceChild(r,i),r.append(i,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=Ft();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){const t=bo().createElement("div");return t.setAttribute("data-fabric","wrapper"),Sc(t,{position:"relative"}),wp(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;Sc(t,T(T({},s),{},{"touch-action":i?"manipulation":Se})),wp(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;_p(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Cu(this.upper.el,t),Cu(this.container,t)}cleanupDOM(t){const e=this.container,{el:s}=this.lower,{el:i}=this.upper;super.cleanupDOM(t),e.removeChild(i),e.removeChild(s),e.parentNode&&e.parentNode.replaceChild(s,e)}dispose(){super.dispose(),Bs().dispose(this.upper.el),delete this.upper,delete this.container}}class Ac extends qa{constructor(){super(...arguments),A(this,"targets",[]),A(this,"_hoveredTargets",[]),A(this,"_objectsToRender",void 0),A(this,"_currentTransform",null),A(this,"_groupSelector",null),A(this,"contextTopDirty",!1)}static getDefaults(){return T(T({},super.getDefaults()),Ac.ownDefaults)}get upperCanvasEl(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.el}get contextTop(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new e_(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){const t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter(e=>!e.group&&e!==t).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(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(){const t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;const e=this.getRetinaScaling(),s=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=s,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,s){const i=this.targetFindTolerance,n=this.pixelFindContext;this.clearContext(n),n.save(),n.translate(-e+i,-s+i),n.transform(...this.viewportTransform);const r=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(n),t.selectionBackgroundColor=r,n.restore();const o=Math.round(i*this.getRetinaScaling());return Zp(n,o,o,o)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(s=>!!s&&t[s]===!0):t[e])}_shouldClearSelection(t,e){const s=this.getActiveObjects(),i=this._activeObject;return!!(!e||e&&i&&s.length>1&&s.indexOf(e)===-1&&i!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&i&&i!==e)}_shouldCenterTransform(t,e,s){if(!t)return;let i;return e===Jl||e===Ce||e===Ge||e===Wa?i=this.centeredScaling||t.centeredScaling:e===pu&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=Lt:["mr","tr","br"].includes(e)&&(s.x=ut),["tl","mt","tr"].includes(e)?s.y=gu:["bl","mb","br"].includes(e)&&(s.y=Re)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?Qn(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},h=s&&o?(i=o.getActionHandler(t,e,o))===null||i===void 0?void 0:i.bind(o):Rv,l=((f,p,m,_)=>{if(!p||!f)return"drag";const v=_.controls[p];return v.getActionName(m,v,_)})(s,r,t,e),d=t[this.centeredKey],u=this._shouldCenterTransform(e,l,d)?{x:J,y:J}:this._getOriginFromCorner(e,r),g={target:e,action:l,actionHandler:h,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:u.x,originY:u.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:Dt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:d,original:T(T({},Tu(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=g,this.fire("before:transform",{e:t,transform:g})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new M(e,s).transform(this.viewportTransform),o=new M(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=Math.min(r.x,o.x),d=Math.min(r.y,o.y),u=Math.max(r.x,o.x),g=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,d,u-l,g-d)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,d+=h,u-=h,g-=h,de.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,d,u-l,g-d))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,rc(t))||i.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const n=this.targets;this.targets=[];const r=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&r&&r!==s?(this.targets=n,s):r}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,o,h,l]=s,d=Math.atan2(o.y-r.y,o.x-r.x),u=ms(d)*n,g=bs(d)*n,f=u+g,p=u-g;s=[new M(r.x-p,r.y-f),new M(o.x+f,o.y-p),new M(h.x+p,h.y+f),new M(l.x-f,l.y+p)]}return At.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,Qn(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const i=t[s];if(this._checkTarget(i,e)){if(ec(i)&&i.subTargetCheck){const n=this._searchPossibleTargets(i._objects,e);n&&this.targets.push(n)}return i}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&ec(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!ec(r)||!r.interactive)return r}return i[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=Sp(t),r=i.width||0,o=i.height||0;r&&o||(Re in i&&gu in i&&(o=Math.abs(i.top-i.bottom)),Lt in i&&ut in i&&(r=Math.abs(i.right-i.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=Qn(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new M(1,1):new M(s.width/r,s.height/o);return n.multiply(l)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Ft(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){const t=this._activeObject;return Kn(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach(h=>{n.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),o.push(h))}),n.forEach(h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),r.push(h))}),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:o})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:o})),i&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),i=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),i}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,Kn(t)&&s!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){const s=this._activeObject;return!!s&&!s.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===s&&this.endCurrentTransform(t),Kn(s)&&s===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){const e=this.getActiveObjects(),s=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[s]});const i=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),i}endCurrentTransform(t){const e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){const e=this._currentTransform,s=e.target,i={e:t,target:s,transform:e,action:e.action};s._scaling&&(s._scaling=!1),s.setCoords(),e.actionPerformed&&(this.fire("object:modified",i),s.fire(Zl,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;Kn(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){const e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,s){const i=this._realizeGroupTransformOnObject(t),n=super._toObject(t,e,s);return t.set(i),n}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&Kn(e)&&this._activeObject===e){const s=$n(t,["angle","flipX","flipY",ut,Ce,Ge,vo,yo,Re]);return Cp(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}A(Ac,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",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",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class s_{constructor(t){A(this,"targets",[]),A(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),Yn(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;!((e=this.target)===null||e===void 0)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}const i_=["target","oldTarget","fireCanvas","e"],Ue={passive:!1},Oo=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},ln=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return a.addEventListener(...e)},rs=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return a.removeEventListener(...e)},n_={mouse:{in:"over",out:"out",targetIn:"mouseover",targetOut:"mouseout",canvasIn:"mouse:over",canvasOut:"mouse:out"},drag:{in:"enter",out:"leave",targetIn:"dragenter",targetOut:"dragleave",canvasIn:"drag:enter",canvasOut:"drag:leave"}};class Ku extends Ac{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),A(this,"_isClick",void 0),A(this,"textEditingManager",new s_(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onDoubleClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(ln,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(yp(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,Ue),t(s,"".concat(i,"out"),this._onMouseOut),t(s,"".concat(i,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel),t(s,"contextmenu",this._onContextMenu),t(s,"dblclick",this._onDoubleClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,Ue)}removeListeners(){this.addOrRemove(rs,"remove");const t=this._getEventPrefix(),e=vs(this.upperCanvasEl);rs(e,"".concat(t,"up"),this._onMouseUp),rs(e,"touchend",this._onTouchEnd,Ue),rs(e,"".concat(t,"move"),this._onMouseMove,Ue),rs(e,"touchmove",this._onMouseMove,Ue)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=T({e:t},Oo(this,t));this.fire("mouse:out",T(T({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",T({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",T(T({},s),{},{target:i})),i&&i.fire("mouseout",T({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",T({e:t},Oo(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;const e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;const s={e:t,target:e};return this.fire("dragstart",s),e.fire("dragstart",s),void ln(this.upperCanvasEl,"drag",this._onDragProgress)}Au(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e==null||e.clearContextTop(),s!==e&&(s==null||s.clearContextTop());const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),i=!0),s&&(r.save(),s.transform(r),s.renderDropTargetEffect(t),r.restore(),i=!0),r.restore(),i&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==Se,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};rs(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let h=0;h<i.length;h++){const l=i[h];l.canDrop(t)&&(o=l),l.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",T({e:t,target:e,subTargets:s,dragSource:this._dragSource},Oo(this,t)));i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&Au(t),this._basicEventHandler("contextmenu",i),!1}_onDoubleClick(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData()}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){t.preventDefault(),this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix(),i=vs(e);ln(i,"touchend",this._onTouchEnd,Ue),ln(i,"touchmove",this._onMouseMove,Ue),rs(e,"".concat(s,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();rs(e,"".concat(s,"move"),this._onMouseMove,Ue);const i=vs(e);ln(i,"".concat(s,"up"),this._onMouseUp),ln(i,"".concat(s,"move"),this._onMouseMove,Ue)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=vs(this.upperCanvasEl);rs(s,"touchend",this._onTouchEnd,Ue),rs(s,"touchmove",this._onMouseMove,Ue),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{ln(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=vs(this.upperCanvasEl);rs(i,"".concat(s,"up"),this._onMouseUp),rs(i,"".concat(s,"move"),this._onMouseMove,Ue),ln(e,"".concat(s,"move"),this._onMouseMove,Ue)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,n=this._target,{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o,h,l=!1;if(s&&(this._finalizeCurrentTransform(t),l=s.actionPerformed),!i){const d=n===this._activeObject;this.handleSelection(t),l||(l=this._shouldRender(n)||!d&&n===this._activeObject)}if(n){const d=n.findControl(this.getViewportPoint(t),rc(t)),{key:u,control:g}=d||{};if(h=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),l=!0;else if(g){const f=g.getMouseUpHandler(t,n,g);f&&(o=this.getScenePoint(t),f.call(g,t,s,o.x,o.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const d=s.target&&s.target.controls[s.corner],u=d&&d.getMouseUpHandler(t,s.target,d);o=o||this.getScenePoint(t),u&&u.call(d,t,s,o.x,o.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),l?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e){const s=this._target,i=this.targets||[],n=T(T({e:t,target:s,subTargets:i},Oo(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{});this.fire("mouse:".concat(e),n),s&&s.fire("mouse".concat(e),n);for(let r=0;r<i.length;r++)i[r]!==s&&i[r].fire("mouse".concat(e),n)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down")}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target;const{button:s}=t;if(s)return(this.fireMiddleClick&&s===1||this.fireRightClick&&s===2)&&this._handleEvent(t,"down"),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let i=this._shouldRender(e),n=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,n=!0,i=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const r=this.getScenePoint(t);this._groupSelector={x:r.x,y:r.y,deltaY:0,deltaX:0}}if(e){const r=e===this._activeObject;e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const o=e.findControl(this.getViewportPoint(t),rc(t));if(e===this._activeObject&&(o||!n)){this._setupCurrentTransform(t,e,r);const h=o?o.control:void 0,l=this.getScenePoint(t),d=h&&h.getMouseDownHandler(t,e,h);d&&d.call(h,t,this._currentTransform,l.x,l.y)}}i&&(this._objectsToRender=void 0),this._handleEvent(t,"down"),i&&this.requestRenderAll()}_resetTransformEventData(){this._target=void 0,this._pointer=void 0,this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=Qn(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=xt(e,i_);const{targetIn:h,targetOut:l,canvasIn:d,canvasOut:u}=n_[t],g=i!==s;if(i&&g){const f=T(T({},o),{},{e:r,target:i,nextTarget:s},Oo(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&g){const f=T(T({},o),{},{e:r,target:s,previousTarget:i},Oo(this,r));n&&this.fire(d,f),s.fire(h,f)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?Qn(e,void 0,i.group.calcTransformMatrix()):e;s.shiftKey=t.shiftKey,s.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,s,n),s.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,s){const{action:i,actionHandler:n,target:r}=e,o=!!n&&n(t,e,s.x,s.y);o&&r.setCoords(),i==="drag"&&o&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||o}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const i=Kn(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const r=n.control;this.setCursor(r.cursorStyleHandler(t,r,e))}else e.subTargetCheck&&this.targets.concat().reverse().map(r=>{s=r.hoverCursor||s}),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,i=Kn(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||i)&&(i||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(i){const n=s.getObjects();if(e===s){const r=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(n,r)||this.searchPossibleTargets(this._objects,r))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(n,t)}else{s.exitEditing&&s.exitEditing();const n=new(z.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(s,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new M(e,s),o=r.add(new M(i,n)),h=r.min(o),l=r.max(o).subtract(h),d=this.collectObjects({left:h.x,top:h.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),u=r.eq(o)?d[0]?[d[0]]:[]:d.length>1?d.filter(g=>!g.onSelect({e:t})).reverse():d;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const g=z.getClass("ActiveSelection");this.setActiveObject(new g(u,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const Dm={x1:0,y1:0,x2:0,y2:0},r_=T(T({},Dm),{},{r1:0,r2:0}),Do=(a,t)=>isNaN(a)&&typeof t=="number"?t:a,o_=/^(\d+\.\d+)%|(\d+)%$/;function Pm(a){return a&&o_.test(a)}function Lm(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(Pm(a)?100:1):NaN;return Jn(0,Do(e,t),1)}const a_=/\s*;\s*/,h_=/\s*:\s*/;function l_(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(a_);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(h_).map(d=>d.trim());h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}const n=new ft(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Lm(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Do(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function c_(a,t){const e=[],s=a.getElementsByTagName("stop"),i=Lm(t,1);for(let n=s.length;n--;)e.push(l_(s[n],i));return e}function Rm(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Fm(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function xs(a,t){return a.getAttribute(t)}function d_(a,t){return function(e,s){let i,{width:n,height:r,gradientUnits:o}=s;return Object.keys(e).reduce((h,l)=>{const d=e[l];return d==="Infinity"?i=1:d==="-Infinity"?i=0:(i=typeof d=="string"?parseFloat(d):d,typeof d=="string"&&Pm(d)&&(i*=.01,o==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(i*=n),l!=="y1"&&l!=="y2"||(i*=r)))),h[l]=i,h},{})}(Rm(a)==="linear"?function(e){return{x1:xs(e,"x1")||0,y1:xs(e,"y1")||0,x2:xs(e,"x2")||"100%",y2:xs(e,"y2")||0}}(a):function(e){return{x1:xs(e,"fx")||xs(e,"cx")||"50%",y1:xs(e,"fy")||xs(e,"cy")||"50%",r1:0,x2:xs(e,"cx")||"50%",y2:xs(e,"cy")||"50%",r2:xs(e,"r")||"50%"}}(a),T(T({},t),{},{gradientUnits:Fm(a)}))}class th{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:T(T({},e==="radial"?r_:Dm),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(on()):on()})}addColorStop(t){for(const e in t){const s=new ft(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return T(T({},$n(this,t)),{},{type:this.type,coords:T({},this.coords),colorStops:this.colorStops.map(e=>T({},e)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],i=this.gradientTransform?this.gradientTransform.concat():xe.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(u=>T({},u)).sort((u,g)=>u.offset-g.offset);let o=-this.offsetX,h=-this.offsetY;var l;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const d=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(Ua(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:g,x2:f,y2:p}=this.coords;s.push("<linearGradient ",d,' x1="',u,'" y1="',g,'" x2="',f,'" y2="',p,`">
42
- `)}else if(this.type==="radial"){const{x1:u,y1:g,x2:f,y2:p,r1:m,r2:_}=this.coords,v=m>_;s.push("<radialGradient ",d,' cx="',v?u:f,'" cy="',v?g:p,'" r="',v?m:_,'" fx="',v?f:u,'" fy="',v?p:g,`">
43
- `),v&&(r.reverse(),r.forEach(S=>{S.offset=1-S.offset}));const x=Math.min(m,_);if(x>0){const S=x/Math.max(m,_);r.forEach(C=>{C.offset+=S*(1-C.offset)})}}return r.forEach(u=>{let{color:g,offset:f,opacity:p}=u;s.push("<stop ",'offset="',100*f+"%",'" style="stop-color:',g,p!==void 0?";stop-opacity: "+p:";",`"/>
44
- `)}),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
45
- `),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:o}=this.coords,h=this.type==="linear"?t.createLinearGradient(e,s,i,n):t.createRadialGradient(e,s,r,i,n,o);return this.colorStops.forEach(l=>{let{color:d,opacity:u,offset:g}=l;h.addColorStop(g,u!==void 0?new ft(d).setAlpha(u).toRgba():d)}),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(T(T({},t),{},{colorStops:e?e.map(i=>T({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=Fm(t),n=e._findCenterFromElement();return new this(T({id:t.getAttribute("id")||void 0,type:Rm(t),coords:d_(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:c_(t,s.opacity),gradientUnits:i,gradientTransform:vc(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}A(th,"type","Gradient"),z.setClass(th,"gradient"),z.setClass(th,"linear"),z.setClass(th,"radial");const u_=["type","source","patternTransform"];class Qu{get type(){return"pattern"}set type(t){ui("warn","Setting type has no effect",t)}constructor(t){A(this,"repeat","repeat"),A(this,"offsetX",0),A(this,"offsetY",0),A(this,"crossOrigin",""),this.id=on(),Object.assign(this,t)}isImageSource(){return!!this.source&&typeof this.source.src=="string"}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const{repeat:e,crossOrigin:s}=this;return T(T({},$n(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:St(this.offsetX,at.NUM_FRACTION_DIGITS),offsetY:St(this.offsetY,at.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:s}=t;const{source:i,repeat:n,id:r}=this,o=Do(this.offsetX/e,0),h=Do(this.offsetY/s,0),l=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):Do(i.width/e,0),d=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):Do(i.height/s,0);return['<pattern id="SVGID_'.concat(r,'" x="').concat(o,'" y="').concat(h,'" width="').concat(l,'" height="').concat(d,'">'),'<image x="0" y="0" width="'.concat(i.width,'" height="').concat(i.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
46
- `)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=xt(t,u_);const o=await Va(i,T(T({},e),{},{crossOrigin:r.crossOrigin}));return new this(T(T({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}A(Qu,"type","Pattern"),z.setClass(Qu),z.setClass(Qu,"pattern");const g_=["path","left","top"],f_=["d"];class Zn extends de{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=xt(e,g_);super(),Object.assign(this,Zn.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(ut,i),typeof n=="number"&&this.set(Re,n)}_setPath(t,e){this.path=_m(Array.isArray(t)?t:km(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new M(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const i of this.path)switch(i[0]){case"L":t.lineTo(i[1]+e,i[2]+s);break;case"M":t.moveTo(i[1]+e,i[2]+s);break;case"C":t.bezierCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s,i[5]+e,i[6]+s);break;case"Q":t.quadraticCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),{},{path:this.path.map(e=>e.slice())})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=Mm(this.path,at.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
- `)]}_getOffsetTransform(){const t=at.NUM_FRACTION_DIGITS;return" translate(".concat(St(-this.pathOffset.x,t),", ").concat(St(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return" "+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:i}=this._calcDimensions();this.set({width:e,height:s,pathOffset:i}),t&&this.setPositionByOrigin(i,J,J)}_calcBoundsFromPath(){const t=[];let e=0,s=0,i=0,n=0;for(const r of this.path)switch(r[0]){case"L":i=r[1],n=r[2],t.push({x:e,y:s},{x:i,y:n});break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...qu(i,n,r[1],r[2],r[3],r[4],r[5],r[6])),i=r[5],n=r[6];break;case"Q":t.push(...qu(i,n,r[1],r[2],r[1],r[2],r[3],r[4])),i=r[3],n=r[4];break;case"Z":i=e,n=s}return Hs(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return T(T({},t),{},{pathOffset:new M(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,s){const i=bi(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,T(T(T({},xt(i,f_)),e),{},{left:void 0,top:void 0}))}}A(Zn,"type","Path"),A(Zn,"cacheProperties",[...pi,"path","fillRule"]),A(Zn,"ATTRIBUTE_NAMES",[...hn,"d"]),z.setClass(Zn),z.setSVGClass(Zn);const p_=["left","top","radius"],Im=["radius","startAngle","endAngle","counterClockwise"];class yi extends de{static getDefaults(){return T(T({},super.getDefaults()),yi.ownDefaults)}constructor(t){super(),Object.assign(this,yi.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),t==="radius"&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,Dt(this.startAngle),Dt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(Ce)}getRadiusY(){return this.get("radius")*this.get(Ge)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Im,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
48
- `];{const{radius:e}=this,s=Dt(this.startAngle),i=Dt(this.endAngle),n=ms(s)*e,r=bs(s)*e,o=ms(i)*e,h=bs(i)*e,l=t>180?1:0,d=this.counterClockwise?0:1;return['<path d="M '.concat(n," ").concat(r," A ").concat(e," ").concat(e," 0 ").concat(l," ").concat(d," ").concat(o," ").concat(h,'" '),"COMMON_PARTS",` />
49
- `]}}static async fromElement(t,e,s){const i=bi(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(T(T({},xt(i,p_)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}A(yi,"type","Circle"),A(yi,"cacheProperties",[...pi,...Im]),A(yi,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),A(yi,"ATTRIBUTE_NAMES",["cx","cy","r",...hn]),z.setClass(yi),z.setSVGClass(yi);const m_=["x1","y1","x2","y2"],b_=["x1","y1","x2","y2"],Ju=["x1","x2","y1","y2"];class tr extends de{constructor(){let[t,e,s,i]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,tr.ownDefaults),this.setOptions(n),this.x1=t,this.x2=s,this.y1=e,this.y2=i,this._setWidthHeight();const{left:r,top:o}=n;typeof r=="number"&&this.set(ut,r),typeof o=="number"&&this.set(Re,o)}_setWidthHeight(){const{x1:t,y1:e,x2:s,y2:i}=this;this.width=Math.abs(s-t),this.height=Math.abs(i-e);const{left:n,top:r,width:o,height:h}=Hs([{x:t,y:e},{x:s,y:i}]),l=new M(n+o/2,r+h/2);this.setPositionByOrigin(l,J,J)}_set(t,e){return super._set(t,e),Ju.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const s=t.strokeStyle;var i;ns(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(i=this.stroke)!==null&&i!==void 0?i:t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=s}_findCenterFromElement(){return new M((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:i,width:n,height:r}=this,o=t<=e?-1:1,h=s<=i?-1:1;return{x1:o*n/2,x2:o*-n/2,y1:h*r/2,y2:h*-r/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(i,`" />
50
- `)]}static async fromElement(t,e,s){const i=bi(t,this.ATTRIBUTE_NAMES,s),{x1:n=0,y1:r=0,x2:o=0,y2:h=0}=i;return new this([n,r,o,h],xt(i,m_))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=xt(t,b_);return this._fromObject(T(T({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}A(tr,"type","Line"),A(tr,"cacheProperties",[...pi,...Ju]),A(tr,"ATTRIBUTE_NAMES",hn.concat(Ju)),z.setClass(tr),z.setSVGClass(tr);class er extends de{static getDefaults(){return T(T({},super.getDefaults()),er.ownDefaults)}constructor(t){super(),Object.assign(this,er.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}A(er,"type","Triangle"),A(er,"ownDefaults",{width:100,height:100}),z.setClass(er),z.setSVGClass(er);const jm=["rx","ry"];class _i extends de{static getDefaults(){return T(T({},super.getDefaults()),_i.ownDefaults)}constructor(t){super(),Object.assign(this,_i.ownDefaults),this.setOptions(t)}_set(t,e){switch(super._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(){return this.get("rx")*this.get(Ce)}getRy(){return this.get("ry")*this.get(Ge)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...jm,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
51
- `)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,gi,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=bi(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function v_(a){if(!a)return[];const t=a.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}A(_i,"type","Ellipse"),A(_i,"cacheProperties",[...pi,...jm]),A(_i,"ownDefaults",{rx:0,ry:0}),A(_i,"ATTRIBUTE_NAMES",[...hn,"cx","cy","rx","ry"]),z.setClass(_i),z.setSVGClass(_i);const y_=["left","top"],Nm={exactBoundingBox:!1};class Ss extends de{static getDefaults(){return T(T({},super.getDefaults()),Ss.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),A(this,"strokeDiff",void 0),Object.assign(this,Ss.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(ut,s),typeof i=="number"&&this.set(Re,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return sm(this.points,t,this.isOpen())}_calcDimensions(t){t=T({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(l=>l.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new M,strokeOffset:new M,strokeDiff:new M};const s=Hs(e),i=Xa(T(T({},t),{},{scaleX:1,scaleY:1})),n=Hs(this.points.map(l=>ce(l,i,!0))),r=new M(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(Dt(this.skewX)),h-=o*Math.tan(Dt(this.skewY))),T(T({},s),{},{pathOffset:new M(o,h),strokeOffset:new M(n.left,n.top).subtract(new M(s.left,s.top)).multiply(r),strokeDiff:new M(s.width,s.height).subtract(new M(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Hs(this.points);return new M(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:s,width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}=this._calcDimensions();this.set({width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}),t&&this.setPositionByOrigin(new M(e+i/2,s+n/2),J,J)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new M(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let r;if(Object.keys(t).some(o=>this.strokeUniform||this.constructor.layoutProperties.includes(o))){var e,s;const{width:o,height:h}=this._calcDimensions(t);r=new M((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new M((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new M(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const s=this.initialized&&this[t]!==e,i=super._set(t,e);return this.exactBoundingBox&&s&&((t===Ce||t===Ge)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),i}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),{},{points:this.points.map(e=>{let{x:s,y:i}=e;return{x:s,y:i}})})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,i=at.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(St(this.points[n].x-e,i),",",St(this.points[n].y-s,i)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
52
- `)]}_render(t){const e=this.points.length,s=this.pathOffset.x,i=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-i);for(let n=0;n<e;n++){const r=this.points[n];t.lineTo(r.x-s,r.y-i)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(v_(t.getAttribute("points")),T(T({},xt(bi(t,this.ATTRIBUTE_NAMES,s),y_)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}A(Ss,"ownDefaults",Nm),A(Ss,"type","Polyline"),A(Ss,"layoutProperties",[vo,yo,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),A(Ss,"cacheProperties",[...pi,"points"]),A(Ss,"ATTRIBUTE_NAMES",[...hn]),z.setClass(Ss),z.setSVGClass(Ss);class Tc extends Ss{isOpen(){return!1}}A(Tc,"ownDefaults",Nm),A(Tc,"type","Polygon"),z.setClass(Tc),z.setSVGClass(Tc);const Bm=["fontSize","fontWeight","fontFamily","fontStyle"],Hm=["underline","overline","linethrough"],Wm=[...Bm,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],zm=[...Wm,...Hm,"textBackgroundColor","direction"],__=[...Bm,...Hm,Ae,"strokeWidth",Rt,"deltaY","textBackgroundColor"],w_={_reNewline:fu,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:ut,fontStyle:"normal",lineHeight:1.16,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:ut,pathAlign:"baseline",_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.315,overline:-.88},_fontSizeMult:1.13,charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2},Xs="justify",Ec="justify-left",eh="justify-right",sh="justify-center";class Xm extends de{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const i in e[s])for(const n in e[s][i])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const i in s)for(const n in s[i])if(s[i][n][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,r=!0,o=0;for(const h in e){s=0;for(const l in e[h]){const d=e[h][l]||{};n++,d[t]!==void 0?(i?d[t]!==i&&(r=!1):i=d[t],d[t]===this[t]&&delete d[t]):r=!1,Object.keys(d).length!==0?s++:delete e[h][l]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)o+=this._textLines[h].length;r&&n===o&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],Object.keys(s[n]).length===0&&delete s[n];Object.keys(s).length===0&&delete e[i]}}_extendStyles(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const n=wu(T(T({},this._getStyleDeclaration(s,i)),e),r=>r!==void 0);this._setStyleDeclaration(s,i,n)}getSelectionStyles(t,e,s){const i=[];for(let n=t;n<(e||t);n++)i.push(this.getStyleAtPosition(n,s));return i}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,i):this._getStyleDeclaration(s,i)}setSelectionStyles(t,e,s){for(let i=e;i<(s||e);i++)this._extendStyles(i,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const i=this.styles&&this.styles[t];return i&&(s=i[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return T(T({},$n(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}A(Xm,"_styleProperties",__);const x_=/ +/g,S_=/"/g;function Zu(a,t,e,s,i){return" ".concat(function(n,r){let{left:o,top:h,width:l,height:d}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:at.NUM_FRACTION_DIGITS;const g=Ya(Rt,n,!1),[f,p,m,_]=[o,h,l,d].map(v=>St(v,u));return"<rect ".concat(g,' x="').concat(f,'" y="').concat(p,'" width="').concat(m,'" height="').concat(_,'"></rect>')}(a,{left:t,top:e,width:s,height:i}),`
53
- `)}const C_=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let tg;class ue extends Xm{static getDefaults(){return T(T({},super.getDefaults()),ue.ownDefaults)}constructor(t,e){super(),A(this,"__charBounds",[]),Object.assign(this,ue.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=$u(t.path))}_splitText(){const t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,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()),this.textAlign.includes(Xs)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,o;for(let h=0,l=this._textLines.length;h<l;h++)if((this.textAlign===Xs||h!==l-1&&!this.isEndOfWrapping(h))&&(i=0,n=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(o=this.textLines[h].match(this._reSpacesAndTabs)))){s=o.length,t=(this.width-e)/s;for(let d=0;d<=n.length;d++)r=this.__charBounds[h][d],this._reSpaceAndTab.test(n[d])?(r.width+=t,r.kernedWidth+=t,r.left+=i,i+=t):r.left+=i}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let i;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const 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(t){this.paintFirst===Ae?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,s){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case J:t.textBaseline="middle";break;case"ascender":t.textBaseline=Re;break;case"descender":t.textBaseline=gu}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,s,i,n,r){this._renderChars(t,e,s,i,n,r)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let i=this._getTopOffset();for(let n=0,r=this._textLines.length;n<r;n++){const o=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=o;continue}const h=this._textLines[n].length,l=this._getLineLeftOffset(n);let d,u,g=0,f=0,p=this.getValueOfPropertyAt(n,0,"textBackgroundColor");for(let m=0;m<h;m++){const _=this.__charBounds[n][m];u=this.getValueOfPropertyAt(n,m,"textBackgroundColor"),this.path?(t.save(),t.translate(_.renderLeft,_.renderTop),t.rotate(_.angle),t.fillStyle=u,u&&t.fillRect(-_.width/2,-o/this.lineHeight*(1-this._fontSizeFraction),_.width,o/this.lineHeight),t.restore()):u!==p?(d=s+l+f,this.direction==="rtl"&&(d=this.width-d-g),t.fillStyle=p,p&&t.fillRect(d,i,g,o/this.lineHeight),f=_.left,g=_.width,p=u):g+=_.kernedWidth}u&&!this.path&&(d=s+l+f,this.direction==="rtl"&&(d=this.width-d-g),t.fillStyle=u,t.fillRect(d,i,g,o/this.lineHeight)),i+=o}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=Ha.getFontCache(e),r=this._getFontDeclaration(e),o=s+t,h=s&&r===this._getFontDeclaration(i),l=e.fontSize/this.CACHE_FONT_SIZE;let d,u,g,f;if(s&&n[s]!==void 0&&(g=n[s]),n[t]!==void 0&&(f=d=n[t]),h&&n[o]!==void 0&&(u=n[o],f=u-g),d===void 0||g===void 0||u===void 0){const p=function(){if(!tg){const m=Ft();m.width=m.height=0,tg=m.getContext("2d")}return tg}();this._setTextStyles(p,e,!0),d===void 0&&(f=d=p.measureText(t).width,n[t]=d),g===void 0&&h&&s&&(g=p.measureText(s).width,n[s]=g),h&&u===void 0&&(u=p.measureText(o).width,n[o]=u,f=u-g)}return{width:d*l,kernedWidth:f*l}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,i=0;const n=this.pathSide===Lt,r=this.path,o=this._textLines[t],h=o.length,l=new Array(h);this.__charBounds[t]=l;for(let d=0;d<h;d++){const u=o[d];s=this._getGraphemeBox(u,t,d,e),l[d]=s,i+=s.kernedWidth,e=u}if(l[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let d=0;const u=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case ut:d=n?u-i:0;break;case J:d=(u-i)/2;break;case Lt:d=n?0:u-i}d+=this.pathStartOffset*(n?-1:1);for(let g=n?h-1:0;n?g>=0:g<h;n?g--:g++)s=l[g],d>u?d%=u:d<0&&(d+=u),this._setGraphemeOnPath(d,s),d+=s.kernedWidth}return{width:i,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,i=this.path,n=Tm(i.path,s,i.segmentsInfo);e.renderLeft=n.x-i.pathOffset.x,e.renderTop=n.y-i.pathOffset.y,e.angle=n.angle+(this.pathSide===Lt?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),o=i?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,r,i,o);let l,d=h.kernedWidth,u=h.width;this.charSpacing!==0&&(l=this._getWidthOfCharSpacing(),u+=l,d+=l);const g={width:u,left:0,height:r.fontSize,kernedWidth:d,deltaY:r.deltaY};if(s>0&&!n){const f=this.__charBounds[e][s-1];g.left=f.left+f.width+h.kernedWidth-h.width}return g}getHeightOfLine(t){if(this.__lineHeights[t])return this.__lineHeights[t];let e=this.getHeightOfChar(t,0);for(let s=1,i=this._textLines[t].length;s<i;s++)e=Math.max(this.getHeightOfChar(t,s),e);return this.__lineHeights[t]=e*this.lineHeight*this._fontSizeMult}calcTextHeight(){let t,e=0;for(let s=0,i=this._textLines.length;s<i;s++)t=this.getHeightOfLine(s),e+=s===i-1?t/this.lineHeight:t;return e}_getLeftOffset(){return this.direction==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const i=this._getLeftOffset(),n=this._getTopOffset();for(let r=0,o=this._textLines.length;r<o;r++){const h=this.getHeightOfLine(r),l=h/this.lineHeight,d=this._getLineLeftOffset(r);this._renderTextLine(e,t,this._textLines[r],i+d,n+s+l,r),s+=h}t.restore()}_renderTextFill(t){(this.fill||this.styleHas(Rt))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&this.strokeWidth!==0||!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(t,e,s,i,n,r){const o=this.getHeightOfLine(r),h=this.textAlign.includes(Xs),l=this.path,d=!h&&this.charSpacing===0&&this.isEmptyStyles(r)&&!l,u=this.direction==="ltr",g=this.direction==="ltr"?1:-1,f=e.direction;let p,m,_,v,x,S="",C=0;if(e.save(),f!==this.direction&&(e.canvas.setAttribute("dir",u?"ltr":"rtl"),e.direction=u?"ltr":"rtl",e.textAlign=u?ut:Lt),n-=o*this._fontSizeFraction/this.lineHeight,d)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let E=0,k=s.length-1;E<=k;E++)v=E===k||this.charSpacing||l,S+=s[E],_=this.__charBounds[r][E],C===0?(i+=g*(_.kernedWidth-_.width),C+=_.width):C+=_.kernedWidth,h&&!v&&this._reSpaceAndTab.test(s[E])&&(v=!0),v||(p=p||this.getCompleteStyleDeclaration(r,E),m=this.getCompleteStyleDeclaration(r,E+1),v=bc(p,m,!1)),v&&(l?(e.save(),e.translate(_.renderLeft,_.renderTop),e.rotate(_.angle),this._renderChar(t,e,r,E,S,-C/2,0),e.restore()):(x=i,this._renderChar(t,e,r,E,S,x,n)),S="",p=m,i+=g*C,C=0);e.restore()}_applyPatternGradientTransformText(t){const e=Ft(),s=this.width+this.strokeWidth,i=this.height+this.strokeWidth,n=e.getContext("2d");return e.width=s,e.height=i,n.beginPath(),n.moveTo(0,0),n.lineTo(s,0),n.lineTo(s,i),n.lineTo(0,i),n.closePath(),n.translate(s/2,i/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(e,"no-repeat")}handleFiller(t,e,s){let i,n;return ns(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(i=-this.width/2,n=-this.height/2,t.translate(i,n),t[e]=this._applyPatternGradientTransformText(s),{offsetX:i,offsetY:n}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:i}=e;return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,i,n,r,o){const h=this._getStyleDeclaration(s,i),l=this.getCompleteStyleDeclaration(s,i),d=t==="fillText"&&l.fill,u=t==="strokeText"&&l.stroke&&l.strokeWidth;if(u||d){if(e.save(),e.font=this._getFontDeclaration(l),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(o+=h.deltaY),d){const g=this._setFillStyles(e,l);e.fillText(n,r-g.offsetX,o-g.offsetY)}if(u){const g=this._setStrokeStyles(e,l);e.strokeText(n,r-g.offsetX,o-g.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,s){const i=this.get2DCursorLocation(t,!0),n=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"fontSize"),r=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"deltaY"),o={fontSize:n*s.size,deltaY:r+n*s.baseline};this.setSelectionStyles(o,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,i=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t);let o=0;return i===Xs||i===sh&&!r||i===eh&&!r||i===Ec&&!r?0:(i===J&&(o=s/2),i===Lt&&(o=s),i===sh&&(o=s/2),i===eh&&(o=s),n==="rtl"&&(i===Lt||i===Xs||i===eh?o=0:i===ut||i===Ec?o=-s:i!==J&&i!==sh||(o=-s/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var i;return(i=this._getStyleDeclaration(t,e)[s])!==null&&i!==void 0?i:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const i=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),o=this.offsets[e];for(let h=0,l=this._textLines.length;h<l;h++){const d=this.getHeightOfLine(h);if(!this[e]&&!this.styleHas(e,h)){s+=d;continue}const u=this._textLines[h],g=d/this.lineHeight,f=this._getLineLeftOffset(h);let p,m,_=0,v=0,x=this.getValueOfPropertyAt(h,0,e),S=this.getValueOfPropertyAt(h,0,Rt);const C=s+g*(1-this._fontSizeFraction);let E=this.getHeightOfChar(h,0),k=this.getValueOfPropertyAt(h,0,"deltaY");for(let D=0,F=u.length;D<F;D++){const B=this.__charBounds[h][D];p=this.getValueOfPropertyAt(h,D,e),m=this.getValueOfPropertyAt(h,D,Rt);const O=this.getHeightOfChar(h,D),R=this.getValueOfPropertyAt(h,D,"deltaY");if(n&&p&&m)t.save(),t.fillStyle=S,t.translate(B.renderLeft,B.renderTop),t.rotate(B.angle),t.fillRect(-B.kernedWidth/2,o*O+R,B.kernedWidth,this.fontSize/15),t.restore();else if((p!==x||m!==S||O!==E||R!==k)&&v>0){let L=i+f+_;this.direction==="rtl"&&(L=this.width-L-v),x&&S&&(t.fillStyle=S,t.fillRect(L,C+o*E+k,v,this.fontSize/15)),_=B.left,v=B.width,x=p,S=m,E=O,k=R}else v+=B.kernedWidth}let P=i+f+_;this.direction==="rtl"&&(P=this.width-P-v),t.fillStyle=m,p&&m&&t.fillRect(P,C+o*E+k,v-r,this.fontSize/15),s+=d}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||ue.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return mc(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
54
- `];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject([...zm,...t])),{},{styles:nm(this.styles,this.text)},this.path?{path:this.path.toObject()}:{})}set(t,e){const{textLayoutProperties:s}=this.constructor;super.set(t,e);let i=!1,n=!1;if(typeof t=="object")for(const r in t)r==="path"&&this.setPathInfo(),i=i||s.includes(r),n=n||r==="path";else i=s.includes(t),n=t==="path";return n&&this.setPathInfo(),i&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,s){const i=bi(t,ue.ATTRIBUTE_NAMES,s),n=T(T({},e),i),{textAnchor:r=ut,textDecoration:o="",dx:h=0,dy:l=0,top:d=0,left:u=0,fontSize:g=uu,strokeWidth:f=1}=n,p=xt(n,C_),m=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),T({left:u+h,top:d+l,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:g},p)),_=m.getScaledHeight()/m.height,v=((m.height+m.strokeWidth)*m.lineHeight-m.height)*_,x=m.getScaledHeight()+v;let S=0;return r===J&&(S=m.getScaledWidth()/2),r===Lt&&(S=m.getScaledWidth()),m.set({left:m.left-S,top:m.top-(x-m.fontSize*(.07+m._fontSizeFraction))/m.lineHeight,strokeWidth:f}),m}static fromObject(t){return this._fromObject(T(T({},t),{},{styles:rm(t.styles||{},t.text)}),{extraParam:"text"})}}A(ue,"textLayoutProperties",Wm),A(ue,"cacheProperties",[...pi,...zm]),A(ue,"ownDefaults",w_),A(ue,"type","Text"),A(ue,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),A(ue,"ATTRIBUTE_NAMES",hn.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Jp(ue,[class extends Pp{_toSVG(){const a=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(a.textTop,a.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(a){return this._createBaseSVGMarkup(this._toSVG(),{reviver:a,noStyle:!0,withShadow:!0})}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(a){let{textBgRects:t,textSpans:e}=a;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ',this.fontFamily?'font-family="'.concat(this.fontFamily.replace(S_,"'"),'" '):"",this.fontSize?'font-size="'.concat(this.fontSize,'" '):"",this.fontStyle?'font-style="'.concat(this.fontStyle,'" '):"",this.fontWeight?'font-weight="'.concat(this.fontWeight,'" '):"",s?'text-decoration="'.concat(s,'" '):"",this.direction==="rtl"?'direction="'.concat(this.direction,'" '):"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
55
- `]}_getSVGTextAndBg(a,t){const e=[],s=[];let i,n=a;this.backgroundColor&&s.push(...Zu(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let r=0,o=this._textLines.length;r<o;r++)i=this._getLineLeftOffset(r),this.direction==="rtl"&&(i+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",r))&&this._setSVGTextLineBg(s,r,t+i,n),this._setSVGTextLineText(e,r,t+i,n),n+=this.getHeightOfLine(r);return{textSpans:e,textBgRects:s}}_createTextCharSpan(a,t,e,s){const i=this.getSvgSpanStyles(t,a!==a.trim()||!!a.match(x_)),n=i?'style="'.concat(i,'"'):"",r=t.deltaY,o=r?' dy="'.concat(St(r,at.NUM_FRACTION_DIGITS),'" '):"";return'<tspan x="'.concat(St(e,at.NUM_FRACTION_DIGITS),'" y="').concat(St(s,at.NUM_FRACTION_DIGITS),'" ').concat(o).concat(n,">").concat(im(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Xs),r=this._textLines[t];let o,h,l,d,u,g="",f=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let p=0,m=r.length-1;p<=m;p++)u=p===m||this.charSpacing,g+=r[p],l=this.__charBounds[t][p],f===0?(e+=l.kernedWidth-l.width,f+=l.width):f+=l.kernedWidth,n&&!u&&this._reSpaceAndTab.test(r[p])&&(u=!0),u||(o=o||this.getCompleteStyleDeclaration(t,p),h=this.getCompleteStyleDeclaration(t,p+1),u=bc(o,h,!0)),u&&(d=this._getStyleDeclaration(t,p),a.push(this._createTextCharSpan(g,d,e,s)),g="",o=h,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(a,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,o=0,h=0,l=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let d=0;d<i.length;d++){const{left:u,width:g,kernedWidth:f}=this.__charBounds[t][d];r=this.getValueOfPropertyAt(t,d,"textBackgroundColor"),r!==l?(l&&a.push(...Zu(l,e+h,s,o,n)),h=u,o=g,l=r):o+=f}r&&a.push(...Zu(l,e+h,s,o,n))}_getSVGLineTopOffset(a){let t,e=0;for(t=0;t<a;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(a){return"".concat(super.getSvgStyles(a)," white-space: pre;")}getSvgSpanStyles(a,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:o,fontWeight:h,deltaY:l}=a,d=this.getSvgTextDecoration(a);return[i?Ya(Ae,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",o?"font-style: ".concat(o,"; "):"",h?"font-weight: ".concat(h,"; "):"",d&&"text-decoration: ".concat(d,"; "),n?Ya(Rt,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter(t=>a[t.replace("-","")]).join(" ")}}]),z.setClass(ue),z.setSVGClass(ue);class A_{constructor(t){A(this,"target",void 0),A(this,"__mouseDownInPlace",!1),A(this,"__dragStartFired",!1),A(this,"__isDraggingOver",!1),A(this,"__dragStartSelection",void 0),A(this,"__dragImageDisposer",void 0),A(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(s=>s()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,o=r.canvas,h=new M(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),d=new M(l.left+l.leftOffset,l.top+l.topOffset).multiply(h).transform(r.calcTransformMatrix()),u=o.getScenePoint(t).subtract(d),g=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),p=d.subtract(new M(f.left,f.top)),m=o.viewportTransform,_=p.add(u).transform(m,!0),v=r.backgroundColor,x=zu(r.styles);r.backgroundColor="";const S={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(S,0,i),r.setSelectionStyles(S,n,r.text.length),r.dirty=!0;const C=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=v,r.styles=x,r.dirty=!0,Sc(C,{position:"fixed",left:"".concat(-C.width,"px"),border:Se,width:"".concat(C.width/g,"px"),height:"".concat(C.height/g,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{C.remove()},vs(t.target||this.target.hiddenTextarea).body.appendChild(C),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(C,_.x,_.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=T({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,o=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},d=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const g=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;h>g&&h<=f?h=g:h>f&&(h-=f-g),r.removeChars(g,f),delete this.__dragStartSelection}r._reNewline.test(d)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,l,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+u,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(Ql,{index:h+u,action:"drop"}),o.fire("text:changed",{target:r}),o.contextTopDirty=!0,o.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:o}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||Se;h===Se?(i.selectionStart=r,i.selectionEnd=o,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),h==="move"&&(i.removeChars(r,o),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(Ql,{index:r,action:"dragend"}),n.fire("text:changed",{target:i}),n.requestRenderAll()),i.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}const Vm=/[ \n\.,;!\?\-]/;class T_ extends ue{constructor(){super(...arguments),A(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return Bu({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:i,onComplete:n,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:r=>{this._currentCursorOpacity=r,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;(t=this._currentTickCompleteState)===null||t===void 0||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,s=t-1;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s--;for(;/\S/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findWordBoundaryRight(t){let e=0,s=t;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s++;for(;/\S/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}findLineBoundaryLeft(t){let e=0,s=t-1;for(;!/\n/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findLineBoundaryRight(t){let e=0,s=t;for(;!/\n/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}searchWordBoundary(t,e){const s=this._text;let i=t>0&&this._reSpace.test(s[t])&&(e===-1||!fu.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!Vm.test(n);)i+=e,n=s[i];return e===-1&&Vm.test(n)&&i++,i}selectWord(t){t=t||this.selectionStart;const e=this.searchWordBoundary(t,-1),s=Math.max(e,this.searchWordBoundary(t,1));this.selectionStart=e,this.selectionEnd=s,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){t=t||this.selectionStart;const e=this.findLineBoundaryLeft(t),s=this.findLineBoundaryRight(t);return this.selectionStart=e,this.selectionEnd=s,this._fireSelectionChanged(),this._updateTextarea(),this}enterEditing(t){!this.isEditing&&this.editable&&(this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;vs(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&i!==n||i!==s&&n!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){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(t,e,s){const i=s.slice(0,t),n=this.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=s.slice(t,e);return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,s){const i=s.slice(0,t).join("").length;return t===e?{selectionStart:i,selectionEnd:i}:{selectionStart:i,selectionEnd:i+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex,r=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,o=e.leftOffset,h=this.getCanvasRetinaScaling(),l=this.canvas.upperCanvasEl,d=l.width/h,u=l.height/h,g=d-r,f=u-r,p=new M(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new M(l.clientWidth/d,l.clientHeight/u));return p.x<0&&(p.x=0),p.x>g&&(p.x=g),p.y<0&&(p.y=0),p.y>f&&(p.y=f),p.x+=this.canvas._offset.left,p.y+=this.canvas._offset.top,{left:"".concat(p.x,"px"),top:"".concat(p.y,"px"),fontSize:"".concat(r,"px"),charHeight:r}}_saveEditingProps(){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(){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.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditing(){const t=this._textBeforeEdit!==this.text;return this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire(Zl),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let o=i;o<this._unwrappedTextLines[s].length;o++)delete this.styles[s][o];if(this.styles[n])for(let o=r;o<this._unwrappedTextLines[n].length;o++){const h=this.styles[n][o];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=h)}for(let o=s+1;o<=n;o++)delete this.styles[o];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const o=this.styles[s],h=r-i;for(let l=i;l<r;l++)delete o[l];for(const l in this.styles[s]){const d=parseInt(l,10);d>=r&&(o[d-h]=o[l],delete o[l])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const g=parseInt(u,10);g>=e&&(h=!0,n[g-e]=this.styles[t][u],o&&e===0||delete this.styles[t][u])}let d=!1;for(h&&!o&&(this.styles[t+s]=n,d=!0),(d||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:T({},i[s-1])}:l?this.styles[t+s]={0:T({},l)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?T({},n):{};s||(s=1);for(const h in r){const l=parseInt(h,10);l>=e&&(n[l+s]=r[l],r[l-s]||delete n[l])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=T({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=T({},o)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let h=0;h<t.length;h++)t[h]===`
56
- `?(o++,n[o]=0):n[o]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),o&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],o),r=1;r<o;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=ut:this._selectionDirection===Lt&&(this._selectionDirection=ut,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Lt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Lt:this._selectionDirection===ut&&(this._selectionDirection=Lt,this.selectionStart=e),this.selectionEnd=s)}}class E_ extends T_{initHiddenTextarea(){const t=this.canvas&&vs(this.canvas.getElement())||bo(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off"}).map(r=>{let[o,h]=r;return e.setAttribute(o,h)});const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(i,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(n,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map(r=>{let[o,h]=r;return e.addEventListener(o,this[h].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?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(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(t){const e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const s=()=>{this.updateFromTextArea(),this.fire(Ql),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void s();const i=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,n=this._text.length,r=i.length,o=this.selectionStart,h=this.selectionEnd,l=o!==h;let d,u,g,f,p=r-n;const m=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=o>m.selectionStart;l?(u=this._text.slice(o,h),p+=h-o):r<n&&(u=_?this._text.slice(h+p,h):this._text.slice(o,o-p));const v=i.slice(m.selectionEnd-p,m.selectionEnd);if(u&&u.length&&(v.length&&(d=this.getSelectionStyles(o,o+1,!1),d=v.map(()=>d[0])),l?(g=o,f=h):_?(g=h-u.length,f=h):(g=h,f=h+u.length),this.removeStyleFromTo(g,f)),v.length){const{copyPasteData:x}=Bs();e&&v.join("")===x.copiedText&&!at.disableStyleCopyPaste&&(d=x.copiedTextStyle),this.insertNewStyleBlock(v,o,d)}s()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:s,selectionEnd:i}=e;this.compositionStart=s,this.compositionEnd=i,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=Bs();t.copiedText=this.getSelectedText(),at.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,r),d=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-l.length+(1-d)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,l=s.length;h<l;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const d=r-i,u=r,g=Math.abs(d-e);o=Math.abs(u-e)<g?h:h-1;break}return n||(o=s.length-1),o}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===Lt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=Jn(0,this.selectionStart,i),this.selectionEnd=Jn(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===ut?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let i;if(t.altKey)i=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this["findLineBoundary".concat(s)](this[e])}return i!==void 0&&this[e]!==i&&(this[e]=i,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=ut,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Lt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=ut,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===ut&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Lt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Lt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const eg=a=>!!a.button;class k_ extends E_{constructor(){super(...arguments),A(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler),this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown),this.draggableTextDelegate=new A_(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}onMouseDown(t){if(!this.canvas)return;this.__newClickTime=+new Date;const e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),Au(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastSelected=this.selected&&!this.getActiveControl()}isTripleClick(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y}doubleClickHandler(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))}tripleClickHandler(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))}_mouseDownHandler(t){let{e}=t;this.canvas&&this.editable&&!eg(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection())))}_mouseDownHandlerBefore(t){let{e}=t;this.canvas&&this.editable&&!eg(e)&&(this.selected=this===this.canvas._activeObject)}mouseUpHandler(t){let{e,transform:s}=t;const i=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const n=this.canvas._activeObject;if(n&&n!==this)return}!this.editable||this.group&&!this.group.interactive||s&&s.actionPerformed||eg(e)||i||(this.__lastSelected&&!this.getActiveControl()?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0)}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),s=this.selectionStart,i=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(s,i,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(Fe(this.calcTransformMatrix())).add(new M(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let l=0;l<this._textLines.length&&s<=e.y;l++)s+=this.getHeightOfLine(l),n=l,l>0&&(i+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));let r=Math.abs(this._getLineLeftOffset(n));const o=this._textLines[n].length,h=this.__charBounds[n];for(let l=0;l<o;l++){const d=r+h[l].kernedWidth;if(e.x<=d){Math.abs(e.x-d)<=Math.abs(e.x-r)&&i++;break}r=d,i++}return Math.min(this.flipX?o-i:i,this._text.length)}}const kc="moveCursorUp",Mc="moveCursorDown",Oc="moveCursorLeft",Dc="moveCursorRight",Pc="exitEditing",M_=T({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,keysMap:{9:Pc,27:Pc,33:kc,34:Mc,35:Dc,36:Oc,37:Oc,38:kc,39:Dc,40:Mc},keysMapRtl:{9:Pc,27:Pc,33:kc,34:Mc,35:Oc,36:Dc,37:Dc,38:kc,39:Oc,40:Mc},ctrlKeysMapDown:{65:"selectAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class wi extends k_{static getDefaults(){return T(T({},super.getDefaults()),wi.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,T(T({},wi.ownDefaults),e)),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):(t==="canvas"&&(this.canvas instanceof Ku&&this.canvas.textEditingManager.remove(this),e instanceof Ku&&e.textEditingManager.add(this)),super._set(t,e))}setSelectionStart(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)}setSelectionEnd(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)}_updateAndFire(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()}_fireSelectionChanged(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart||0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionEnd,s=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,s)}setSelectionStyles(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionStart||0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,s)}get2DCursorLocation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const s=super.toCanvasElement(t);return this.isEditing=e,s}renderCursorOrSelection(){if(!this.isEditing)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries();this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),this.canvas.contextTopDirty=!0,t.restore()}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:s,top:i,leftOffset:n.left,topOffset:n.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:i,lineIndex:n}=this.get2DCursorLocation(t);for(let l=0;l<n;l++)e+=this.getHeightOfLine(l);const r=this._getLineLeftOffset(n),o=this.__charBounds[n][i];o&&(s=o.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===Lt||this.textAlign===Xs||this.textAlign===eh?h.left*=-1:this.textAlign===ut||this.textAlign===Ec?h.left=r-(s>0?s:0):this.textAlign!==J&&this.textAlign!==sh||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){const e=this._getCursorBoundaries(t,!0);this._renderCursor(this.canvas.contextTop,e,t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}_renderCursor(t,e,s){const i=this.get2DCursorLocation(s),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,o=this.getValueOfPropertyAt(n,r,"fontSize"),h=this.getObjectScaling().x*this.canvas.getZoom(),l=this.cursorWidth/h,d=this.getValueOfPropertyAt(n,r,"deltaY"),u=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-o*(1-this._fontSizeFraction);this.inCompositionMode&&this.renderSelection(t,e),t.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,Rt),t.globalAlpha=this._currentCursorOpacity,t.fillRect(e.left+e.leftOffset-l/2,u+e.top+d,l,o)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const i=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(Xs),o=this.get2DCursorLocation(i),h=this.get2DCursorLocation(n),l=o.lineIndex,d=h.lineIndex,u=o.charIndex<0?0:o.charIndex,g=h.charIndex<0?0:h.charIndex;for(let f=l;f<=d;f++){const p=this._getLineLeftOffset(f)||0;let m=this.getHeightOfLine(f),_=0,v=0,x=0;if(f===l&&(v=this.__charBounds[l][u].left),f>=l&&f<d)x=r&&!this.isEndOfWrapping(f)?this.width:this.getLineWidth(f)||5;else if(f===d)if(g===0)x=this.__charBounds[d][g].left;else{const P=this._getWidthOfCharSpacing();x=this.__charBounds[d][g-1].left+this.__charBounds[d][g-1].width-P}_=m,(this.lineHeight<1||f===d&&this.lineHeight>1)&&(m/=this.lineHeight);let S=s.left+p+v,C=m,E=0;const k=x-v;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",C=1,E=m):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Lt||this.textAlign===Xs||this.textAlign===eh?S=this.width-S-k:this.textAlign===ut||this.textAlign===Ec?S=s.left+p-x:this.textAlign!==J&&this.textAlign!==sh||(S=s.left+p-x)),t.fillRect(S,s.top+s.topOffset+E,k,C),s.topOffset+=_}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,Rt)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this._exitEditing(),this.draggableTextDelegate.dispose(),super.dispose()}}A(wi,"ownDefaults",M_),A(wi,"type","IText"),z.setClass(wi),z.setClass(wi,"i-text");class sr extends wi{static getDefaults(){return T(T({},super.getDefaults()),sr.ownDefaults)}constructor(t,e){super(t,T(T({},sr.ownDefaults),e))}static createControls(){return{controls:gy()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this.textAlign.includes(Xs)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,i=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)t.graphemeText[i]===`
57
- `&&r>0?(s=0,i++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[i])&&r>0&&(s++,i++),n[r]={line:e,offset:s},i+=t.graphemeLines[r].length,s+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,i=t+1,n=!1;const r=this._styleMap[t],o=this._styleMap[t+1];r&&(t=r.line,s=r.offset),o&&(i=o.line,n=i===t,e=o.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const l in h)for(const d in h[l]){const u=parseInt(d,10);if(u>=s&&(!n||u<e))for(const g in h[l][d])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const i=this._styleMap[t];super._setStyleDeclaration(i.line,i.offset+e,s)}_deleteStyleDeclaration(t,e){const s=this._styleMap[t];super._deleteStyleDeclaration(s.line,s.offset+e)}_getLineStyle(t){const e=this._styleMap[t];return!!this.styles[e.line]}_setLineStyle(t){const e=this._styleMap[t];super._setLineStyle(e.line)}_wrapText(t,e){this.isWrapping=!0;const s=this.getGraphemeDataForRender(t),i=[];for(let n=0;n<s.wordsData.length;n++)i.push(...this._wrapLine(n,e,s));return this.isWrapping=!1,i}getGraphemeDataForRender(t){const e=this.splitByGrapheme,s=e?"":" ";let i=0;return{wordsData:t.map((n,r)=>{let o=0;const h=e?this.graphemeSplit(n):this.wordSplit(n);return h.length===0?[{word:[],width:0}]:h.map(l=>{const d=e?[l]:this.graphemeSplit(l),u=this._measureWord(d,r,o);return i=Math.max(u,i),o+=d.length+s.length,{word:d,width:u}})}),largestWordWidth:i}}_measureWord(t,e){let s,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,n=0;for(let r=0,o=t.length;r<o;r++)n+=this._getGraphemeBox(t[r],e,r+i,s,!0).kernedWidth,s=t[r];return n}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:i,wordsData:n}=s,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const o=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,l=[],d=h?"":" ";let u=0,g=[],f=0,p=0,m=!0;e-=r;const _=Math.max(e,i,this.dynamicMinWidth),v=n[t];let x;for(f=0,x=0;x<v.length;x++){const{word:S,width:C}=v[x];f+=S.length,u+=p+C-o,u>_&&!m?(l.push(g),g=[],u=C,m=!0):u+=o,m||h||g.push(d),g=g.concat(S),p=h?0:this._measureWord([d],t,f),f++,m=!1}return x&&l.push(g),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),l}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}A(sr,"type","Textbox"),A(sr,"textLayoutProperties",[...wi.textLayoutProperties,"width"]),A(sr,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),z.setClass(sr);class Gm extends wc{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:s}=t,{clipPath:i,group:n}=s;if(!i||!this.shouldPerformLayout(t))return;const{width:r,height:o}=Hs(pm(s,i)),h=new M(r,o);if(i.absolutePositioned)return{center:Qn(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:h};{const l=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:d=new M,correction:u=new M}=this.calcBoundingBox(e,t)||{};return{center:d.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}A(Gm,"type","clip-path"),z.setClass(Gm);class Um extends wc{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new M(s.width||i.x,s.height||i.y)}}A(Um,"type","fixed"),z.setClass(Um);class O_ extends Ja{subscribeTargets(t){const e=t.target;t.targets.reduce((s,i)=>(i.parent&&s.add(i.parent),s),new Set).forEach(s=>{s.layoutManager.subscribeTargets({target:s,targets:[e]})})}unsubscribeTargets(t){const e=t.target,s=e.getObjects();t.targets.reduce((i,n)=>(n.parent&&i.add(n.parent),i),new Set).forEach(i=>{!s.some(n=>n.parent===i)&&i.layoutManager.unsubscribeTargets({target:i,targets:[e]})})}}class ir extends zs{static getDefaults(){return T(T({},super.getDefaults()),ir.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,ir.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new O_})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];this.multiSelectionStacking==="selection-order"?this.add(...e):e.forEach(i=>{const n=this._objects.findIndex(o=>o.isInFrontOf(i)),r=n===-1?this.size():n;this.insertAt(r,i)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(ui("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);const s=new Set;e.forEach(i=>{const{parent:n}=i;n&&s.add(n)}),t===Gu?s.forEach(i=>{i._onAfterObjectsChange(yc,e)}):s.forEach(i=>{i._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=T(T({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}A(ir,"type","ActiveSelection"),A(ir,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),z.setClass(ir),z.setClass(ir,"activeSelection");class D_{constructor(){A(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const o={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach(l=>{l.applyTo(o)});const{imageData:h}=o;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),o}}class Ym{constructor(){let{tileSize:t=at.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};A(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),A(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=Ft();s.width=t,s.height=e;const i=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});i&&(i.clearColor(0,0,0,0),this.canvas=s,this.gl=i)}applyFilters(t,e,s,i,n,r){const o=this.gl,h=n.getContext("2d");if(!o||!h)return;let l;r&&(l=this.getCachedTexture(r,e));const d={originalWidth:e.width||e.originalWidth||0,originalHeight:e.height||e.originalHeight||0,sourceWidth:s,sourceHeight:i,destinationWidth:s,destinationHeight:i,context:o,sourceTexture:this.createTexture(o,s,i,l?void 0:e),targetTexture:this.createTexture(o,s,i),originalTexture:l||this.createTexture(o,s,i,l?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),t.forEach(g=>{g&&g.applyTo(d)}),function(g){const f=g.targetCanvas,p=f.width,m=f.height,_=g.destinationWidth,v=g.destinationHeight;p===_&&m===v||(f.width=_,f.height=v)}(d),this.copyGLTo2D(o,d),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(d.sourceTexture),o.deleteTexture(d.targetTexture),o.deleteFramebuffer(u),h.setTransform(1,0,0,1,0,0),d}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,s,i,n){const{NEAREST:r,TEXTURE_2D:o,RGBA:h,UNSIGNED_BYTE:l,CLAMP_TO_EDGE:d,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:g,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:p}=t,m=t.createTexture();return t.bindTexture(o,m),t.texParameteri(o,u,n||r),t.texParameteri(o,g,n||r),t.texParameteri(o,f,d),t.texParameteri(o,p,d),i?t.texImage2D(o,0,h,h,l,i):t.texImage2D(o,0,h,e,s,0,h,l,null),m}getCachedTexture(t,e,s){const{textureCache:i}=this;if(i[t])return i[t];{const n=this.createTexture(this.gl,e.width,e.height,e,s);return n&&(i[t]=n),n}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const s=t.canvas,i=e.targetCanvas,n=i.getContext("2d");if(!n)return;n.translate(0,i.height),n.scale(1,-1);const r=s.height-i.height;n.drawImage(s,0,r,i.width,i.height,0,0,i.width,i.height)}copyGLTo2DPutImageData(t,e){const s=e.targetCanvas.getContext("2d"),i=e.destinationWidth,n=e.destinationHeight,r=i*n*4;if(!s)return;const o=new Uint8Array(this.imageBuffer,0,r),h=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,o);const l=new ImageData(h,i,n);s.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let sg;function P_(){const{WebGLProbe:a}=Bs();return a.queryWebGL(Ft()),at.enableGLFiltering&&a.isSupported(at.textureSize)?new Ym({tileSize:at.textureSize}):new D_}function ig(){return!sg&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(sg=P_()),sg}const L_=["filters","resizeFilter","src","crossOrigin","type"],qm=["cropX","cropY"];class ge extends de{static getDefaults(){return T(T({},super.getDefaults()),ge.ownDefaults)}constructor(t,e){super(),A(this,"_lastScaleX",1),A(this,"_lastScaleY",1),A(this,"_filterScalingX",1),A(this,"_filterScalingY",1),this.filters=[],Object.assign(this,ge.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(on()),this.setElement(typeof t=="string"?(this.canvas&&vs(this.canvas.getElement())||bo()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(e),t.classList.add(ge.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=ig(!1);e instanceof Ym&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{const e=this[t];e&&Bs().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach(s=>{s&&e.push(s.toObject())}),T(T({},super.toObject([...qm,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,i=-this.height/2;let n=[],r=[],o="",h="";if(!e)return[];if(this.hasCrop()){const l=on();n.push('<clipPath id="imageCrop_'+l+`">
58
- `,' <rect x="'+s+'" y="'+i+'" width="'+this.width+'" height="'+this.height+`" />
59
- `,`</clipPath>
60
- `),o=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(h=' image-rendering="optimizeSpeed"'),t.push(" <image ","COMMON_PARTS",'xlink:href="'.concat(this.getSvgSrc(!0),'" x="').concat(s-this.cropX,'" y="').concat(i-this.cropY,'" width="').concat(e.width||e.naturalWidth,'" height="').concat(e.height||e.naturalHeight,'"').concat(h).concat(o,`></image>
61
- `)),this.stroke||this.strokeDashArray){const l=this.fill;this.fill=null,r=[' <rect x="'.concat(s,'" y="').concat(i,'" width="').concat(this.width,'" height="').concat(this.height,'" style="').concat(this.getSvgStyles(),`" />
62
- `)],this.fill=l}return n=this.paintFirst!==Rt?n.concat(r,t):n.concat(t,r),n}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Va(t,{crossOrigin:e,signal:s}).then(i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)})}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),i=s.x,n=s.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||i>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=i,void(this._lastScaleY=n);const o=Ft(),h=r.width,l=r.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,ig().applyFilters([t],r,h,l,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter(n=>n&&!n.isNeutralState()),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){const n=Ft();n.width=s,n.height=i,this._element=n,this._filteredEl=n}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,s,i),this._lastScaleX=1,this._lastScaleY=1);ig().applyFilters(t,this._originalElement,s,i,this._element),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)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,i=this._filterScalingY,n=this.width,r=this.height,o=Math.max(this.cropX,0),h=Math.max(this.cropY,0),l=e.naturalWidth||e.width,d=e.naturalHeight||e.height,u=o*s,g=h*i,f=Math.min(n*s,l-u),p=Math.min(r*i,d-g),m=-n/2,_=-r/2,v=Math.min(n,l/s-o),x=Math.min(r,d/i-h);e&&t.drawImage(e,u,g,f,p,m,_,v,x)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=Su(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,o=this._element.height,h=1,l=1,d=0,u=0,g=0,f=0;return!t||t.alignX===Se&&t.alignY===Se?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=bm(this._element,i),n=(e-r*h)/2,t.alignX==="Min"&&(d=-n),t.alignX==="Max"&&(d=n),n=(s-o*l)/2,t.alignY==="Min"&&(u=-n),t.alignY==="Max"&&(u=n)),t.meetOrSlice==="slice"&&(h=l=vm(this._element,i),n=r-e/h,t.alignX==="Mid"&&(g=n/2),t.alignX==="Max"&&(g=n),n=o-s/l,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/h,o=s/l)),{width:r,height:o,scaleX:h,scaleY:l,offsetLeft:d,offsetTop:u,cropX:g,cropY:f}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:o}=t,h=xt(t,L_);return Promise.all([Va(n,T(T({},e),{},{crossOrigin:r})),s&&So(s,e),i&&So([i],e),Ga(h,e)]).then(l=>{let[d,u=[],[g]=[],f={}]=l;return new this(d,T(T({},h),{},{src:n,filters:u,resizeFilter:g},f))})}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;return Va(t,{crossOrigin:e,signal:s}).then(n=>new this(n,i))}static async fromElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;const i=bi(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"],e,i).catch(n=>(ui("log","Unable to parse Image",n),null))}}function ng(a){if(!Nv.test(a.nodeName))return{};const t=a.getAttribute("viewBox");let e,s,i=1,n=1,r=0,o=0;const h=a.getAttribute("width"),l=a.getAttribute("height"),d=a.getAttribute("x")||0,u=a.getAttribute("y")||0,g=!(t&&Fp.test(t)),f=!h||!l||h==="100%"||l==="100%";let p="",m=0,_=0;if(g&&(d||u)&&a.parentNode&&a.parentNode.nodeName!=="#document"&&(p=" translate("+Te(d||"0")+" "+Te(u||"0")+") ",e=(a.getAttribute("transform")||"")+p,a.setAttribute("transform",e),a.removeAttribute("x"),a.removeAttribute("y")),g&&f)return{width:0,height:0};const v={width:0,height:0};if(g)return v.width=Te(h),v.height=Te(l),v;const x=t.match(Fp);r=-parseFloat(x[1]),o=-parseFloat(x[2]);const S=parseFloat(x[3]),C=parseFloat(x[4]);v.minX=r,v.minY=o,v.viewBoxWidth=S,v.viewBoxHeight=C,f?(v.width=S,v.height=C):(v.width=Te(h),v.height=Te(l),i=v.width/S,n=v.height/C);const E=Su(a.getAttribute("preserveAspectRatio")||"");if(E.alignX!==Se&&(E.meetOrSlice==="meet"&&(n=i=i>n?n:i),E.meetOrSlice==="slice"&&(n=i=i>n?i:n),m=v.width-S*i,_=v.height-C*i,E.alignX==="Mid"&&(m/=2),E.alignY==="Mid"&&(_/=2),E.alignX==="Min"&&(m=0),E.alignY==="Min"&&(_=0)),i===1&&n===1&&r===0&&o===0&&d===0&&u===0)return v;if((d||u)&&a.parentNode.nodeName!=="#document"&&(p=" translate("+Te(d||"0")+" "+Te(u||"0")+") "),e=p+" matrix("+i+" 0 0 "+n+" "+(r*i+m)+" "+(o*n+_)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(Mu,"g");a.firstChild;)s.appendChild(a.firstChild);a.appendChild(s)}else s=a,s.removeAttribute("x"),s.removeAttribute("y"),e=s.getAttribute("transform")+e;return s.setAttribute("transform",e),v}A(ge,"type","Image"),A(ge,"cacheProperties",[...pi,...qm]),A(ge,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),A(ge,"CSS_CANVAS","canvas-img"),A(ge,"ATTRIBUTE_NAMES",[...hn,"x","y","width","height","preserveAspectRatio","xlink:href","crossOrigin","image-rendering"]),z.setClass(ge),z.setSVGClass(ge);const Lc=a=>a.tagName.replace("svg:",""),R_=hc(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function $m(a,t){let e,s,i,n,r=[];for(i=0,n=t.length;i<n;i++)e=t[i],s=a.getElementsByTagNameNS("http://www.w3.org/2000/svg",e),r=r.concat(Array.from(s));return r}const F_=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],rg="xlink:href";function Km(a,t){var e;const s=((e=t.getAttribute(rg))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(rg)&&Km(a,i),i&&(F_.forEach(n=>{const r=i.getAttribute(n);!t.hasAttribute(n)&&r&&t.setAttribute(n,r)}),!t.children.length)){const n=i.cloneNode(!0);for(;n.firstChild;)t.appendChild(n.firstChild)}t.removeAttribute(rg)}const I_=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function j_(a){const t=a.getElementsByTagName("style");let e,s;const i={};for(e=0,s=t.length;e<s;e++){const n=(t[e].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");n.trim()!==""&&n.split("}").filter((r,o,h)=>h.length>1&&r.trim()).forEach(r=>{if((r.match(/{/g)||[]).length>1&&r.trim().startsWith("@"))return;const o=r.split("{"),h={},l=o[1].trim().split(";").filter(function(d){return d.trim()});for(e=0,s=l.length;e<s;e++){const d=l[e].split(":"),u=d[0].trim(),g=d[1].trim();h[u]=g}(r=o[0].trim()).split(",").forEach(d=>{(d=d.replace(/^svg/i,"").trim())!==""&&(i[d]=T(T({},i[d]||{}),h))})})}return i}const Qm=a=>z.getSVGClass(Lc(a).toLowerCase());class N_{constructor(t,e,s,i,n){this.elements=t,this.options=e,this.reviver=s,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=i,this.clipPaths=n,this.gradientDefs=function(r){const o=$m(r,I_),h={};let l=o.length;for(;l--;){const d=o[l];d.getAttribute("xlink:href")&&Km(r,d);const u=d.getAttribute("id");u&&(h[u]=d)}return h}(i),this.cssRules=j_(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=Qm(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,Rt),this.resolveGradient(s,t,Ae),s instanceof ge&&s._originalElement?Cc(s,s.parsePreserveAspectRatioAttribute()):Cc(s),await this.resolveClipPath(s,t),this.reviver&&this.reviver(t,s),s}return null}extractPropertyDefinition(t,e,s){const i=t[e],n=this.regexUrl;if(!n.test(i))return;n.lastIndex=0;const r=n.exec(i)[1];return n.lastIndex=0,s[r]}resolveGradient(t,e,s){const i=this.extractPropertyDefinition(t,s,this.gradientDefs);if(i){const n=e.getAttribute(s+"-opacity"),r=th.fromElement(i,t,T(T({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e){const s=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(s){const i=Fe(t.calcTransformMatrix()),n=s[0].parentElement;let r=e;for(;r.parentElement&&r.getAttribute("clip-path")!==t.clipPath;)r=r.parentElement;r.parentElement.appendChild(n);const o=vc("".concat(r.getAttribute("transform")||""," ").concat(n.getAttribute("originalTransform")||""));n.setAttribute("transform","matrix(".concat(o.join(","),")"));const h=await Promise.all(s.map(v=>Qm(v).fromElement(v,this.options,this.cssRules).then(x=>(Cc(x),x.fillRule=x.clipRule,delete x.clipRule,x)))),l=h.length===1?h[0]:new zs(h),d=It(i,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,r);const{scaleX:u,scaleY:g,angle:f,skewX:p,translateX:m,translateY:_}=qn(d);l.set({flipX:!1,flipY:!1}),l.set({scaleX:u,scaleY:g,angle:f,skewX:p,skewY:0}),l.setPositionByOrigin(new M(m,_),J,J),t.clipPath=l}else delete t.clipPath}}const Jm=a=>jv.test(Lc(a)),og=()=>({objects:[],elements:[],options:{},allElements:[]});async function B_(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return ui("log",new lu("parseSVGDocument")),og();const i=a.documentElement;(function(d){const u=$m(d,["use","svg:use"]),g=["x","y","xlink:href","href","transform"];for(const f of u){const p=f.attributes,m={};for(const F of p)F.value&&(m[F.name]=F.value);const _=(m["xlink:href"]||m.href||"").slice(1);if(_==="")return;const v=d.getElementById(_);if(v===null)return;let x=v.cloneNode(!0);const S=x.attributes,C={};for(const F of S)F.value&&(C[F.name]=F.value);const{x:E=0,y:k=0,transform:P=""}=m,D="".concat(P," ").concat(C.transform||""," translate(").concat(E,", ").concat(k,")");if(ng(x),/^svg$/i.test(x.nodeName)){const F=x.ownerDocument.createElementNS(Mu,"g");Object.entries(C).forEach(B=>{let[O,R]=B;return F.setAttributeNS(Mu,O,R)}),F.append(...x.childNodes),x=F}for(const F of p){if(!F)continue;const{name:B,value:O}=F;if(!g.includes(B))if(B==="style"){const R={};Vu(O,R),Object.entries(C).forEach(j=>{let[G,Y]=j;R[G]=Y}),Vu(C.style||"",R);const L=Object.entries(R).map(j=>j.join(":")).join(";");x.setAttribute(B,L)}else!C[B]&&x.setAttribute(B,O)}x.setAttribute("transform",D),x.setAttribute("instantiated_by_use","1"),x.removeAttribute("id"),f.parentNode.replaceChild(x,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=T(T({},ng(i)),{},{crossOrigin:e,signal:s}),o=n.filter(d=>(ng(d),Jm(d)&&!function(u){let g=u;for(;g&&(g=g.parentElement);)if(g&&g.nodeName&&R_.test(Lc(g))&&!g.getAttribute("instantiated_by_use"))return!0;return!1}(d)));if(!o||o&&!o.length)return T(T({},og()),{},{options:r,allElements:n});const h={};return n.filter(d=>Lc(d)==="clipPath").forEach(d=>{d.setAttribute("originalTransform",d.getAttribute("transform")||"");const u=d.getAttribute("id");h[u]=Array.from(d.getElementsByTagName("*")).filter(g=>Jm(g))}),{objects:await new N_(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function H_(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{Om(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>B_(s,t,e)).catch(()=>og())}const Rc=a=>a.webgl!==void 0,ag="precision highp float",W_=`
63
- `.concat(ag,`;
64
- varying vec2 vTexCoord;
65
- uniform sampler2D uTexture;
66
- void main() {
67
- gl_FragColor = texture2D(uTexture, vTexCoord);
68
- }`),z_=["type"],X_=["type"],V_=new RegExp(ag,"g");class Ut{get type(){return this.constructor.type}constructor(){let t=xt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},z_);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return W_}getVertexSource(){return`
69
- attribute vec2 aPosition;
70
- varying vec2 vTexCoord;
71
- void main() {
72
- vTexCoord = aPosition;
73
- gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
74
- }`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:i="highp"}}=Bs();i!=="highp"&&(e=e.replace(V_,ag.replace("highp",i)));const n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER),o=t.createProgram();if(!n||!r||!o)throw new Ns("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Ns("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Ns("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(r)));if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new Ns('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(o)));const h=this.getUniformLocations(t,o)||{};return h.uStepW=t.getUniformLocation(o,"uStepW"),h.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:h}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const s=this.constructor.uniformLocations,i={};for(let n=0;n<s.length;n++)i[s[n]]=t.getUniformLocation(e,s[n]);return i}sendAttributeData(t,e,s){const i=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const s=t.destinationWidth,i=t.destinationHeight;t.sourceWidth===s&&t.sourceHeight===i||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,s,i)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){Rc(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){const e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){const e=t.context,s=this.retrieveShader(t);t.pass===0&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(s.program),this.sendAttributeData(e,s.attributeLocations,t.aPosition),e.uniform1f(s.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(s.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,s.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,s){t.activeTexture(s),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const e=Ft();e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}}toObject(){const t=Object.keys(this.constructor.defaults||{});return T({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(xt(t,X_))}}A(Ut,"type","BaseFilter"),A(Ut,"uniformLocations",[]);const G_={multiply:`gl_FragColor.rgb *= uColor.rgb;
75
- `,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
76
- `,add:`gl_FragColor.rgb += uColor.rgb;
77
- `,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
78
- `,subtract:`gl_FragColor.rgb -= uColor.rgb;
79
- `,lighten:`gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);
80
- `,darken:`gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);
81
- `,exclusion:`gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);
82
- `,overlay:`
83
- if (uColor.r < 0.5) {
84
- gl_FragColor.r *= 2.0 * uColor.r;
85
- } else {
86
- gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);
87
- }
88
- if (uColor.g < 0.5) {
89
- gl_FragColor.g *= 2.0 * uColor.g;
90
- } else {
91
- gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);
92
- }
93
- if (uColor.b < 0.5) {
94
- gl_FragColor.b *= 2.0 * uColor.b;
95
- } else {
96
- gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);
97
- }
98
- `,tint:`
99
- gl_FragColor.rgb *= (1.0 - uColor.a);
100
- gl_FragColor.rgb += uColor.rgb;
101
- `};class Fc extends Ut{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
102
- precision highp float;
103
- uniform sampler2D uTexture;
104
- uniform vec4 uColor;
105
- varying vec2 vTexCoord;
106
- void main() {
107
- vec4 color = texture2D(uTexture, vTexCoord);
108
- gl_FragColor = color;
109
- if (color.a > 0.0) {
110
- `.concat(G_[this.mode],`
111
- }
112
- }
113
- `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new ft(this.color).getSource(),i=s[0]*this.alpha,n=s[1]*this.alpha,r=s[2]*this.alpha,o=1-this.alpha;for(let h=0;h<e.length;h+=4){const l=e[h],d=e[h+1],u=e[h+2];switch(this.mode){case"multiply":e[h]=l*i/255,e[h+1]=d*n/255,e[h+2]=u*r/255;break;case"screen":e[h]=255-(255-l)*(255-i)/255,e[h+1]=255-(255-d)*(255-n)/255,e[h+2]=255-(255-u)*(255-r)/255;break;case"add":e[h]=l+i,e[h+1]=d+n,e[h+2]=u+r;break;case"difference":e[h]=Math.abs(l-i),e[h+1]=Math.abs(d-n),e[h+2]=Math.abs(u-r);break;case"subtract":e[h]=l-i,e[h+1]=d-n,e[h+2]=u-r;break;case"darken":e[h]=Math.min(l,i),e[h+1]=Math.min(d,n),e[h+2]=Math.min(u,r);break;case"lighten":e[h]=Math.max(l,i),e[h+1]=Math.max(d,n),e[h+2]=Math.max(u,r);break;case"overlay":e[h]=i<128?2*l*i/255:255-2*(255-l)*(255-i)/255,e[h+1]=n<128?2*d*n/255:255-2*(255-d)*(255-n)/255,e[h+2]=r<128?2*u*r/255:255-2*(255-u)*(255-r)/255;break;case"exclusion":e[h]=i+l-2*i*l/255,e[h+1]=n+d-2*n*d/255,e[h+2]=r+u-2*r*u/255;break;case"tint":e[h]=i+l*o,e[h+1]=n+d*o,e[h+2]=r+u*o}}}sendUniformData(t,e){const s=new ft(this.color).getSource();s[0]=this.alpha*s[0]/255,s[1]=this.alpha*s[1]/255,s[2]=this.alpha*s[2]/255,s[3]=this.alpha,t.uniform4fv(e.uColor,s)}}A(Fc,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),A(Fc,"type","BlendColor"),A(Fc,"uniformLocations",["uColor"]),z.setClass(Fc);const U_={multiply:`
114
- precision highp float;
115
- uniform sampler2D uTexture;
116
- uniform sampler2D uImage;
117
- uniform vec4 uColor;
118
- varying vec2 vTexCoord;
119
- varying vec2 vTexCoord2;
120
- void main() {
121
- vec4 color = texture2D(uTexture, vTexCoord);
122
- vec4 color2 = texture2D(uImage, vTexCoord2);
123
- color.rgba *= color2.rgba;
124
- gl_FragColor = color;
125
- }
126
- `,mask:`
127
- precision highp float;
128
- uniform sampler2D uTexture;
129
- uniform sampler2D uImage;
130
- uniform vec4 uColor;
131
- varying vec2 vTexCoord;
132
- varying vec2 vTexCoord2;
133
- void main() {
134
- vec4 color = texture2D(uTexture, vTexCoord);
135
- vec4 color2 = texture2D(uImage, vTexCoord2);
136
- color.a = color2.a;
137
- gl_FragColor = color;
138
- }
139
- `},Y_=["type","image"];class Ic extends Ut{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return U_[this.mode]}getVertexSource(){return`
140
- attribute vec2 aPosition;
141
- varying vec2 vTexCoord;
142
- varying vec2 vTexCoord2;
143
- uniform mat3 uTransformMatrix;
144
- void main() {
145
- vTexCoord = aPosition;
146
- vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
147
- gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
148
- }
149
- `}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:i},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=Ft());const o=n.blendImage,h=o.getContext("2d");o.width!==s||o.height!==i?(o.width=s,o.height=i):h.clearRect(0,0,s,i),h.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),h.drawImage(r.getElement(),0,0,s,i);const l=h.getImageData(0,0,s,i).data;for(let d=0;d<e.length;d+=4){const u=e[d],g=e[d+1],f=e[d+2],p=e[d+3],m=l[d],_=l[d+1],v=l[d+2],x=l[d+3];switch(this.mode){case"multiply":e[d]=u*m/255,e[d+1]=g*_/255,e[d+2]=f*v/255,e[d+3]=p*x/255;break;case"mask":e[d+3]=x}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return T(T({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=xt(t,Y_);return ge.fromObject(i,e).then(r=>new this(T(T({},n),{},{image:r})))}}A(Ic,"type","BlendImage"),A(Ic,"defaults",{mode:"multiply",alpha:1}),A(Ic,"uniformLocations",["uTransformMatrix","uImage"]),z.setClass(Ic);class jc extends Ut{getFragmentSource(){return`
150
- precision highp float;
151
- uniform sampler2D uTexture;
152
- uniform vec2 uDelta;
153
- varying vec2 vTexCoord;
154
- const float nSamples = 15.0;
155
- vec3 v3offset = vec3(12.9898, 78.233, 151.7182);
156
- float random(vec3 scale) {
157
- /* use the fragment position for a different seed per-pixel */
158
- return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);
159
- }
160
- void main() {
161
- vec4 color = vec4(0.0);
162
- float total = 0.0;
163
- float offset = random(v3offset);
164
- for (float t = -nSamples; t <= nSamples; t++) {
165
- float percent = (t + offset - 0.5) / nSamples;
166
- float weight = 1.0 - abs(percent);
167
- color += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;
168
- total += weight;
169
- }
170
- gl_FragColor = color / total;
171
- }
172
- `}applyTo(t){Rc(t)?(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(t){t.imageData=this.simpleBlur(t)}simpleBlur(t){let{ctx:e,imageData:s,filterBackend:{resources:i}}=t;const{width:n,height:r}=s;i.blurLayer1||(i.blurLayer1=Ft(),i.blurLayer2=Ft());const o=i.blurLayer1,h=i.blurLayer2;o.width===n&&o.height===r||(h.width=o.width=n,h.height=o.height=r);const l=o.getContext("2d"),d=h.getContext("2d"),u=15,g=.06*this.blur*.5;let f,p,m,_;for(l.putImageData(s,0,0),d.clearRect(0,0,n,r),_=-15;_<=u;_++)f=(Math.random()-.5)/4,p=_/u,m=g*p*n+f,d.globalAlpha=1-Math.abs(p),d.drawImage(o,m,f),l.drawImage(h,0,0),d.globalAlpha=1,d.clearRect(0,0,h.width,h.height);for(_=-15;_<=u;_++)f=(Math.random()-.5)/4,p=_/u,m=g*p*r+f,d.globalAlpha=1-Math.abs(p),d.drawImage(o,f,m),l.drawImage(h,0,0),d.globalAlpha=1,d.clearRect(0,0,h.width,h.height);e.drawImage(o,0,0);const v=e.getImageData(0,0,o.width,o.height);return l.globalAlpha=1,l.clearRect(0,0,o.width,o.height),v}sendUniformData(t,e){const s=this.chooseRightDelta();t.uniform2fv(e.uDelta,s)}isNeutralState(){return this.blur===0}chooseRightDelta(){let t=1;const e=[0,0];this.horizontal?this.aspectRatio>1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio);const s=t*this.blur*.12;return this.horizontal?e[0]=s:e[1]=s,e}}A(jc,"type","Blur"),A(jc,"defaults",{blur:0}),A(jc,"uniformLocations",["uDelta"]),z.setClass(jc);class Nc extends Ut{getFragmentSource(){return`
173
- precision highp float;
174
- uniform sampler2D uTexture;
175
- uniform float uBrightness;
176
- varying vec2 vTexCoord;
177
- void main() {
178
- vec4 color = texture2D(uTexture, vTexCoord);
179
- color.rgb += uBrightness;
180
- gl_FragColor = color;
181
- }
182
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.round(255*this.brightness);for(let i=0;i<e.length;i+=4)e[i]=e[i]+s,e[i+1]=e[i+1]+s,e[i+2]=e[i+2]+s}isNeutralState(){return this.brightness===0}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}A(Nc,"type","Brightness"),A(Nc,"defaults",{brightness:0}),A(Nc,"uniformLocations",["uBrightness"]),z.setClass(Nc);class Po extends Ut{getFragmentSource(){return`
183
- precision highp float;
184
- uniform sampler2D uTexture;
185
- varying vec2 vTexCoord;
186
- uniform mat4 uColorMatrix;
187
- uniform vec4 uConstants;
188
- void main() {
189
- vec4 color = texture2D(uTexture, vTexCoord);
190
- color *= uColorMatrix;
191
- color += uConstants;
192
- gl_FragColor = color;
193
- }`}applyTo2d(t){const e=t.imageData.data,s=this.matrix,i=this.colorsOnly;for(let n=0;n<e.length;n+=4){const r=e[n],o=e[n+1],h=e[n+2];if(i)e[n]=r*s[0]+o*s[1]+h*s[2]+255*s[4],e[n+1]=r*s[5]+o*s[6]+h*s[7]+255*s[9],e[n+2]=r*s[10]+o*s[11]+h*s[12]+255*s[14];else{const l=e[n+3];e[n]=r*s[0]+o*s[1]+h*s[2]+l*s[3]+255*s[4],e[n+1]=r*s[5]+o*s[6]+h*s[7]+l*s[8]+255*s[9],e[n+2]=r*s[10]+o*s[11]+h*s[12]+l*s[13]+255*s[14],e[n+3]=r*s[15]+o*s[16]+h*s[17]+l*s[18]+255*s[19]}}}sendUniformData(t,e){const s=this.matrix,i=[s[0],s[1],s[2],s[3],s[5],s[6],s[7],s[8],s[10],s[11],s[12],s[13],s[15],s[16],s[17],s[18]],n=[s[4],s[9],s[14],s[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,i),t.uniform4fv(e.uConstants,n)}toObject(){return T(T({},super.toObject()),{},{matrix:[...this.matrix]})}}function nr(a,t){var e;const s=(A(e=class extends Po{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),A(e,"defaults",{colorsOnly:!1,matrix:t}),e);return z.setClass(s,a),s}A(Po,"type","ColorMatrix"),A(Po,"defaults",{matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0}),A(Po,"uniformLocations",["uColorMatrix","uConstants"]),z.setClass(Po),nr("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),nr("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),nr("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),nr("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),nr("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),nr("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),nr("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]);class Zm extends Ut{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){Rc(t)&&(t.passes+=this.subFilters.length-1),this.subFilters.forEach(e=>{e.applyTo(t)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(t=>t.toObject())}}isNeutralState(){return!this.subFilters.some(t=>!t.isNeutralState())}static fromObject(t,e){return Promise.all((t.subFilters||[]).map(s=>z.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}A(Zm,"type","Composed"),z.setClass(Zm);class Bc extends Ut{getFragmentSource(){return`
194
- precision highp float;
195
- uniform sampler2D uTexture;
196
- uniform float uContrast;
197
- varying vec2 vTexCoord;
198
- void main() {
199
- vec4 color = texture2D(uTexture, vTexCoord);
200
- float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
201
- color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
202
- gl_FragColor = color;
203
- }`}isNeutralState(){return this.contrast===0}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.floor(255*this.contrast),i=259*(s+255)/(255*(259-s));for(let n=0;n<e.length;n+=4)e[n]=i*(e[n]-128)+128,e[n+1]=i*(e[n+1]-128)+128,e[n+2]=i*(e[n+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}A(Bc,"type","Contrast"),A(Bc,"defaults",{contrast:0}),A(Bc,"uniformLocations",["uContrast"]),z.setClass(Bc);const q_={Convolute_3_1:`
204
- precision highp float;
205
- uniform sampler2D uTexture;
206
- uniform float uMatrix[9];
207
- uniform float uStepW;
208
- uniform float uStepH;
209
- varying vec2 vTexCoord;
210
- void main() {
211
- vec4 color = vec4(0, 0, 0, 0);
212
- for (float h = 0.0; h < 3.0; h+=1.0) {
213
- for (float w = 0.0; w < 3.0; w+=1.0) {
214
- vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));
215
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];
216
- }
217
- }
218
- gl_FragColor = color;
219
- }
220
- `,Convolute_3_0:`
221
- precision highp float;
222
- uniform sampler2D uTexture;
223
- uniform float uMatrix[9];
224
- uniform float uStepW;
225
- uniform float uStepH;
226
- varying vec2 vTexCoord;
227
- void main() {
228
- vec4 color = vec4(0, 0, 0, 1);
229
- for (float h = 0.0; h < 3.0; h+=1.0) {
230
- for (float w = 0.0; w < 3.0; w+=1.0) {
231
- vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));
232
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];
233
- }
234
- }
235
- float alpha = texture2D(uTexture, vTexCoord).a;
236
- gl_FragColor = color;
237
- gl_FragColor.a = alpha;
238
- }
239
- `,Convolute_5_1:`
240
- precision highp float;
241
- uniform sampler2D uTexture;
242
- uniform float uMatrix[25];
243
- uniform float uStepW;
244
- uniform float uStepH;
245
- varying vec2 vTexCoord;
246
- void main() {
247
- vec4 color = vec4(0, 0, 0, 0);
248
- for (float h = 0.0; h < 5.0; h+=1.0) {
249
- for (float w = 0.0; w < 5.0; w+=1.0) {
250
- vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));
251
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];
252
- }
253
- }
254
- gl_FragColor = color;
255
- }
256
- `,Convolute_5_0:`
257
- precision highp float;
258
- uniform sampler2D uTexture;
259
- uniform float uMatrix[25];
260
- uniform float uStepW;
261
- uniform float uStepH;
262
- varying vec2 vTexCoord;
263
- void main() {
264
- vec4 color = vec4(0, 0, 0, 1);
265
- for (float h = 0.0; h < 5.0; h+=1.0) {
266
- for (float w = 0.0; w < 5.0; w+=1.0) {
267
- vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));
268
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];
269
- }
270
- }
271
- float alpha = texture2D(uTexture, vTexCoord).a;
272
- gl_FragColor = color;
273
- gl_FragColor.a = alpha;
274
- }
275
- `,Convolute_7_1:`
276
- precision highp float;
277
- uniform sampler2D uTexture;
278
- uniform float uMatrix[49];
279
- uniform float uStepW;
280
- uniform float uStepH;
281
- varying vec2 vTexCoord;
282
- void main() {
283
- vec4 color = vec4(0, 0, 0, 0);
284
- for (float h = 0.0; h < 7.0; h+=1.0) {
285
- for (float w = 0.0; w < 7.0; w+=1.0) {
286
- vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));
287
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];
288
- }
289
- }
290
- gl_FragColor = color;
291
- }
292
- `,Convolute_7_0:`
293
- precision highp float;
294
- uniform sampler2D uTexture;
295
- uniform float uMatrix[49];
296
- uniform float uStepW;
297
- uniform float uStepH;
298
- varying vec2 vTexCoord;
299
- void main() {
300
- vec4 color = vec4(0, 0, 0, 1);
301
- for (float h = 0.0; h < 7.0; h+=1.0) {
302
- for (float w = 0.0; w < 7.0; w+=1.0) {
303
- vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));
304
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];
305
- }
306
- }
307
- float alpha = texture2D(uTexture, vTexCoord).a;
308
- gl_FragColor = color;
309
- gl_FragColor.a = alpha;
310
- }
311
- `,Convolute_9_1:`
312
- precision highp float;
313
- uniform sampler2D uTexture;
314
- uniform float uMatrix[81];
315
- uniform float uStepW;
316
- uniform float uStepH;
317
- varying vec2 vTexCoord;
318
- void main() {
319
- vec4 color = vec4(0, 0, 0, 0);
320
- for (float h = 0.0; h < 9.0; h+=1.0) {
321
- for (float w = 0.0; w < 9.0; w+=1.0) {
322
- vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));
323
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];
324
- }
325
- }
326
- gl_FragColor = color;
327
- }
328
- `,Convolute_9_0:`
329
- precision highp float;
330
- uniform sampler2D uTexture;
331
- uniform float uMatrix[81];
332
- uniform float uStepW;
333
- uniform float uStepH;
334
- varying vec2 vTexCoord;
335
- void main() {
336
- vec4 color = vec4(0, 0, 0, 1);
337
- for (float h = 0.0; h < 9.0; h+=1.0) {
338
- for (float w = 0.0; w < 9.0; w+=1.0) {
339
- vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));
340
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];
341
- }
342
- }
343
- float alpha = texture2D(uTexture, vTexCoord).a;
344
- gl_FragColor = color;
345
- gl_FragColor.a = alpha;
346
- }
347
- `};class Hc extends Ut{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return q_[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,s=e.data,i=this.matrix,n=Math.round(Math.sqrt(i.length)),r=Math.floor(n/2),o=e.width,h=e.height,l=t.ctx.createImageData(o,h),d=l.data,u=this.opaque?1:0;let g,f,p,m,_,v,x,S,C,E,k,P,D;for(k=0;k<h;k++)for(E=0;E<o;E++){for(_=4*(k*o+E),g=0,f=0,p=0,m=0,D=0;D<n;D++)for(P=0;P<n;P++)x=k+D-r,v=E+P-r,x<0||x>=h||v<0||v>=o||(S=4*(x*o+v),C=i[D*n+P],g+=s[S]*C,f+=s[S+1]*C,p+=s[S+2]*C,u||(m+=s[S+3]*C));d[_]=g,d[_+1]=f,d[_+2]=p,d[_+3]=u?s[_+3]:m}t.imageData=l}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return T(T({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}A(Hc,"type","Convolute"),A(Hc,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),A(Hc,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),z.setClass(Hc);const t0="Gamma";class Wc extends Ut{getFragmentSource(){return`
348
- precision highp float;
349
- uniform sampler2D uTexture;
350
- uniform vec3 uGamma;
351
- varying vec2 vTexCoord;
352
- void main() {
353
- vec4 color = texture2D(uTexture, vTexCoord);
354
- vec3 correction = (1.0 / uGamma);
355
- color.r = pow(color.r, correction.r);
356
- color.g = pow(color.g, correction.g);
357
- color.b = pow(color.b, correction.b);
358
- gl_FragColor = color;
359
- gl_FragColor.rgb *= color.a;
360
- }
361
- `}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.gamma,i=1/s[0],n=1/s[1],r=1/s[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const o=this.rgbValues;for(let h=0;h<256;h++)o.r[h]=255*Math.pow(h/255,i),o.g[h]=255*Math.pow(h/255,n),o.b[h]=255*Math.pow(h/255,r);for(let h=0;h<e.length;h+=4)e[h]=o.r[e[h]],e[h+1]=o.g[e[h+1]],e[h+2]=o.b[e[h+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return t[0]===1&&t[1]===1&&t[2]===1}toObject(){return{type:t0,gamma:this.gamma.concat()}}}A(Wc,"type",t0),A(Wc,"defaults",{gamma:[1,1,1]}),A(Wc,"uniformLocations",["uGamma"]),z.setClass(Wc);const $_={average:`
362
- precision highp float;
363
- uniform sampler2D uTexture;
364
- varying vec2 vTexCoord;
365
- void main() {
366
- vec4 color = texture2D(uTexture, vTexCoord);
367
- float average = (color.r + color.b + color.g) / 3.0;
368
- gl_FragColor = vec4(average, average, average, color.a);
369
- }
370
- `,lightness:`
371
- precision highp float;
372
- uniform sampler2D uTexture;
373
- uniform int uMode;
374
- varying vec2 vTexCoord;
375
- void main() {
376
- vec4 col = texture2D(uTexture, vTexCoord);
377
- float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;
378
- gl_FragColor = vec4(average, average, average, col.a);
379
- }
380
- `,luminosity:`
381
- precision highp float;
382
- uniform sampler2D uTexture;
383
- uniform int uMode;
384
- varying vec2 vTexCoord;
385
- void main() {
386
- vec4 col = texture2D(uTexture, vTexCoord);
387
- float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
388
- gl_FragColor = vec4(average, average, average, col.a);
389
- }
390
- `};class zc extends Ut{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,i=0;i<e.length;i+=4){switch(this.mode){case"average":s=(e[i]+e[i+1]+e[i+2])/3;break;case"lightness":s=(Math.min(e[i],e[i+1],e[i+2])+Math.max(e[i],e[i+1],e[i+2]))/2;break;case"luminosity":s=.21*e[i]+.72*e[i+1]+.07*e[i+2]}e[i]=s,e[i+1]=s,e[i+2]=s}}getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return $_[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}A(zc,"type","Grayscale"),A(zc,"defaults",{mode:"average"}),A(zc,"uniformLocations",["uMode"]),z.setClass(zc);class hg extends Po{calculateMatrix(){const t=this.rotation*Math.PI,e=ms(t),s=bs(t),i=1/3,n=Math.sqrt(i)*s,r=1-e;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]=e+r/3,this.matrix[1]=i*r-n,this.matrix[2]=i*r+n,this.matrix[5]=i*r+n,this.matrix[6]=e+i*r,this.matrix[7]=i*r-n,this.matrix[10]=i*r-n,this.matrix[11]=i*r+n,this.matrix[12]=e+i*r}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}A(hg,"type","HueRotation"),A(hg,"defaults",{rotation:0}),z.setClass(hg);class Xc extends Ut{applyTo2d(t){let{imageData:{data:e}}=t;for(let s=0;s<e.length;s+=4)e[s]=255-e[s],e[s+1]=255-e[s+1],e[s+2]=255-e[s+2],this.alpha&&(e[s+3]=255-e[s+3])}getFragmentSource(){return`
391
- precision highp float;
392
- uniform sampler2D uTexture;
393
- uniform int uInvert;
394
- uniform int uAlpha;
395
- varying vec2 vTexCoord;
396
- void main() {
397
- vec4 color = texture2D(uTexture, vTexCoord);
398
- if (uInvert == 1) {
399
- if (uAlpha == 1) {
400
- gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,1.0 -color.a);
401
- } else {
402
- gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);
403
- }
404
- } else {
405
- gl_FragColor = color;
406
- }
407
- }
408
- `}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}A(Xc,"type","Invert"),A(Xc,"defaults",{alpha:!1,invert:!0}),A(Xc,"uniformLocations",["uInvert","uAlpha"]),z.setClass(Xc);class Vc extends Ut{getFragmentSource(){return`
409
- precision highp float;
410
- uniform sampler2D uTexture;
411
- uniform float uStepH;
412
- uniform float uNoise;
413
- uniform float uSeed;
414
- varying vec2 vTexCoord;
415
- float rand(vec2 co, float seed, float vScale) {
416
- return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);
417
- }
418
- void main() {
419
- vec4 color = texture2D(uTexture, vTexCoord);
420
- color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
421
- gl_FragColor = color;
422
- }
423
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.noise;for(let i=0;i<e.length;i+=4){const n=(.5-Math.random())*s;e[i]+=n,e[i+1]+=n,e[i+2]+=n}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return this.noise===0}}A(Vc,"type","Noise"),A(Vc,"defaults",{noise:0}),A(Vc,"uniformLocations",["uNoise","uSeed"]),z.setClass(Vc);class Gc extends Ut{applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;for(let n=0;n<i;n+=this.blocksize)for(let r=0;r<s;r+=this.blocksize){const o=4*n*s+4*r,h=e[o],l=e[o+1],d=e[o+2],u=e[o+3];for(let g=n;g<Math.min(n+this.blocksize,i);g++)for(let f=r;f<Math.min(r+this.blocksize,s);f++){const p=4*g*s+4*f;e[p]=h,e[p+1]=l,e[p+2]=d,e[p+3]=u}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
424
- precision highp float;
425
- uniform sampler2D uTexture;
426
- uniform float uBlocksize;
427
- uniform float uStepW;
428
- uniform float uStepH;
429
- varying vec2 vTexCoord;
430
- void main() {
431
- float blockW = uBlocksize * uStepW;
432
- float blockH = uBlocksize * uStepH;
433
- int posX = int(vTexCoord.x / blockW);
434
- int posY = int(vTexCoord.y / blockH);
435
- float fposX = float(posX);
436
- float fposY = float(posY);
437
- vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);
438
- vec4 color = texture2D(uTexture, squareCoords);
439
- gl_FragColor = color;
440
- }
441
- `}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}A(Gc,"type","Pixelate"),A(Gc,"defaults",{blocksize:4}),A(Gc,"uniformLocations",["uBlocksize"]),z.setClass(Gc);class Uc extends Ut{getFragmentSource(){return`
442
- precision highp float;
443
- uniform sampler2D uTexture;
444
- uniform vec4 uLow;
445
- uniform vec4 uHigh;
446
- varying vec2 vTexCoord;
447
- void main() {
448
- gl_FragColor = texture2D(uTexture, vTexCoord);
449
- if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {
450
- gl_FragColor.a = 0.0;
451
- }
452
- }
453
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new ft(this.color).getSource(),n=[i[0]-s,i[1]-s,i[2]-s],r=[i[0]+s,i[1]+s,i[2]+s];for(let o=0;o<e.length;o+=4){const h=e[o],l=e[o+1],d=e[o+2];h>n[0]&&l>n[1]&&d>n[2]&&h<r[0]&&l<r[1]&&d<r[2]&&(e[o+3]=0)}}sendUniformData(t,e){const s=new ft(this.color).getSource(),i=this.distance,n=[0+s[0]/255-i,0+s[1]/255-i,0+s[2]/255-i,1],r=[s[0]/255+i,s[1]/255+i,s[2]/255+i,1];t.uniform4fv(e.uLow,n),t.uniform4fv(e.uHigh,r)}}A(Uc,"type","RemoveColor"),A(Uc,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),A(Uc,"uniformLocations",["uLow","uHigh"]),z.setClass(Uc);class Yc extends Ut{sendUniformData(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)}getFilterWindow(){const t=this.tempScale;return Math.ceil(this.lanczosLobes/t)}getCacheKey(){const t=this.getFilterWindow();return"".concat(this.type,"_").concat(t)}getFragmentSource(){const t=this.getFilterWindow();return this.generateShader(t)}getTaps(){const t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,s=this.getFilterWindow(),i=new Array(s);for(let n=1;n<=s;n++)i[n-1]=t(n*e);return i}generateShader(t){const e=new Array(t);for(let s=1;s<=t;s++)e[s-1]="".concat(s,".0 * uDelta");return`
454
- precision highp float;
455
- uniform sampler2D uTexture;
456
- uniform vec2 uDelta;
457
- varying vec2 vTexCoord;
458
- uniform float uTaps[`.concat(t,`];
459
- void main() {
460
- vec4 color = texture2D(uTexture, vTexCoord);
461
- float sum = 1.0;
462
- `).concat(e.map((s,i)=>`
463
- color += texture2D(uTexture, vTexCoord + `.concat(s,") * uTaps[").concat(i,"] + texture2D(uTexture, vTexCoord - ").concat(s,") * uTaps[").concat(i,`];
464
- sum += 2.0 * uTaps[`).concat(i,`];
465
- `)).join(`
466
- `),`
467
- gl_FragColor = color / sum;
468
- }
469
- `)}applyToForWebgl(t){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,super.applyTo(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,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){Rc(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<11920929e-14&&e>-11920929e-14)return 1;const s=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(s)/s}}applyTo2d(t){const e=t.imageData,s=this.scaleX,i=this.scaleY;this.rcpScaleX=1/s,this.rcpScaleY=1/i;const n=e.width,r=e.height,o=Math.round(n*s),h=Math.round(r*i);let l;l=this.resizeType==="sliceHack"?this.sliceByTwo(t,n,r,o,h):this.resizeType==="hermite"?this.hermiteFastResize(t,n,r,o,h):this.resizeType==="bilinear"?this.bilinearFiltering(t,n,r,o,h):this.resizeType==="lanczos"?this.lanczosResize(t,n,r,o,h):new ImageData(o,h),t.imageData=l}sliceByTwo(t,e,s,i,n){const r=t.imageData,o=.5;let h=!1,l=!1,d=e*o,u=s*o;const g=t.filterBackend.resources;let f=0,p=0;const m=e;let _=0;g.sliceByTwo||(g.sliceByTwo=Ft());const v=g.sliceByTwo;(v.width<1.5*e||v.height<s)&&(v.width=1.5*e,v.height=s);const x=v.getContext("2d");for(x.clearRect(0,0,1.5*e,s),x.putImageData(r,0,0),i=Math.floor(i),n=Math.floor(n);!h||!l;)e=d,s=u,i<Math.floor(d*o)?d=Math.floor(d*o):(d=i,h=!0),n<Math.floor(u*o)?u=Math.floor(u*o):(u=n,l=!0),x.drawImage(v,f,p,e,s,m,_,d,u),f=m,p=_,_+=u;return x.getImageData(f,p,i,n)}lanczosResize(t,e,s,i,n){const r=t.imageData.data,o=t.ctx.createImageData(i,n),h=o.data,l=this.lanczosCreate(this.lanczosLobes),d=this.rcpScaleX,u=this.rcpScaleY,g=2/this.rcpScaleX,f=2/this.rcpScaleY,p=Math.ceil(d*this.lanczosLobes/2),m=Math.ceil(u*this.lanczosLobes/2),_={},v={x:0,y:0},x={x:0,y:0};return function S(C){let E,k,P,D,F,B,O,R,L,j,G;for(v.x=(C+.5)*d,x.x=Math.floor(v.x),E=0;E<n;E++){for(v.y=(E+.5)*u,x.y=Math.floor(v.y),F=0,B=0,O=0,R=0,L=0,k=x.x-p;k<=x.x+p;k++)if(!(k<0||k>=e)){j=Math.floor(1e3*Math.abs(k-v.x)),_[j]||(_[j]={});for(let Y=x.y-m;Y<=x.y+m;Y++)Y<0||Y>=s||(G=Math.floor(1e3*Math.abs(Y-v.y)),_[j][G]||(_[j][G]=l(Math.sqrt(Math.pow(j*g,2)+Math.pow(G*f,2))/1e3)),P=_[j][G],P>0&&(D=4*(Y*e+k),F+=P,B+=P*r[D],O+=P*r[D+1],R+=P*r[D+2],L+=P*r[D+3]))}D=4*(E*i+C),h[D]=B/F,h[D+1]=O/F,h[D+2]=R/F,h[D+3]=L/F}return++C<i?S(C):o}(0)}bilinearFiltering(t,e,s,i,n){let r,o,h,l,d,u,g,f,p,m,_,v,x,S=0;const C=this.rcpScaleX,E=this.rcpScaleY,k=4*(e-1),P=t.imageData.data,D=t.ctx.createImageData(i,n),F=D.data;for(g=0;g<n;g++)for(f=0;f<i;f++)for(d=Math.floor(C*f),u=Math.floor(E*g),p=C*f-d,m=E*g-u,x=4*(u*e+d),_=0;_<4;_++)r=P[x+_],o=P[x+4+_],h=P[x+k+_],l=P[x+k+4+_],v=r*(1-p)*(1-m)+o*p*(1-m)+h*m*(1-p)+l*p*m,F[S++]=v;return D}hermiteFastResize(t,e,s,i,n){const r=this.rcpScaleX,o=this.rcpScaleY,h=Math.ceil(r/2),l=Math.ceil(o/2),d=t.imageData.data,u=t.ctx.createImageData(i,n),g=u.data;for(let f=0;f<n;f++)for(let p=0;p<i;p++){const m=4*(p+f*i);let _=0,v=0,x=0,S=0,C=0,E=0,k=0;const P=(f+.5)*o;for(let D=Math.floor(f*o);D<(f+1)*o;D++){const F=Math.abs(P-(D+.5))/l,B=(p+.5)*r,O=F*F;for(let R=Math.floor(p*r);R<(p+1)*r;R++){let L=Math.abs(B-(R+.5))/h;const j=Math.sqrt(O+L*L);j>1&&j<-1||(_=2*j*j*j-3*j*j+1,_>0&&(L=4*(R+D*e),k+=_*d[L+3],x+=_,d[L+3]<255&&(_=_*d[L+3]/250),S+=_*d[L],C+=_*d[L+1],E+=_*d[L+2],v+=_))}}g[m]=S/v,g[m+1]=C/v,g[m+2]=E/v,g[m+3]=k/x}return u}}A(Yc,"type","Resize"),A(Yc,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),A(Yc,"uniformLocations",["uDelta","uTaps"]),z.setClass(Yc);class qc extends Ut{getFragmentSource(){return`
470
- precision highp float;
471
- uniform sampler2D uTexture;
472
- uniform float uSaturation;
473
- varying vec2 vTexCoord;
474
- void main() {
475
- vec4 color = texture2D(uTexture, vTexCoord);
476
- float rgMax = max(color.r, color.g);
477
- float rgbMax = max(rgMax, color.b);
478
- color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;
479
- color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;
480
- color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
481
- gl_FragColor = color;
482
- }
483
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;for(let i=0;i<e.length;i+=4){const n=Math.max(e[i],e[i+1],e[i+2]);e[i]+=n!==e[i]?(n-e[i])*s:0,e[i+1]+=n!==e[i+1]?(n-e[i+1])*s:0,e[i+2]+=n!==e[i+2]?(n-e[i+2])*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}A(qc,"type","Saturation"),A(qc,"defaults",{saturation:0}),A(qc,"uniformLocations",["uSaturation"]),z.setClass(qc);class $c extends Ut{getFragmentSource(){return`
484
- precision highp float;
485
- uniform sampler2D uTexture;
486
- uniform float uVibrance;
487
- varying vec2 vTexCoord;
488
- void main() {
489
- vec4 color = texture2D(uTexture, vTexCoord);
490
- float max = max(color.r, max(color.g, color.b));
491
- float avg = (color.r + color.g + color.b) / 3.0;
492
- float amt = (abs(max - avg) * 2.0) * uVibrance;
493
- color.r += max != color.r ? (max - color.r) * amt : 0.00;
494
- color.g += max != color.g ? (max - color.g) * amt : 0.00;
495
- color.b += max != color.b ? (max - color.b) * amt : 0.00;
496
- gl_FragColor = color;
497
- }
498
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=Math.max(e[i],e[i+1],e[i+2]),r=(e[i]+e[i+1]+e[i+2])/3,o=2*Math.abs(n-r)/255*s;e[i]+=n!==e[i]?(n-e[i])*o:0,e[i+1]+=n!==e[i+1]?(n-e[i+1])*o:0,e[i+2]+=n!==e[i+2]?(n-e[i+2])*o:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}A($c,"type","Vibrance"),A($c,"defaults",{vibrance:0}),A($c,"uniformLocations",["uVibrance"]),z.setClass($c);var ih={};ih.d=(a,t)=>{for(var e in t)ih.o(t,e)&&!ih.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},ih.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var $=globalThis.pdfjsLib={};ih.d($,{AbortException:()=>or,AnnotationEditorLayer:()=>Ug,AnnotationEditorParamsType:()=>K,AnnotationEditorType:()=>tt,AnnotationEditorUIManager:()=>hr,AnnotationLayer:()=>Ux,AnnotationMode:()=>cn,CMapCompressionType:()=>dg,ColorPicker:()=>ud,DOMSVGFactory:()=>vg,DrawLayer:()=>Yg,FeatureTest:()=>Ie,GlobalWorkerOptions:()=>Ai,ImageKind:()=>Kc,InvalidPDFException:()=>s0,MissingPDFException:()=>rr,OPS:()=>Cs,OutputScale:()=>xg,PDFDataRangeTransport:()=>j0,PDFDateString:()=>f0,PDFWorker:()=>Ro,PasswordResponses:()=>Z_,PermissionFlag:()=>J_,PixelsPerInch:()=>un,RenderingCancelledException:()=>yg,TextLayer:()=>dh,UnexpectedResponseException:()=>td,Util:()=>V,VerbosityLevel:()=>Qc,XfaLayer:()=>W0,build:()=>Ex,createValidAbsoluteUrl:()=>iw,fetchData:()=>sd,getDocument:()=>vx,getFilenameFromUrl:()=>fw,getPdfFilenameFromUrl:()=>pw,getXfaPageViewport:()=>mw,isDataScheme:()=>id,isPdfFile:()=>_g,noContextMenu:()=>os,normalizeUnicode:()=>lw,setLayerDimensions:()=>ar,shadow:()=>rt,version:()=>Tx});const fe=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),e0=[1,0,0,1,0,0],lg=[.001,0,0,.001,0,0],K_=1e7,cg=1.35,Ye={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},cn={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Q_="pdfjs_internal_editor_",tt={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},K={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},J_={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},pe={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Kc={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Yt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},nh={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Qc={ERRORS:0,WARNINGS:1,INFOS:5},dg={NONE:0,BINARY:1},Cs={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},Z_={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Jc=Qc.WARNINGS;function tw(a){Number.isInteger(a)&&(Jc=a)}function ew(){return Jc}function Zc(a){Jc>=Qc.INFOS&&console.log(`Info: ${a}`)}function st(a){Jc>=Qc.WARNINGS&&console.log(`Warning: ${a}`)}function Wt(a){throw new Error(a)}function qt(a,t){a||Wt(t)}function sw(a){switch(a==null?void 0:a.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function iw(a,t=null,e=null){if(!a)return null;try{if(e&&typeof a=="string"){if(e.addDefaultProtocol&&a.startsWith("www.")){const i=a.match(/\./g);(i==null?void 0:i.length)>=2&&(a=`http://${a}`)}if(e.tryConvertEncoding)try{a=hw(a)}catch{}}const s=t?new URL(a,t):new URL(a);if(sw(s))return s}catch{}return null}function rt(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const dn=function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class ug extends dn{constructor(t,e){super(t,"PasswordException"),this.code=e}}class gg extends dn{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class s0 extends dn{constructor(t){super(t,"InvalidPDFException")}}class rr extends dn{constructor(t){super(t,"MissingPDFException")}}class td extends dn{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class nw extends dn{constructor(t){super(t,"FormatError")}}class or extends dn{constructor(t){super(t,"AbortException")}}function i0(a){(typeof a!="object"||(a==null?void 0:a.length)===void 0)&&Wt("Invalid argument for bytesToString");const t=a.length,e=8192;if(t<e)return String.fromCharCode.apply(null,a);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=a.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function ed(a){typeof a!="string"&&Wt("Invalid argument for stringToBytes");const t=a.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=a.charCodeAt(s)&255;return e}function rw(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function fg(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function ow(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function aw(){try{return new Function(""),!0}catch{return!1}}class Ie{static get isLittleEndian(){return rt(this,"isLittleEndian",ow())}static get isEvalSupported(){return rt(this,"isEvalSupported",aw())}static get isOffscreenCanvasSupported(){return rt(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?rt(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):rt(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,e;return rt(this,"isCSSRoundSupported",(e=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:e.call(t,"width: round(1.5px, 1px)"))}}const pg=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class V{static makeHexColor(t,e,s){return`#${pg[t]}${pg[e]}${pg[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){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],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],r[0]),Math.min(s[1],i[1],n[1],r[1]),Math.max(s[0],i[0],n[0],r[0]),Math.max(s[1],i[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],o=(s+r)/2,h=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,l=o+h||1,d=o-h||1;return[Math.sqrt(l),Math.sqrt(d)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static bezierBoundingBox(t,e,s,i,n,r,o,h,l){return l?(l[0]=Math.min(l[0],t,o),l[1]=Math.min(l[1],e,h),l[2]=Math.max(l[2],t,o),l[3]=Math.max(l[3],e,h)):l=[Math.min(t,o),Math.min(e,h),Math.max(t,o),Math.max(e,h)],y(this,Ei,Zg).call(this,t,s,n,o,e,i,r,h,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),l),y(this,Ei,Zg).call(this,t,s,n,o,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),l),l}}Ei=new WeakSet,Ld=function(t,e,s,i,n,r,o,h,l,d){if(l<=0||l>=1)return;const u=1-l,g=l*l,f=g*l,p=u*(u*(u*t+3*l*e)+3*g*s)+f*i,m=u*(u*(u*n+3*l*r)+3*g*o)+f*h;d[0]=Math.min(d[0],p),d[1]=Math.min(d[1],m),d[2]=Math.max(d[2],p),d[3]=Math.max(d[3],m)},Zg=function(t,e,s,i,n,r,o,h,l,d,u,g){if(Math.abs(l)<1e-12){Math.abs(d)>=1e-12&&y(this,Ei,Ld).call(this,t,e,s,i,n,r,o,h,-u/d,g);return}const f=d**2-4*u*l;if(f<0)return;const p=Math.sqrt(f),m=2*l;y(this,Ei,Ld).call(this,t,e,s,i,n,r,o,h,(-d+p)/m,g),y(this,Ei,Ld).call(this,t,e,s,i,n,r,o,h,(-d-p)/m,g)},w(V,Ei);function hw(a){return decodeURIComponent(escape(a))}let mg=null,n0=null;function lw(a){return mg||(mg=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,n0=new Map([["ſt","ſt"]])),a.replaceAll(mg,(t,e,s)=>e?e.normalize("NFKC"):n0.get(s))}function cw(){if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.randomUUID)=="function")return crypto.randomUUID();const a=new Uint8Array(32);if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.getRandomValues)=="function")crypto.getRandomValues(a);else for(let t=0;t<32;t++)a[t]=Math.floor(Math.random()*255);return i0(a)}const bg="pdfjs_internal_id_",xi={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};class r0{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class o0{constructor({enableHWA:t=!1}){w(this,mh,!1);b(this,mh,t)}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!c(this,mh)})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){Wt("Abstract method `_createCanvas` called.")}}mh=new WeakMap;class a0{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),s=this.isCompressed?dg.BINARY:dg.NONE;return this._fetchData(e,s).catch(i=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}_fetchData(t,e){Wt("Abstract method `_fetchData` called.")}}class h0{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}_fetchData(t){Wt("Abstract method `_fetchData` called.")}}class dw{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){Wt("Abstract method `_createSVG` called.")}}const Si="http://www.w3.org/2000/svg",dr=class dr{};Q(dr,"CSS",96),Q(dr,"PDF",72),Q(dr,"PDF_TO_CSS_UNITS",dr.CSS/dr.PDF);let un=dr;class uw extends r0{constructor({docId:e,ownerDocument:s=globalThis.document}){super();w(this,W);w(this,ur);w(this,gr);w(this,Gs);w(this,ki);w(this,me);w(this,pd);w(this,fr,0);b(this,ki,e),b(this,me,s)}addFilter(e){if(!e)return"none";let s=c(this,W,we).get(e);if(s)return s;const[i,n,r]=y(this,W,Rd).call(this,e),o=e.length===1?i:`${i}${n}${r}`;if(s=c(this,W,we).get(o),s)return c(this,W,we).set(e,s),s;const h=`g_${c(this,ki)}_transfer_map_${Pe(this,fr)._++}`,l=y(this,W,Fa).call(this,h);c(this,W,we).set(e,l),c(this,W,we).set(o,l);const d=y(this,W,Ia).call(this,h);return y(this,W,jl).call(this,i,n,r,d),l}addHCMFilter(e,s){var p;const i=`${e}-${s}`,n="base";let r=c(this,W,La).get(n);if((r==null?void 0:r.key)===i||(r?((p=r.filter)==null||p.remove(),r.key=i,r.url="none",r.filter=null):(r={key:i,url:"none",filter:null},c(this,W,La).set(n,r)),!e||!s))return r.url;const o=y(this,W,Nl).call(this,e);e=V.makeHexColor(...o);const h=y(this,W,Nl).call(this,s);if(s=V.makeHexColor(...h),c(this,W,Ra).style.color="",e==="#000000"&&s==="#ffffff"||e===s)return r.url;const l=new Array(256);for(let m=0;m<=255;m++){const _=m/255;l[m]=_<=.03928?_/12.92:((_+.055)/1.055)**2.4}const d=l.join(","),u=`g_${c(this,ki)}_hcm_filter`,g=r.filter=y(this,W,Ia).call(this,u);y(this,W,jl).call(this,d,d,d,g),y(this,W,tf).call(this,g);const f=(m,_)=>{const v=o[m]/255,x=h[m]/255,S=new Array(_+1);for(let C=0;C<=_;C++)S[C]=v+C/_*(x-v);return S.join(",")};return y(this,W,jl).call(this,f(0,5),f(1,5),f(2,5),g),r.url=y(this,W,Fa).call(this,u),r.url}addAlphaFilter(e){let s=c(this,W,we).get(e);if(s)return s;const[i]=y(this,W,Rd).call(this,[e]),n=`alpha_${i}`;if(s=c(this,W,we).get(n),s)return c(this,W,we).set(e,s),s;const r=`g_${c(this,ki)}_alpha_map_${Pe(this,fr)._++}`,o=y(this,W,Fa).call(this,r);c(this,W,we).set(e,o),c(this,W,we).set(n,o);const h=y(this,W,Ia).call(this,r);return y(this,W,ef).call(this,i,h),o}addLuminosityFilter(e){let s=c(this,W,we).get(e||"luminosity");if(s)return s;let i,n;if(e?([i]=y(this,W,Rd).call(this,[e]),n=`luminosity_${i}`):n="luminosity",s=c(this,W,we).get(n),s)return c(this,W,we).set(e,s),s;const r=`g_${c(this,ki)}_luminosity_map_${Pe(this,fr)._++}`,o=y(this,W,Fa).call(this,r);c(this,W,we).set(e,o),c(this,W,we).set(n,o);const h=y(this,W,Ia).call(this,r);return y(this,W,tb).call(this,h),e&&y(this,W,ef).call(this,i,h),o}addHighlightHCMFilter(e,s,i,n,r){var x;const o=`${s}-${i}-${n}-${r}`;let h=c(this,W,La).get(e);if((h==null?void 0:h.key)===o||(h?((x=h.filter)==null||x.remove(),h.key=o,h.url="none",h.filter=null):(h={key:o,url:"none",filter:null},c(this,W,La).set(e,h)),!s||!i))return h.url;const[l,d]=[s,i].map(y(this,W,Nl).bind(this));let u=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),g=Math.round(.2126*d[0]+.7152*d[1]+.0722*d[2]),[f,p]=[n,r].map(y(this,W,Nl).bind(this));g<u&&([u,g,f,p]=[g,u,p,f]),c(this,W,Ra).style.color="";const m=(S,C,E)=>{const k=new Array(256),P=(g-u)/E,D=S/255,F=(C-S)/(255*E);let B=0;for(let O=0;O<=E;O++){const R=Math.round(u+O*P),L=D+O*F;for(let j=B;j<=R;j++)k[j]=L;B=R+1}for(let O=B;O<256;O++)k[O]=k[B-1];return k.join(",")},_=`g_${c(this,ki)}_hcm_${e}_filter`,v=h.filter=y(this,W,Ia).call(this,_);return y(this,W,tf).call(this,v),y(this,W,jl).call(this,m(f[0],p[0],5),m(f[1],p[1],5),m(f[2],p[2],5),v),h.url=y(this,W,Fa).call(this,_),h.url}destroy(e=!1){e&&c(this,W,La).size!==0||(c(this,Gs)&&(c(this,Gs).parentNode.parentNode.remove(),b(this,Gs,null)),c(this,gr)&&(c(this,gr).clear(),b(this,gr,null)),b(this,fr,0))}}ur=new WeakMap,gr=new WeakMap,Gs=new WeakMap,ki=new WeakMap,me=new WeakMap,pd=new WeakMap,fr=new WeakMap,W=new WeakSet,we=function(){return c(this,gr)||b(this,gr,new Map)},La=function(){return c(this,pd)||b(this,pd,new Map)},Ra=function(){if(!c(this,Gs)){const e=c(this,me).createElement("div"),{style:s}=e;s.visibility="hidden",s.contain="strict",s.width=s.height=0,s.position="absolute",s.top=s.left=0,s.zIndex=-1;const i=c(this,me).createElementNS(Si,"svg");i.setAttribute("width",0),i.setAttribute("height",0),b(this,Gs,c(this,me).createElementNS(Si,"defs")),e.append(i),i.append(c(this,Gs)),c(this,me).body.append(e)}return c(this,Gs)},Rd=function(e){if(e.length===1){const l=e[0],d=new Array(256);for(let g=0;g<256;g++)d[g]=l[g]/255;const u=d.join(",");return[u,u,u]}const[s,i,n]=e,r=new Array(256),o=new Array(256),h=new Array(256);for(let l=0;l<256;l++)r[l]=s[l]/255,o[l]=i[l]/255,h[l]=n[l]/255;return[r.join(","),o.join(","),h.join(",")]},Fa=function(e){if(c(this,ur)===void 0){b(this,ur,"");const s=c(this,me).URL;s!==c(this,me).baseURI&&(id(s)?st('#createUrl: ignore "data:"-URL for performance reasons.'):b(this,ur,s.split("#",1)[0]))}return`url(${c(this,ur)}#${e})`},tb=function(e){const s=c(this,me).createElementNS(Si,"feColorMatrix");s.setAttribute("type","matrix"),s.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),e.append(s)},tf=function(e){const s=c(this,me).createElementNS(Si,"feColorMatrix");s.setAttribute("type","matrix"),s.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),e.append(s)},Ia=function(e){const s=c(this,me).createElementNS(Si,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",e),c(this,W,Ra).append(s),s},Il=function(e,s,i){const n=c(this,me).createElementNS(Si,s);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),e.append(n)},jl=function(e,s,i,n){const r=c(this,me).createElementNS(Si,"feComponentTransfer");n.append(r),y(this,W,Il).call(this,r,"feFuncR",e),y(this,W,Il).call(this,r,"feFuncG",s),y(this,W,Il).call(this,r,"feFuncB",i)},ef=function(e,s){const i=c(this,me).createElementNS(Si,"feComponentTransfer");s.append(i),y(this,W,Il).call(this,i,"feFuncA",e)},Nl=function(e){return c(this,W,Ra).style.color=e,wg(getComputedStyle(c(this,W,Ra)).getPropertyValue("color"))};class gw extends o0{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}async function sd(a,t="text"){if(oh(a,document.baseURI)){const e=await fetch(a);if(!e.ok)throw new Error(e.statusText);switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",a,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"arraybuffer":case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class l0 extends a0{_fetchData(t,e){return sd(t,this.isCompressed?"arraybuffer":"text").then(s=>({cMapData:s instanceof ArrayBuffer?new Uint8Array(s):ed(s),compressionType:e}))}}class c0 extends h0{_fetchData(t){return sd(t,"arraybuffer").then(e=>new Uint8Array(e))}}class vg extends dw{_createSVG(t){return document.createElementNS(Si,t)}}class rh{constructor({viewBox:t,scale:e,rotation:s,offsetX:i=0,offsetY:n=0,dontFlip:r=!1}){this.viewBox=t,this.scale=e,this.rotation=s,this.offsetX=i,this.offsetY=n;const o=(t[2]+t[0])/2,h=(t[3]+t[1])/2;let l,d,u,g;switch(s%=360,s<0&&(s+=360),s){case 180:l=-1,d=0,u=0,g=1;break;case 90:l=0,d=1,u=1,g=0;break;case 270:l=0,d=-1,u=-1,g=0;break;case 0:l=1,d=0,u=0,g=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}r&&(u=-u,g=-g);let f,p,m,_;l===0?(f=Math.abs(h-t[1])*e+i,p=Math.abs(o-t[0])*e+n,m=(t[3]-t[1])*e,_=(t[2]-t[0])*e):(f=Math.abs(o-t[0])*e+i,p=Math.abs(h-t[1])*e+n,m=(t[2]-t[0])*e,_=(t[3]-t[1])*e),this.transform=[l*e,d*e,u*e,g*e,f-l*e*o-u*e*h,p-d*e*o-g*e*h],this.width=m,this.height=_}get rawDims(){const{viewBox:t}=this;return rt(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new rh({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return V.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=V.applyTransform([t[0],t[1]],this.transform),s=V.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return V.applyInverseTransform([t,e],this.transform)}}class yg extends dn{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function id(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function _g(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function fw(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function pw(a,t="document.pdf"){if(typeof a!="string")return t;if(id(a))return st('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(a);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class d0{constructor(){Q(this,"started",Object.create(null));Q(this,"times",[])}time(t){t in this.started&&st(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||st(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
499
- `);return t.join("")}}function oh(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function os(a){a.preventDefault()}function u0(a){console.log("Deprecated API usage: "+a)}let g0;class f0{static toDateObject(t){if(!t||typeof t!="string")return null;g0||(g0=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const e=g0.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(e[5],10);o=o>=0&&o<=59?o:0;let h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const l=e[7]||"Z";let d=parseInt(e[8],10);d=d>=0&&d<=23?d:0;let u=parseInt(e[9],10)||0;return u=u>=0&&u<=59?u:0,l==="-"?(r+=d,o+=u):l==="+"&&(r-=d,o-=u),new Date(Date.UTC(s,i,n,r,o,h))}}function mw(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new rh({viewBox:n,scale:t,rotation:e})}function wg(a){if(a.startsWith("#")){const t=parseInt(a.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return a.startsWith("rgb(")?a.slice(4,-1).split(",").map(t=>parseInt(t)):a.startsWith("rgba(")?a.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(st(`Not a valid color format: "${a}"`),[0,0,0])}function bw(a){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of a.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;a.set(e,wg(s))}t.remove()}function Tt(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function Ci(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform().invertSelf();return[t,e,s,i,n,r]}function ar(a,t,e=!1,s=!0){if(t instanceof rh){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Ie.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,d=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=d,r.height=u):(r.width=u,r.height=d)}s&&a.setAttribute("data-main-rotation",t.rotation)}class xg{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}const Mi=class Mi{constructor(t){w(this,Me);w(this,pn,null);w(this,pr,null);w(this,As);w(this,mr,null);w(this,bh,null);b(this,As,t),c(Mi,vh)||b(Mi,vh,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=b(this,pn,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=c(this,As)._uiManager._signal;t.addEventListener("contextmenu",os,{signal:e}),t.addEventListener("pointerdown",y(Mi,md,eb),{signal:e});const s=b(this,mr,document.createElement("div"));s.className="buttons",t.append(s);const i=c(this,As).toolbarPosition;if(i){const{style:n}=t,r=c(this,As)._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return y(this,Me,nb).call(this),t}get div(){return c(this,pn)}hide(){var t;c(this,pn).classList.add("hidden"),(t=c(this,pr))==null||t.hideDropdown()}show(){var t;c(this,pn).classList.remove("hidden"),(t=c(this,bh))==null||t.shown()}async addAltText(t){const e=await t.render();y(this,Me,Fd).call(this,e),c(this,mr).prepend(e,c(this,Me,sf)),b(this,bh,t)}addColorPicker(t){b(this,pr,t);const e=t.renderButton();y(this,Me,Fd).call(this,e),c(this,mr).prepend(e,c(this,Me,sf))}remove(){var t;c(this,pn).remove(),(t=c(this,pr))==null||t.destroy(),b(this,pr,null)}};pn=new WeakMap,pr=new WeakMap,As=new WeakMap,mr=new WeakMap,bh=new WeakMap,vh=new WeakMap,md=new WeakSet,eb=function(t){t.stopPropagation()},Me=new WeakSet,sb=function(t){c(this,As)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},ib=function(t){c(this,As)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},Fd=function(t){const e=c(this,As)._uiManager._signal;t.addEventListener("focusin",y(this,Me,sb).bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",y(this,Me,ib).bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",os,{signal:e})},nb=function(){const{editorType:t,_uiManager:e}=c(this,As),s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",c(Mi,vh)[t]),y(this,Me,Fd).call(this,s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),c(this,mr).append(s)},sf=function(){const t=document.createElement("div");return t.className="divider",t},w(Mi,md),w(Mi,vh,null);let Sg=Mi;class vw{constructor(t){w(this,mn);w(this,yh,null);w(this,br,null);w(this,vr);b(this,vr,t)}show(t,e,s){const[i,n]=y(this,mn,ob).call(this,e,s),{style:r}=c(this,br)||b(this,br,y(this,mn,rb).call(this));t.append(c(this,br)),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){c(this,br).remove()}}yh=new WeakMap,br=new WeakMap,vr=new WeakMap,mn=new WeakSet,rb=function(){const t=b(this,br,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",os,{signal:c(this,vr)._signal});const e=b(this,yh,document.createElement("div"));return e.className="buttons",t.append(e),y(this,mn,ab).call(this),t},ob=function(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const o=n.x+(e?n.width:0);if(r>s){i=o,s=r;continue}e?o>i&&(i=o):o<i&&(i=o)}return[e?1-i:i,s]},ab=function(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=c(this,vr)._signal;t.addEventListener("contextmenu",os,{signal:s}),t.addEventListener("click",()=>{c(this,vr).highlightSelection("floating_button")},{signal:s}),c(this,yh).append(t)};function nd(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}function yw(a){return Math.round(Math.min(255,Math.max(1,255*a))).toString(16).padStart(2,"0")}class _w{constructor(){w(this,bd,0)}get id(){return`${Q_}${Pe(this,bd)._++}`}}bd=new WeakMap;const $g=class $g{constructor(){w(this,Io);w(this,Fo,cw());w(this,_h,0);w(this,be,null)}static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return rt(this,"_isSVGFittingCanvas",n)}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return y(this,Io,Id).call(this,`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return y(this,Io,Id).call(this,t,t)}async getFromBlob(t,e){const s=await e;return y(this,Io,Id).call(this,t,s)}async getFromId(t){c(this,be)||b(this,be,new Map);const e=c(this,be).get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){c(this,be)||b(this,be,new Map);let s=c(this,be).get(t);if(s!=null&&s.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${c(this,Fo)}_${Pe(this,_h)._++}`,refCounter:1,isSvg:!1},c(this,be).set(t,s),c(this,be).set(s.id,s),s}getSvgUrl(t){const e=c(this,be).get(t);return e!=null&&e.isSvg?e.svgUrl:null}deleteId(t){var i;c(this,be)||b(this,be,new Map);const e=c(this,be).get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const n=new OffscreenCanvas(s.width,s.height);n.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=n.convertToBlob()}(i=s.close)==null||i.call(s),e.bitmap=null}isValidId(t){return t.startsWith(`image_${c(this,Fo)}_`)}};Fo=new WeakMap,_h=new WeakMap,be=new WeakMap,Io=new WeakSet,Id=async function(t,e){c(this,be)||b(this,be,new Map);let s=c(this,be).get(t);if(s===null)return null;if(s!=null&&s.bitmap)return s.refCounter+=1,s;try{s||(s={bitmap:null,id:`image_${c(this,Fo)}_${Pe(this,_h)._++}`,refCounter:0,isSvg:!1});let i;if(typeof e=="string"?(s.url=e,i=await sd(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=$g._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((l,d)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,l()},r.onload=async()=>{const u=s.svgUrl=r.result;o.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},o.onerror=r.onerror=d});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){console.error(i),s=null}return c(this,be).set(t,s),s&&c(this,be).set(s.id,s),s};let Cg=$g;class ww{constructor(t=128){w(this,Zt,[]);w(this,bn,!1);w(this,wh);w(this,te,-1);b(this,wh,t)}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),c(this,bn))return;const h={cmd:t,undo:e,post:s,type:n};if(c(this,te)===-1){c(this,Zt).length>0&&(c(this,Zt).length=0),b(this,te,0),c(this,Zt).push(h);return}if(r&&c(this,Zt)[c(this,te)].type===n){o&&(h.undo=c(this,Zt)[c(this,te)].undo),c(this,Zt)[c(this,te)]=h;return}const l=c(this,te)+1;l===c(this,wh)?c(this,Zt).splice(0,1):(b(this,te,l),l<c(this,Zt).length&&c(this,Zt).splice(l)),c(this,Zt).push(h)}undo(){if(c(this,te)===-1)return;b(this,bn,!0);const{undo:t,post:e}=c(this,Zt)[c(this,te)];t(),e==null||e(),b(this,bn,!1),b(this,te,c(this,te)-1)}redo(){if(c(this,te)<c(this,Zt).length-1){b(this,te,c(this,te)+1),b(this,bn,!0);const{cmd:t,post:e}=c(this,Zt)[c(this,te)];t(),e==null||e(),b(this,bn,!1)}}hasSomethingToUndo(){return c(this,te)!==-1}hasSomethingToRedo(){return c(this,te)<c(this,Zt).length-1}destroy(){b(this,Zt,null)}}Zt=new WeakMap,bn=new WeakMap,wh=new WeakMap,te=new WeakMap;class ah{constructor(t){w(this,vd);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Ie.platform;for(const[s,i,n={}]of t)for(const r of s){const o=r.startsWith("mac+");e&&o?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!o&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(y(this,vd,hb).call(this,e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:o=null}}=s;o&&!o(t,e)||(i.bind(t,...r,e)(),n||(e.stopPropagation(),e.preventDefault()))}}vd=new WeakSet,hb=function(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e};const yd=class yd{get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return bw(t),rt(this,"_colors",t)}convert(t){const e=wg(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return yd._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?V.makeHexColor(...e):t}};Q(yd,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Ag=yd;const Xo=class Xo{constructor(t,e,s,i,n,r,o,h,l,d,u){w(this,N);w(this,jo,new AbortController);w(this,$e,null);w(this,$t,new Map);w(this,re,new Map);w(this,No,null);w(this,Oi,null);w(this,Bo,null);w(this,Ts,new ww);w(this,vn,null);w(this,Ho,0);w(this,yr,new Set);w(this,Us,null);w(this,Es,null);w(this,_r,new Set);w(this,xh,!1);w(this,Sh,!1);w(this,Wo,!1);w(this,Ch,null);w(this,Ys,null);w(this,yn,null);w(this,zo,null);w(this,_n,!1);w(this,qs,null);w(this,_d,new _w);w(this,wn,!1);w(this,Ah,!1);w(this,xn,null);w(this,wr,null);w(this,Th,null);w(this,Eh,null);w(this,ee,tt.NONE);w(this,pt,new Set);w(this,Di,null);w(this,xr,null);w(this,kh,null);w(this,Mh,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});w(this,Sn,[0,0]);w(this,$s,null);w(this,Pi,null);w(this,Oh,null);w(this,ls,null);const g=this._signal=c(this,jo).signal;b(this,Pi,t),b(this,Oh,e),b(this,No,s),this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",f=>this.updateParams(f.type,f.value),{signal:g}),y(this,N,db).call(this),y(this,N,pb).call(this),y(this,N,rf).call(this),b(this,Oi,n.annotationStorage),b(this,Ch,n.filterFactory),b(this,xr,r),b(this,zo,o||null),b(this,xh,h),b(this,Sh,l),b(this,Wo,d),b(this,Eh,u||null),this.viewParameters={realScale:un.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=Xo.prototype,e=r=>c(r,Pi).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:h}=o;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return rt(this,"_keyboardManager",new ah([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&c(r,Pi).contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&c(r,Pi).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}destroy(){var t,e,s,i;(t=c(this,ls))==null||t.resolve(),b(this,ls,null),(e=c(this,jo))==null||e.abort(),b(this,jo,null),this._signal=null;for(const n of c(this,re).values())n.destroy();c(this,re).clear(),c(this,$t).clear(),c(this,_r).clear(),b(this,$e,null),c(this,pt).clear(),c(this,Ts).destroy(),(s=c(this,No))==null||s.destroy(),(i=c(this,qs))==null||i.hide(),b(this,qs,null),c(this,Ys)&&(clearTimeout(c(this,Ys)),b(this,Ys,null)),c(this,$s)&&(clearTimeout(c(this,$s)),b(this,$s,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return c(this,Eh)}get useNewAltTextFlow(){return c(this,Sh)}get useNewAltTextWhenAddingImage(){return c(this,Wo)}get hcmFilter(){return rt(this,"hcmFilter",c(this,xr)?c(this,Ch).addHCMFilter(c(this,xr).foreground,c(this,xr).background):"none")}get direction(){return rt(this,"direction",getComputedStyle(c(this,Pi)).direction)}get highlightColors(){return rt(this,"highlightColors",c(this,zo)?new Map(c(this,zo).split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return rt(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){b(this,Th,t)}editAltText(t,e=!1){var s;(s=c(this,No))==null||s.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":b(this,Wo,e);break}}onPageChanging({pageNumber:t}){b(this,Ho,t-1)}focusMainContainer(){c(this,Pi).focus()}findParent(t,e){for(const s of c(this,re).values()){const{x:i,y:n,width:r,height:o}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+o)return s}return null}disableUserSelect(t=!1){c(this,Oh).classList.toggle("noUserSelect",t)}addShouldRescale(t){c(this,_r).add(t)}removeShouldRescale(t){c(this,_r).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*un.PDF_TO_CSS_UNITS;for(const e of c(this,_r))e.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,o=e.toString(),l=y(this,N,jd).call(this,e).closest(".textLayer"),d=this.getSelectionBoxes(l);if(!d)return;e.empty();const u=y(this,N,nf).call(this,l),g=c(this,ee)===tt.NONE,f=()=>{u==null||u.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:d,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:o}),g&&this.showAllEditors("highlight",!0,!0)};if(g){this.switchToMode(tt.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&c(this,Oi)&&!c(this,Oi).has(t.id)&&c(this,Oi).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,c(this,_n)&&(b(this,_n,!1),y(this,N,Nd).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of c(this,pt))if(e.div.contains(t)){b(this,wr,[e,t]),e._focusEventsAllowed=!1;break}}focus(){if(!c(this,wr))return;const[t,e]=c(this,wr);b(this,wr,null),e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}addEditListeners(){y(this,N,rf).call(this),y(this,N,of).call(this)}removeEditListeners(){y(this,N,fb).call(this),y(this,N,af).call(this)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of c(this,Es))if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of c(this,Es))if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){var s;if(t.preventDefault(),(s=c(this,$e))==null||s.commitOrRemove(),!this.hasSelection)return;const e=[];for(const i of c(this,pt)){const n=i.serialize(!0);n&&e.push(n)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of c(this,Es))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){st(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)y(this,N,hf).call(this,h);y(this,N,lf).call(this,n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){st(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),c(this,ee)!==tt.NONE&&!this.isEditorHandlingKeyboard&&Xo._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,c(this,_n)&&(b(this,_n,!1),y(this,N,Nd).call(this,"main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}setEditingState(t){t?(y(this,N,ub).call(this),y(this,N,of).call(this),y(this,N,Le).call(this,{isEditing:c(this,ee)!==tt.NONE,isEmpty:y(this,N,Bl).call(this),hasSomethingToUndo:c(this,Ts).hasSomethingToUndo(),hasSomethingToRedo:c(this,Ts).hasSomethingToRedo(),hasSelectedEditor:!1})):(y(this,N,gb).call(this),y(this,N,af).call(this),y(this,N,Le).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!c(this,Es)){b(this,Es,t);for(const e of c(this,Es))y(this,N,Vn).call(this,e.defaultPropertiesToUpdate)}}getId(){return c(this,_d).id}get currentLayer(){return c(this,re).get(c(this,Ho))}getLayer(t){return c(this,re).get(t)}get currentPageIndex(){return c(this,Ho)}addLayer(t){c(this,re).set(t.pageIndex,t),c(this,wn)?t.enable():t.disable()}removeLayer(t){c(this,re).delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(c(this,ee)!==t&&!(c(this,ls)&&(await c(this,ls).promise,!c(this,ls)))){if(b(this,ls,Promise.withResolvers()),b(this,ee,t),t===tt.NONE){this.setEditingState(!1),y(this,N,bb).call(this),c(this,ls).resolve();return}this.setEditingState(!0),await y(this,N,mb).call(this),this.unselectAll();for(const i of c(this,re).values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),c(this,ls).resolve();return}for(const i of c(this,$t).values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();c(this,ls).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==c(this,ee)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){var s;if(c(this,Es)){switch(t){case K.CREATE:this.currentLayer.addNewEditor();return;case K.HIGHLIGHT_DEFAULT_COLOR:(s=c(this,Th))==null||s.updateColor(e);break;case K.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(c(this,kh)||b(this,kh,new Map)).set(t,e),this.showAllEditors("highlight",e);break}for(const i of c(this,pt))i.updateParams(t,e);for(const i of c(this,Es))i.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){var n;for(const r of c(this,$t).values())r.editorType===t&&r.show(e);(((n=c(this,kh))==null?void 0:n.get(K.HIGHLIGHT_SHOW_ALL))??!0)!==e&&y(this,N,Vn).call(this,[[K.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(c(this,Ah)!==t){b(this,Ah,t);for(const e of c(this,re).values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}getEditors(t){const e=[];for(const s of c(this,$t).values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return c(this,$t).get(t)}addEditor(t){c(this,$t).set(t.id,t)}removeEditor(t){var e;t.div.contains(document.activeElement)&&(c(this,Ys)&&clearTimeout(c(this,Ys)),b(this,Ys,setTimeout(()=>{this.focusMainContainer(),b(this,Ys,null)},0))),c(this,$t).delete(t.id),this.unselect(t),(!t.annotationElementId||!c(this,yr).has(t.annotationElementId))&&((e=c(this,Oi))==null||e.remove(t.id))}addDeletedAnnotationElement(t){c(this,yr).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return c(this,yr).has(t)}removeDeletedAnnotationElement(t){c(this,yr).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){c(this,$e)!==t&&(b(this,$e,t),t&&y(this,N,Vn).call(this,t.propertiesToUpdate))}updateUI(t){c(this,N,vb)===t&&y(this,N,Vn).call(this,t.propertiesToUpdate)}toggleSelected(t){if(c(this,pt).has(t)){c(this,pt).delete(t),t.unselect(),y(this,N,Le).call(this,{hasSelectedEditor:this.hasSelection});return}c(this,pt).add(t),t.select(),y(this,N,Vn).call(this,t.propertiesToUpdate),y(this,N,Le).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const e of c(this,pt))e!==t&&e.unselect();c(this,pt).clear(),c(this,pt).add(t),t.select(),y(this,N,Vn).call(this,t.propertiesToUpdate),y(this,N,Le).call(this,{hasSelectedEditor:!0})}isSelected(t){return c(this,pt).has(t)}get firstSelectedEditor(){return c(this,pt).values().next().value}unselect(t){t.unselect(),c(this,pt).delete(t),y(this,N,Le).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return c(this,pt).size!==0}get isEnterHandled(){return c(this,pt).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){c(this,Ts).undo(),y(this,N,Le).call(this,{hasSomethingToUndo:c(this,Ts).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:y(this,N,Bl).call(this)})}redo(){c(this,Ts).redo(),y(this,N,Le).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:c(this,Ts).hasSomethingToRedo(),isEmpty:y(this,N,Bl).call(this)})}addCommands(t){c(this,Ts).add(t),y(this,N,Le).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:y(this,N,Bl).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...c(this,pt)],e=()=>{for(const i of t)i.remove()},s=()=>{for(const i of t)y(this,N,hf).call(this,i)};this.addCommands({cmd:e,undo:s,mustExec:!0})}commitOrRemove(){var t;(t=c(this,$e))==null||t.commitOrRemove()}hasSomethingToControl(){return c(this,$e)||this.hasSelection}selectAll(){for(const t of c(this,pt))t.commit();y(this,N,lf).call(this,c(this,$t).values())}unselectAll(){if(!(c(this,$e)&&(c(this,$e).commitOrRemove(),c(this,ee)!==tt.NONE))&&this.hasSelection){for(const t of c(this,pt))t.unselect();c(this,pt).clear(),y(this,N,Le).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;c(this,Sn)[0]+=t,c(this,Sn)[1]+=e;const[i,n]=c(this,Sn),r=[...c(this,pt)],o=1e3;c(this,$s)&&clearTimeout(c(this,$s)),b(this,$s,setTimeout(()=>{b(this,$s,null),c(this,Sn)[0]=c(this,Sn)[1]=0,this.addCommands({cmd:()=>{for(const h of r)c(this,$t).has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)c(this,$t).has(h.id)&&h.translateInPage(-i,-n)},mustExec:!1})},o));for(const h of r)h.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),b(this,Us,new Map);for(const t of c(this,pt))c(this,Us).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!c(this,Us))return!1;this.disableUserSelect(!1);const t=c(this,Us);b(this,Us,null);let e=!1;for(const[{x:i,y:n,pageIndex:r},o]of t)o.newX=i,o.newY=n,o.newPageIndex=r,e||(e=i!==o.savedX||n!==o.savedY||r!==o.savedPageIndex);if(!e)return!1;const s=(i,n,r,o)=>{if(c(this,$t).has(i.id)){const h=c(this,re).get(o);h?i._setParentAndPosition(h,n,r):(i.pageIndex=o,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:o}]of t)s(i,n,r,o)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:o}]of t)s(i,n,r,o)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(c(this,Us))for(const s of c(this,Us).keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){var t;return((t=this.getActive())==null?void 0:t.shouldGetKeyboardEvents())||c(this,pt).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return c(this,$e)===t}getActive(){return c(this,$e)}getMode(){return c(this,ee)}get imageManager(){return rt(this,"imageManager",new Cg)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,d=e.rangeCount;l<d;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(l,d,u,g)=>({x:(d-i)/r,y:1-(l+u-s)/n,width:g/r,height:u/n});break;case"180":o=(l,d,u,g)=>({x:1-(l+u-s)/n,y:1-(d+g-i)/r,width:u/n,height:g/r});break;case"270":o=(l,d,u,g)=>({x:1-(d+g-i)/r,y:(l-s)/n,width:g/r,height:u/n});break;default:o=(l,d,u,g)=>({x:(l-s)/n,y:(d-i)/r,width:u/n,height:g/r});break}const h=[];for(let l=0,d=e.rangeCount;l<d;l++){const u=e.getRangeAt(l);if(!u.collapsed)for(const{x:g,y:f,width:p,height:m}of u.getClientRects())p===0||m===0||h.push(o(g,f,p,m))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(c(this,Bo)||b(this,Bo,new Map)).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){var e;(e=c(this,Bo))==null||e.delete(t)}renderAnnotationElement(t){var i;const e=(i=c(this,Bo))==null?void 0:i.get(t.data.id);if(!e)return;const s=c(this,Oi).getRawValue(e);s&&(c(this,ee)===tt.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}};jo=new WeakMap,$e=new WeakMap,$t=new WeakMap,re=new WeakMap,No=new WeakMap,Oi=new WeakMap,Bo=new WeakMap,Ts=new WeakMap,vn=new WeakMap,Ho=new WeakMap,yr=new WeakMap,Us=new WeakMap,Es=new WeakMap,_r=new WeakMap,xh=new WeakMap,Sh=new WeakMap,Wo=new WeakMap,Ch=new WeakMap,Ys=new WeakMap,yn=new WeakMap,zo=new WeakMap,_n=new WeakMap,qs=new WeakMap,_d=new WeakMap,wn=new WeakMap,Ah=new WeakMap,xn=new WeakMap,wr=new WeakMap,Th=new WeakMap,Eh=new WeakMap,ee=new WeakMap,pt=new WeakMap,Di=new WeakMap,xr=new WeakMap,kh=new WeakMap,Mh=new WeakMap,Sn=new WeakMap,$s=new WeakMap,Pi=new WeakMap,Oh=new WeakMap,ls=new WeakMap,N=new WeakSet,jd=function({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t},nf=function(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of c(this,re).values())if(s.hasTextLayer(t))return s;return null},lb=function(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=y(this,N,jd).call(this,t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(c(this,qs)||b(this,qs,new vw(this)),c(this,qs).show(s,i,this.direction==="ltr"))},cb=function(){var n,r,o;const t=document.getSelection();if(!t||t.isCollapsed){c(this,Di)&&((n=c(this,qs))==null||n.hide(),b(this,Di,null),y(this,N,Le).call(this,{hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===c(this,Di))return;const i=y(this,N,jd).call(this,t).closest(".textLayer");if(!i){c(this,Di)&&((r=c(this,qs))==null||r.hide(),b(this,Di,null),y(this,N,Le).call(this,{hasSelectedText:!1}));return}if((o=c(this,qs))==null||o.hide(),b(this,Di,e),y(this,N,Le).call(this,{hasSelectedText:!0}),!(c(this,ee)!==tt.HIGHLIGHT&&c(this,ee)!==tt.NONE)&&(c(this,ee)===tt.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),b(this,_n,this.isShiftKeyDown),!this.isShiftKeyDown)){const h=c(this,ee)===tt.HIGHLIGHT?y(this,N,nf).call(this,i):null;h==null||h.toggleDrawing();const l=new AbortController,d=this.combinedSignal(l),u=g=>{g.type==="pointerup"&&g.button!==0||(l.abort(),h==null||h.toggleDrawing(!0),g.type==="pointerup"&&y(this,N,Nd).call(this,"main_toolbar"))};window.addEventListener("pointerup",u,{signal:d}),window.addEventListener("blur",u,{signal:d})}},Nd=function(t=""){c(this,ee)===tt.HIGHLIGHT?this.highlightSelection(t):c(this,xh)&&y(this,N,lb).call(this)},db=function(){document.addEventListener("selectionchange",y(this,N,cb).bind(this),{signal:this._signal})},ub=function(){if(c(this,yn))return;b(this,yn,new AbortController);const t=this.combinedSignal(c(this,yn));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},gb=function(){var t;(t=c(this,yn))==null||t.abort(),b(this,yn,null)},rf=function(){if(c(this,xn))return;b(this,xn,new AbortController);const t=this.combinedSignal(c(this,xn));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},fb=function(){var t;(t=c(this,xn))==null||t.abort(),b(this,xn,null)},of=function(){if(c(this,vn))return;b(this,vn,new AbortController);const t=this.combinedSignal(c(this,vn));document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})},af=function(){var t;(t=c(this,vn))==null||t.abort(),b(this,vn,null)},pb=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Le=function(t){Object.entries(t).some(([s,i])=>c(this,Mh)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(c(this,Mh),t)}),c(this,ee)===tt.HIGHLIGHT&&t.hasSelectedEditor===!1&&y(this,N,Vn).call(this,[[K.HIGHLIGHT_FREE,!0]]))},Vn=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},mb=async function(){if(!c(this,wn)){b(this,wn,!0);const t=[];for(const e of c(this,re).values())t.push(e.enable());await Promise.all(t);for(const e of c(this,$t).values())e.enable()}},bb=function(){if(this.unselectAll(),c(this,wn)){b(this,wn,!1);for(const t of c(this,re).values())t.disable();for(const t of c(this,$t).values())t.disable()}},hf=function(t){const e=c(this,re).get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},vb=function(){let t=null;for(t of c(this,pt));return t},Bl=function(){if(c(this,$t).size===0)return!0;if(c(this,$t).size===1)for(const t of c(this,$t).values())return t.isEmpty();return!1},lf=function(t){for(const e of c(this,pt))e.unselect();c(this,pt).clear();for(const e of t)e.isEmpty()||(c(this,pt).add(e),e.select());y(this,N,Le).call(this,{hasSelectedEditor:this.hasSelection})},Q(Xo,"TRANSLATE_SMALL",1),Q(Xo,"TRANSLATE_BIG",10);let hr=Xo;const ie=class ie{constructor(t){w(this,ti);w(this,se,null);w(this,Ks,!1);w(this,ks,null);w(this,Qs,null);w(this,Ke,null);w(this,Vo,!1);w(this,Js,null);w(this,Be,null);w(this,Li,null);w(this,Sr,null);w(this,Zs,!1);b(this,Be,t),b(this,Zs,t._uiManager.useNewAltTextFlow),c(ie,Go)||b(ie,Go,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(t){ie._l10nPromise||(ie._l10nPromise=t)}async render(){const t=b(this,ks,document.createElement("button"));t.className="altText";let e;c(this,Zs)?(t.classList.add("new"),e=await ie._l10nPromise.get(c(ie,Go).missing)):e=await ie._l10nPromise.get("pdfjs-editor-alt-text-button-label"),t.textContent=e,t.setAttribute("aria-label",e),t.tabIndex="0";const s=c(this,Be)._uiManager._signal;t.addEventListener("contextmenu",os,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),c(this,Be)._uiManager.editAltText(c(this,Be)),c(this,Zs)&&c(this,Be)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:c(this,ti,Bd)}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(b(this,Vo,!0),i(n))},{signal:s}),await y(this,ti,Hd).call(this),t}finish(){c(this,ks)&&(c(this,ks).focus({focusVisible:c(this,Vo)}),b(this,Vo,!1))}isEmpty(){return c(this,Zs)?c(this,se)===null:!c(this,se)&&!c(this,Ks)}hasData(){return c(this,Zs)?c(this,se)!==null||!!c(this,Li):this.isEmpty()}get guessedText(){return c(this,Li)}async setGuessedText(t){c(this,se)===null&&(b(this,Li,t),b(this,Sr,await ie._l10nPromise.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer")({generatedAltText:t})),y(this,ti,Hd).call(this))}toggleAltTextBadge(t=!1){var e;if(!c(this,Zs)||c(this,se)){(e=c(this,Js))==null||e.remove(),b(this,Js,null);return}if(!c(this,Js)){const s=b(this,Js,document.createElement("div"));s.className="noAltTextBadge",c(this,Be).div.append(s)}c(this,Js).classList.toggle("hidden",!t)}serialize(t){let e=c(this,se);return!t&&c(this,Li)===e&&(e=c(this,Sr)),{altText:e,decorative:c(this,Ks),guessedText:c(this,Li),textWithDisclaimer:c(this,Sr)}}get data(){return{altText:c(this,se),decorative:c(this,Ks)}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(b(this,Li,s),b(this,Sr,i)),!(c(this,se)===t&&c(this,Ks)===e)&&(n||(b(this,se,t),b(this,Ks,e)),y(this,ti,Hd).call(this))}toggle(t=!1){c(this,ks)&&(!t&&c(this,Ke)&&(clearTimeout(c(this,Ke)),b(this,Ke,null)),c(this,ks).disabled=!t)}shown(){c(this,Be)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:c(this,ti,Bd)}})}destroy(){var t,e;(t=c(this,ks))==null||t.remove(),b(this,ks,null),b(this,Qs,null),(e=c(this,Js))==null||e.remove(),b(this,Js,null)}};se=new WeakMap,Ks=new WeakMap,ks=new WeakMap,Qs=new WeakMap,Ke=new WeakMap,Vo=new WeakMap,Js=new WeakMap,Be=new WeakMap,Li=new WeakMap,Sr=new WeakMap,Zs=new WeakMap,Go=new WeakMap,ti=new WeakSet,Bd=function(){return c(this,se)&&"added"||c(this,se)===null&&this.guessedText&&"review"||"missing"},Hd=async function(){var i,n;const t=c(this,ks);if(!t)return;if(c(this,Zs)){if(t.classList.toggle("done",!!c(this,se)),ie._l10nPromise.get(c(ie,Go)[c(this,ti,Bd)]).then(r=>{t.setAttribute("aria-label",r);for(const o of t.childNodes)if(o.nodeType===Node.TEXT_NODE){o.textContent=r;break}}),!c(this,se)){(i=c(this,Qs))==null||i.remove();return}}else{if(!c(this,se)&&!c(this,Ks)){t.classList.remove("done"),(n=c(this,Qs))==null||n.remove();return}t.classList.add("done"),ie._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(r=>{t.setAttribute("aria-label",r)})}let e=c(this,Qs);if(!e){b(this,Qs,e=document.createElement("span")),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${c(this,Be).id}`;const r=100,o=c(this,Be)._uiManager._signal;o.addEventListener("abort",()=>{clearTimeout(c(this,Ke)),b(this,Ke,null)},{once:!0}),t.addEventListener("mouseenter",()=>{b(this,Ke,setTimeout(()=>{b(this,Ke,null),c(this,Qs).classList.add("show"),c(this,Be)._reportTelemetry({action:"alt_text_tooltip"})},r))},{signal:o}),t.addEventListener("mouseleave",()=>{var h;c(this,Ke)&&(clearTimeout(c(this,Ke)),b(this,Ke,null)),(h=c(this,Qs))==null||h.classList.remove("show")},{signal:o})}e.innerText=c(this,Ks)?await ie._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):c(this,se),e.parentNode||t.append(e);const s=c(this,Be).getImageForAltText();s==null||s.setAttribute("aria-describedby",e.id)},w(ie,Go,null),Q(ie,"_l10nPromise",null);let rd=ie;const lt=class lt{constructor(t){w(this,et);w(this,Cr,null);w(this,Ms,null);w(this,Et,null);w(this,Uo,!1);w(this,Ar,!1);w(this,oe,null);w(this,Tr,null);w(this,Cn,null);w(this,Dh,"");w(this,Er,!1);w(this,An,null);w(this,Ph,!1);w(this,kr,!1);w(this,Ri,!1);w(this,ei,null);w(this,Yo,0);w(this,qo,0);w(this,cs,null);Q(this,"_editToolbar",null);Q(this,"_initialOptions",Object.create(null));Q(this,"_initialData",null);Q(this,"_isVisible",!0);Q(this,"_uiManager",null);Q(this,"_focusEventsAllowed",!0);w(this,Lh,!1);w(this,wd,lt._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=lt.prototype._resizeWithKeyboard,e=hr.TRANSLATE_SMALL,s=hr.TRANSLATE_BIG;return rt(this,"_resizerKeyboardManager",new ah([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],lt.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return rt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new xw({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e,s){if(lt._l10nResizer||(lt._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),lt._l10nPromise||(lt._l10nPromise=new Map([...["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-new-alt-text-added-button-label","pdfjs-editor-new-alt-text-missing-button-label","pdfjs-editor-new-alt-text-to-review-button-label"].map(n=>[n,t.get(n)]),...["pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer"].map(n=>[n,t.get.bind(t,n)])])),s!=null&&s.strings)for(const n of s.strings)lt._l10nPromise.set(n,t.get(n));if(lt._borderLineWidth!==-1)return;const i=getComputedStyle(document.documentElement);lt._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){Wt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return c(this,Lh)}set _isDraggable(t){var e;b(this,Lh,t),(e=this.div)==null||e.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=c(this,wd)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):y(this,et,Hl).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(c(this,Er)?b(this,Er,!1):this.parent.setSelected(this))}focusout(t){var s;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const e=t.relatedTarget;e!=null&&e.closest(`#${this.id}`)||(t.preventDefault(),(s=this.parent)!=null&&s.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}translate(t,e){y(this,et,cf).call(this,this.parentDimensions,t,e)}translateInPage(t,e){c(this,An)||b(this,An,[this.x,this.y]),y(this,et,cf).call(this,this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){c(this,An)||b(this,An,[this.x,this.y]);const[s,i]=this.parentDimensions;if(this.x+=t/s,this.y+=e/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:l,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,l,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:n,y:r}=this;const[o,h]=this.getBaseTranslation();n+=o,r+=h,this.div.style.left=`${(100*n).toFixed(2)}%`,this.div.style.top=`${(100*r).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!c(this,An)&&(c(this,An)[0]!==this.x||c(this,An)[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=lt,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[e,s]=this.pageDimensions;let{x:i,y:n,width:r,height:o}=this;if(r*=e,o*=s,i*=e,n*=s,this._mustFixPosition)switch(t){case 0:i=Math.max(0,Math.min(e-r,i)),n=Math.max(0,Math.min(s-o,n));break;case 90:i=Math.max(0,Math.min(e-o,i)),n=Math.min(s,Math.max(r,n));break;case 180:i=Math.min(e,Math.max(r,i)),n=Math.min(s,Math.max(o,n));break;case 270:i=Math.min(e,Math.max(o,i)),n=Math.max(0,Math.min(s-r,n));break}this.x=i/=e,this.y=n/=s;const[h,l]=this.getBaseTranslation();i+=h,n+=l;const{style:d}=this.div;d.left=`${(100*i).toFixed(2)}%`,d.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(t,e){var s;return y(s=lt,Rh,df).call(s,t,e,this.parentRotation)}pageTranslationToScreen(t,e){var s;return y(s=lt,Rh,df).call(s,t,e,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,c(this,Ar)||(this.div.style.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!c(this,Ar)&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!c(this,Ar)&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=c(this,Et))==null||t.finish()}async addEditToolbar(){return this._editToolbar||c(this,kr)?this._editToolbar:(this._editToolbar=new Sg(this),this.div.append(this._editToolbar.render()),c(this,Et)&&await this._editToolbar.addAltText(c(this,Et)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=c(this,Et))==null||t.destroy())}addContainer(t){var s;const e=(s=this._editToolbar)==null?void 0:s.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){c(this,Et)||(rd.initialize(lt._l10nPromise),b(this,Et,new rd(this)),c(this,Cr)&&(c(this,Et).data=c(this,Cr),b(this,Cr,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=c(this,Et))==null?void 0:t.data}set altTextData(t){c(this,Et)&&(c(this,Et).data=t)}get guessedAltText(){var t;return(t=c(this,Et))==null?void 0:t.guessedText}async setGuessedAltText(t){var e;await((e=c(this,Et))==null?void 0:e.setGuessedText(t))}serializeAltText(t){var e;return(e=c(this,Et))==null?void 0:e.serialize(t)}hasAltText(){return!!c(this,Et)&&!c(this,Et).isEmpty()}hasAltTextData(){var t;return((t=c(this,Et))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=c(this,Uo)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),y(this,et,mf).call(this);const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),nd(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=Ie.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(b(this,Er,!0),this._isDraggable){y(this,et,wb).call(this,t);return}y(this,et,pf).call(this,t)}moveInDOM(){c(this,ei)&&clearTimeout(c(this,ei)),b(this,ei,setTimeout(()=>{var t;b(this,ei,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[o,h]=this.pageTranslation,l=t/i,d=e/i,u=this.x*n,g=this.y*r,f=this.width*n,p=this.height*r;switch(s){case 0:return[u+l+o,r-g-d-p+h,u+l+f+o,r-g-d+h];case 90:return[u+d+o,r-g+l+h,u+d+p+o,r-g+l+f+h];case 180:return[u-l-f+o,r-g+d+h,u-l+o,r-g+d+p+h];case 270:return[u-d-p+o,r-g-l-f+h,u-d+o,r-g-l+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,o,h];case 90:return[s,e-i,h,o];case 180:return[n,e-i,o,h];case 270:return[n,e-r,h,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){b(this,kr,!0)}disableEditMode(){b(this,kr,!1)}isInEditMode(){return c(this,kr)}shouldGetKeyboardEvents(){return c(this,Ri)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){y(this,et,mf).call(this)}rotate(t){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,e=null){Wt("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,b(i,Cr,t.accessibilityData);const[n,r]=i.pageDimensions,[o,h,l,d]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=d/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t;if((t=c(this,Cn))==null||t.abort(),b(this,Cn,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),c(this,ei)&&(clearTimeout(c(this,ei)),b(this,ei,null)),y(this,et,Hl).call(this),this.removeEditToolbar(),c(this,cs)){for(const e of c(this,cs).values())clearTimeout(e);b(this,cs,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(y(this,et,yb).call(this),c(this,oe).classList.remove("hidden"),nd(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),b(this,Tr,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const e=c(this,oe).children;if(!c(this,Ms)){b(this,Ms,Array.from(e));const r=y(this,et,xb).bind(this),o=y(this,et,Sb).bind(this),h=this._uiManager._signal;for(const l of c(this,Ms)){const d=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:h}),l.addEventListener("blur",o,{signal:h}),l.addEventListener("focus",y(this,et,Cb).bind(this,d),{signal:h}),l.setAttribute("data-l10n-id",lt._l10nResizer[d])}}const s=c(this,Ms)[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(c(this,Ms).length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)c(this,oe).append(c(this,oe).firstChild);else if(n>i)for(let o=0;o<n-i;o++)c(this,oe).firstChild.before(c(this,oe).lastChild);let r=0;for(const o of e){const l=c(this,Ms)[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",lt._l10nResizer[l])}}y(this,et,bf).call(this,0),b(this,Ri,!0),c(this,oe).firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}_resizeWithKeyboard(t,e){c(this,Ri)&&y(this,et,ff).call(this,c(this,Dh),{movementX:t,movementY:e})}_stopResizingWithKeyboard(){y(this,et,Hl).call(this),this.div.focus()}select(){var t,e,s;if(this.makeResizable(),(t=this.div)==null||t.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{var i,n;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((n=this._editToolbar)==null||n.show())});return}(e=this._editToolbar)==null||e.show(),(s=c(this,Et))==null||s.toggleAltTextBadge(!1)}unselect(){var t,e,s,i,n;(t=c(this,oe))==null||t.classList.add("hidden"),(e=this.div)==null||e.classList.remove("selectedEditor"),(s=this.div)!=null&&s.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(n=c(this,Et))==null||n.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return c(this,Ph)}set isEditing(t){b(this,Ph,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){b(this,Ar,!0);const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){c(this,cs)||b(this,cs,new Map);const{action:s}=t;let i=c(this,cs).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),c(this,cs).delete(s),c(this,cs).size===0&&b(this,cs,null)},lt._telemetryTimeout),c(this,cs).set(s,i);return}t.type||(t.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),b(this,Uo,!1)}disable(){this.div&&(this.div.tabIndex=-1),b(this,Uo,!0)}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;(e==null?void 0:e.nodeName)==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}};Cr=new WeakMap,Ms=new WeakMap,Et=new WeakMap,Uo=new WeakMap,Ar=new WeakMap,oe=new WeakMap,Tr=new WeakMap,Cn=new WeakMap,Dh=new WeakMap,Er=new WeakMap,An=new WeakMap,Ph=new WeakMap,kr=new WeakMap,Ri=new WeakMap,ei=new WeakMap,Yo=new WeakMap,qo=new WeakMap,cs=new WeakMap,Lh=new WeakMap,wd=new WeakMap,et=new WeakSet,cf=function([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()},Rh=new WeakSet,df=function(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}},uf=function(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}},yb=function(){if(c(this,oe))return;b(this,oe,document.createElement("div")),c(this,oe).classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");c(this,oe).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",y(this,et,_b).bind(this,s),{signal:e}),i.addEventListener("contextmenu",os,{signal:e}),i.tabIndex=-1}this.div.prepend(c(this,oe))},_b=function(t,e){var p;e.preventDefault();const{isMac:s}=Ie.platform;if(e.button!==0||e.ctrlKey&&s)return;(p=c(this,Et))==null||p.toggle(!1);const i=this._isDraggable;this._isDraggable=!1;const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",y(this,et,ff).bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("contextmenu",os,{signal:r});const o=this.x,h=this.y,l=this.width,d=this.height,u=this.parent.div.style.cursor,g=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const f=()=>{var m;n.abort(),this.parent.togglePointerEvents(!0),(m=c(this,Et))==null||m.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=u,this.div.style.cursor=g,y(this,et,gf).call(this,o,h,l,d)};window.addEventListener("pointerup",f,{signal:r}),window.addEventListener("blur",f,{signal:r})},gf=function(t,e,s,i){const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:()=>{this.width=o,this.height=h,this.x=n,this.y=r;const[l,d]=this.parentDimensions;this.setDims(l*o,d*h),this.fixAndSetPosition()},undo:()=>{this.width=s,this.height=i,this.x=t,this.y=e;const[l,d]=this.parentDimensions;this.setDims(l*s,d*i),this.fixAndSetPosition()},mustExec:!0})},ff=function(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=lt.MIN_SIZE/s,d=lt.MIN_SIZE/i,u=X=>Math.round(X*1e4)/1e4,g=y(this,et,uf).call(this,this.rotation),f=(X,H)=>[g[0]*X+g[2]*H,g[1]*X+g[3]*H],p=y(this,et,uf).call(this,360-this.rotation),m=(X,H)=>[p[0]*X+p[2]*H,p[1]*X+p[3]*H];let _,v,x=!1,S=!1;switch(t){case"topLeft":x=!0,_=(X,H)=>[0,0],v=(X,H)=>[X,H];break;case"topMiddle":_=(X,H)=>[X/2,0],v=(X,H)=>[X/2,H];break;case"topRight":x=!0,_=(X,H)=>[X,0],v=(X,H)=>[0,H];break;case"middleRight":S=!0,_=(X,H)=>[X,H/2],v=(X,H)=>[0,H/2];break;case"bottomRight":x=!0,_=(X,H)=>[X,H],v=(X,H)=>[0,0];break;case"bottomMiddle":_=(X,H)=>[X/2,H],v=(X,H)=>[X/2,0];break;case"bottomLeft":x=!0,_=(X,H)=>[0,H],v=(X,H)=>[X,0];break;case"middleLeft":S=!0,_=(X,H)=>[0,H/2],v=(X,H)=>[X,H/2];break}const C=_(o,h),E=v(o,h);let k=f(...E);const P=u(n+k[0]),D=u(r+k[1]);let F=1,B=1,[O,R]=this.screenToPageTranslation(e.movementX,e.movementY);if([O,R]=m(O/s,R/i),x){const X=Math.hypot(o,h);F=B=Math.max(Math.min(Math.hypot(E[0]-C[0]-O,E[1]-C[1]-R)/X,1/o,1/h),l/o,d/h)}else S?F=Math.max(l,Math.min(1,Math.abs(E[0]-C[0]-O)))/o:B=Math.max(d,Math.min(1,Math.abs(E[1]-C[1]-R)))/h;const L=u(o*F),j=u(h*B);k=f(...v(L,j));const G=P-k[0],Y=D-k[1];this.width=L,this.height=j,this.x=G,this.y=Y,this.setDims(s*L,i*j),this.fixAndSetPosition()},pf=function(t){const{isMac:e}=Ie.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)},wb=function(t){const e=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();const s=new AbortController,i=this._uiManager.combinedSignal(s);if(e){this.div.classList.add("moving"),b(this,Yo,t.clientX),b(this,qo,t.clientY);const r=o=>{const{clientX:h,clientY:l}=o,[d,u]=this.screenToPageTranslation(h-c(this,Yo),l-c(this,qo));b(this,Yo,h),b(this,qo,l),this._uiManager.dragSelectedEditors(d,u)};window.addEventListener("pointermove",r,{passive:!0,capture:!0,signal:i})}const n=()=>{s.abort(),e&&this.div.classList.remove("moving"),b(this,Er,!1),this._uiManager.endDragSession()||y(this,et,pf).call(this,t)};window.addEventListener("pointerup",n,{signal:i}),window.addEventListener("blur",n,{signal:i})},mf=function(){if(c(this,Cn)||!this.div)return;b(this,Cn,new AbortController);const t=this._uiManager.combinedSignal(c(this,Cn));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},xb=function(t){lt._resizerKeyboardManager.exec(this,t)},Sb=function(t){var e;c(this,Ri)&&((e=t.relatedTarget)==null?void 0:e.parentNode)!==c(this,oe)&&y(this,et,Hl).call(this)},Cb=function(t){b(this,Dh,c(this,Ri)?t:"")},bf=function(t){if(c(this,Ms))for(const e of c(this,Ms))e.tabIndex=t},Hl=function(){if(b(this,Ri,!1),y(this,et,bf).call(this,-1),c(this,Tr)){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=c(this,Tr);y(this,et,gf).call(this,t,e,s,i),b(this,Tr,null)}},w(lt,Rh),Q(lt,"_l10nPromise",null),Q(lt,"_l10nResizer",null),Q(lt,"_borderLineWidth",-1),Q(lt,"_colorManager",new Ag),Q(lt,"_zIndex",1),Q(lt,"_telemetryTimeout",1e3);let gt=lt;class xw extends gt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const p0=3285377520,as=4294901760,Vs=65535;class m0{constructor(t){this.h1=t?t&4294967295:p0,this.h2=t?t&4294967295:p0}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let m=0,_=t.length;m<_;m++){const v=t.charCodeAt(m);v<=255?e[s++]=v:(e[s++]=v>>>8,e[s++]=v&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let o=0,h=0,l=this.h1,d=this.h2;const u=3432918353,g=461845907,f=u&Vs,p=g&Vs;for(let m=0;m<i;m++)m&1?(o=r[m],o=o*u&as|o*f&Vs,o=o<<15|o>>>17,o=o*g&as|o*p&Vs,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[m],h=h*u&as|h*f&Vs,h=h<<15|h>>>17,h=h*g&as|h*p&Vs,d^=h,d=d<<13|d>>>19,d=d*5+3864292196);switch(o=0,n){case 3:o^=e[i*4+2]<<16;case 2:o^=e[i*4+1]<<8;case 1:o^=e[i*4],o=o*u&as|o*f&Vs,o=o<<15|o>>>17,o=o*g&as|o*p&Vs,i&1?l^=o:d^=o}this.h1=l,this.h2=d}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&as|t*36045&Vs,e=e*4283543511&as|((e<<16|t>>>16)*2950163797&as)>>>16,t^=e>>>1,t=t*444984403&as|t*60499&Vs,e=e*3301882366&as|((e<<16|t>>>16)*3120437893&as)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Tg=Object.freeze({map:null,hash:"",transfer:void 0});class Eg{constructor(){w(this,xd);w(this,Mr,!1);w(this,Or,null);w(this,ne,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=c(this,ne).get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return c(this,ne).get(t)}remove(t){if(c(this,ne).delete(t),c(this,ne).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of c(this,ne).values())if(e instanceof gt)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=c(this,ne).get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,c(this,ne).set(t,e);i&&y(this,xd,Ab).call(this),e instanceof gt&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return c(this,ne).has(t)}getAll(){return c(this,ne).size>0?fg(c(this,ne)):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return c(this,ne).size}resetModified(){c(this,Mr)&&(b(this,Mr,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new b0(this)}get serializable(){if(c(this,ne).size===0)return Tg;const t=new Map,e=new m0,s=[],i=Object.create(null);let n=!1;for(const[r,o]of c(this,ne)){const h=o instanceof gt?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||(n=!!h.bitmap))}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Tg}get editorStats(){let t=null;const e=new Map;for(const s of c(this,ne).values()){if(!(s instanceof gt))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||(t=Object.create(null));const r=t[n]||(t[n]=new Map);for(const[o,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const d=l.get(h)??0;l.set(h,d+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){b(this,Or,null)}get modifiedIds(){if(c(this,Or))return c(this,Or);const t=[];for(const e of c(this,ne).values())!(e instanceof gt)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return b(this,Or,{ids:new Set(t),hash:t.join(",")})}}Mr=new WeakMap,Or=new WeakMap,ne=new WeakMap,xd=new WeakSet,Ab=function(){c(this,Mr)||(b(this,Mr,!0),typeof this.onSetModified=="function"&&this.onSetModified())};class b0 extends Eg{constructor(e){super();w(this,Fh);const{map:s,hash:i,transfer:n}=e.serializable,r=structuredClone(s,n?{transfer:n}:null);b(this,Fh,{map:r,hash:i,transfer:n})}get print(){Wt("Should not call PrintAnnotationStorage.print")}get serializable(){return c(this,Fh)}get modifiedIds(){return rt(this,"modifiedIds",{ids:new Set,hash:""})}}Fh=new WeakMap;class Sw{constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){w(this,$o,new Set);this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),c(this,$o).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||c(this,$o).has(t.loadedName))){if(qt(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),c(this,$o).add(s),e==null||e(t)}catch{st(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}Wt("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw st(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){var e;const t=!!((e=this._document)!=null&&e.fonts);return rt(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(fe||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),rt(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(qt(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return rt(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(C,E){return C.charCodeAt(E)<<24|C.charCodeAt(E+1)<<16|C.charCodeAt(E+2)<<8|C.charCodeAt(E+3)&255}function i(C,E,k,P){const D=C.substring(0,E),F=C.substring(E+k);return D+P+F}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function d(C,E){if(++l>30){st("Load test font never loaded."),E();return}if(h.font="30px "+C,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){E();return}setTimeout(d.bind(null,C,E))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let g=this._loadTestFont;g=i(g,976,u.length,u);const p=16,m=1482184792;let _=s(g,p);for(n=0,r=u.length-3;n<r;n+=4)_=_-m+s(u,n)|0;n<u.length&&(_=_-m+s(u+"XXX",n)|0),g=i(g,p,4,rw(_));const v=`url(data:font/opentype;base64,${btoa(g)});`,x=`@font-face {font-family:"${u}";src:${v}}`;this.insertRule(x);const S=this._document.createElement("div");S.style.visibility="hidden",S.style.width=S.style.height="10px",S.style.position="absolute",S.style.top=S.style.left="0px";for(const C of[t.loadedName,u]){const E=this._document.createElement("span");E.textContent="Hi",E.style.fontFamily=C,S.append(E)}this._document.body.append(S),d(u,()=>{S.remove(),e.complete()})}}$o=new WeakMap;class Cw{constructor(t,{disableFontFace:e=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const i in t)this[i]=t[i];this.disableFontFace=e===!0,this._inspectFont=s}createNativeFontFace(){var e;if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const s={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(s.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,s)}return(e=this._inspectFont)==null||e.call(this,this),t}createFontFaceRule(){var i;if(!this.data||this.disableFontFace)return null;const t=i0(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let s;if(!this.cssFontInfo)s=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),s=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${n}src:${e}}`}return(i=this._inspectFont)==null||i.call(this,this,e),s}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];let s;try{s=t.get(this.loadedName+"_path_"+e)}catch(n){st(`getPathGenerator - ignoring character: "${n}".`)}if(!Array.isArray(s)||s.length===0)return this.compiledGlyphs[e]=function(n,r){};const i=[];for(let n=0,r=s.length;n<r;)switch(s[n++]){case xi.BEZIER_CURVE_TO:{const[o,h,l,d,u,g]=s.slice(n,n+6);i.push(f=>f.bezierCurveTo(o,h,l,d,u,g)),n+=6}break;case xi.MOVE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.moveTo(o,h)),n+=2}break;case xi.LINE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.lineTo(o,h)),n+=2}break;case xi.QUADRATIC_CURVE_TO:{const[o,h,l,d]=s.slice(n,n+4);i.push(u=>u.quadraticCurveTo(o,h,l,d)),n+=4}break;case xi.RESTORE:i.push(o=>o.restore());break;case xi.SAVE:i.push(o=>o.save());break;case xi.SCALE:qt(i.length===2,"Scale command is only valid at the third position.");break;case xi.TRANSFORM:{const[o,h,l,d,u,g]=s.slice(n,n+6);i.push(f=>f.transform(o,h,l,d,u,g)),n+=6}break;case xi.TRANSLATE:{const[o,h]=s.slice(n,n+2);i.push(l=>l.translate(o,h)),n+=2}break}return this.compiledGlyphs[e]=function(r,o){i[0](r),i[1](r),r.scale(o,-o);for(let h=2,l=i.length;h<l;h++)i[h](r)}}}if(fe){var kg=Promise.withResolvers(),hh=null;(async()=>{const t=await Promise.resolve().then(()=>fd),e=await Promise.resolve().then(()=>fd),s=await Promise.resolve().then(()=>fd),i=await Promise.resolve().then(()=>fd);let n,r;return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:n,path2d:r}))})().then(t=>{hh=t,kg.resolve()},t=>{st(`loadPackages: ${t}`),hh=new Map,kg.resolve()})}class gn{static get promise(){return kg.promise}static get(t){return hh==null?void 0:hh.get(t)}}const v0=function(a){return gn.get("fs").promises.readFile(a).then(e=>new Uint8Array(e))};class Aw extends r0{}class Tw extends o0{_createCanvas(t,e){return gn.get("canvas").createCanvas(t,e)}}class Ew extends a0{_fetchData(t,e){return v0(t).then(s=>({cMapData:s,compressionType:e}))}}class kw extends h0{_fetchData(t){return v0(t)}}const ke={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Mg(a,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),a.clip(i)}class Og{getPattern(){Wt("Abstract method `getPattern` called.")}}class Mw extends Og{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===ke.STROKE||i===ke.FILL){const r=e.current.getClippedPathBoundingBox(i,Tt(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),d=l.context;d.clearRect(0,0,d.canvas.width,d.canvas.height),d.beginPath(),d.rect(0,0,d.canvas.width,d.canvas.height),d.translate(-r[0],-r[1]),s=V.transform(s,[1,0,0,1,r[0],r[1]]),d.transform(...e.baseTransform),this.matrix&&d.transform(...this.matrix),Mg(d,this._bbox),d.fillStyle=this._createGradient(d),d.fill(),n=t.createPattern(l.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else Mg(t,this._bbox),n=this._createGradient(t);return n}}function Dg(a,t,e,s,i,n,r,o){const h=t.coords,l=t.colors,d=a.data,u=a.width*4;let g;h[e+1]>h[s+1]&&(g=e,e=s,s=g,g=n,n=r,r=g),h[s+1]>h[i+1]&&(g=s,s=i,i=g,g=r,r=o,o=g),h[e+1]>h[s+1]&&(g=e,e=s,s=g,g=n,n=r,r=g);const f=(h[e]+t.offsetX)*t.scaleX,p=(h[e+1]+t.offsetY)*t.scaleY,m=(h[s]+t.offsetX)*t.scaleX,_=(h[s+1]+t.offsetY)*t.scaleY,v=(h[i]+t.offsetX)*t.scaleX,x=(h[i+1]+t.offsetY)*t.scaleY;if(p>=x)return;const S=l[n],C=l[n+1],E=l[n+2],k=l[r],P=l[r+1],D=l[r+2],F=l[o],B=l[o+1],O=l[o+2],R=Math.round(p),L=Math.round(x);let j,G,Y,X,H,_t,dt,_e;for(let Bt=R;Bt<=L;Bt++){if(Bt<_){const ht=Bt<p?0:(p-Bt)/(p-_);j=f-(f-m)*ht,G=S-(S-k)*ht,Y=C-(C-P)*ht,X=E-(E-D)*ht}else{let ht;Bt>x?ht=1:_===x?ht=0:ht=(_-Bt)/(_-x),j=m-(m-v)*ht,G=k-(k-F)*ht,Y=P-(P-B)*ht,X=D-(D-O)*ht}let wt;Bt<p?wt=0:Bt>x?wt=1:wt=(p-Bt)/(p-x),H=f-(f-v)*wt,_t=S-(S-F)*wt,dt=C-(C-B)*wt,_e=E-(E-O)*wt;const De=Math.round(Math.min(j,H)),Ve=Math.round(Math.max(j,H));let Gt=u*Bt+De*4;for(let ht=De;ht<=Ve;ht++)wt=(j-ht)/(j-H),wt<0?wt=0:wt>1&&(wt=1),d[Gt++]=G-(G-_t)*wt|0,d[Gt++]=Y-(Y-dt)*wt|0,d[Gt++]=X-(X-_e)*wt|0,d[Gt++]=255}}function Ow(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,h=Math.floor(s.length/o)-1,l=o-1;for(n=0;n<h;n++){let d=n*o;for(let u=0;u<l;u++,d++)Dg(a,e,s[d],s[d+1],s[d+o],i[d],i[d+1],i[d+o]),Dg(a,e,s[d+o+1],s[d+1],s[d+o],i[d+o+1],i[d+1],i[d+o])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)Dg(a,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class Dw extends Og{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const o=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-o,d=Math.ceil(this._bounds[3])-h,u=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),g=Math.min(Math.ceil(Math.abs(d*t[1]*1.1)),3e3),f=l/u,p=d/g,m={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/f,scaleY:1/p},_=u+2*2,v=g+2*2,x=s.getCanvas("mesh",_,v),S=x.context,C=S.createImageData(u,g);if(e){const k=C.data;for(let P=0,D=k.length;P<D;P+=4)k[P]=e[0],k[P+1]=e[1],k[P+2]=e[2],k[P+3]=255}for(const k of this._figures)Ow(C,k,m);return S.putImageData(C,2,2),{canvas:x.canvas,offsetX:o-2*f,offsetY:h-2*p,scaleX:f,scaleY:p}}getPattern(t,e,s,i){Mg(t,this._bbox);let n;if(i===ke.SHADING)n=V.singularValueDecompose2dScale(Tt(t));else if(n=V.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=V.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===ke.SHADING?null:this._background,e.cachedCanvases);return i!==ke.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class Pw extends Og{getPattern(){return"hotpink"}}function Lw(a){switch(a[0]){case"RadialAxial":return new Mw(a);case"Mesh":return new Dw(a);case"Dummy":return new Pw}throw new Error(`Unknown IR type: ${a[0]}`)}const y0={COLORED:1,UNCOLORED:2},Sd=class Sd{constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),Zc("TilingType: "+n);const d=e[0],u=e[1],g=e[2],f=e[3],p=g-d,m=f-u,_=V.singularValueDecompose2dScale(this.matrix),v=V.singularValueDecompose2dScale(this.baseTransform),x=_[0]*v[0],S=_[1]*v[1];let C=p,E=m,k=!1,P=!1;const D=Math.ceil(h*x),F=Math.ceil(l*S),B=Math.ceil(p*x),O=Math.ceil(m*S);D>=B?C=h:k=!0,F>=O?E=l:P=!0;const R=this.getSizeAndScale(C,this.ctx.canvas.width,x),L=this.getSizeAndScale(E,this.ctx.canvas.height,S),j=t.cachedCanvases.getCanvas("pattern",R.size,L.size),G=j.context,Y=o.createCanvasGraphics(G);if(Y.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(Y,i,r),G.translate(-R.scale*d,-L.scale*u),Y.transform(R.scale,0,0,L.scale,0,0),G.save(),this.clipBbox(Y,d,u,g,f),Y.baseTransform=Tt(Y.ctx),Y.executeOperatorList(s),Y.endDrawing(),G.restore(),k||P){const X=j.canvas;k&&(C=h),P&&(E=l);const H=this.getSizeAndScale(C,this.ctx.canvas.width,x),_t=this.getSizeAndScale(E,this.ctx.canvas.height,S),dt=H.size,_e=_t.size,Bt=t.cachedCanvases.getCanvas("pattern-workaround",dt,_e),wt=Bt.context,De=k?Math.floor(p/h):0,Ve=P?Math.floor(m/l):0;for(let Gt=0;Gt<=De;Gt++)for(let ht=0;ht<=Ve;ht++)wt.drawImage(X,dt*Gt,_e*ht,dt,_e,0,0,dt,_e);return{canvas:Bt.canvas,scaleX:H.scale,scaleY:_t.scale,offsetX:d,offsetY:u}}return{canvas:j.canvas,scaleX:R.scale,scaleY:L.scale,offsetX:d,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(Sd.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,o=n-s;t.ctx.rect(e,s,r,o),t.current.updateRectMinMax(Tt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case y0.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case y0.UNCOLORED:const o=V.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new nw(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==ke.SHADING&&(n=V.transform(n,e.baseTransform),this.matrix&&(n=V.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let o=new DOMMatrix(n);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(o),h}};Q(Sd,"MAX_PATTERN_SIZE",3e3);let Pg=Sd;function Rw({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Ie.isLittleEndian?4278190080:255,[h,l]=r?[n,o]:[o,n],d=s>>3,u=s&7,g=a.length;e=new Uint32Array(e.buffer);let f=0;for(let p=0;p<i;p++){for(const _=t+d;t<_;t++){const v=t<g?a[t]:255;e[f++]=v&128?l:h,e[f++]=v&64?l:h,e[f++]=v&32?l:h,e[f++]=v&16?l:h,e[f++]=v&8?l:h,e[f++]=v&4?l:h,e[f++]=v&2?l:h,e[f++]=v&1?l:h}if(u===0)continue;const m=t<g?a[t++]:255;for(let _=0;_<u;_++)e[f++]=m&1<<7-_?l:h}return{srcPos:t,destPos:f}}const _0=16,w0=100,Fw=15,x0=10,S0=1e3,je=16;function Iw(a,t){if(a._removeMirroring)throw new Error("Context is already forwarding operations.");a.__originalSave=a.save,a.__originalRestore=a.restore,a.__originalRotate=a.rotate,a.__originalScale=a.scale,a.__originalTranslate=a.translate,a.__originalTransform=a.transform,a.__originalSetTransform=a.setTransform,a.__originalResetTransform=a.resetTransform,a.__originalClip=a.clip,a.__originalMoveTo=a.moveTo,a.__originalLineTo=a.lineTo,a.__originalBezierCurveTo=a.bezierCurveTo,a.__originalRect=a.rect,a.__originalClosePath=a.closePath,a.__originalBeginPath=a.beginPath,a._removeMirroring=()=>{a.save=a.__originalSave,a.restore=a.__originalRestore,a.rotate=a.__originalRotate,a.scale=a.__originalScale,a.translate=a.__originalTranslate,a.transform=a.__originalTransform,a.setTransform=a.__originalSetTransform,a.resetTransform=a.__originalResetTransform,a.clip=a.__originalClip,a.moveTo=a.__originalMoveTo,a.lineTo=a.__originalLineTo,a.bezierCurveTo=a.__originalBezierCurveTo,a.rect=a.__originalRect,a.closePath=a.__originalClosePath,a.beginPath=a.__originalBeginPath,delete a._removeMirroring},a.save=function(){t.save(),this.__originalSave()},a.restore=function(){t.restore(),this.__originalRestore()},a.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},a.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},a.transform=function(s,i,n,r,o,h){t.transform(s,i,n,r,o,h),this.__originalTransform(s,i,n,r,o,h)},a.setTransform=function(s,i,n,r,o,h){t.setTransform(s,i,n,r,o,h),this.__originalSetTransform(s,i,n,r,o,h)},a.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},a.rotate=function(s){t.rotate(s),this.__originalRotate(s)},a.clip=function(s){t.clip(s),this.__originalClip(s)},a.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},a.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},a.bezierCurveTo=function(e,s,i,n,r,o){t.bezierCurveTo(e,s,i,n,r,o),this.__originalBezierCurveTo(e,s,i,n,r,o)},a.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},a.closePath=function(){t.closePath(),this.__originalClosePath()},a.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class jw{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function od(a,t,e,s,i,n,r,o,h,l){const[d,u,g,f,p,m]=Tt(a);if(u===0&&g===0){const x=r*d+p,S=Math.round(x),C=o*f+m,E=Math.round(C),k=(r+h)*d+p,P=Math.abs(Math.round(k)-S)||1,D=(o+l)*f+m,F=Math.abs(Math.round(D)-E)||1;return a.setTransform(Math.sign(d),0,0,Math.sign(f),S,E),a.drawImage(t,e,s,i,n,0,0,P,F),a.setTransform(d,u,g,f,p,m),[P,F]}if(d===0&&f===0){const x=o*g+p,S=Math.round(x),C=r*u+m,E=Math.round(C),k=(o+l)*g+p,P=Math.abs(Math.round(k)-S)||1,D=(r+h)*u+m,F=Math.abs(Math.round(D)-E)||1;return a.setTransform(0,Math.sign(u),Math.sign(g),0,S,E),a.drawImage(t,e,s,i,n,0,0,F,P),a.setTransform(d,u,g,f,p,m),[F,P]}a.drawImage(t,e,s,i,n,r,o,h,l);const _=Math.hypot(d,u),v=Math.hypot(g,f);return[_*h,v*l]}function Nw(a){const{width:t,height:e}=a;if(t>S0||e>S0)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),o,h,l;const d=t+7&-8;let u=new Uint8Array(d*e),g=0;for(const v of a.data){let x=128;for(;x>0;)u[g++]=v&x?0:255,x>>=1}let f=0;for(g=0,u[g]!==0&&(r[0]=1,++f),h=1;h<t;h++)u[g]!==u[g+1]&&(r[h]=u[g]?2:1,++f),g++;for(u[g]!==0&&(r[h]=2,++f),o=1;o<e;o++){g=o*d,l=o*n,u[g-d]!==u[g]&&(r[l]=u[g]?1:8,++f);let v=(u[g]?4:0)+(u[g-d]?8:0);for(h=1;h<t;h++)v=(v>>2)+(u[g+1]?4:0)+(u[g-d+1]?8:0),i[v]&&(r[l+h]=i[v],++f),g++;if(u[g-d]!==u[g]&&(r[l+h]=u[g]?2:4,++f),f>s)return null}for(g=d*(e-1),l=o*n,u[g]!==0&&(r[l]=8,++f),h=1;h<t;h++)u[g]!==u[g+1]&&(r[l+h]=u[g]?4:8,++f),g++;if(u[g]!==0&&(r[l+h]=4,++f),f>s)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),m=new Path2D;for(o=0;f&&o<=e;o++){let v=o*n;const x=v+t;for(;v<x&&!r[v];)v++;if(v===x)continue;m.moveTo(v%n,o);const S=v;let C=r[v];do{const E=p[C];do v+=E;while(!r[v]);const k=r[v];k!==5&&k!==10?(C=k,r[v]=0):(C=k&51*C>>4,r[v]&=C>>2|C<<2),m.lineTo(v%n,v/n|0),r[v]||--f}while(S!==v);--o}return u=null,r=null,function(v){v.save(),v.scale(1/t,-1/e),v.translate(0,-e),v.fill(m),v.beginPath(),v.restore()}}class C0{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=e0,this.textMatrixScale=1,this.fontMatrix=lg,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=pe.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=V.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=V.applyTransform(e,t),i=V.applyTransform(e.slice(2),t),n=V.applyTransform([e[0],e[3]],t),r=V.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],r[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],r[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],r[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],r[1])}updateScalingPathMinMax(t,e){V.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,o,h,l,d){const u=V.bezierBoundingBox(e,s,i,n,r,o,h,l,d);d||this.updateRectMinMax(t,u)}getPathBoundingBox(t=ke.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===ke.STROKE){e||Wt("Stroke bounding box must include transform.");const i=V.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,r=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=r,s[2]+=n,s[3]+=r}return s}updateClipFromPath(){const t=V.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=ke.FILL,e=null){return V.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function A0(a,t){if(typeof ImageData<"u"&&t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%je,n=(e-i)/je,r=i===0?n:n+1,o=a.createImageData(s,je);let h=0,l;const d=t.data,u=o.data;let g,f,p,m;if(t.kind===Kc.GRAYSCALE_1BPP){const _=d.byteLength,v=new Uint32Array(u.buffer,0,u.byteLength>>2),x=v.length,S=s+7>>3,C=4294967295,E=Ie.isLittleEndian?4278190080:255;for(g=0;g<r;g++){for(p=g<n?je:i,l=0,f=0;f<p;f++){const k=_-h;let P=0;const D=k>S?s:k*8-7,F=D&-8;let B=0,O=0;for(;P<F;P+=8)O=d[h++],v[l++]=O&128?C:E,v[l++]=O&64?C:E,v[l++]=O&32?C:E,v[l++]=O&16?C:E,v[l++]=O&8?C:E,v[l++]=O&4?C:E,v[l++]=O&2?C:E,v[l++]=O&1?C:E;for(;P<D;P++)B===0&&(O=d[h++],B=128),v[l++]=O&B?C:E,B>>=1}for(;l<x;)v[l++]=0;a.putImageData(o,0,g*je)}}else if(t.kind===Kc.RGBA_32BPP){for(f=0,m=s*je*4,g=0;g<n;g++)u.set(d.subarray(h,h+m)),h+=m,a.putImageData(o,0,f),f+=je;g<r&&(m=s*i*4,u.set(d.subarray(h,h+m)),a.putImageData(o,0,f))}else if(t.kind===Kc.RGB_24BPP)for(p=je,m=s*p,g=0;g<r;g++){for(g>=n&&(p=i,m=s*p),l=0,f=m;f--;)u[l++]=d[h++],u[l++]=d[h++],u[l++]=d[h++],u[l++]=255;a.putImageData(o,0,g*je)}else throw new Error(`bad image kind: ${t.kind}`)}function T0(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%je,n=(e-i)/je,r=i===0?n:n+1,o=a.createImageData(s,je);let h=0;const l=t.data,d=o.data;for(let u=0;u<r;u++){const g=u<n?je:i;({srcPos:h}=Rw({src:l,srcPos:h,dest:d,width:s,height:g,nonBlackColor:0})),a.putImageData(o,0,u*je)}}function lh(a,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)a[s]!==void 0&&(t[s]=a[s]);a.setLineDash!==void 0&&(t.setLineDash(a.getLineDash()),t.lineDashOffset=a.lineDashOffset)}function ad(a){if(a.strokeStyle=a.fillStyle="#000000",a.fillRule="nonzero",a.globalAlpha=1,a.lineWidth=1,a.lineCap="butt",a.lineJoin="miter",a.miterLimit=10,a.globalCompositeOperation="source-over",a.font="10px sans-serif",a.setLineDash!==void 0&&(a.setLineDash([]),a.lineDashOffset=0),!fe){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function E0(a,t){if(t)return!0;const e=V.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*un.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const Bw=["butt","round","square"],Hw=["miter","round","bevel"],Ww={},k0={},Kg=class Kg{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){w(this,Tn);this.ctx=t,this.current=new C0(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=r,this.cachedCanvases=new jw(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...Tt(this.compositeCtx))}this.ctx.save(),ad(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=Tt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>x0&&typeof s=="function",d=l?Date.now()+Fw:0;let u=0;const g=this.commonObjs,f=this.objs;let p;for(;;){if(i!==void 0&&o===i.nextBreakPoint)return i.breakIt(o,s),o;if(p=r[o],p!==Cs.dependency)this[p].apply(this,n[o]);else for(const m of n[o]){const _=m.startsWith("g_")?g:f;if(!_.has(m))return _.get(m,s),o}if(o++,o===h)return o;if(l&&++u>x0){if(Date.now()>d)return s(),o;u=0}}}endDrawing(){y(this,Tn,vf).call(this),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),y(this,Tn,yf).call(this)}_scaleImage(t,e){const s=t.width,i=t.height;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i,l="prescale1",d,u;for(;n>2&&o>1||r>2&&h>1;){let g=o,f=h;n>2&&o>1&&(g=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/g),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),d=this.cachedCanvases.getCanvas(l,g,f),u=d.context,u.clearRect(0,0,g,f),u.drawImage(t,0,0,o,h,0,0,g,f),t=d.canvas,o=g,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=Tt(e);let h,l,d,u;if((t.bitmap||t.data)&&t.count>1){const D=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(D),h||(h=new Map,this._cachedBitmapsMap.set(D,h));const F=h.get(l);if(F&&!r){const B=Math.round(Math.min(o[0],o[2])+o[4]),O=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:F,offsetX:B,offsetY:O}}d=F}d||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),T0(u.context,t));let g=V.transform(o,[1/s,0,0,-1/i,0,0]);g=V.transform(g,[1,0,0,1,0,-i]);const[f,p,m,_]=V.getAxialAlignedBoundingBox([0,0,s,i],g),v=Math.round(m-f)||1,x=Math.round(_-p)||1,S=this.cachedCanvases.getCanvas("fillCanvas",v,x),C=S.context,E=f,k=p;C.translate(-E,-k),C.transform(...g),d||(d=this._scaleImage(u.canvas,Ci(C)),d=d.img,h&&r&&h.set(l,d)),C.imageSmoothingEnabled=E0(Tt(C),t.interpolate),od(C,d,0,0,d.width,d.height,0,0,s,i),C.globalCompositeOperation="source-in";const P=V.transform(Ci(C),[1,0,0,1,-E,-k]);return C.fillStyle=r?n.getPattern(e,this,P,ke.FILL):n,C.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,S.canvas)),{canvas:S.canvas,offsetX:Math.round(E),offsetY:Math.round(k)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Bw[t]}setLineJoin(t){this.ctx.lineJoin=Hw[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...Tt(this.suspendedCtx)),lh(this.suspendedCtx,n),Iw(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),lh(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;o===0||h===0||(this.genericComposeSMask(e.context,s,o,h,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,o,h,l,d,u){let g=t.canvas,f=h-d,p=l-u;if(r){if(f<0||p<0||f+s>g.width||p+i>g.height){const _=this.cachedCanvases.getCanvas("maskExtension",s,i),v=_.context;v.drawImage(g,-f,-p),r.some(x=>x!==0)&&(v.globalCompositeOperation="destination-atop",v.fillStyle=V.makeHexColor(...r),v.fillRect(0,0,s,i),v.globalCompositeOperation="source-over"),g=_.canvas,f=p=0}else if(r.some(_=>_!==0)){t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const _=new Path2D;_.rect(f,p,s,i),t.clip(_),t.globalCompositeOperation="destination-atop",t.fillStyle=V.makeHexColor(...r),t.fillRect(f,p,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&o?e.filter=this.filterFactory.addAlphaFilter(o):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(o));const m=new Path2D;m.rect(h,l,s,i),e.clip(m),e.globalCompositeOperation="destination-in",e.drawImage(g,f,p,s,i,h,l,s,i),e.restore()}save(){this.inSMaskMode?(lh(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),lh(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const d=Tt(i),u=d[0]===0&&d[3]===0||d[1]===0&&d[2]===0,g=u?s.slice(0):null;for(let f=0,p=0,m=t.length;f<m;f++)switch(t[f]|0){case Cs.rectangle:r=e[p++],o=e[p++];const _=e[p++],v=e[p++],x=r+_,S=o+v;i.moveTo(r,o),_===0||v===0?i.lineTo(x,S):(i.lineTo(x,o),i.lineTo(x,S),i.lineTo(r,S)),u||n.updateRectMinMax(d,[r,o,x,S]),i.closePath();break;case Cs.moveTo:r=e[p++],o=e[p++],i.moveTo(r,o),u||n.updatePathMinMax(d,r,o);break;case Cs.lineTo:r=e[p++],o=e[p++],i.lineTo(r,o),u||n.updatePathMinMax(d,r,o);break;case Cs.curveTo:h=r,l=o,r=e[p+4],o=e[p+5],i.bezierCurveTo(e[p],e[p+1],e[p+2],e[p+3],r,o),n.updateCurvePathMinMax(d,h,l,e[p],e[p+1],e[p+2],e[p+3],r,o,g),p+=6;break;case Cs.curveTo2:h=r,l=o,i.bezierCurveTo(r,o,e[p],e[p+1],e[p+2],e[p+3]),n.updateCurvePathMinMax(d,h,l,r,o,e[p],e[p+1],e[p+2],e[p+3],g),r=e[p+2],o=e[p+3],p+=4;break;case Cs.curveTo3:h=r,l=o,r=e[p+2],o=e[p+3],i.bezierCurveTo(e[p],e[p+1],r,o,r,o),n.updateCurvePathMinMax(d,h,l,e[p],e[p+1],r,o,r,o,g),p+=4;break;case Cs.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(d,g),n.setCurrentPoint(r,o)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&(s!=null&&s.getPattern)?(e.save(),e.strokeStyle=s.getPattern(e,this,Ci(e),ke.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,Ci(e),ke.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=Ww}eoClip(){this.pendingClip=k0}beginText(){this.current.textMatrix=e0,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}e.save(),e.beginPath();for(const s of t)e.setTransform(...s.transform),e.translate(s.x,s.y),s.addToPath(e,s.fontSize);e.restore(),e.clip(),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){var d;const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||lg,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&st("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=((d=s.systemFontInfo)==null?void 0:d.css)||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<_0?l=_0:e>w0&&(l=w0),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,s,i){const n=this.ctx,r=this.current,o=r.font,h=r.textRenderingMode,l=r.fontSize/r.fontSizeScale,d=h&pe.FILL_STROKE_MASK,u=!!(h&pe.ADD_TO_PATH_FLAG),g=r.patternFill&&!o.missingFile;let f;(o.disableFontFace||u||g)&&(f=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||g?(n.save(),n.translate(e,s),n.beginPath(),f(n,l),i&&n.setTransform(...i),(d===pe.FILL||d===pe.FILL_STROKE)&&n.fill(),(d===pe.STROKE||d===pe.FILL_STROKE)&&n.stroke(),n.restore()):((d===pe.FILL||d===pe.FILL_STROKE)&&n.fillText(t,e,s),(d===pe.STROKE||d===pe.FILL_STROKE)&&n.strokeText(t,e,s)),u&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Tt(n),x:e,y:s,fontSize:l,addToPath:f})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return rt(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,d=e.textHScale*l,u=t.length,g=s.vertical,f=g?1:-1,p=s.defaultVMetrics,m=i*e.fontMatrix[0],_=e.textRenderingMode===pe.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(d,-1):n.scale(d,1);let v;if(e.patternFill){n.save();const k=e.fillColor.getPattern(n,this,Ci(n),ke.FILL);v=Tt(n),n.restore(),n.fillStyle=k}let x=e.lineWidth;const S=e.textMatrixScale;if(S===0||x===0){const k=e.textRenderingMode&pe.FILL_STROKE_MASK;(k===pe.STROKE||k===pe.FILL_STROKE)&&(x=this.getSinglePixelWidth())}else x/=S;if(r!==1&&(n.scale(r,r),x/=r),n.lineWidth=x,s.isInvalidPDFjsFont){const k=[];let P=0;for(const D of t)k.push(D.unicode),P+=D.width;n.fillText(k.join(""),0,0),e.x+=P*m*d,n.restore(),this.compose();return}let C=0,E;for(E=0;E<u;++E){const k=t[E];if(typeof k=="number"){C+=f*k*i/1e3;continue}let P=!1;const D=(k.isSpace?h:0)+o,F=k.fontChar,B=k.accent;let O,R,L=k.width;if(g){const G=k.vmetric||p,Y=-(k.vmetric?G[1]:L*.5)*m,X=G[2]*m;L=G?-G[0]:L,O=Y/r,R=(C+X)/r}else O=C/r,R=0;if(s.remeasure&&L>0){const G=n.measureText(F).width*1e3/i*r;if(L<G&&this.isFontSubpixelAAEnabled){const Y=L/G;P=!0,n.save(),n.scale(Y,1),O/=Y}else L!==G&&(O+=(L-G)/2e3*i/r)}if(this.contentVisible&&(k.isInFont||s.missingFile)){if(_&&!B)n.fillText(F,O,R);else if(this.paintChar(F,O,R,v),B){const G=O+i*B.offset.x/r,Y=R-i*B.offset.y/r;this.paintChar(B.fontChar,G,Y,v)}}const j=g?L*m-D*l:L*m+D*l;C+=j,P&&n.restore()}g?e.y-=C:e.x+=C*d,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,d=s.textHScale*r,u=s.fontMatrix||lg,g=t.length,f=s.textRenderingMode===pe.INVISIBLE;let p,m,_,v;if(!(f||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(d,r),p=0;p<g;++p){if(m=t[p],typeof m=="number"){v=o*m*n/1e3,this.ctx.translate(v,0),s.x+=v*d;continue}const x=(m.isSpace?l:0)+h,S=i.charProcOperatorList[m.operatorListId];if(!S){st(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(S),this.restore()),_=V.applyTransform([m.width,0],u)[0]*n+x,e.translate(_,0),s.x+=_*d}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,r){this.ctx.rect(s,i,n-s,r-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||Tt(this.ctx),n={createCanvasGraphics:r=>new Kg(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new Pg(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=V.makeHexColor(t,e,s)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=V.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=Lw(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,Ci(e),ke.SHADING);const i=Ci(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,d]=V.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,h,l-o,d-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){Wt("Should not call beginInlineImage")}beginImageData(){Wt("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Tt(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(Tt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||Zc("TODO: Support non-isolated groups."),t.knockout&&st("Knockout groups not supported.");const s=Tt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=V.getAxialAlignedBoundingBox(t.bbox,Tt(e));const n=[0,0,e.canvas.width,e.canvas.height];i=V.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),o=Math.floor(i[1]),h=Math.max(Math.ceil(i[2])-r,1),l=Math.max(Math.ceil(i[3])-o,1);this.current.startNewPathAndClipBox([0,0,h,l]);let d="groupAt"+this.groupLevel;t.smask&&(d+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(d,h,l),g=u.context;g.translate(-r,-o),g.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:g,offsetX:r,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(r,o),e.save()),lh(e,g),this.ctx=g,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=Tt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=V.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(y(this,Tn,vf).call(this),ad(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],o=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=o;const[h,l]=V.singularValueDecompose2dScale(Tt(this.ctx)),{viewportScale:d}=this,u=Math.ceil(r*this.outputScaleX*d),g=Math.ceil(o*this.outputScaleY*d);this.annotationCanvas=this.canvasFactory.create(u,g);const{canvas:f,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(h,0,0,-l,0,o*l),ad(this.ctx)}else ad(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new C0(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),y(this,Tn,yf).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=Nw(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=Tt(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let d=0,u=r.length;d<u;d+=2){const g=V.transform(h,[e,s,i,n,r[d],r[d+1]]),[f,p]=V.applyTransform([0,0],g);o.drawImage(l.canvas,f,p)}o.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:r,width:o,height:h,transform:l}=n,d=this.cachedCanvases.getCanvas("maskCanvas",o,h),u=d.context;u.save();const g=this.getObject(r,n);T0(u,g),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,Ci(e),ke.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),od(e,d.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){st("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){st("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,d=i.length;l<d;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!fe){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;A0(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,Ci(i));i.imageSmoothingEnabled=E0(Tt(i),t.interpolate),od(i,r.img,0,0,r.paintWidth,r.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,r=t.height,h=this.cachedCanvases.getCanvas("inlineImage",n,r).context;A0(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),od(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===k0?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Tt(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const d=h*t;r=o=d<1?1/d:1}else if(t===0)r=1/h,o=1/l;else{const d=h*t,u=l*t;r=d<1?1/d:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),d=Math.hypot(i,n);if(t===0)r=d/h,o=l/h;else{const u=t*h;r=d>u?d/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};Tn=new WeakSet,vf=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)},yf=function(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}};let Lo=Kg;for(const a in Cs)Lo.prototype[a]!==void 0&&(Lo.prototype[Cs[a]]=Lo.prototype[a]);class Ai{static get workerPort(){return c(this,Ih)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");b(this,Ih,t)}static get workerSrc(){return c(this,jh)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");b(this,jh,t)}}Ih=new WeakMap,jh=new WeakMap,w(Ai,Ih,null),w(Ai,jh,"");const hd={UNKNOWN:0,DATA:1,ERROR:2},zt={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function qe(a){switch(a instanceof Error||typeof a=="object"&&a!==null||Wt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new or(a.message);case"MissingPDFException":return new rr(a.message);case"PasswordException":return new ug(a.message,a.code);case"UnexpectedResponseException":return new td(a.message,a.status);case"UnknownErrorException":return new gg(a.message,a.details);default:return new gg(a.message,a.toString())}}class ch{constructor(t,e,s){w(this,si);this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=i=>{const n=i.data;if(n.targetName!==this.sourceName)return;if(n.stream){y(this,si,Eb).call(this,n);return}if(n.callback){const o=n.callbackId,h=this.callbackCapabilities[o];if(!h)throw new Error(`Cannot resolve callback ${o}`);if(delete this.callbackCapabilities[o],n.callback===hd.DATA)h.resolve(n.data);else if(n.callback===hd.ERROR)h.reject(qe(n.reason));else throw new Error("Unexpected callback case");return}const r=this.actionHandler[n.action];if(!r)throw new Error(`Unknown action from worker: ${n.action}`);if(n.callbackId){const o=this.sourceName,h=n.sourceName;new Promise(function(l){l(r(n.data))}).then(function(l){s.postMessage({sourceName:o,targetName:h,callback:hd.DATA,callbackId:n.callbackId,data:l})},function(l){s.postMessage({sourceName:o,targetName:h,callback:hd.ERROR,callbackId:n.callbackId,reason:qe(l)})});return}if(n.streamId){y(this,si,Tb).call(this,n);return}r(n.data)},s.addEventListener("message",this._onComObjOnMessage)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,o=this.targetName,h=this.comObj;return new ReadableStream({start:l=>{const d=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:d,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),d.promise},pull:l=>{const d=Promise.withResolvers();return this.streamControllers[n].pullCall=d,h.postMessage({sourceName:r,targetName:o,stream:zt.PULL,streamId:n,desiredSize:l.desiredSize}),d.promise},cancel:l=>{qt(l instanceof Error,"cancel must have a valid reason");const d=Promise.withResolvers();return this.streamControllers[n].cancelCall=d,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:zt.CANCEL,streamId:n,reason:qe(l)}),d.promise}},s)}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}si=new WeakSet,Tb=function(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=this.actionHandler[t.action],h={enqueue(l,d=1,u){if(this.isCancelled)return;const g=this.desiredSize;this.desiredSize-=d,g>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:zt.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:zt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){qt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:zt.ERROR,streamId:e,reason:qe(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,new Promise(function(l){l(o(t.data,h))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:zt.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:zt.START_COMPLETE,streamId:e,reason:qe(l)})})},Eb=function(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],o=this.streamSinks[e];switch(t.stream){case zt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(qe(t.reason));break;case zt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(qe(t.reason));break;case zt.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:zt.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,new Promise(function(h){var l;h((l=o.onPull)==null?void 0:l.call(o))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:zt.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:zt.PULL_COMPLETE,streamId:e,reason:qe(h)})});break;case zt.ENQUEUE:if(qt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case zt.CLOSE:if(qt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),y(this,si,Wd).call(this,r,e);break;case zt.ERROR:qt(r,"error should have stream controller"),r.controller.error(qe(t.reason)),y(this,si,Wd).call(this,r,e);break;case zt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(qe(t.reason)),y(this,si,Wd).call(this,r,e);break;case zt.CANCEL:if(!o)break;new Promise(function(h){var l;h((l=o.onCancel)==null?void 0:l.call(o,qe(t.reason)))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:zt.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:zt.CANCEL_COMPLETE,streamId:e,reason:qe(h)})}),o.sinkCapability.reject(qe(t.reason)),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}},Wd=async function(t,e){var s,i,n;await Promise.allSettled([(s=t.startCall)==null?void 0:s.promise,(i=t.pullCall)==null?void 0:i.promise,(n=t.cancelCall)==null?void 0:n.promise]),delete this.streamControllers[e]};class zw{constructor({parsedData:t,rawData:e}){w(this,Dr);w(this,Nh);b(this,Dr,t),b(this,Nh,e)}getRaw(){return c(this,Nh)}get(t){return c(this,Dr).get(t)??null}getAll(){return fg(c(this,Dr))}has(t){return c(this,Dr).has(t)}}Dr=new WeakMap,Nh=new WeakMap;const fn=Symbol("INTERNAL");class Xw{constructor(t,{name:e,intent:s,usage:i}){w(this,Bh,!1);w(this,Hh,!1);w(this,Wh,!1);w(this,Ko,!0);b(this,Bh,!!(t&Ye.DISPLAY)),b(this,Hh,!!(t&Ye.PRINT)),this.name=e,this.intent=s,this.usage=i}get visible(){if(c(this,Wh))return c(this,Ko);if(!c(this,Ko))return!1;const{print:t,view:e}=this.usage;return c(this,Bh)?(e==null?void 0:e.viewState)!=="OFF":c(this,Hh)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,e,s=!1){t!==fn&&Wt("Internal method `_setVisible` called."),b(this,Wh,s),b(this,Ko,e)}}Bh=new WeakMap,Hh=new WeakMap,Wh=new WeakMap,Ko=new WeakMap;class Vw{constructor(t,e=Ye.DISPLAY){w(this,zh);w(this,En,null);w(this,mt,new Map);w(this,Qo,null);w(this,Jo,null);if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,b(this,Jo,t.order);for(const s of t.groups)c(this,mt).set(s.id,new Xw(e,s));if(t.baseState==="OFF")for(const s of c(this,mt).values())s._setVisible(fn,!1);for(const s of t.on)c(this,mt).get(s)._setVisible(fn,!0);for(const s of t.off)c(this,mt).get(s)._setVisible(fn,!1);b(this,Qo,this.getHash())}}isVisible(t){if(c(this,mt).size===0)return!0;if(!t)return Zc("Optional content group not defined."),!0;if(t.type==="OCG")return c(this,mt).has(t.id)?c(this,mt).get(t.id).visible:(st(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return y(this,zh,_f).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!c(this,mt).has(e))return st(`Optional content group not found: ${e}`),!0;if(c(this,mt).get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!c(this,mt).has(e))return st(`Optional content group not found: ${e}`),!0;if(!c(this,mt).get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!c(this,mt).has(e))return st(`Optional content group not found: ${e}`),!0;if(!c(this,mt).get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!c(this,mt).has(e))return st(`Optional content group not found: ${e}`),!0;if(c(this,mt).get(e).visible)return!1}return!0}return st(`Unknown optional content policy ${t.policy}.`),!0}return st(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0){const s=c(this,mt).get(t);if(!s){st(`Optional content group not found: ${t}`);return}s._setVisible(fn,!!e,!0),b(this,En,null)}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=c(this,mt).get(i);if(n)switch(s){case"ON":n._setVisible(fn,!0);break;case"OFF":n._setVisible(fn,!1);break;case"Toggle":n._setVisible(fn,!n.visible);break}}b(this,En,null)}get hasInitialVisibility(){return c(this,Qo)===null||this.getHash()===c(this,Qo)}getOrder(){return c(this,mt).size?c(this,Jo)?c(this,Jo).slice():[...c(this,mt).keys()]:null}getGroups(){return c(this,mt).size>0?fg(c(this,mt)):null}getGroup(t){return c(this,mt).get(t)||null}getHash(){if(c(this,En)!==null)return c(this,En);const t=new m0;for(const[e,s]of c(this,mt))t.update(`${e}:${s.visible}`);return b(this,En,t.hexdigest())}}En=new WeakMap,mt=new WeakMap,Qo=new WeakMap,Jo=new WeakMap,zh=new WeakSet,_f=function(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=y(this,zh,_f).call(this,n);else if(c(this,mt).has(n))r=c(this,mt).get(n).visible;else return st(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"};class Gw{constructor(t,{disableRange:e=!1,disableStream:s=!1}){qt(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:o}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=o,(n==null?void 0:n.length)>0){const h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,l)=>{this._onReceiveData({begin:h,chunk:l})}),t.addProgressListener((h,l)=>{this._onProgress({loaded:h,total:l})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});qt(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}_onProgress(t){var e,s,i,n;t.total===void 0?(s=(e=this._rangeReaders[0])==null?void 0:e.onProgress)==null||s.call(e,{loaded:t.loaded}):(n=(i=this._fullRequestReader)==null?void 0:i.onProgress)==null||n.call(i,{loaded:t.loaded,total:t.total})}_onProgressiveDone(){var t;(t=this._fullRequestReader)==null||t.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){qt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Uw(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Yw(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeReaders.slice(0))s.cancel(t);this._pdfDataRangeTransport.abort()}}class Uw{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=_g(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Yw{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function qw(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let d=o(e);return d=unescape(d),d=h(d),d=l(d),n(d)}if(e=r(a),e){const d=l(e);return n(d)}if(e=s("filename","i").exec(a),e){e=e[1];let d=o(e);return d=l(d),n(d)}function s(d,u){return new RegExp("(?:^|;)\\s*"+d+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(d,u){if(d){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const g=new TextDecoder(d,{fatal:!0}),f=ed(u);u=g.decode(f),t=!1}catch{}}return u}function n(d){return t&&/[\x80-\xff]/.test(d)&&(d=i("utf-8",d),t&&(d=i("iso-8859-1",d))),d}function r(d){const u=[];let g;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(g=f.exec(d))!==null;){let[,m,_,v]=g;if(m=parseInt(m,10),m in u){if(m===0)break;continue}u[m]=[_,v]}const p=[];for(let m=0;m<u.length&&m in u;++m){let[_,v]=u[m];v=o(v),_&&(v=unescape(v),m===0&&(v=h(v))),p.push(v)}return p.join("")}function o(d){if(d.startsWith('"')){const u=d.slice(1).split('\\"');for(let g=0;g<u.length;++g){const f=u[g].indexOf('"');f!==-1&&(u[g]=u[g].slice(0,f),u.length=g+1),u[g]=u[g].replaceAll(/\\(.)/g,"$1")}d=u.join('"')}return d}function h(d){const u=d.indexOf("'");if(u===-1)return d;const g=d.slice(0,u),p=d.slice(u+1).replace(/^[^']*'/,"");return i(g,p)}function l(d){return!d.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(d)?d:d.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(u,g,f,p){if(f==="q"||f==="Q")return p=p.replaceAll("_"," "),p=p.replaceAll(/=([0-9a-fA-F]{2})/g,function(m,_){return String.fromCharCode(parseInt(_,16))}),i(g,p);try{p=atob(p)}catch{}return i(g,p)})}return""}function Lg(a,t){const e=new Headers;if(!a||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function Rg({responseHeaders:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a.get("Accept-Ranges")!=="bytes"||(a.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function Fg(a){const t=a.get("Content-Disposition");if(t){let e=qw(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(_g(e))return e}return null}function ld(a,t){return a===404||a===0&&t.startsWith("file:")?new rr('Missing PDF "'+t+'".'):new td(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function M0(a){return a===200||a===206}function O0(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function D0(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(st(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class P0{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=Lg(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return qt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new $w(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Kw(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeRequestReaders.slice(0))s.cancel(t)}}class $w{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers),i=e.url;fetch(i,O0(s,this._withCredentials,this._abortController)).then(n=>{if(!M0(n.status))throw ld(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=Rg({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=Fg(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new or("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded,total:this._contentLength}),{value:D0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}class Kw{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,O0(n,this._withCredentials,this._abortController)).then(o=>{if(!M0(o.status))throw ld(o.status,r);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:D0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}const Ig=200,jg=206;function Qw(a){const t=a.response;return typeof t!="string"?t:ed(t).buffer}class Jw{constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Lg(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,s){const i={begin:t,end:e};for(const n in s)i[n]=s[n];return this.request(i)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=jg):i.expectedStatus=Ig,e.responseType="arraybuffer",t.onError&&(e.onerror=function(n){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){var i;const s=this.pendingRequests[t];s&&((i=s.onProgress)==null||i.call(s,e))}onStateChange(t,e){var h,l,d;const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){(h=s.onError)==null||h.call(s,i.status);return}const n=i.status||Ig;if(!(n===Ig&&s.expectedStatus===jg)&&n!==s.expectedStatus){(l=s.onError)==null||l.call(s,i.status);return}const o=Qw(i);if(n===jg){const u=i.getResponseHeader("Content-Range"),g=/bytes (\d+)-(\d+)\/(\d+)/.exec(u);s.onDone({begin:parseInt(g[1],10),chunk:o})}else o?s.onDone({begin:0,chunk:o}):(d=s.onError)==null||d.call(s,i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Zw{constructor(t){this._source=t,this._manager=new Jw(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return qt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new tx(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new ex(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeRequestReaders.slice(0))s.cancel(t)}}class tx{constructor(t,e){this._manager=t;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(s),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),s=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map(r=>{const[o,...h]=r.split(": ");return[o,h.join(": ")]})),{allowRangeRequests:i,suggestedLength:n}=Rg({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Fg(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=ld(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){var e;(e=this.onProgress)==null||e.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class ex{constructor(t,e,s){this._manager=t;const i={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,s,i),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){var t;(t=this.onClosed)==null||t.call(this,this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=ld(t,this._url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){var e;this.isStreamingSupported||(e=this.onProgress)==null||e.call(this,{loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const sx=/^[a-z][a-z0-9\-+.]+:/i;function ix(a){if(sx.test(a))return new URL(a);const t=gn.get("url");return new URL(t.pathToFileURL(a))}function L0(a,t,e){return a.protocol==="http:"?gn.get("http").request(a,{headers:t},e):gn.get("https").request(a,{headers:t},e)}class nx{constructor(t){this.source=t,this.url=ix(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=Lg(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return qt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new ax(this):new rx(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new hx(this,t,e):new ox(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeRequestReaders.slice(0))s.cancel(t)}}class R0{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new or("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class F0{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class rx extends R0{constructor(t){super(t);const e=Object.fromEntries(t.headers),s=i=>{if(i.statusCode===404){const h=new rr(`Missing PDF "${this._url}".`);this._storedError=h,this._headersCapability.reject(h);return}this._headersCapability.resolve(),this._setReadableStream(i);const n=new Headers(this._readableStream.headers),{allowRangeRequests:r,suggestedLength:o}=Rg({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=o||this._contentLength,this._filename=Fg(n)};this._request=L0(this._url,e,s),this._request.on("error",i=>{this._storedError=i,this._headersCapability.reject(i)}),this._request.end()}}class ox extends F0{constructor(t,e,s){super(t);const i=Object.fromEntries(t.headers);i.Range=`bytes=${e}-${s-1}`;const n=r=>{if(r.statusCode===404){const o=new rr(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(r)};this._request=L0(this._url,i,n),this._request.on("error",r=>{this._storedError=r}),this._request.end()}}class ax extends R0{constructor(t){super(t);const e=gn.get("fs");e.promises.lstat(this._url).then(s=>{this._contentLength=s.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()},s=>{s.code==="ENOENT"&&(s=new rr(`Missing PDF "${this._url}".`)),this._storedError=s,this._headersCapability.reject(s)})}}class hx extends F0{constructor(t,e,s){super(t);const i=gn.get("fs");this._setReadableStream(i.createReadStream(this._url,{start:e,end:s-1}))}}const lx=1e5,Ne=30,cx=.8,Kt=class Kt{constructor({textContentSource:t,container:e,viewport:s}){w(this,Ii);w(this,kn,Promise.withResolvers());w(this,He,null);w(this,Xh,!1);w(this,Vh,!!((J0=globalThis.FontInspector)!=null&&J0.enabled));w(this,Pr,null);w(this,Fi,null);w(this,Gh,0);w(this,Uh,0);w(this,Lr,null);w(this,Zo,null);w(this,ta,0);w(this,Mn,0);w(this,ea,Object.create(null));w(this,Yh,[]);w(this,sa,null);w(this,Rr,[]);w(this,qh,new WeakMap);w(this,$h,null);var h;if(t instanceof ReadableStream)b(this,sa,t);else if(typeof t=="object")b(this,sa,new ReadableStream({start(l){l.enqueue(t),l.close()}}));else throw new Error('No "textContentSource" parameter specified.');b(this,He,b(this,Zo,e)),b(this,Mn,s.scale*(globalThis.devicePixelRatio||1)),b(this,ta,s.rotation),b(this,Fi,{div:null,properties:null,ctx:null});const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;b(this,$h,[1,0,0,-1,-r,o+n]),b(this,Uh,i),b(this,Gh,n),y(h=Kt,Qe,Ob).call(h),ar(e,s),c(this,kn).promise.finally(()=>{c(Kt,ia).delete(this),b(this,Fi,null),b(this,ea,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Ie.platform;return rt(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{c(this,Lr).read().then(({value:e,done:s})=>{if(s){c(this,kn).resolve();return}c(this,Pr)??b(this,Pr,e.lang),Object.assign(c(this,ea),e.styles),y(this,Ii,kb).call(this,e.items),t()},c(this,kn).reject)};return b(this,Lr,c(this,sa).getReader()),c(Kt,ia).add(this),t(),c(this,kn).promise}update({viewport:t,onBefore:e=null}){var n;const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==c(this,ta)&&(e==null||e(),b(this,ta,i),ar(c(this,Zo),{rotation:i})),s!==c(this,Mn)){e==null||e(),b(this,Mn,s);const r={div:null,properties:null,ctx:y(n=Kt,Qe,zd).call(n,c(this,Pr))};for(const o of c(this,Rr))r.properties=c(this,qh).get(o),r.div=o,y(this,Ii,wf).call(this,r)}}cancel(){var e;const t=new or("TextLayer task cancelled.");(e=c(this,Lr))==null||e.cancel(t).catch(()=>{}),b(this,Lr,null),c(this,kn).reject(t)}get textDivs(){return c(this,Rr)}get textContentItemsStr(){return c(this,Yh)}static cleanup(){if(!(c(this,ia).size>0)){c(this,Fr).clear();for(const{canvas:t}of c(this,Ir).values())t.remove();c(this,Ir).clear()}}};kn=new WeakMap,He=new WeakMap,Xh=new WeakMap,Vh=new WeakMap,Pr=new WeakMap,Fi=new WeakMap,Gh=new WeakMap,Uh=new WeakMap,Lr=new WeakMap,Zo=new WeakMap,ta=new WeakMap,Mn=new WeakMap,ea=new WeakMap,Yh=new WeakMap,sa=new WeakMap,Rr=new WeakMap,qh=new WeakMap,$h=new WeakMap,Fr=new WeakMap,Ir=new WeakMap,Kh=new WeakMap,On=new WeakMap,ia=new WeakMap,Ii=new WeakSet,kb=function(t){var i,n;if(c(this,Xh))return;(n=c(this,Fi)).ctx??(n.ctx=y(i=Kt,Qe,zd).call(i,c(this,Pr)));const e=c(this,Rr),s=c(this,Yh);for(const r of t){if(e.length>lx){st("Ignoring additional textDivs for performance reasons."),b(this,Xh,!0);return}if(r.str===void 0){if(r.type==="beginMarkedContentProps"||r.type==="beginMarkedContent"){const o=c(this,He);b(this,He,document.createElement("span")),c(this,He).classList.add("markedContent"),r.id!==null&&c(this,He).setAttribute("id",`${r.id}`),o.append(c(this,He))}else r.type==="endMarkedContent"&&b(this,He,c(this,He).parentNode);continue}s.push(r.str),y(this,Ii,Mb).call(this,r)}},Mb=function(t){var m;const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};c(this,Rr).push(e);const i=V.transform(c(this,$h),t.transform);let n=Math.atan2(i[1],i[0]);const r=c(this,ea)[t.fontName];r.vertical&&(n+=Math.PI/2);let o=c(this,Vh)&&r.fontSubstitution||r.fontFamily;o=Kt.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*y(m=Kt,Qe,Db).call(m,o,c(this,Pr));let d,u;n===0?(d=i[4],u=i[5]-l):(d=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const g="calc(var(--scale-factor)*",f=e.style;c(this,He)===c(this,Zo)?(f.left=`${(100*d/c(this,Uh)).toFixed(2)}%`,f.top=`${(100*u/c(this,Gh)).toFixed(2)}%`):(f.left=`${g}${d.toFixed(2)}px)`,f.top=`${g}${u.toFixed(2)}px)`),f.fontSize=`${g}${(c(Kt,On)*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,c(this,Vh)&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const _=Math.abs(t.transform[0]),v=Math.abs(t.transform[3]);_!==v&&Math.max(_,v)/Math.min(_,v)>1.5&&(p=!0)}if(p&&(s.canvasWidth=r.vertical?t.height:t.width),c(this,qh).set(e,s),c(this,Fi).div=e,c(this,Fi).properties=s,y(this,Ii,wf).call(this,c(this,Fi)),s.hasText&&c(this,He).append(e),s.hasEOL){const _=document.createElement("br");_.setAttribute("role","presentation"),c(this,He).append(_)}},wf=function(t){var o;const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(c(Kt,On)>1&&(r=`scale(${1/c(Kt,On)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:h}=n,{canvasWidth:l,fontSize:d}=s;y(o=Kt,Qe,xf).call(o,i,d*c(this,Mn),h);const{width:u}=i.measureText(e.textContent);u>0&&(r=`scaleX(${l*c(this,Mn)/u}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)},Qe=new WeakSet,zd=function(t=null){let e=c(this,Ir).get(t||(t=""));if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),c(this,Ir).set(t,e),c(this,Kh).set(e,{size:0,family:""})}return e},xf=function(t,e,s){const i=c(this,Kh).get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)},Ob=function(){if(c(this,On)!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),b(this,On,t.getBoundingClientRect().height),t.remove()},Db=function(t,e){const s=c(this,Fr).get(t);if(s)return s;const i=y(this,Qe,zd).call(this,e);i.canvas.width=i.canvas.height=Ne,y(this,Qe,xf).call(this,i,Ne,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const d=r/(r+o);return c(this,Fr).set(t,d),i.canvas.width=i.canvas.height=0,d}i.strokeStyle="red",i.clearRect(0,0,Ne,Ne),i.strokeText("g",0,0);let h=i.getImageData(0,0,Ne,Ne).data;o=0;for(let d=h.length-1-3;d>=0;d-=4)if(h[d]>0){o=Math.ceil(d/4/Ne);break}i.clearRect(0,0,Ne,Ne),i.strokeText("A",0,Ne),h=i.getImageData(0,0,Ne,Ne).data,r=0;for(let d=0,u=h.length;d<u;d+=4)if(h[d]>0){r=Ne-Math.floor(d/4/Ne);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):cx;return c(this,Fr).set(t,l),l},w(Kt,Qe),w(Kt,Fr,new Map),w(Kt,Ir,new Map),w(Kt,Kh,new WeakMap),w(Kt,On,null),w(Kt,ia,new Set);let dh=Kt;class uh{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){var h;if(!n)return;let r=null;const o=n.name;if(o==="#text")r=n.value;else if(uh.shouldBuildText(o))(h=n==null?void 0:n.attributes)!=null&&h.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const l of n.children)i(l)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const dx=65536,ux=100,gx=5e3,fx=fe?Tw:gw,px=fe?Ew:l0,mx=fe?Aw:uw,bx=fe?kw:c0;function vx(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new Ng,{docId:e}=t,s=a.url?yx(a.url):null,i=a.data?_x(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof j0?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:dx;let d=a.worker instanceof Ro?a.worker:null;const u=a.verbosity,g=typeof a.docBaseUrl=="string"&&!id(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,p=a.cMapPacked!==!1,m=a.CMapReaderFactory||px,_=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,v=a.StandardFontDataFactory||bx,x=a.stopAtErrors!==!0,S=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,C=a.isEvalSupported!==!1,E=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!fe,k=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,P=typeof a.disableFontFace=="boolean"?a.disableFontFace:fe,D=a.fontExtraProperties===!0,F=a.enableXfa===!0,B=a.ownerDocument||globalThis.document,O=a.disableRange===!0,R=a.disableStream===!0,L=a.disableAutoFetch===!0,j=a.pdfBug===!0,G=a.CanvasFactory||fx,Y=a.FilterFactory||mx,X=a.enableHWA===!0,H=h?h.length:a.length??NaN,_t=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!fe&&!P,dt=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:m===l0&&v===c0&&f&&_&&oh(f,document.baseURI)&&oh(_,document.baseURI);a.canvasFactory&&u0("`canvasFactory`-instance option, please use `CanvasFactory` instead."),a.filterFactory&&u0("`filterFactory`-instance option, please use `FilterFactory` instead.");const _e=null;tw(u);const Bt={canvasFactory:new G({ownerDocument:B,enableHWA:X}),filterFactory:new Y({docId:e,ownerDocument:B}),cMapReaderFactory:dt?null:new m({baseUrl:f,isCompressed:p}),standardFontDataFactory:dt?null:new v({baseUrl:_})};if(!d){const Ve={verbosity:u,port:Ai.workerPort};d=Ve.port?Ro.fromPort(Ve):new Ro(Ve),t._worker=d}const wt={docId:e,apiVersion:"4.7.76",data:i,password:o,disableAutoFetch:L,rangeChunkSize:l,length:H,docBaseUrl:g,enableXfa:F,evaluatorOptions:{maxImageSize:S,disableFontFace:P,ignoreErrors:x,isEvalSupported:C,isOffscreenCanvasSupported:E,canvasMaxAreaInBytes:k,fontExtraProperties:D,useSystemFonts:_t,cMapUrl:dt?f:null,standardFontDataUrl:dt?_:null}},De={disableFontFace:P,fontExtraProperties:D,ownerDocument:B,pdfBug:j,styleElement:_e,loadingParams:{disableAutoFetch:L,enableXfa:F}};return d.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const Ve=d.messageHandler.sendWithPromise("GetDocRequest",wt,i?[i.buffer]:null);let Gt;if(h)Gt=new Gw(h,{disableRange:O,disableStream:R});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let ht;fe?ht=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&oh(s)?P0:nx:ht=oh(s)?P0:Zw,Gt=new ht({url:s,length:H,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:O,disableStream:R})}return Ve.then(ht=>{if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const Rl=new ch(e,ht,d.port),Fl=new Cx(Rl,t,Gt,De,Bt);t._transport=Fl,Rl.send("Ready",null)})}).catch(t._capability.reject),t}function yx(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(fe&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function _x(a){if(fe&&typeof Buffer<"u"&&a instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength)return a;if(typeof a=="string")return ed(a);if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)||typeof a=="object"&&!isNaN(a==null?void 0:a.length))return new Uint8Array(a);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function I0(a){return typeof a=="object"&&Number.isInteger(a==null?void 0:a.num)&&a.num>=0&&Number.isInteger(a==null?void 0:a.gen)&&a.gen>=0}const Ad=class Ad{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Pe(Ad,Cd)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){var t,e,s;this.destroyed=!0;try{(t=this._worker)!=null&&t.port&&(this._worker._pendingDestroy=!0),await((e=this._transport)==null?void 0:e.destroy())}catch(i){throw(s=this._worker)!=null&&s.port&&delete this._worker._pendingDestroy,i}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}};Cd=new WeakMap,w(Ad,Cd,0);let Ng=Ad;class j0{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){Wt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class wx{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return rt(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class xx{constructor(t,e,s,i=!1){w(this,ds);w(this,Dn,null);w(this,ji,!1);this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new d0:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new N0,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new rh({viewBox:this.view,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return rt(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var t;return((t=this._transport._htmlForXfa)==null?void 0:t.children[this._pageIndex])||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=cn.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:d=null,isEditing:u=!1}){var C,E;(C=this._stats)==null||C.time("Overall");const g=this._transport.getRenderingIntent(s,i,d,u),{renderingIntent:f,cacheKey:p}=g;b(this,ji,!1),y(this,ds,Xd).call(this),o||(o=this._transport.getOptionalContentConfig(f));let m=this._intentStates.get(p);m||(m=Object.create(null),this._intentStates.set(p,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const _=!!(f&Ye.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(E=this._stats)==null||E.time("Page Request"),this._pumpOperatorList(g));const v=k=>{var P;m.renderTasks.delete(x),(this._maybeCleanupAfterRender||_)&&b(this,ji,!0),y(this,ds,ja).call(this,!_),k?(x.capability.reject(k),this._abortOperatorList({intentState:m,reason:k instanceof Error?k:new Error(k)})):x.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(P=globalThis.Stats)!=null&&P.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},x=new Bg({callback:v,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!_,pdfBug:this._pdfBug,pageColors:l});(m.renderTasks||(m.renderTasks=new Set)).add(x);const S=x.task;return Promise.all([m.displayReadyCapability.promise,o]).then(([k,P])=>{var D;if(this.destroyed){v();return}if((D=this._stats)==null||D.time("Rendering"),!(P.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");x.initializeGraphics({transparency:k,optionalContentConfig:P}),x.operatorListChanged()}).catch(v),S}getOperatorList({intent:t="display",annotationMode:e=cn.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){var l;function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let o=this._intentStates.get(r.cacheKey);o||(o=Object.create(null),this._intentStates.set(r.cacheKey,o));let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||(o.renderTasks=new Set)).add(h),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(l=this._stats)==null||l.time("Page Request"),this._pumpOperatorList(r)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>uh.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:l}){if(l){s(o);return}o.lang??(o.lang=h.lang),Object.assign(o.styles,h.styles),o.items.push(...h.items),n()},i)}const r=e.getReader(),o={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),b(this,ji,!1),y(this,ds,Xd).call(this),Promise.all(t)}cleanup(t=!1){b(this,ji,!0);const e=y(this,ds,ja).call(this,!1);return t&&e&&this._stats&&(this._stats=new d0),e}_startRenderPage(t,e){var i,n;const s=this._intentStates.get(e);s&&((i=this._stats)==null||i.timeEnd("Page Request"),(n=s.displayReadyCapability)==null||n.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&y(this,ds,ja).call(this,!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),l=this._intentStates.get(e);l.streamReader=h;const d=()=>{h.read().then(({value:u,done:g})=>{if(g){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,l),d())},u=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const g of l.renderTasks)g.operatorListChanged();y(this,ds,ja).call(this,!0)}if(l.displayReadyCapability)l.displayReadyCapability.reject(u);else if(l.opListReadCapability)l.opListReadCapability.reject(u);else throw u}})};d()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof yg){let i=ux;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}if(t.streamReader.cancel(new or(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}Dn=new WeakMap,ji=new WeakMap,ds=new WeakSet,ja=function(t=!1){if(y(this,ds,Xd).call(this),!c(this,ji)||this.destroyed)return!1;if(t)return b(this,Dn,setTimeout(()=>{b(this,Dn,null),y(this,ds,ja).call(this,!1)},gx)),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),b(this,ji,!1),!0},Xd=function(){c(this,Dn)&&(clearTimeout(c(this,Dn)),b(this,Dn,null))};class Sx{constructor(){w(this,jr,new Set);w(this,Td,Promise.resolve())}postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};c(this,Td).then(()=>{for(const i of c(this,jr))i.call(this,s)})}addEventListener(t,e){c(this,jr).add(e)}removeEventListener(t,e){c(this,jr).delete(e)}terminate(){c(this,jr).clear()}}jr=new WeakMap,Td=new WeakMap;const Ct=class Ct{constructor({name:t=null,port:e=null,verbosity:s=ew()}={}){w(this,na);var i;if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if((i=c(Ct,Br))!=null&&i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(c(Ct,Br)||b(Ct,Br,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return fe?Promise.all([gn.promise,this._readyCapability.promise]):this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new ch("main","worker",t),this._messageHandler.on("ready",function(){}),y(this,na,Vd).call(this)}_initialize(){if(c(Ct,Nr)||c(Ct,ra,Gd)){this._setupFakeWorker();return}let{workerSrc:t}=Ct;try{Ct._isSameOrigin(window.location.href,t)||(t=Ct._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new ch("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",o=>{if(n.abort(),this.destroyed||!o){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,y(this,na,Vd).call(this)}),s.on("ready",o=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const o=new Uint8Array;s.send("test",o,[o.buffer])};r();return}catch{Zc("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){c(Ct,Nr)||(st("Setting up fake worker."),b(Ct,Nr,!0)),Ct._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Sx;this._port=e;const s=`fake${Pe(Ct,Ed)._++}`,i=new ch(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new ch(s,s+"_worker",e),y(this,na,Vd).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t;this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),(t=c(Ct,Br))==null||t.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){var s;if(!(t!=null&&t.port))throw new Error("PDFWorker.fromPort - invalid method signature.");const e=(s=c(this,Br))==null?void 0:s.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new Ct(t)}static get workerSrc(){if(Ai.workerSrc)return Ai.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return rt(this,"_setupFakeWorkerGlobal",(async()=>c(this,ra,Gd)?c(this,ra,Gd):(await import(this.workerSrc)).WorkerMessageHandler)())}};Ed=new WeakMap,Nr=new WeakMap,Br=new WeakMap,na=new WeakSet,Vd=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},ra=new WeakSet,Gd=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},w(Ct,ra),w(Ct,Ed,0),w(Ct,Nr,!1),w(Ct,Br),fe&&(b(Ct,Nr,!0),Ai.workerSrc||(Ai.workerSrc="./pdf.worker.mjs")),Ct._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},Ct._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let Ro=Ct;class Cx{constructor(t,e,s,i,n){w(this,Hr);w(this,Ni,new Map);w(this,ii,new Map);w(this,oa,new Map);w(this,aa,new Map);w(this,ni,null);this.messageHandler=t,this.loadingTask=e,this.commonObjs=new N0,this.fontLoader=new Sw({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}get annotationStorage(){return rt(this,"annotationStorage",new Eg)}getRenderingIntent(t,e=cn.ENABLE,s=null,i=!1,n=!1){let r=Ye.DISPLAY,o=Tg;switch(t){case"any":r=Ye.ANY;break;case"display":break;case"print":r=Ye.PRINT;break;default:st(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Ye.PRINT&&s instanceof b0?s:this.annotationStorage;switch(e){case cn.DISABLE:r+=Ye.ANNOTATIONS_DISABLE;break;case cn.ENABLE:break;case cn.ENABLE_FORMS:r+=Ye.ANNOTATIONS_FORMS;break;case cn.ENABLE_STORAGE:r+=Ye.ANNOTATIONS_STORAGE,o=h.serializable;break;default:st(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Ye.IS_EDITING),n&&(r+=Ye.OPLIST);const{ids:l,hash:d}=h.modifiedIds,u=[r,o.hash,d];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}destroy(){var s;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(s=c(this,ni))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const i of c(this,ii).values())t.push(i._destroy());c(this,ii).clear(),c(this,oa).clear(),c(this,aa).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{var i;this.commonObjs.clear(),this.fontLoader.clear(),c(this,Ni).clear(),this.filterFactory.destroy(),dh.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new or("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{qt(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:r}){if(r){i.close();return}qt(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",s=>{const i=Promise.withResolvers(),n=this._fullReader;return n.headersReady.then(()=>{var r;(!n.isStreamingSupported||!n.isRangeSupported)&&(this._lastProgress&&((r=e.onProgress)==null||r.call(e,this._lastProgress)),n.onProgress=o=>{var h;(h=e.onProgress)==null||h.call(e,{loaded:o.loaded,total:o.total})}),i.resolve({isStreamingSupported:n.isStreamingSupported,isRangeSupported:n.isRangeSupported,contentLength:n.contentLength})},i.reject),i.promise}),t.on("GetRangeReader",(s,i)=>{qt(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:o}){if(o){i.close();return}qt(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new wx(s,this))}),t.on("DocException",function(s){let i;switch(s.name){case"PasswordException":i=new ug(s.message,s.code);break;case"InvalidPDFException":i=new s0(s.message);break;case"MissingPDFException":i=new rr(s.message);break;case"UnexpectedResponseException":i=new td(s.message,s.status);break;case"UnknownErrorException":i=new gg(s.message,s.details);break;default:Wt("DocException - expected a valid Error.")}e._capability.reject(i)}),t.on("PasswordRequest",s=>{if(b(this,ni,Promise.withResolvers()),e.onPassword){const i=n=>{n instanceof Error?c(this,ni).reject(n):c(this,ni).resolve({password:n})};try{e.onPassword(i,s.code)}catch(n){c(this,ni).reject(n)}}else c(this,ni).reject(new ug(s.message,s.code));return c(this,ni).promise}),t.on("DataLoaded",s=>{var i;(i=e.onProgress)==null||i.call(e,{loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;c(this,ii).get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{var r;if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:o,fontExtraProperties:h,pdfBug:l}=this._params;if("error"in n){const f=n.error;st(`Error during font loading: ${f}`),this.commonObjs.resolve(s,f);break}const d=l&&((r=globalThis.FontInspector)!=null&&r.enabled)?(f,p)=>globalThis.FontInspector.fontAdded(f,p):null,u=new Cw(n,{disableFontFace:o,inspectFont:d});this.fontLoader.bind(u).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!h&&u.data&&(u.data=null),this.commonObjs.resolve(s,u)});break;case"CopyLocalImage":const{imageRef:g}=n;qt(g,"The imageRef must be defined.");for(const f of c(this,ii).values())for(const[,p]of f.objs)if((p==null?void 0:p.ref)===g)return p.dataLen?(this.commonObjs.resolve(s,structuredClone(p)),p.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{var h;if(this.destroyed)return;const o=c(this,ii).get(i);if(!o.objs.has(s)){if(o._intentStates.size===0){(h=r==null?void 0:r.bitmap)==null||h.close();return}switch(n){case"Image":o.objs.resolve(s,r),(r==null?void 0:r.dataLen)>K_&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{var i;this.destroyed||(i=e.onProgress)==null||i.call(e,{loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",s=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(s):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))),t.on("FetchStandardFontData",s=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(s):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var s;this.annotationStorage.size<=0&&st("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((s=this._fullReader)==null?void 0:s.filename)??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=c(this,oa).get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&c(this,aa).set(n.refStr,t);const r=new xx(e,n,this,this._params.pdfBug);return c(this,ii).set(e,r),r});return c(this,oa).set(e,i),i}getPageIndex(t){return I0(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return y(this,Hr,Wl).call(this,"GetFieldObjects")}hasJSActions(){return y(this,Hr,Wl).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return y(this,Hr,Wl).call(this,"GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return y(this,Hr,Wl).call(this,"GetOptionalContentConfig").then(e=>new Vw(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=c(this,Ni).get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>{var n,r;return{info:i[0],metadata:i[1]?new zw(i[1]):null,contentDispositionFilename:((n=this._fullReader)==null?void 0:n.filename)??null,contentLength:((r=this._fullReader)==null?void 0:r.contentLength)??null}});return c(this,Ni).set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of c(this,ii).values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),c(this,Ni).clear(),this.filterFactory.destroy(!0),dh.cleanup()}}cachedPageNumber(t){if(!I0(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return c(this,aa).get(e)??null}}Ni=new WeakMap,ii=new WeakMap,oa=new WeakMap,aa=new WeakMap,ni=new WeakMap,Hr=new WeakSet,Wl=function(t,e=null){const s=c(this,Ni).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return c(this,Ni).set(t,i),i};const cd=Symbol("INITIAL_DATA");class N0{constructor(){w(this,Qh);w(this,Os,Object.create(null))}get(t,e=null){if(e){const i=y(this,Qh,Sf).call(this,t);return i.promise.then(()=>e(i.data)),null}const s=c(this,Os)[t];if(!s||s.data===cd)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=c(this,Os)[t];return!!e&&e.data!==cd}resolve(t,e=null){const s=y(this,Qh,Sf).call(this,t);s.data=e,s.resolve()}clear(){var t;for(const e in c(this,Os)){const{data:s}=c(this,Os)[e];(t=s==null?void 0:s.bitmap)==null||t.close()}b(this,Os,Object.create(null))}*[Symbol.iterator](){for(const t in c(this,Os)){const{data:e}=c(this,Os)[t];e!==cd&&(yield[t,e])}}}Os=new WeakMap,Qh=new WeakSet,Sf=function(t){var e;return(e=c(this,Os))[t]||(e[t]={...Promise.withResolvers(),data:cd})};class Ax{constructor(t){w(this,Pn,null);b(this,Pn,t),this.onContinue=null}get promise(){return c(this,Pn).capability.promise}cancel(t=0){c(this,Pn).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=c(this,Pn).operatorList;if(!t)return!1;const{annotationCanvasMap:e}=c(this,Pn);return t.form||t.canvas&&(e==null?void 0:e.size)>0}}Pn=new WeakMap;const zr=class zr{constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:l,useRequestAnimationFrame:d=!1,pdfBug:u=!1,pageColors:g=null}){w(this,Ln,null);this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=h,this.filterFactory=l,this._pdfBug=u,this.pageColors=g,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=d===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Ax(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){var o,h;if(this.cancelled)return;if(this._canvas){if(c(zr,Wr).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");c(zr,Wr).add(this._canvas)}this._pdfBug&&((o=globalThis.StepperManager)!=null&&o.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:r}=this.params;this.gfx=new Lo(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,(h=this.graphicsReadyCallback)==null||h.call(this)}cancel(t=null,e=0){var s;this.running=!1,this.cancelled=!0,(s=this.gfx)==null||s.endDrawing(),c(this,Ln)&&(window.cancelAnimationFrame(c(this,Ln)),b(this,Ln,null)),c(zr,Wr).delete(this._canvas),this.callback(t||new yg(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){var t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?b(this,Ln,window.requestAnimationFrame(()=>{b(this,Ln,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),c(zr,Wr).delete(this._canvas),this.callback())))}};Ln=new WeakMap,Wr=new WeakMap,w(zr,Wr,new WeakSet);let Bg=zr;const Tx="4.7.76",Ex="8b73b828b";function B0(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function gh(a){return Math.max(0,Math.min(255,255*a))}class H0{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=gh(t),[t,t,t]}static G_HTML([t]){const e=B0(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(gh)}static RGB_HTML(t){return`#${t.map(B0).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[gh(1-Math.min(1,t+i)),gh(1-Math.min(1,s+i)),gh(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,o=Math.min(i,n,r);return["CMYK",i,n,r,o]}}class W0{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",o=>{i.setValue(e,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const o of s.children)o.attributes.value===r.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const h=o.target.options,l=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,o=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,l]of Object.entries(r))if(l!=null)switch(h){case"class":l.length&&t.setAttribute(h,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,l)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){var u,g;const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const o=n!=="richText",h=t.div;if(h.append(r),t.viewport){const f=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=f}o&&h.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const f=document.createTextNode(i.value);r.append(f),o&&uh.shouldBuildText(i.name)&&l.push(f)}return{textDivs:l}}const d=[[i,-1,r]];for(;d.length>0;){const[f,p,m]=d.at(-1);if(p+1===f.children.length){d.pop();continue}const _=f.children[++d.at(-1)[1]];if(_===null)continue;const{name:v}=_;if(v==="#text"){const S=document.createTextNode(_.value);l.push(S),m.append(S);continue}const x=(u=_==null?void 0:_.attributes)!=null&&u.xmlns?document.createElementNS(_.attributes.xmlns,v):document.createElement(v);if(m.append(x),_.attributes&&this.setAttributes({html:x,element:_,storage:e,intent:n,linkService:s}),((g=_.children)==null?void 0:g.length)>0)d.push([_,-1,x]);else if(_.value){const S=document.createTextNode(_.value);o&&uh.shouldBuildText(v)&&l.push(S),x.append(S)}}for(const f of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))f.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const fh=1e3,kx=9,lr=new WeakSet;function Ti(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class Mx{static create(t){switch(t.data.annotationType){case Yt.LINK:return new z0(t);case Yt.TEXT:return new Ox(t);case Yt.WIDGET:switch(t.data.fieldType){case"Tx":return new Dx(t);case"Btn":return t.data.radioButton?new X0(t):t.data.checkBox?new Lx(t):new Rx(t);case"Ch":return new Fx(t);case"Sig":return new Px(t)}return new cr(t);case Yt.POPUP:return new Hg(t);case Yt.FREETEXT:return new V0(t);case Yt.LINE:return new jx(t);case Yt.SQUARE:return new Nx(t);case Yt.CIRCLE:return new Bx(t);case Yt.POLYLINE:return new G0(t);case Yt.CARET:return new Wx(t);case Yt.INK:return new Wg(t);case Yt.POLYGON:return new Hx(t);case Yt.HIGHLIGHT:return new U0(t);case Yt.UNDERLINE:return new zx(t);case Yt.SQUIGGLY:return new Xx(t);case Yt.STRIKEOUT:return new Vx(t);case Yt.STAMP:return new Y0(t);case Yt.FILEATTACHMENT:return new Gx(t);default:return new jt(t)}}}const Qg=class Qg{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){w(this,Jh);w(this,Xr,null);w(this,ha,!1);w(this,la,null);this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t!=null&&t.str||e!=null&&e.str||s!=null&&s.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Qg._hasPopupData(this.data)}updateEdited(t){var s;if(!this.container)return;c(this,Xr)||b(this,Xr,{rect:this.data.rect.slice(0)});const{rect:e}=t;e&&y(this,Jh,Cf).call(this,e),(s=c(this,la))==null||s.popup.updateEdited(t)}resetEdited(){var t;c(this,Xr)&&(y(this,Jh,Cf).call(this,c(this,Xr).rect),(t=c(this,la))==null||t.popup.resetEdited(),b(this,Xr,null))}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof cr||(n.tabIndex=fh);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,e.popupRef&&n.setAttribute("aria-haspopup","dialog"),e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Hg){const{rotation:m}=e;return!e.hasOwnCanvas&&m!==0&&this.setRotation(m,n),n}const{width:o,height:h}=Ti(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const m=e.borderStyle.horizontalCornerRadius,_=e.borderStyle.verticalCornerRadius;if(m>0||_>0){const x=`calc(${m}px * var(--scale-factor)) / calc(${_}px * var(--scale-factor))`;r.borderRadius=x}else if(this instanceof X0){const x=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=x}switch(e.borderStyle.style){case nh.SOLID:r.borderStyle="solid";break;case nh.DASHED:r.borderStyle="dashed";break;case nh.BEVELED:st("Unimplemented border style: beveled");break;case nh.INSET:st("Unimplemented border style: inset");break;case nh.UNDERLINE:r.borderBottomStyle="solid";break}const v=e.borderColor||null;v?(b(this,ha,!0),r.borderColor=V.makeHexColor(v[0]|0,v[1]|0,v[2]|0)):r.borderWidth=0}const l=V.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:d,pageHeight:u,pageX:g,pageY:f}=i.rawDims;r.left=`${100*(l[0]-g)/d}%`,r.top=`${100*(l[1]-f)/u}%`;const{rotation:p}=e;return e.hasOwnCanvas||p===0?(r.width=`${100*o/d}%`,r.height=`${100*h/u}%`):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:r}=Ti(this.data.rect);let o,h;t%180===0?(o=100*n/s,h=100*r/i):(o=100*r/s,h=100*n/i),e.style.width=`${o}%`,e.style.height=`${h}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],o=n.slice(1);i.target.style[s]=H0[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:H0[`${r}_rgb`](o)})};return rt(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail)){const n=t[i]||s[i];n==null||n(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const o={detail:{[i]:n},target:t};r(o),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(m=>Math.fround(m));if(t.length===8){const[m,_,v,x]=t.subarray(2,6);if(i===m&&n===_&&e===v&&s===x)return}const{style:r}=this.container;let o;if(c(this,ha)){const{borderColor:m,borderWidth:_}=r;r.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${m}" stroke-width="${_}">`],this.container.classList.add("hasBorder")}const h=i-e,l=n-s,{svgFactory:d}=this,u=d.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const g=d.createElement("defs");u.append(g);const f=d.createElement("clipPath"),p=`clippath_${this.data.id}`;f.setAttribute("id",p),f.setAttribute("clipPathUnits","objectBoundingBox"),g.append(f);for(let m=2,_=t.length;m<_;m+=8){const v=t[m],x=t[m+1],S=t[m+2],C=t[m+3],E=d.createElement("rect"),k=(S-e)/h,P=(n-x)/l,D=(v-S)/h,F=(x-C)/l;E.setAttribute("x",k),E.setAttribute("y",P),E.setAttribute("width",D),E.setAttribute("height",F),f.append(E),o==null||o.push(`<rect vector-effect="non-scaling-stroke" x="${k}" y="${P}" width="${D}" height="${F}"/>`)}c(this,ha)&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{container:t,data:e}=this;t.setAttribute("aria-haspopup","dialog");const s=b(this,la,new Hg({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(s.render())}render(){Wt("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:o}of i){if(n===-1||r===e)continue;const h=typeof o=="string"?o:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!lr.has(l)){st(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&lr.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){var t;this.container&&(this.container.hidden=!1),(t=this.popup)==null||t.maybeShow()}hide(){var t;this.container&&(this.container.hidden=!0),(t=this.popup)==null||t.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{var s;(s=this.linkService.eventBus)==null||s.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}};Xr=new WeakMap,ha=new WeakMap,la=new WeakMap,Jh=new WeakSet,Cf=function(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}}}=this;s==null||s.splice(0,4,...t);const{width:l,height:d}=Ti(t);e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*l/n}%`,e.height=`${100*d/r}%`):this.setRotation(i)};let jt=Qg;class z0 extends jt{constructor(e,s=null){super(e,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});w(this,Je);this.isTooltipOnly=e.data.isTooltipOnly}render(){const{data:e,linkService:s}=this,i=document.createElement("a");i.setAttribute("data-element-id",e.id);let n=!1;return e.url?(s.addLinkAttributes(i,e.url,e.newWindow),n=!0):e.action?(this._bindNamedAction(i,e.action),n=!0):e.attachment?(y(this,Je,Pb).call(this,i,e.attachment,e.attachmentDest),n=!0):e.setOCGState?(y(this,Je,Lb).call(this,i,e.setOCGState),n=!0):e.dest?(this._bindLink(i,e.dest),n=!0):(e.actions&&(e.actions.Action||e.actions["Mouse Up"]||e.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,e),n=!0),e.resetForm?(this._bindResetFormAction(i,e.resetForm),n=!0):this.isTooltipOnly&&!n&&(this._bindLink(i,""),n=!0)),this.container.classList.add("linkAnnotation"),n&&this.container.append(i),this.container}_bindLink(e,s){e.href=this.linkService.getDestinationHash(s),e.onclick=()=>(s&&this.linkService.goToDestination(s),!1),(s||s==="")&&y(this,Je,go).call(this)}_bindNamedAction(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(s),!1),y(this,Je,go).call(this)}_bindJSAction(e,s){e.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(s.actions)){const r=i.get(n);r&&(e[r]=()=>{var o;return(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s.id,name:n}}),!1})}e.onclick||(e.onclick=()=>!1),y(this,Je,go).call(this)}_bindResetFormAction(e,s){const i=e.onclick;if(i||(e.href=this.linkService.getAnchorUrl("")),y(this,Je,go).call(this),!this._fieldObjects){st('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(e.onclick=()=>!1);return}e.onclick=()=>{var u;i==null||i();const{fields:n,refs:r,include:o}=s,h=[];if(n.length!==0||r.length!==0){const g=new Set(r);for(const f of n){const p=this._fieldObjects[f]||[];for(const{id:m}of p)g.add(m)}for(const f of Object.values(this._fieldObjects))for(const p of f)g.has(p.id)===o&&h.push(p)}else for(const g of Object.values(this._fieldObjects))h.push(...g);const l=this.annotationStorage,d=[];for(const g of h){const{id:f}=g;switch(d.push(f),g.type){case"text":{const m=g.defaultValue||"";l.setValue(f,{value:m});break}case"checkbox":case"radiobutton":{const m=g.defaultValue===g.exportValues;l.setValue(f,{value:m});break}case"combobox":case"listbox":{const m=g.defaultValue||"";l.setValue(f,{value:m});break}default:continue}const p=document.querySelector(`[data-element-id="${f}"]`);if(p){if(!lr.has(p)){st(`_bindResetFormAction - element not allowed: ${f}`);continue}}else continue;p.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((u=this.linkService.eventBus)==null||u.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:d,name:"ResetForm"}})),!1}}}Je=new WeakSet,go=function(){this.container.setAttribute("data-internal-link","")},Pb=function(e,s,i=null){e.href=this.linkService.getAnchorUrl(""),s.description&&(e.title=s.description),e.onclick=()=>{var n;return(n=this.downloadManager)==null||n.openOrDownloadData(s.content,s.filename,i),!1},y(this,Je,go).call(this)},Lb=function(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(s),!1),y(this,Je,go).call(this)};class Ox extends jt{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class cr extends jt{render(){return this.container}showElementAndHideCanvas(t){var e;this.data.hasOwnCanvas&&(((e=t.previousSibling)==null?void 0:e.nodeName)==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Ie.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{var o;(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{var o;if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&((o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}}))})}_setEventListeners(t,e,s,i){var n,r,o;for(const[h,l]of s)(l==="Action"||(n=this.data.actions)!=null&&n[l])&&((l==="Focus"||l==="Blur")&&(e||(e={focused:!1})),this._setEventListener(t,e,h,l,i),l==="Focus"&&!((r=this.data.actions)!=null&&r.Blur)?this._setEventListener(t,e,"blur","Blur",null):l==="Blur"&&!((o=this.data.actions)!=null&&o.Focus)&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":V.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||kx,n=t.style;let r;const o=2,h=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o),d=Math.round(l/(cg*i))||1,u=l/d;r=Math.min(i,h(u/cg))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/cg))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=V.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class Dx extends cr{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){var i,n;const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const r=t.getValue(e,{value:this.data.fieldValue});let o=r.value||"";const h=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;h&&o.length>h&&(o=o.slice(0,h));let l=r.formattedValue||((i=this.data.textContent)==null?void 0:i.join(`
500
- `))||null;l&&this.data.comb&&(l=l.replaceAll(/\s+/g,""));const d={userValue:o,formattedValue:l,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=l??o,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",l??o),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),lr.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=fh,this._setRequired(s,this.data.required),h&&(s.maxLength=h),s.addEventListener("input",g=>{t.setValue(e,{value:g.target.value}),this.setPropertyOnSiblings(s,"value",g.target.value,"value"),d.formattedValue=null}),s.addEventListener("resetform",g=>{const f=this.data.defaultFieldValue??"";s.value=d.userValue=f,d.formattedValue=null});let u=g=>{const{formattedValue:f}=d;f!=null&&(g.target.value=f),g.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",f=>{var m;if(d.focused)return;const{target:p}=f;d.userValue&&(p.value=d.userValue),d.lastCommittedValue=p.value,d.commitKey=1,(m=this.data.actions)!=null&&m.Focus||(d.focused=!0)}),s.addEventListener("updatefromsandbox",f=>{this.showElementAndHideCanvas(f.target);const p={value(m){d.userValue=m.detail.value??"",t.setValue(e,{value:d.userValue.toString()}),m.target.value=d.userValue},formattedValue(m){const{formattedValue:_}=m.detail;d.formattedValue=_,_!=null&&m.target!==document.activeElement&&(m.target.value=_),t.setValue(e,{formattedValue:_})},selRange(m){m.target.setSelectionRange(...m.detail.selRange)},charLimit:m=>{var S;const{charLimit:_}=m.detail,{target:v}=m;if(_===0){v.removeAttribute("maxLength");return}v.setAttribute("maxLength",_);let x=d.userValue;!x||x.length<=_||(x=x.slice(0,_),v.value=d.userValue=x,t.setValue(e,{value:x}),(S=this.linkService.eventBus)==null||S.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:x,willCommit:!0,commitKey:1,selStart:v.selectionStart,selEnd:v.selectionEnd}}))}};this._dispatchEventFromSandbox(p,f)}),s.addEventListener("keydown",f=>{var _;d.commitKey=1;let p=-1;if(f.key==="Escape"?p=0:f.key==="Enter"&&!this.data.multiLine?p=2:f.key==="Tab"&&(d.commitKey=3),p===-1)return;const{value:m}=f.target;d.lastCommittedValue!==m&&(d.lastCommittedValue=m,d.userValue=m,(_=this.linkService.eventBus)==null||_.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:m,willCommit:!0,commitKey:p,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}}))});const g=u;u=null,s.addEventListener("blur",f=>{var m,_;if(!d.focused||!f.relatedTarget)return;(m=this.data.actions)!=null&&m.Blur||(d.focused=!1);const{value:p}=f.target;d.userValue=p,d.lastCommittedValue!==p&&((_=this.linkService.eventBus)==null||_.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:p,willCommit:!0,commitKey:d.commitKey,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}})),g(f)}),(n=this.data.actions)!=null&&n.Keystroke&&s.addEventListener("beforeinput",f=>{var E;d.lastCommittedValue=null;const{data:p,target:m}=f,{value:_,selectionStart:v,selectionEnd:x}=m;let S=v,C=x;switch(f.inputType){case"deleteWordBackward":{const k=_.substring(0,v).match(/\w*[^\w]*$/);k&&(S-=k[0].length);break}case"deleteWordForward":{const k=_.substring(v).match(/^[^\w]*\w*/);k&&(C+=k[0].length);break}case"deleteContentBackward":v===x&&(S-=1);break;case"deleteContentForward":v===x&&(C+=1);break}f.preventDefault(),(E=this.linkService.eventBus)==null||E.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:_,change:p||"",willCommit:!1,selStart:S,selEnd:C}})}),this._setEventListeners(s,d,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],f=>f.target.value)}if(u&&s.addEventListener("blur",u),this.data.comb){const f=(this.data.rect[2]-this.data.rect[0])/h;s.classList.add("comb"),s.style.letterSpacing=`calc(${f}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class Px extends cr{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Lx extends cr{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return lr.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=fh,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s)){const d=h&&l.exportValue===e.exportValue;l.domElement&&(l.domElement.checked=d),t.setValue(l.id,{value:d})}t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue||"Off";r.target.checked=o===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const o={value(h){h.target.checked=h.detail.value!=="Off",t.setValue(s,{value:h.target.checked})}};this._dispatchEventFromSandbox(o,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class X0 extends cr{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if(typeof i=="string"&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(lr.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=fh,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s))t.setValue(l.id,{value:!1});t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue;r.target.checked=o!=null&&o===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",o=>{const h={value:l=>{const d=r===l.detail.value;for(const u of this._getElementsByName(l.target.name)){const g=d&&u.id===s;u.domElement&&(u.domElement.checked=g),t.setValue(u.id,{value:g})}}};this._dispatchEventFromSandbox(h,o)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Rx extends z0{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),t}}class Fx extends cr{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");lr.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=fh;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",d=>{const u=this.data.defaultFieldValue;for(const g of i.options)g.selected=g.value===u});for(const d of this.data.options){const u=document.createElement("option");u.textContent=d.displayValue,u.value=d.exportValue,s.value.includes(d.exportValue)&&(u.setAttribute("selected",!0),n=!1),i.append(u)}let r=null;if(n){const d=document.createElement("option");d.value=" ",d.setAttribute("hidden",!0),d.setAttribute("selected",!0),i.prepend(d),r=()=>{d.remove(),i.removeEventListener("input",r),r=null},i.addEventListener("input",r)}const o=d=>{const u=d?"value":"textContent",{options:g,multiple:f}=i;return f?Array.prototype.filter.call(g,p=>p.selected).map(p=>p[u]):g.selectedIndex===-1?null:g[g.selectedIndex][u]};let h=o(!1);const l=d=>{const u=d.target.options;return Array.prototype.map.call(u,g=>({displayValue:g.textContent,exportValue:g.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",d=>{const u={value(g){r==null||r();const f=g.detail.value,p=new Set(Array.isArray(f)?f:[f]);for(const m of i.options)m.selected=p.has(m.value);t.setValue(e,{value:o(!0)}),h=o(!1)},multipleSelection(g){i.multiple=!0},remove(g){const f=i.options,p=g.detail.remove;f[p].selected=!1,i.remove(p),f.length>0&&Array.prototype.findIndex.call(f,_=>_.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:o(!0),items:l(g)}),h=o(!1)},clear(g){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),h=o(!1)},insert(g){const{index:f,displayValue:p,exportValue:m}=g.detail.insert,_=i.children[f],v=document.createElement("option");v.textContent=p,v.value=m,_?_.before(v):i.append(v),t.setValue(e,{value:o(!0),items:l(g)}),h=o(!1)},items(g){const{items:f}=g.detail;for(;i.length!==0;)i.remove(0);for(const p of f){const{displayValue:m,exportValue:_}=p,v=document.createElement("option");v.textContent=m,v.value=_,i.append(v)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:o(!0),items:l(g)}),h=o(!1)},indices(g){const f=new Set(g.detail.indices);for(const p of g.target.options)p.selected=f.has(p.index);t.setValue(e,{value:o(!0)}),h=o(!1)},editable(g){g.target.disabled=!g.detail.editable}};this._dispatchEventFromSandbox(u,d)}),i.addEventListener("input",d=>{var f;const u=o(!0),g=o(!1);t.setValue(e,{value:u}),d.preventDefault(),(f=this.linkService.eventBus)==null||f.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:h,change:g,changeEx:u,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],d=>d.target.value)):i.addEventListener("input",function(d){t.setValue(e,{value:o(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Hg extends jt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:jt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Ix({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const s of this.elements)s.popup=t,e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${bg}${s}`).join(",")),this.container}}class Ix{constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:o,parent:h,rect:l,parentRect:d,open:u}){w(this,bt);w(this,ca,y(this,bt,Ib).bind(this));w(this,kd,y(this,bt,Tf).bind(this));w(this,Md,y(this,bt,qd).bind(this));w(this,da,y(this,bt,Yd).bind(this));w(this,Vr,null);w(this,Pt,null);w(this,Bi,null);w(this,ua,null);w(this,Zh,null);w(this,tl,null);w(this,ga,null);w(this,Hi,!1);w(this,Ds,null);w(this,Wi,null);w(this,el,null);w(this,zi,null);w(this,sl,null);w(this,Gr,null);w(this,Ur,!1);var g;b(this,Pt,t),b(this,sl,i),b(this,Bi,r),b(this,zi,o),b(this,tl,h),b(this,Vr,e),b(this,el,l),b(this,ga,d),b(this,Zh,s),b(this,ua,f0.toDateObject(n)),this.trigger=s.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",c(this,da)),f.addEventListener("mouseenter",c(this,Md)),f.addEventListener("mouseleave",c(this,kd)),f.classList.add("popupTriggerArea");for(const f of s)(g=f.container)==null||g.addEventListener("keydown",c(this,ca));c(this,Pt).hidden=!0,u&&y(this,bt,Yd).call(this)}render(){if(c(this,Ds))return;const t=b(this,Ds,document.createElement("div"));if(t.className="popup",c(this,Vr)){const n=t.style.outlineColor=V.makeHexColor(...c(this,Vr));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=V.makeHexColor(...c(this,Vr).map(o=>Math.floor(.7*(255-o)+o)))}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),{dir:s.dir,str:s.textContent}=c(this,sl),t.append(e),c(this,ua)){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:c(this,ua).valueOf()})),e.append(n)}const i=c(this,bt,Ud);if(i)W0.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(c(this,Bi));t.append(n)}c(this,Pt).append(t)}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let n=0,r=i.length;n<r;++n){const o=i[n];s.append(document.createTextNode(o)),n<r-1&&s.append(document.createElement("br"))}return s}updateEdited({rect:t,popupContent:e}){var s;c(this,Gr)||b(this,Gr,{contentsObj:c(this,Bi),richText:c(this,zi)}),t&&b(this,Wi,null),e&&(b(this,zi,y(this,bt,Fb).call(this,e)),b(this,Bi,null)),(s=c(this,Ds))==null||s.remove(),b(this,Ds,null)}resetEdited(){var t;c(this,Gr)&&({contentsObj:Pe(this,Bi)._,richText:Pe(this,zi)._}=c(this,Gr),b(this,Gr,null),(t=c(this,Ds))==null||t.remove(),b(this,Ds,null),b(this,Wi,null))}forceHide(){b(this,Ur,this.isVisible),c(this,Ur)&&(c(this,Pt).hidden=!0)}maybeShow(){c(this,Ur)&&(c(this,Ds)||y(this,bt,qd).call(this),b(this,Ur,!1),c(this,Pt).hidden=!1)}get isVisible(){return c(this,Pt).hidden===!1}}ca=new WeakMap,kd=new WeakMap,Md=new WeakMap,da=new WeakMap,Vr=new WeakMap,Pt=new WeakMap,Bi=new WeakMap,ua=new WeakMap,Zh=new WeakMap,tl=new WeakMap,ga=new WeakMap,Hi=new WeakMap,Ds=new WeakMap,Wi=new WeakMap,el=new WeakMap,zi=new WeakMap,sl=new WeakMap,Gr=new WeakMap,Ur=new WeakMap,bt=new WeakSet,Ud=function(){const t=c(this,zi),e=c(this,Bi);return t!=null&&t.str&&(!(e!=null&&e.str)||e.str===t.str)&&c(this,zi).html||null},Af=function(){var t,e,s;return((s=(e=(t=c(this,bt,Ud))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.fontSize)||0},Rb=function(){var t,e,s;return((s=(e=(t=c(this,bt,Ud))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.color)||null},Fb=function(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:c(this,bt,Rb),fontSize:c(this,bt,Af)?`calc(${c(this,bt,Af)}px * var(--scale-factor))`:""}};for(const n of t.split(`
501
- `))e.push({name:"span",value:n,attributes:i});return s},Ib=function(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&c(this,Hi))&&y(this,bt,Yd).call(this)},jb=function(){if(c(this,Wi)!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=c(this,tl);let r=!!c(this,ga),o=r?c(this,ga):c(this,el);for(const p of c(this,Zh))if(!o||V.intersect(p.data.rect,o)!==null){o=p.data.rect,r=!0;break}const h=V.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]),d=r?o[2]-o[0]+5:0,u=h[0]+d,g=h[1];b(this,Wi,[100*(u-i)/e,100*(g-n)/s]);const{style:f}=c(this,Pt);f.left=`${c(this,Wi)[0]}%`,f.top=`${c(this,Wi)[1]}%`},Yd=function(){b(this,Hi,!c(this,Hi)),c(this,Hi)?(y(this,bt,qd).call(this),c(this,Pt).addEventListener("click",c(this,da)),c(this,Pt).addEventListener("keydown",c(this,ca))):(y(this,bt,Tf).call(this),c(this,Pt).removeEventListener("click",c(this,da)),c(this,Pt).removeEventListener("keydown",c(this,ca)))},qd=function(){c(this,Ds)||this.render(),this.isVisible?c(this,Hi)&&c(this,Pt).classList.add("focused"):(y(this,bt,jb).call(this),c(this,Pt).hidden=!1,c(this,Pt).style.zIndex=parseInt(c(this,Pt).style.zIndex)+1e3)},Tf=function(){c(this,Pt).classList.remove("focused"),!(c(this,Hi)||!this.isVisible)&&(c(this,Pt).hidden=!0,c(this,Pt).style.zIndex=parseInt(c(this,Pt).style.zIndex)-1e3)};class V0 extends jt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=tt.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class jx extends jt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,il,null)}render(){this.container.classList.add("lineAnnotation");const e=this.data,{width:s,height:i}=Ti(e.rect),n=this.svgFactory.create(s,i,!0),r=b(this,il,this.svgFactory.createElement("svg:line"));return r.setAttribute("x1",e.rect[2]-e.lineCoordinates[0]),r.setAttribute("y1",e.rect[3]-e.lineCoordinates[1]),r.setAttribute("x2",e.rect[2]-e.lineCoordinates[2]),r.setAttribute("y2",e.rect[3]-e.lineCoordinates[3]),r.setAttribute("stroke-width",e.borderStyle.width||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),n.append(r),this.container.append(n),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return c(this,il)}addHighlightArea(){this.container.classList.add("highlightArea")}}il=new WeakMap;class Nx extends jt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,nl,null)}render(){this.container.classList.add("squareAnnotation");const e=this.data,{width:s,height:i}=Ti(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,nl,this.svgFactory.createElement("svg:rect"));return o.setAttribute("x",r/2),o.setAttribute("y",r/2),o.setAttribute("width",s-r),o.setAttribute("height",i-r),o.setAttribute("stroke-width",r||1),o.setAttribute("stroke","transparent"),o.setAttribute("fill","transparent"),n.append(o),this.container.append(n),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return c(this,nl)}addHighlightArea(){this.container.classList.add("highlightArea")}}nl=new WeakMap;class Bx extends jt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,rl,null)}render(){this.container.classList.add("circleAnnotation");const e=this.data,{width:s,height:i}=Ti(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,rl,this.svgFactory.createElement("svg:ellipse"));return o.setAttribute("cx",s/2),o.setAttribute("cy",i/2),o.setAttribute("rx",s/2-r/2),o.setAttribute("ry",i/2-r/2),o.setAttribute("stroke-width",r||1),o.setAttribute("stroke","transparent"),o.setAttribute("fill","transparent"),n.append(o),this.container.append(n),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return c(this,rl)}addHighlightArea(){this.container.classList.add("highlightArea")}}rl=new WeakMap;class G0 extends jt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,ol,null);this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,vertices:s,borderStyle:i,popupRef:n}}=this;if(!s)return this.container;const{width:r,height:o}=Ti(e),h=this.svgFactory.create(r,o,!0);let l=[];for(let u=0,g=s.length;u<g;u+=2){const f=s[u]-e[0],p=e[3]-s[u+1];l.push(`${f},${p}`)}l=l.join(" ");const d=b(this,ol,this.svgFactory.createElement(this.svgElementName));return d.setAttribute("points",l),d.setAttribute("stroke-width",i.width||1),d.setAttribute("stroke","transparent"),d.setAttribute("fill","transparent"),h.append(d),this.container.append(h),!n&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return c(this,ol)}addHighlightArea(){this.container.classList.add("highlightArea")}}ol=new WeakMap;class Hx extends G0{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Wx extends jt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class Wg extends jt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,al,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?tt.HIGHLIGHT:tt.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{width:r,height:o}=Ti(e),h=this.svgFactory.create(r,o,!0);for(const l of s){let d=[];for(let g=0,f=l.length;g<f;g+=2){const p=l[g]-e[0],m=e[3]-l[g+1];d.push(`${p},${m}`)}d=d.join(" ");const u=this.svgFactory.createElement(this.svgElementName);c(this,al).push(u),u.setAttribute("points",d),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),!n&&this.hasPopupData&&this._createPopup(),h.append(u)}return this.container.append(h),this._editOnDoubleClick(),this.container}getElementsToTriggerPopup(){return c(this,al)}addHighlightArea(){this.container.classList.add("highlightArea")}}al=new WeakMap;class U0 extends jt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=tt.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class zx extends jt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class Xx extends jt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class Vx extends jt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class Y0 extends jt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=tt.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Gx extends jt{constructor(e){var i;super(e,{isRenderable:!0});w(this,ll);w(this,hl,null);const{file:s}=this.data;this.filename=s.filename,this.content=s.content,(i=this.linkService.eventBus)==null||i.dispatch("fileattachmentannotation",{source:this,...s})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:e,data:s}=this;let i;s.hasAppearance||s.fillAlpha===0?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(s.name)?"paperclip":"pushpin"}.svg`,s.fillAlpha&&s.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(s.fillAlpha*100)}%);`)),i.addEventListener("dblclick",y(this,ll,Ef).bind(this)),b(this,hl,i);const{isMac:n}=Ie.platform;return e.addEventListener("keydown",r=>{r.key==="Enter"&&(n?r.metaKey:r.ctrlKey)&&y(this,ll,Ef).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),e.append(i),e}getElementsToTriggerPopup(){return c(this,hl)}addHighlightArea(){this.container.classList.add("highlightArea")}}hl=new WeakMap,ll=new WeakSet,Ef=function(){var e;(e=this.downloadManager)==null||e.openOrDownloadData(this.content,this.filename)};class Ux{constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){w(this,$r);w(this,cl,null);w(this,Yr,null);w(this,qr,new Map);w(this,dl,null);this.div=t,b(this,cl,e),b(this,Yr,s),b(this,dl,o||null),this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return c(this,qr).size>0}async render(t){var r;const{annotations:e}=t,s=this.div;ar(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new vg,annotationStorage:t.annotationStorage||new Eg,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const o of e){if(o.noHTML)continue;const h=o.annotationType===Yt.POPUP;if(h){const u=i.get(o.id);if(!u)continue;n.elements=u}else{const{width:u,height:g}=Ti(o.rect);if(u<=0||g<=0)continue}n.data=o;const l=Mx.create(n);if(!l.isRenderable)continue;if(!h&&o.popupRef){const u=i.get(o.popupRef);u?u.push(l):i.set(o.popupRef,[l])}const d=l.render();o.hidden&&(d.style.visibility="hidden"),await y(this,$r,Nb).call(this,d,o.id),l._isEditable&&(c(this,qr).set(l.data.id,l),(r=this._annotationEditorUIManager)==null||r.renderAnnotationElement(l))}y(this,$r,kf).call(this)}update({viewport:t}){const e=this.div;this.viewport=t,ar(e,{rotation:t.rotation}),y(this,$r,kf).call(this),e.hidden=!1}getEditableAnnotations(){return Array.from(c(this,qr).values())}getEditableAnnotation(t){return c(this,qr).get(t)}}cl=new WeakMap,Yr=new WeakMap,qr=new WeakMap,dl=new WeakMap,$r=new WeakSet,Nb=async function(t,e){var r,o;const s=t.firstChild||t,i=s.id=`${bg}${e}`,n=await((r=c(this,dl))==null?void 0:r.getAriaAttributes(i));if(n)for(const[h,l]of n)s.setAttribute(h,l);this.div.append(t),(o=c(this,cl))==null||o.moveElementInDOM(this.div,t,s,!1)},kf=function(){if(!c(this,Yr))return;const t=this.div;for(const[e,s]of c(this,Yr)){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}c(this,Yr).clear()};const dd=/\r\n?|\n/g,yt=class yt extends gt{constructor(e){super({...e,name:"freeTextEditor"});w(this,Xt);w(this,Ps);w(this,Ze,"");w(this,ul,`${this.id}-editor`);w(this,Kr,null);w(this,ts);b(this,Ps,e.color||yt._defaultColor||gt._defaultLineColor),b(this,ts,e.fontSize||yt._defaultFontSize)}static get _keyboardManager(){const e=yt.prototype,s=r=>r.isEmpty(),i=hr.TRANSLATE_SMALL,n=hr.TRANSLATE_BIG;return rt(this,"_keyboardManager",new ah([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],e.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],e.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],e._translateEmpty,{args:[-i,0],checker:s}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e._translateEmpty,{args:[-n,0],checker:s}],[["ArrowRight","mac+ArrowRight"],e._translateEmpty,{args:[i,0],checker:s}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e._translateEmpty,{args:[n,0],checker:s}],[["ArrowUp","mac+ArrowUp"],e._translateEmpty,{args:[0,-i],checker:s}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e._translateEmpty,{args:[0,-n],checker:s}],[["ArrowDown","mac+ArrowDown"],e._translateEmpty,{args:[0,i],checker:s}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e._translateEmpty,{args:[0,n],checker:s}]]))}static initialize(e,s){gt.initialize(e,s,{strings:["pdfjs-free-text-default-content"]});const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,s){switch(e){case K.FREETEXT_SIZE:yt._defaultFontSize=s;break;case K.FREETEXT_COLOR:yt._defaultColor=s;break}}updateParams(e,s){switch(e){case K.FREETEXT_SIZE:y(this,Xt,Bb).call(this,s);break;case K.FREETEXT_COLOR:y(this,Xt,Hb).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[K.FREETEXT_SIZE,yt._defaultFontSize],[K.FREETEXT_COLOR,yt._defaultColor||gt._defaultLineColor]]}get propertiesToUpdate(){return[[K.FREETEXT_SIZE,c(this,ts)],[K.FREETEXT_COLOR,c(this,Ps)]]}_translateEmpty(e,s){this._uiManager.translateSelectedEditors(e,s,!0)}getInitialTranslation(){const e=this.parentScale;return[-yt._internalPadding*e,-(yt._internalPadding+c(this,ts))*e]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(tt.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),b(this,Kr,new AbortController);const e=this._uiManager.combinedSignal(c(this,Kr));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:e})}disableEditMode(){var e;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",c(this,ul)),this._isDraggable=!0,(e=c(this,Kr))==null||e.abort(),b(this,Kr,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var e;this.width||(this.enableEditMode(),this.editorDiv.focus(),(e=this._initialOptions)!=null&&e.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const e=c(this,Ze),s=b(this,Ze,y(this,Xt,Wb).call(this).trimEnd());if(e===s)return;const i=n=>{if(b(this,Ze,n),!n){this.remove();return}y(this,Xt,Qd).call(this),this._uiManager.rebuild(this),y(this,Xt,$d).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(e)},mustExec:!1}),y(this,Xt,$d).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(e){this.enterInEditMode()}keydown(e){e.target===this.div&&e.key==="Enter"&&(this.enterInEditMode(),e.preventDefault())}editorDivKeydown(e){yt._keyboardManager.exec(this,e)}editorDivFocus(e){this.isEditing=!0}editorDivBlur(e){this.isEditing=!1}editorDivInput(e){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let e,s;this.width&&(e=this.x,s=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",c(this,ul)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),gt._l10nPromise.get("pdfjs-free-text-default-content").then(n=>{var r;return(r=this.editorDiv)==null?void 0:r.setAttribute("default-content",n)}),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${c(this,ts)}px * var(--scale-factor))`,i.color=c(this,Ps),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),nd(this,this.div,["dblclick","keydown"]),this.width){const[n,r]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[h,l]=this.getInitialTranslation();[h,l]=this.pageTranslationToScreen(h,l);const[d,u]=this.pageDimensions,[g,f]=this.pageTranslation;let p,m;switch(this.rotation){case 0:p=e+(o[0]-g)/d,m=s+this.height-(o[1]-f)/u;break;case 90:p=e+(o[0]-g)/d,m=s-(o[1]-f)/u,[h,l]=[l,-h];break;case 180:p=e-this.width+(o[0]-g)/d,m=s-(o[1]-f)/u,[h,l]=[-h,-l];break;case 270:p=e+(o[0]-g-this.height*u)/d,m=s+(o[1]-f-this.width*d)/u,[h,l]=[-l,h];break}this.setAt(p*n,m*r,h,l)}else this.setAt(e*n,s*r,this.width*n,this.height*r);y(this,Xt,Qd).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(e){var p,m,_;const s=e.clipboardData||window.clipboardData,{types:i}=s;if(i.length===1&&i[0]==="text/plain")return;e.preventDefault();const n=y(p=yt,Xi,Mf).call(p,s.getData("text")||"").replaceAll(dd,`
502
- `);if(!n)return;const r=window.getSelection();if(!r.rangeCount)return;this.editorDiv.normalize(),r.deleteFromDocument();const o=r.getRangeAt(0);if(!n.includes(`
503
- `)){o.insertNode(document.createTextNode(n)),this.editorDiv.normalize(),r.collapseToStart();return}const{startContainer:h,startOffset:l}=o,d=[],u=[];if(h.nodeType===Node.TEXT_NODE){const v=h.parentElement;if(u.push(h.nodeValue.slice(l).replaceAll(dd,"")),v!==this.editorDiv){let x=d;for(const S of this.editorDiv.childNodes){if(S===v){x=u;continue}x.push(y(m=yt,Xi,Kd).call(m,S))}}d.push(h.nodeValue.slice(0,l).replaceAll(dd,""))}else if(h===this.editorDiv){let v=d,x=0;for(const S of this.editorDiv.childNodes)x++===l&&(v=u),v.push(y(_=yt,Xi,Kd).call(_,S))}b(this,Ze,`${d.join(`
504
- `)}${n}${u.join(`
505
- `)}`),y(this,Xt,Qd).call(this);const g=new Range;let f=d.reduce((v,x)=>v+x.length,0);for(const{firstChild:v}of this.editorDiv.childNodes)if(v.nodeType===Node.TEXT_NODE){const x=v.nodeValue.length;if(f<=x){g.setStart(v,f),g.setEnd(v,f);break}f-=x}r.removeAllRanges(),r.addRange(g)}get contentDiv(){return this.editorDiv}static async deserialize(e,s,i){var o;let n=null;if(e instanceof V0){const{data:{defaultAppearanceData:{fontSize:h,fontColor:l},rect:d,rotation:u,id:g,popupRef:f},textContent:p,textPosition:m,parent:{page:{pageNumber:_}}}=e;if(!p||p.length===0)return null;n=e={annotationType:tt.FREETEXT,color:Array.from(l),fontSize:h,value:p.join(`
506
- `),position:m,pageIndex:_-1,rect:d.slice(0),rotation:u,id:g,deleted:!1,popupRef:f}}const r=await super.deserialize(e,s,i);return b(r,ts,e.fontSize),b(r,Ps,V.makeHexColor(...e.color)),b(r,Ze,y(o=yt,Xi,Mf).call(o,e.value)),r.annotationElementId=e.id||null,r._initialData=n,r}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=yt._internalPadding*this.parentScale,i=this.getRect(s,s),n=gt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:c(this,Ps)),r={annotationType:tt.FREETEXT,color:n,fontSize:c(this,ts),value:y(this,Xt,zb).call(this),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?r:this.annotationElementId&&!y(this,Xt,Xb).call(this,r)?null:(r.id=this.annotationElementId,r)}renderAnnotationElement(e){const s=super.renderAnnotationElement(e);if(this.deleted)return s;const{style:i}=s;i.fontSize=`calc(${c(this,ts)}px * var(--scale-factor))`,i.color=c(this,Ps),s.replaceChildren();for(const r of c(this,Ze).split(`
507
- `)){const o=document.createElement("div");o.append(r?document.createTextNode(r):document.createElement("br")),s.append(o)}const n=yt._internalPadding*this.parentScale;return e.updateEdited({rect:this.getRect(n,n),popupContent:c(this,Ze)}),s}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}};Ps=new WeakMap,Ze=new WeakMap,ul=new WeakMap,Kr=new WeakMap,ts=new WeakMap,Xt=new WeakSet,Bb=function(e){const s=n=>{this.editorDiv.style.fontSize=`calc(${n}px * var(--scale-factor))`,this.translate(0,-(n-c(this,ts))*this.parentScale),b(this,ts,n),y(this,Xt,$d).call(this)},i=c(this,ts);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Hb=function(e){const s=n=>{b(this,Ps,this.editorDiv.style.color=n)},i=c(this,Ps);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Wb=function(){var i;const e=[];this.editorDiv.normalize();let s=null;for(const n of this.editorDiv.childNodes)(s==null?void 0:s.nodeType)===Node.TEXT_NODE&&n.nodeName==="BR"||(e.push(y(i=yt,Xi,Kd).call(i,n)),s=n);return e.join(`
508
- `)},$d=function(){const[e,s]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:n,div:r}=this,o=r.style.display,h=r.classList.contains("hidden");r.classList.remove("hidden"),r.style.display="hidden",n.div.append(this.div),i=r.getBoundingClientRect(),r.remove(),r.style.display=o,r.classList.toggle("hidden",h)}this.rotation%180===this.parentRotation%180?(this.width=i.width/e,this.height=i.height/s):(this.width=i.height/e,this.height=i.width/s),this.fixAndSetPosition()},Xi=new WeakSet,Kd=function(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(dd,"")},Qd=function(){if(this.editorDiv.replaceChildren(),!!c(this,Ze))for(const e of c(this,Ze).split(`
509
- `)){const s=document.createElement("div");s.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(s)}},zb=function(){return c(this,Ze).replaceAll(" "," ")},Mf=function(e){return e.replaceAll(" "," ")},Xb=function(e){const{value:s,fontSize:i,color:n,pageIndex:r}=this._initialData;return this._hasBeenMoved||e.value!==s||e.fontSize!==i||e.color.some((o,h)=>o!==n[h])||e.pageIndex!==r},w(yt,Xi),Q(yt,"_freeTextDefaultContent",""),Q(yt,"_internalPadding",0),Q(yt,"_defaultColor",null),Q(yt,"_defaultFontSize",10),Q(yt,"_type","freetext"),Q(yt,"_editorType",tt.FREETEXT);let zg=yt;class q0{constructor(t,e=0,s=0,i=!0){w(this,Oe);w(this,gl);w(this,Rn,[]);w(this,Ls,[]);let n=1/0,r=-1/0,o=1/0,h=-1/0;const d=10**-4;for(const{x:v,y:x,width:S,height:C}of t){const E=Math.floor((v-e)/d)*d,k=Math.ceil((v+S+e)/d)*d,P=Math.floor((x-e)/d)*d,D=Math.ceil((x+C+e)/d)*d,F=[E,P,D,!0],B=[k,P,D,!1];c(this,Rn).push(F,B),n=Math.min(n,E),r=Math.max(r,k),o=Math.min(o,P),h=Math.max(h,D)}const u=r-n+2*s,g=h-o+2*s,f=n-s,p=o-s,m=c(this,Rn).at(i?-1:-2),_=[m[0],m[2]];for(const v of c(this,Rn)){const[x,S,C]=v;v[0]=(x-f)/u,v[1]=(S-p)/g,v[2]=(C-p)/g}b(this,gl,{x:f,y:p,width:u,height:g,lastPoint:_})}getOutlines(){c(this,Rn).sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of c(this,Rn))e[3]?(t.push(...y(this,Oe,Of).call(this,e)),y(this,Oe,Gb).call(this,e)):(y(this,Oe,Ub).call(this,e),t.push(...y(this,Oe,Of).call(this,e)));return y(this,Oe,Vb).call(this,t)}}gl=new WeakMap,Rn=new WeakMap,Ls=new WeakMap,Oe=new WeakSet,Vb=function(t){const e=[],s=new Set;for(const r of t){const[o,h,l]=r;e.push([o,h,r],[o,l,r])}e.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=e.length;r<o;r+=2){const h=e[r][2],l=e[r+1][2];h.push(l),l.push(h),s.add(h),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,l,d,u]=r;s.delete(r);let g=o,f=h;for(n=[o,l],i.push(n);;){let p;if(s.has(d))p=d;else if(s.has(u))p=u;else break;s.delete(p),[o,h,l,d,u]=p,g!==o&&(n.push(g,f,o,f===h?h:l),g=o),f=f===h?l:h}n.push(g,f)}return new Yx(i,c(this,gl))},Jd=function(t){const e=c(this,Ls);let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1},Gb=function([,t,e]){const s=y(this,Oe,Jd).call(this,t);c(this,Ls).splice(s,0,[t,e])},Ub=function([,t,e]){const s=y(this,Oe,Jd).call(this,t);for(let i=s;i<c(this,Ls).length;i++){const[n,r]=c(this,Ls)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ls).splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=c(this,Ls)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ls).splice(i,1);return}}},Of=function(t){const[e,s,i]=t,n=[[e,s,i]],r=y(this,Oe,Jd).call(this,i);for(let o=0;o<r;o++){const[h,l]=c(this,Ls)[o];for(let d=0,u=n.length;d<u;d++){const[,g,f]=n[d];if(!(l<=g||f<=h)){if(g>=h){if(f>l)n[d][1]=l;else{if(u===1)return[];n.splice(d,1),d--,u--}continue}n[d][2]=h,f>l&&n.push([e,l,f])}}}return n};class $0{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(t,e){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof Xg}}class Yx extends $0{constructor(e,s){super();w(this,fl);w(this,fa);b(this,fa,e),b(this,fl,s)}toSVGPath(){const e=[];for(const s of c(this,fa)){let[i,n]=s;e.push(`M${i} ${n}`);for(let r=2;r<s.length;r+=2){const o=s[r],h=s[r+1];o===i?(e.push(`V${h}`),n=h):h===n&&(e.push(`H${o}`),i=o)}e.push("Z")}return e.join(" ")}serialize([e,s,i,n],r){const o=[],h=i-e,l=n-s;for(const d of c(this,fa)){const u=new Array(d.length);for(let g=0;g<d.length;g+=2)u[g]=e+d[g]*h,u[g+1]=n-d[g+1]*l;o.push(u)}return o}get box(){return c(this,fl)}}fl=new WeakMap,fa=new WeakMap;const Gi=class Gi{constructor({x:t,y:e},s,i,n,r,o=0){w(this,vl);w(this,ri);w(this,Vi,[]);w(this,pa);w(this,ma);w(this,oi,[]);w(this,ot,new Float64Array(18));w(this,Qr);w(this,Jr);w(this,pl);w(this,ml);w(this,ba);w(this,va);w(this,Fn,[]);b(this,ri,s),b(this,va,n*i),b(this,ma,r),c(this,ot).set([NaN,NaN,NaN,NaN,t,e],6),b(this,pa,o),b(this,ml,c(Gi,bl)*i),b(this,pl,c(Gi,Dd)*i),b(this,ba,i),c(this,Fn).push(t,e)}get free(){return!0}isEmpty(){return isNaN(c(this,ot)[8])}add({x:t,y:e}){var F;b(this,Qr,t),b(this,Jr,e);const[s,i,n,r]=c(this,ri);let[o,h,l,d]=c(this,ot).subarray(8,12);const u=t-l,g=e-d,f=Math.hypot(u,g);if(f<c(this,pl))return!1;const p=f-c(this,ml),m=p/f,_=m*u,v=m*g;let x=o,S=h;o=l,h=d,l+=_,d+=v,(F=c(this,Fn))==null||F.push(t,e);const C=-v/p,E=_/p,k=C*c(this,va),P=E*c(this,va);return c(this,ot).set(c(this,ot).subarray(2,8),0),c(this,ot).set([l+k,d+P],4),c(this,ot).set(c(this,ot).subarray(14,18),12),c(this,ot).set([l-k,d-P],16),isNaN(c(this,ot)[6])?(c(this,oi).length===0&&(c(this,ot).set([o+k,h+P],2),c(this,oi).push(NaN,NaN,NaN,NaN,(o+k-s)/n,(h+P-i)/r),c(this,ot).set([o-k,h-P],14),c(this,Vi).push(NaN,NaN,NaN,NaN,(o-k-s)/n,(h-P-i)/r)),c(this,ot).set([x,S,o,h,l,d],6),!this.isEmpty()):(c(this,ot).set([x,S,o,h,l,d],6),Math.abs(Math.atan2(S-h,x-o)-Math.atan2(v,_))<Math.PI/2?([o,h,l,d]=c(this,ot).subarray(2,6),c(this,oi).push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+d)/2-i)/r),[o,h,x,S]=c(this,ot).subarray(14,18),c(this,Vi).push(NaN,NaN,NaN,NaN,((x+o)/2-s)/n,((S+h)/2-i)/r),!0):([x,S,o,h,l,d]=c(this,ot).subarray(0,6),c(this,oi).push(((x+5*o)/6-s)/n,((S+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+d)/6-i)/r,((o+l)/2-s)/n,((h+d)/2-i)/r),[l,d,o,h,x,S]=c(this,ot).subarray(12,18),c(this,Vi).push(((x+5*o)/6-s)/n,((S+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+d)/6-i)/r,((o+l)/2-s)/n,((h+d)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=c(this,oi),e=c(this,Vi),s=c(this,ot).subarray(4,6),i=c(this,ot).subarray(16,18),[n,r,o,h]=c(this,ri),[l,d,u,g]=y(this,vl,Df).call(this);if(isNaN(c(this,ot)[6])&&!this.isEmpty())return`M${(c(this,ot)[2]-n)/o} ${(c(this,ot)[3]-r)/h} L${(c(this,ot)[4]-n)/o} ${(c(this,ot)[5]-r)/h} L${l} ${d} L${u} ${g} L${(c(this,ot)[16]-n)/o} ${(c(this,ot)[17]-r)/h} L${(c(this,ot)[14]-n)/o} ${(c(this,ot)[15]-r)/h} Z`;const f=[];f.push(`M${t[4]} ${t[5]}`);for(let p=6;p<t.length;p+=6)isNaN(t[p])?f.push(`L${t[p+4]} ${t[p+5]}`):f.push(`C${t[p]} ${t[p+1]} ${t[p+2]} ${t[p+3]} ${t[p+4]} ${t[p+5]}`);f.push(`L${(s[0]-n)/o} ${(s[1]-r)/h} L${l} ${d} L${u} ${g} L${(i[0]-n)/o} ${(i[1]-r)/h}`);for(let p=e.length-6;p>=6;p-=6)isNaN(e[p])?f.push(`L${e[p+4]} ${e[p+5]}`):f.push(`C${e[p]} ${e[p+1]} ${e[p+2]} ${e[p+3]} ${e[p+4]} ${e[p+5]}`);return f.push(`L${e[4]} ${e[5]} Z`),f.join(" ")}getOutlines(){var v;const t=c(this,oi),e=c(this,Vi),s=c(this,ot),i=s.subarray(4,6),n=s.subarray(16,18),[r,o,h,l]=c(this,ri),d=new Float64Array((((v=c(this,Fn))==null?void 0:v.length)??0)+2);for(let x=0,S=d.length-2;x<S;x+=2)d[x]=(c(this,Fn)[x]-r)/h,d[x+1]=(c(this,Fn)[x+1]-o)/l;d[d.length-2]=(c(this,Qr)-r)/h,d[d.length-1]=(c(this,Jr)-o)/l;const[u,g,f,p]=y(this,vl,Df).call(this);if(isNaN(s[6])&&!this.isEmpty()){const x=new Float64Array(36);return x.set([NaN,NaN,NaN,NaN,(s[2]-r)/h,(s[3]-o)/l,NaN,NaN,NaN,NaN,(s[4]-r)/h,(s[5]-o)/l,NaN,NaN,NaN,NaN,u,g,NaN,NaN,NaN,NaN,f,p,NaN,NaN,NaN,NaN,(s[16]-r)/h,(s[17]-o)/l,NaN,NaN,NaN,NaN,(s[14]-r)/h,(s[15]-o)/l],0),new Xg(x,d,c(this,ri),c(this,ba),c(this,pa),c(this,ma))}const m=new Float64Array(c(this,oi).length+24+c(this,Vi).length);let _=t.length;for(let x=0;x<_;x+=2){if(isNaN(t[x])){m[x]=m[x+1]=NaN;continue}m[x]=t[x],m[x+1]=t[x+1]}m.set([NaN,NaN,NaN,NaN,(i[0]-r)/h,(i[1]-o)/l,NaN,NaN,NaN,NaN,u,g,NaN,NaN,NaN,NaN,f,p,NaN,NaN,NaN,NaN,(n[0]-r)/h,(n[1]-o)/l],_),_+=24;for(let x=e.length-6;x>=6;x-=6)for(let S=0;S<6;S+=2){if(isNaN(e[x+S])){m[_]=m[_+1]=NaN,_+=2;continue}m[_]=e[x+S],m[_+1]=e[x+S+1],_+=2}return m.set([NaN,NaN,NaN,NaN,e[4],e[5]],_),new Xg(m,d,c(this,ri),c(this,ba),c(this,pa),c(this,ma))}};ri=new WeakMap,Vi=new WeakMap,pa=new WeakMap,ma=new WeakMap,oi=new WeakMap,ot=new WeakMap,Qr=new WeakMap,Jr=new WeakMap,pl=new WeakMap,ml=new WeakMap,ba=new WeakMap,va=new WeakMap,Fn=new WeakMap,bl=new WeakMap,Od=new WeakMap,Dd=new WeakMap,vl=new WeakSet,Df=function(){const t=c(this,ot).subarray(4,6),e=c(this,ot).subarray(16,18),[s,i,n,r]=c(this,ri);return[(c(this,Qr)+(t[0]-e[0])/2-s)/n,(c(this,Jr)+(t[1]-e[1])/2-i)/r,(c(this,Qr)+(e[0]-t[0])/2-s)/n,(c(this,Jr)+(e[1]-t[1])/2-i)/r]},w(Gi,bl,8),w(Gi,Od,2),w(Gi,Dd,c(Gi,bl)+c(Gi,Od));let ph=Gi;class Xg extends $0{constructor(e,s,i,n,r,o){super();w(this,We);w(this,ya);w(this,Zr,null);w(this,Ui);w(this,yl);w(this,es);w(this,_l);w(this,Nt);b(this,Nt,e),b(this,es,s),b(this,ya,i),b(this,_l,n),b(this,Ui,r),b(this,yl,o),y(this,We,Yb).call(this,o);const{x:h,y:l,width:d,height:u}=c(this,Zr);for(let g=0,f=e.length;g<f;g+=2)e[g]=(e[g]-h)/d,e[g+1]=(e[g+1]-l)/u;for(let g=0,f=s.length;g<f;g+=2)s[g]=(s[g]-h)/d,s[g+1]=(s[g+1]-l)/u}toSVGPath(){const e=[`M${c(this,Nt)[4]} ${c(this,Nt)[5]}`];for(let s=6,i=c(this,Nt).length;s<i;s+=6){if(isNaN(c(this,Nt)[s])){e.push(`L${c(this,Nt)[s+4]} ${c(this,Nt)[s+5]}`);continue}e.push(`C${c(this,Nt)[s]} ${c(this,Nt)[s+1]} ${c(this,Nt)[s+2]} ${c(this,Nt)[s+3]} ${c(this,Nt)[s+4]} ${c(this,Nt)[s+5]}`)}return e.push("Z"),e.join(" ")}serialize([e,s,i,n],r){const o=i-e,h=n-s;let l,d;switch(r){case 0:l=y(this,We,zl).call(this,c(this,Nt),e,n,o,-h),d=y(this,We,zl).call(this,c(this,es),e,n,o,-h);break;case 90:l=y(this,We,Xl).call(this,c(this,Nt),e,s,o,h),d=y(this,We,Xl).call(this,c(this,es),e,s,o,h);break;case 180:l=y(this,We,zl).call(this,c(this,Nt),i,s,-o,h),d=y(this,We,zl).call(this,c(this,es),i,s,-o,h);break;case 270:l=y(this,We,Xl).call(this,c(this,Nt),i,n,-o,-h),d=y(this,We,Xl).call(this,c(this,es),i,n,-o,-h);break}return{outline:Array.from(l),points:[Array.from(d)]}}get box(){return c(this,Zr)}getNewOutline(e,s){const{x:i,y:n,width:r,height:o}=c(this,Zr),[h,l,d,u]=c(this,ya),g=r*d,f=o*u,p=i*d+h,m=n*u+l,_=new ph({x:c(this,es)[0]*g+p,y:c(this,es)[1]*f+m},c(this,ya),c(this,_l),e,c(this,yl),s??c(this,Ui));for(let v=2;v<c(this,es).length;v+=2)_.add({x:c(this,es)[v]*g+p,y:c(this,es)[v+1]*f+m});return _.getOutlines()}}ya=new WeakMap,Zr=new WeakMap,Ui=new WeakMap,yl=new WeakMap,es=new WeakMap,_l=new WeakMap,Nt=new WeakMap,We=new WeakSet,zl=function(e,s,i,n,r){const o=new Float64Array(e.length);for(let h=0,l=e.length;h<l;h+=2)o[h]=s+e[h]*n,o[h+1]=i+e[h+1]*r;return o},Xl=function(e,s,i,n,r){const o=new Float64Array(e.length);for(let h=0,l=e.length;h<l;h+=2)o[h]=s+e[h+1]*n,o[h+1]=i+e[h]*r;return o},Yb=function(e){const s=c(this,Nt);let i=s[4],n=s[5],r=i,o=n,h=i,l=n,d=i,u=n;const g=e?Math.max:Math.min;for(let v=6,x=s.length;v<x;v+=6){if(isNaN(s[v]))r=Math.min(r,s[v+4]),o=Math.min(o,s[v+5]),h=Math.max(h,s[v+4]),l=Math.max(l,s[v+5]),u<s[v+5]?(d=s[v+4],u=s[v+5]):u===s[v+5]&&(d=g(d,s[v+4]));else{const S=V.bezierBoundingBox(i,n,...s.slice(v,v+6));r=Math.min(r,S[0]),o=Math.min(o,S[1]),h=Math.max(h,S[2]),l=Math.max(l,S[3]),u<S[3]?(d=S[2],u=S[3]):u===S[3]&&(d=g(d,S[2]))}i=s[v+4],n=s[v+5]}const f=r-c(this,Ui),p=o-c(this,Ui),m=h-r+2*c(this,Ui),_=l-o+2*c(this,Ui);b(this,Zr,{x:f,y:p,width:m,height:_,lastPoint:[d,u]})};const ze=class ze{constructor({editor:t=null,uiManager:e=null}){w(this,vt);w(this,wl,y(this,vt,qb).bind(this));w(this,xl,y(this,vt,$b).bind(this));w(this,Rs,null);w(this,to,null);w(this,_a);w(this,Qt,null);w(this,Sl,!1);w(this,wa,!1);w(this,Cl,null);w(this,Al);w(this,Fs,null);w(this,xa);var s;t?(b(this,wa,!1),b(this,xa,K.HIGHLIGHT_COLOR),b(this,Cl,t)):(b(this,wa,!0),b(this,xa,K.HIGHLIGHT_DEFAULT_COLOR)),b(this,Fs,(t==null?void 0:t._uiManager)||e),b(this,Al,c(this,Fs)._eventBus),b(this,_a,(t==null?void 0:t.color)||((s=c(this,Fs))==null?void 0:s.highlightColors.values().next().value)||"#FFFF98"),c(ze,Tl)||b(ze,Tl,Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"}))}static get _keyboardManager(){return rt(this,"_keyboardManager",new ah([[["Escape","mac+Escape"],ze.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ze.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ze.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ze.prototype._moveToPrevious],[["Home","mac+Home"],ze.prototype._moveToBeginning],[["End","mac+End"],ze.prototype._moveToEnd]]))}renderButton(){const t=b(this,Rs,document.createElement("button"));t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=c(this,Fs)._signal;t.addEventListener("click",y(this,vt,fo).bind(this),{signal:e}),t.addEventListener("keydown",c(this,wl),{signal:e});const s=b(this,to,document.createElement("span"));return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=c(this,_a),t.append(s),t}renderMainDropdown(){const t=b(this,Qt,y(this,vt,Pf).call(this));return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}_colorSelectFromKeyboard(t){if(t.target===c(this,Rs)){y(this,vt,fo).call(this,t);return}const e=t.target.getAttribute("data-color");e&&y(this,vt,Lf).call(this,e,t)}_moveToNext(t){var e,s;if(!c(this,vt,Gn)){y(this,vt,fo).call(this,t);return}if(t.target===c(this,Rs)){(e=c(this,Qt).firstChild)==null||e.focus();return}(s=t.target.nextSibling)==null||s.focus()}_moveToPrevious(t){var e,s;if(t.target===((e=c(this,Qt))==null?void 0:e.firstChild)||t.target===c(this,Rs)){c(this,vt,Gn)&&this._hideDropdownFromKeyboard();return}c(this,vt,Gn)||y(this,vt,fo).call(this,t),(s=t.target.previousSibling)==null||s.focus()}_moveToBeginning(t){var e;if(!c(this,vt,Gn)){y(this,vt,fo).call(this,t);return}(e=c(this,Qt).firstChild)==null||e.focus()}_moveToEnd(t){var e;if(!c(this,vt,Gn)){y(this,vt,fo).call(this,t);return}(e=c(this,Qt).lastChild)==null||e.focus()}hideDropdown(){var t;(t=c(this,Qt))==null||t.classList.add("hidden"),window.removeEventListener("pointerdown",c(this,xl))}_hideDropdownFromKeyboard(){var t;if(!c(this,wa)){if(!c(this,vt,Gn)){(t=c(this,Cl))==null||t.unselect();return}this.hideDropdown(),c(this,Rs).focus({preventScroll:!0,focusVisible:c(this,Sl)})}}updateColor(t){if(c(this,to)&&(c(this,to).style.backgroundColor=t),!c(this,Qt))return;const e=c(this,Fs).highlightColors.values();for(const s of c(this,Qt).children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){var t,e;(t=c(this,Rs))==null||t.remove(),b(this,Rs,null),b(this,to,null),(e=c(this,Qt))==null||e.remove(),b(this,Qt,null)}};wl=new WeakMap,xl=new WeakMap,Rs=new WeakMap,to=new WeakMap,_a=new WeakMap,Qt=new WeakMap,Sl=new WeakMap,wa=new WeakMap,Cl=new WeakMap,Al=new WeakMap,Fs=new WeakMap,xa=new WeakMap,Tl=new WeakMap,vt=new WeakSet,Pf=function(){const t=document.createElement("div"),e=c(this,Fs)._signal;t.addEventListener("contextmenu",os,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of c(this,Fs).highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",c(ze,Tl)[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===c(this,_a)),n.addEventListener("click",y(this,vt,Lf).bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",c(this,wl),{signal:e}),t},Lf=function(t,e){e.stopPropagation(),c(this,Al).dispatch("switchannotationeditorparams",{source:this,type:c(this,xa),value:t})},qb=function(t){ze._keyboardManager.exec(this,t)},fo=function(t){if(c(this,vt,Gn)){this.hideDropdown();return}if(b(this,Sl,t.detail===0),window.addEventListener("pointerdown",c(this,xl),{signal:c(this,Fs)._signal}),c(this,Qt)){c(this,Qt).classList.remove("hidden");return}const e=b(this,Qt,y(this,vt,Pf).call(this));c(this,Rs).append(e)},$b=function(t){var e;(e=c(this,Qt))!=null&&e.contains(t.target)||this.hideDropdown()},Gn=function(){return c(this,Qt)&&!c(this,Qt).classList.contains("hidden")},w(ze,Tl,null);let ud=ze;const ct=class ct extends gt{constructor(e){super({...e,name:"highlightEditor"});w(this,Z);w(this,Sa,null);w(this,El,0);w(this,Yi);w(this,eo,null);w(this,Ca,null);w(this,us,null);w(this,kl,null);w(this,Ml,0);w(this,so,null);w(this,Is,null);w(this,ve,null);w(this,Xe,!1);w(this,Aa,null);w(this,qi);w(this,Jt,null);w(this,Ta,"");w(this,gs);w(this,Ol,"");this.color=e.color||ct._defaultColor,b(this,gs,e.thickness||ct._defaultThickness),b(this,qi,e.opacity||ct._defaultOpacity),b(this,Yi,e.boxes||null),b(this,Ol,e.methodOfCreation||""),b(this,Ta,e.text||""),this._isDraggable=!1,e.highlightId>-1?(b(this,Xe,!0),y(this,Z,Zd).call(this,e),y(this,Z,po).call(this)):c(this,Yi)&&(b(this,Sa,e.anchorNode),b(this,El,e.anchorOffset),b(this,kl,e.focusNode),b(this,Ml,e.focusOffset),y(this,Z,Rf).call(this),y(this,Z,po).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const e=ct.prototype;return rt(this,"_keyboardManager",new ah([[["ArrowLeft","mac+ArrowLeft"],e._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],e._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],e._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],e._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:c(this,Xe)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:c(this,gs),methodOfCreation:c(this,Ol)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get("color").size}}static initialize(e,s){var i;gt.initialize(e,s),ct._defaultColor||(ct._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(e,s){switch(e){case K.HIGHLIGHT_DEFAULT_COLOR:ct._defaultColor=s;break;case K.HIGHLIGHT_THICKNESS:ct._defaultThickness=s;break}}translateInPage(e,s){}get toolbarPosition(){return c(this,Aa)}updateParams(e,s){switch(e){case K.HIGHLIGHT_COLOR:y(this,Z,Kb).call(this,s);break;case K.HIGHLIGHT_THICKNESS:y(this,Z,Qb).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[K.HIGHLIGHT_DEFAULT_COLOR,ct._defaultColor],[K.HIGHLIGHT_THICKNESS,ct._defaultThickness]]}get propertiesToUpdate(){return[[K.HIGHLIGHT_COLOR,this.color||ct._defaultColor],[K.HIGHLIGHT_THICKNESS,c(this,gs)||ct._defaultThickness],[K.HIGHLIGHT_FREE,c(this,Xe)]]}async addEditToolbar(){const e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(b(this,Ca,new ud({editor:this})),e.addColorPicker(c(this,Ca))),e):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(y(this,Z,Vl).call(this))}getBaseTranslation(){return[0,0]}getRect(e,s){return super.getRect(e,s,y(this,Z,Vl).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){y(this,Z,Ff).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(y(this,Z,po).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?y(this,Z,Ff).call(this):e&&(y(this,Z,po).call(this,e),s=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(e),this.show(this._isVisible),s&&this.select()}rotate(e){var n,r,o;const{drawLayer:s}=this.parent;let i;c(this,Xe)?(e=(e-this.rotation+360)%360,i=y(n=ct,fs,Na).call(n,c(this,Is).box,e)):i=y(r=ct,fs,Na).call(r,this,e),s.rotate(c(this,ve),e),s.rotate(c(this,Jt),e),s.updateBox(c(this,ve),i),s.updateBox(c(this,Jt),y(o=ct,fs,Na).call(o,c(this,us).box,e))}render(){if(this.div)return this.div;const e=super.render();c(this,Ta)&&(e.setAttribute("aria-label",c(this,Ta)),e.setAttribute("role","mark")),c(this,Xe)?e.classList.add("free"):this.div.addEventListener("keydown",y(this,Z,Zb).bind(this),{signal:this._uiManager._signal});const s=b(this,so,document.createElement("div"));e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=c(this,eo);const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),nd(this,c(this,so),["pointerover","pointerleave"]),this.enableEditing(),e}pointerover(){this.parent.drawLayer.addClass(c(this,Jt),"hovered")}pointerleave(){this.parent.drawLayer.removeClass(c(this,Jt),"hovered")}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:y(this,Z,tu).call(this,!0);break;case 1:case 3:y(this,Z,tu).call(this,!1);break}}select(){var e,s;super.select(),c(this,Jt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Jt),"hovered"),(s=this.parent)==null||s.drawLayer.addClass(c(this,Jt),"selected"))}unselect(){var e;super.unselect(),c(this,Jt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Jt),"selected"),c(this,Xe)||y(this,Z,tu).call(this,!1))}get _mustFixPosition(){return!c(this,Xe)}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.show(c(this,ve),e),this.parent.drawLayer.show(c(this,Jt),e))}static startHighlighting(e,s,{target:i,x:n,y:r}){const{x:o,y:h,width:l,height:d}=i.getBoundingClientRect(),u=new AbortController,g=e.combinedSignal(u),f=m=>{m.preventDefault(),m.stopPropagation()},p=m=>{u.abort(),y(this,fs,iv).call(this,e,m)};window.addEventListener("blur",p,{signal:g}),window.addEventListener("pointerup",p,{signal:g}),window.addEventListener("pointerdown",f,{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",os,{signal:g}),i.addEventListener("pointermove",y(this,fs,sv).bind(this,e),{signal:g}),this._freeHighlight=new ph({x:n,y:r},[o,h,l,d],e.scale,this._defaultThickness/2,s,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(e,s,i){var m,_,v,x;let n=null;if(e instanceof U0){const{data:{quadPoints:S,rect:C,rotation:E,id:k,color:P,opacity:D,popupRef:F},parent:{page:{pageNumber:B}}}=e;n=e={annotationType:tt.HIGHLIGHT,color:Array.from(P),opacity:D,quadPoints:S,boxes:null,pageIndex:B-1,rect:C.slice(0),rotation:E,id:k,deleted:!1,popupRef:F}}else if(e instanceof Wg){const{data:{inkLists:S,rect:C,rotation:E,id:k,color:P,borderStyle:{rawWidth:D},popupRef:F},parent:{page:{pageNumber:B}}}=e;n=e={annotationType:tt.HIGHLIGHT,color:Array.from(P),thickness:D,inkLists:S,boxes:null,pageIndex:B-1,rect:C.slice(0),rotation:E,id:k,deleted:!1,popupRef:F}}const{color:r,quadPoints:o,inkLists:h,opacity:l}=e,d=await super.deserialize(e,s,i);d.color=V.makeHexColor(...r),b(d,qi,l||1),h&&b(d,gs,e.thickness),d.annotationElementId=e.id||null,d._initialData=n;const[u,g]=d.pageDimensions,[f,p]=d.pageTranslation;if(o){const S=b(d,Yi,[]);for(let C=0;C<o.length;C+=8)S.push({x:(o[C]-f)/u,y:1-(o[C+1]-p)/g,width:(o[C+2]-o[C])/u,height:(o[C+1]-o[C+5])/g});y(m=d,Z,Rf).call(m),y(_=d,Z,po).call(_),d.rotate(d.rotation)}else if(h){b(d,Xe,!0);const S=h[0],C={x:S[0]-f,y:g-(S[1]-p)},E=new ph(C,[0,0,u,g],1,c(d,gs)/2,!0,.001);for(let D=0,F=S.length;D<F;D+=2)C.x=S[D]-f,C.y=g-(S[D+1]-p),E.add(C);const{id:k,clipPathId:P}=s.drawLayer.highlight(E,d.color,d._defaultOpacity,!0);y(v=d,Z,Zd).call(v,{highlightOutlines:E.getOutlines(),highlightId:k,clipPathId:P}),y(x=d,Z,po).call(x)}return d}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();const s=this.getRect(0,0),i=gt._colorManager.convert(this.color),n={annotationType:tt.HIGHLIGHT,color:i,opacity:c(this,qi),thickness:c(this,gs),quadPoints:y(this,Z,tv).call(this),outlines:y(this,Z,ev).call(this,s),pageIndex:this.pageIndex,rect:s,rotation:y(this,Z,Vl).call(this),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!y(this,Z,nv).call(this,n)?null:(n.id=this.annotationElementId,n)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}};Sa=new WeakMap,El=new WeakMap,Yi=new WeakMap,eo=new WeakMap,Ca=new WeakMap,us=new WeakMap,kl=new WeakMap,Ml=new WeakMap,so=new WeakMap,Is=new WeakMap,ve=new WeakMap,Xe=new WeakMap,Aa=new WeakMap,qi=new WeakMap,Jt=new WeakMap,Ta=new WeakMap,gs=new WeakMap,Ol=new WeakMap,Z=new WeakSet,Rf=function(){const e=new q0(c(this,Yi),.001);b(this,Is,e.getOutlines()),{x:this.x,y:this.y,width:this.width,height:this.height}=c(this,Is).box;const s=new q0(c(this,Yi),.0025,.001,this._uiManager.direction==="ltr");b(this,us,s.getOutlines());const{lastPoint:i}=c(this,us).box;b(this,Aa,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height])},Zd=function({highlightOutlines:e,highlightId:s,clipPathId:i}){var u,g;if(b(this,Is,e),b(this,us,e.getNewOutline(c(this,gs)/2+1.5,.0025)),s>=0)b(this,ve,s),b(this,eo,i),this.parent.drawLayer.finalizeLine(s,e),b(this,Jt,this.parent.drawLayer.highlightOutline(c(this,us)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(c(this,ve),e),this.parent.drawLayer.updateBox(c(this,ve),y(u=ct,fs,Na).call(u,c(this,Is).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(c(this,Jt),c(this,us)),this.parent.drawLayer.updateBox(c(this,Jt),y(g=ct,fs,Na).call(g,c(this,us).box,f))}const{x:r,y:o,width:h,height:l}=e.box;switch(this.rotation){case 0:this.x=r,this.y=o,this.width=h,this.height=l;break;case 90:{const[f,p]=this.parentDimensions;this.x=o,this.y=1-r,this.width=h*p/f,this.height=l*f/p;break}case 180:this.x=1-r,this.y=1-o,this.width=h,this.height=l;break;case 270:{const[f,p]=this.parentDimensions;this.x=1-o,this.y=r,this.width=h*p/f,this.height=l*f/p;break}}const{lastPoint:d}=c(this,us).box;b(this,Aa,[(d[0]-r)/h,(d[1]-o)/l])},Kb=function(e){const s=(r,o)=>{var h,l,d;this.color=r,(h=this.parent)==null||h.drawLayer.changeColor(c(this,ve),r),(l=c(this,Ca))==null||l.updateColor(r),b(this,qi,o),(d=this.parent)==null||d.drawLayer.changeOpacity(c(this,ve),o)},i=this.color,n=c(this,qi);this.addCommands({cmd:s.bind(this,e,ct._defaultOpacity),undo:s.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(e)},!0)},Qb=function(e){const s=c(this,gs),i=n=>{b(this,gs,n),y(this,Z,Jb).call(this,n)};this.addCommands({cmd:i.bind(this,e),undo:i.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:e},!0)},Jb=function(e){if(!c(this,Xe))return;y(this,Z,Zd).call(this,{highlightOutlines:c(this,Is).getNewOutline(e/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},Ff=function(){c(this,ve)===null||!this.parent||(this.parent.drawLayer.remove(c(this,ve)),b(this,ve,null),this.parent.drawLayer.remove(c(this,Jt)),b(this,Jt,null))},po=function(e=this.parent){c(this,ve)===null&&({id:Pe(this,ve)._,clipPathId:Pe(this,eo)._}=e.drawLayer.highlight(c(this,Is),this.color,c(this,qi)),b(this,Jt,e.drawLayer.highlightOutline(c(this,us))),c(this,so)&&(c(this,so).style.clipPath=c(this,eo)))},fs=new WeakSet,Na=function({x:e,y:s,width:i,height:n},r){switch(r){case 90:return{x:1-s-n,y:e,width:n,height:i};case 180:return{x:1-e-i,y:1-s-n,width:i,height:n};case 270:return{x:s,y:1-e-i,width:n,height:i}}return{x:e,y:s,width:i,height:n}},Zb=function(e){ct._keyboardManager.exec(this,e)},tu=function(e){if(!c(this,Sa))return;const s=window.getSelection();e?s.setPosition(c(this,Sa),c(this,El)):s.setPosition(c(this,kl),c(this,Ml))},Vl=function(){return c(this,Xe)?this.rotation:0},tv=function(){if(c(this,Xe))return null;const[e,s]=this.pageDimensions,[i,n]=this.pageTranslation,r=c(this,Yi),o=new Float32Array(r.length*8);let h=0;for(const{x:l,y:d,width:u,height:g}of r){const f=l*e+i,p=(1-d-g)*s+n;o[h]=o[h+4]=f,o[h+1]=o[h+3]=p,o[h+2]=o[h+6]=f+u*e,o[h+5]=o[h+7]=p+g*s,h+=8}return o},ev=function(e){return c(this,Is).serialize(e,y(this,Z,Vl).call(this))},sv=function(e,s){this._freeHighlight.add(s)&&e.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},iv=function(e,s){this._freeHighlight.isEmpty()?e.drawLayer.removeFreeHighlight(this._freeHighlightId):e.createAndAddNewEditor(s,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},nv=function(e){const{color:s}=this._initialData;return e.color.some((i,n)=>i!==s[n])},w(ct,fs),Q(ct,"_defaultColor",null),Q(ct,"_defaultOpacity",1),Q(ct,"_defaultThickness",12),Q(ct,"_type","highlight"),Q(ct,"_editorType",tt.HIGHLIGHT),Q(ct,"_freeHighlightId",-1),Q(ct,"_freeHighlight",null),Q(ct,"_freeHighlightClipId","");let gd=ct;const kt=class kt extends gt{constructor(e){super({...e,name:"inkEditor"});w(this,I);w(this,io,0);w(this,no,0);w(this,ai,null);w(this,$i,new Path2D);w(this,ps,!1);w(this,ro,null);w(this,oo,!1);w(this,ao,!1);w(this,Ki,null);w(this,Ea,null);w(this,ho,0);w(this,lo,0);w(this,In,null);this.color=e.color||null,this.thickness=e.thickness||null,this.opacity=e.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(e,s){gt.initialize(e,s)}static updateDefaultParams(e,s){switch(e){case K.INK_THICKNESS:kt._defaultThickness=s;break;case K.INK_COLOR:kt._defaultColor=s;break;case K.INK_OPACITY:kt._defaultOpacity=s/100;break}}updateParams(e,s){switch(e){case K.INK_THICKNESS:y(this,I,rv).call(this,s);break;case K.INK_COLOR:y(this,I,ov).call(this,s);break;case K.INK_OPACITY:y(this,I,av).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[K.INK_THICKNESS,kt._defaultThickness],[K.INK_COLOR,kt._defaultColor||gt._defaultLineColor],[K.INK_OPACITY,Math.round(kt._defaultOpacity*100)]]}get propertiesToUpdate(){return[[K.INK_THICKNESS,this.thickness||kt._defaultThickness],[K.INK_COLOR,this.color||kt._defaultColor||gt._defaultLineColor],[K.INK_OPACITY,Math.round(100*(this.opacity??kt._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(y(this,I,eu).call(this),y(this,I,su).call(this)),this.isAttachedToDOM||(this.parent.add(this),y(this,I,Ba).call(this)),y(this,I,Gl).call(this)))}remove(){var e;this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,c(this,ai)&&(clearTimeout(c(this,ai)),b(this,ai,null)),(e=c(this,Ki))==null||e.disconnect(),b(this,Ki,null),super.remove())}setParent(e){!this.parent&&e?this._uiManager.removeShouldRescale(this):this.parent&&e===null&&this._uiManager.addShouldRescale(this),super.setParent(e)}onScaleChanging(){const[e,s]=this.parentDimensions,i=this.width*e,n=this.height*s;this.setDimensions(i,n)}enableEditMode(){c(this,ps)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,y(this,I,Nf).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),y(this,I,Bf).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){c(this,ps)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),b(this,ps,!0),this.div.classList.add("disabled"),y(this,I,Gl).call(this,!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(e){this._focusEventsAllowed&&(super.focusin(e),this.enableEditMode())}canvasPointerdown(e){e.button!==0||!this.isInEditMode()||c(this,ps)||(this.setInForeground(),e.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),y(this,I,lv).call(this,e.offsetX,e.offsetY))}canvasPointermove(e){e.preventDefault(),y(this,I,jf).call(this,e.offsetX,e.offsetY)}canvasPointerup(e){e.preventDefault(),y(this,I,Hf).call(this,e)}canvasPointerleave(e){y(this,I,Hf).call(this,e)}get isResizable(){return!this.isEmpty()&&c(this,ps)}render(){if(this.div)return this.div;let e,s;this.width&&(e=this.x,s=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[i,n,r,o]=y(this,I,hv).call(this);if(this.setAt(i,n,0,0),this.setDims(r,o),y(this,I,eu).call(this),this.width){const[h,l]=this.parentDimensions;this.setAspectRatio(this.width*h,this.height*l),this.setAt(e*h,s*l,this.width*h,this.height*l),b(this,ao,!0),y(this,I,Ba).call(this),this.setDims(this.width*h,this.height*l),y(this,I,mo).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return y(this,I,su).call(this),this.div}setDimensions(e,s){const i=Math.round(e),n=Math.round(s);if(c(this,ho)===i&&c(this,lo)===n)return;b(this,ho,i),b(this,lo,n),this.canvas.style.visibility="hidden";const[r,o]=this.parentDimensions;this.width=e/r,this.height=s/o,this.fixAndSetPosition(),c(this,ps)&&y(this,I,Wf).call(this,e,s),y(this,I,Ba).call(this),y(this,I,mo).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(e,s,i){var _,v,x;if(e instanceof Wg)return null;const n=await super.deserialize(e,s,i);n.thickness=e.thickness,n.color=V.makeHexColor(...e.color),n.opacity=e.opacity;const[r,o]=n.pageDimensions,h=n.width*r,l=n.height*o,d=n.parentScale,u=e.thickness/2;b(n,ps,!0),b(n,ho,Math.round(h)),b(n,lo,Math.round(l));const{paths:g,rect:f,rotation:p}=e;for(let{bezier:S}of g){S=y(_=kt,Qi,mv).call(_,S,f,p);const C=[];n.paths.push(C);let E=d*(S[0]-u),k=d*(S[1]-u);for(let D=2,F=S.length;D<F;D+=6){const B=d*(S[D]-u),O=d*(S[D+1]-u),R=d*(S[D+2]-u),L=d*(S[D+3]-u),j=d*(S[D+4]-u),G=d*(S[D+5]-u);C.push([[E,k],[B,O],[R,L],[j,G]]),E=j,k=G}const P=y(this,Qi,pv).call(this,C);n.bezierPath2D.push(P)}const m=y(v=n,I,Xf).call(v);return b(n,no,Math.max(gt.MIN_SIZE,m[2]-m[0])),b(n,io,Math.max(gt.MIN_SIZE,m[3]-m[1])),y(x=n,I,Wf).call(x,h,l),n}serialize(){if(this.isEmpty())return null;const e=this.getRect(0,0),s=gt._colorManager.convert(this.ctx.strokeStyle);return{annotationType:tt.INK,color:s,thickness:this.thickness,opacity:this.opacity,paths:y(this,I,bv).call(this,this.scaleFactor/this.parentScale,this.translationX,this.translationY,e),pageIndex:this.pageIndex,rect:e,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}};io=new WeakMap,no=new WeakMap,ai=new WeakMap,$i=new WeakMap,ps=new WeakMap,ro=new WeakMap,oo=new WeakMap,ao=new WeakMap,Ki=new WeakMap,Ea=new WeakMap,ho=new WeakMap,lo=new WeakMap,In=new WeakMap,I=new WeakSet,rv=function(e){const s=n=>{this.thickness=n,y(this,I,Gl).call(this)},i=this.thickness;this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},ov=function(e){const s=n=>{this.color=n,y(this,I,mo).call(this)},i=this.color;this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},av=function(e){const s=n=>{this.opacity=n,y(this,I,mo).call(this)};e/=100;const i=this.opacity;this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},hv=function(){const{parentRotation:e,parentDimensions:[s,i]}=this;switch(e){case 90:return[0,i,i,s];case 180:return[s,i,s,i];case 270:return[s,0,i,s];default:return[0,0,s,i]}},If=function(){const{ctx:e,color:s,opacity:i,thickness:n,parentScale:r,scaleFactor:o}=this;e.lineWidth=n*r/o,e.lineCap="round",e.lineJoin="round",e.miterLimit=10,e.strokeStyle=`${s}${yw(i)}`},lv=function(e,s){this.canvas.addEventListener("contextmenu",os,{signal:this._uiManager._signal}),y(this,I,Bf).call(this),b(this,ro,new AbortController);const i=this._uiManager.combinedSignal(c(this,ro));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,c(this,ao)||(b(this,ao,!0),y(this,I,Ba).call(this),this.thickness||(this.thickness=kt._defaultThickness),this.color||(this.color=kt._defaultColor||gt._defaultLineColor),this.opacity??(this.opacity=kt._defaultOpacity)),this.currentPath.push([e,s]),b(this,oo,!1),y(this,I,If).call(this),b(this,In,()=>{y(this,I,uv).call(this),c(this,In)&&window.requestAnimationFrame(c(this,In))}),window.requestAnimationFrame(c(this,In))},jf=function(e,s){const[i,n]=this.currentPath.at(-1);if(this.currentPath.length>1&&e===i&&s===n)return;const r=this.currentPath;let o=c(this,$i);if(r.push([e,s]),b(this,oo,!0),r.length<=2){o.moveTo(...r[0]),o.lineTo(e,s);return}r.length===3&&(b(this,$i,o=new Path2D),o.moveTo(...r[0])),y(this,I,gv).call(this,o,...r.at(-3),...r.at(-2),e,s)},cv=function(){if(this.currentPath.length===0)return;const e=this.currentPath.at(-1);c(this,$i).lineTo(...e)},dv=function(e,s){b(this,In,null),e=Math.min(Math.max(e,0),this.canvas.width),s=Math.min(Math.max(s,0),this.canvas.height),y(this,I,jf).call(this,e,s),y(this,I,cv).call(this);let i;if(this.currentPath.length!==1)i=y(this,I,fv).call(this);else{const l=[e,s];i=[[l,l.slice(),l.slice(),l]]}const n=c(this,$i),r=this.currentPath;this.currentPath=[],b(this,$i,new Path2D);const o=()=>{this.allRawPaths.push(r),this.paths.push(i),this.bezierPath2D.push(n),this._uiManager.rebuild(this)},h=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(y(this,I,eu).call(this),y(this,I,su).call(this)),y(this,I,Gl).call(this))};this.addCommands({cmd:o,undo:h,mustExec:!0})},uv=function(){if(!c(this,oo))return;b(this,oo,!1);const e=Math.ceil(this.thickness*this.parentScale),s=this.currentPath.slice(-3),i=s.map(o=>o[0]),n=s.map(o=>o[1]);Math.min(...i)-e,Math.max(...i)+e,Math.min(...n)-e,Math.max(...n)+e;const{ctx:r}=this;r.save(),r.clearRect(0,0,this.canvas.width,this.canvas.height);for(const o of this.bezierPath2D)r.stroke(o);r.stroke(c(this,$i)),r.restore()},gv=function(e,s,i,n,r,o,h){const l=(s+n)/2,d=(i+r)/2,u=(n+o)/2,g=(r+h)/2;e.bezierCurveTo(l+2*(n-l)/3,d+2*(r-d)/3,u+2*(n-u)/3,g+2*(r-g)/3,u,g)},fv=function(){const e=this.currentPath;if(e.length<=2)return[[e[0],e[0],e.at(-1),e.at(-1)]];const s=[];let i,[n,r]=e[0];for(i=1;i<e.length-2;i++){const[f,p]=e[i],[m,_]=e[i+1],v=(f+m)/2,x=(p+_)/2,S=[n+2*(f-n)/3,r+2*(p-r)/3],C=[v+2*(f-v)/3,x+2*(p-x)/3];s.push([[n,r],S,C,[v,x]]),[n,r]=[v,x]}const[o,h]=e[i],[l,d]=e[i+1],u=[n+2*(o-n)/3,r+2*(h-r)/3],g=[l+2*(o-l)/3,d+2*(h-d)/3];return s.push([[n,r],u,g,[l,d]]),s},mo=function(){if(this.isEmpty()){y(this,I,iu).call(this);return}y(this,I,If).call(this);const{canvas:e,ctx:s}=this;s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),y(this,I,iu).call(this);for(const i of this.bezierPath2D)s.stroke(i)},Nf=function(){if(c(this,Ea))return;b(this,Ea,new AbortController);const e=this._uiManager.combinedSignal(c(this,Ea));this.canvas.addEventListener("pointerdown",this.canvasPointerdown.bind(this),{signal:e})},Bf=function(){var e;(e=this.pointerdownAC)==null||e.abort(),this.pointerdownAC=null},Hf=function(e){var s;(s=c(this,ro))==null||s.abort(),b(this,ro,null),y(this,I,Nf).call(this),c(this,ai)&&clearTimeout(c(this,ai)),b(this,ai,setTimeout(()=>{b(this,ai,null),this.canvas.removeEventListener("contextmenu",os)},10)),y(this,I,dv).call(this,e.offsetX,e.offsetY),this.addToAnnotationStorage(),this.setInBackground()},eu=function(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")},su=function(){b(this,Ki,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&this.setDimensions(s.width,s.height)})),c(this,Ki).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,Ki))==null||e.disconnect(),b(this,Ki,null)},{once:!0})},Ba=function(){if(!c(this,ao))return;const[e,s]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*e),this.canvas.height=Math.ceil(this.height*s),y(this,I,iu).call(this)},Wf=function(e,s){const i=y(this,I,nu).call(this),n=(e-i)/c(this,no),r=(s-i)/c(this,io);this.scaleFactor=Math.min(n,r)},iu=function(){const e=y(this,I,nu).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+e,this.translationY*this.scaleFactor+e)},Qi=new WeakSet,pv=function(e){const s=new Path2D;for(let i=0,n=e.length;i<n;i++){const[r,o,h,l]=e[i];i===0&&s.moveTo(...r),s.bezierCurveTo(o[0],o[1],h[0],h[1],l[0],l[1])}return s},zf=function(e,s,i){const[n,r,o,h]=s;switch(i){case 0:for(let l=0,d=e.length;l<d;l+=2)e[l]+=n,e[l+1]=h-e[l+1];break;case 90:for(let l=0,d=e.length;l<d;l+=2){const u=e[l];e[l]=e[l+1]+n,e[l+1]=u+r}break;case 180:for(let l=0,d=e.length;l<d;l+=2)e[l]=o-e[l],e[l+1]+=r;break;case 270:for(let l=0,d=e.length;l<d;l+=2){const u=e[l];e[l]=o-e[l+1],e[l+1]=h-u}break;default:throw new Error("Invalid rotation")}return e},mv=function(e,s,i){const[n,r,o,h]=s;switch(i){case 0:for(let l=0,d=e.length;l<d;l+=2)e[l]-=n,e[l+1]=h-e[l+1];break;case 90:for(let l=0,d=e.length;l<d;l+=2){const u=e[l];e[l]=e[l+1]-r,e[l+1]=u-n}break;case 180:for(let l=0,d=e.length;l<d;l+=2)e[l]=o-e[l],e[l+1]-=r;break;case 270:for(let l=0,d=e.length;l<d;l+=2){const u=e[l];e[l]=h-e[l+1],e[l+1]=o-u}break;default:throw new Error("Invalid rotation")}return e},bv=function(e,s,i,n){var d,u;const r=[],o=this.thickness/2,h=e*s+o,l=e*i+o;for(const g of this.paths){const f=[],p=[];for(let m=0,_=g.length;m<_;m++){const[v,x,S,C]=g[m];if(v[0]===C[0]&&v[1]===C[1]&&_===1){const L=e*v[0]+h,j=e*v[1]+l;f.push(L,j),p.push(L,j);break}const E=e*v[0]+h,k=e*v[1]+l,P=e*x[0]+h,D=e*x[1]+l,F=e*S[0]+h,B=e*S[1]+l,O=e*C[0]+h,R=e*C[1]+l;m===0&&(f.push(E,k),p.push(E,k)),f.push(P,D,F,B,O,R),p.push(P,D),m===_-1&&p.push(O,R)}r.push({bezier:y(d=kt,Qi,zf).call(d,f,n,this.rotation),points:y(u=kt,Qi,zf).call(u,p,n,this.rotation)})}return r},Xf=function(){let e=1/0,s=-1/0,i=1/0,n=-1/0;for(const r of this.paths)for(const[o,h,l,d]of r){const u=V.bezierBoundingBox(...o,...h,...l,...d);e=Math.min(e,u[0]),i=Math.min(i,u[1]),s=Math.max(s,u[2]),n=Math.max(n,u[3])}return[e,i,s,n]},nu=function(){return c(this,ps)?Math.ceil(this.thickness*this.parentScale):0},Gl=function(e=!1){if(this.isEmpty())return;if(!c(this,ps)){y(this,I,mo).call(this);return}const s=y(this,I,Xf).call(this),i=y(this,I,nu).call(this);b(this,no,Math.max(gt.MIN_SIZE,s[2]-s[0])),b(this,io,Math.max(gt.MIN_SIZE,s[3]-s[1]));const n=Math.ceil(i+c(this,no)*this.scaleFactor),r=Math.ceil(i+c(this,io)*this.scaleFactor),[o,h]=this.parentDimensions;this.width=n/o,this.height=r/h,this.setAspectRatio(n,r);const l=this.translationX,d=this.translationY;this.translationX=-s[0],this.translationY=-s[1],y(this,I,Ba).call(this),y(this,I,mo).call(this),b(this,ho,n),b(this,lo,r),this.setDims(n,r);const u=e?i/this.scaleFactor/2:0;this.translate(l-this.translationX-u,d-this.translationY-u)},w(kt,Qi),Q(kt,"_defaultColor",null),Q(kt,"_defaultOpacity",1),Q(kt,"_defaultThickness",1),Q(kt,"_type","ink"),Q(kt,"_editorType",tt.INK);let Vg=kt;const Dl=class Dl extends gt{constructor(e){super({...e,name:"stampEditor"});w(this,it);w(this,Mt,null);w(this,ae,null);w(this,jn,null);w(this,Ji,null);w(this,Nn,null);w(this,ka,"");w(this,hi,null);w(this,Zi,null);w(this,li,null);w(this,ss,!1);w(this,Ma,!1);b(this,Ji,e.bitmapUrl),b(this,Nn,e.bitmapFile)}static initialize(e,s){gt.initialize(e,s)}static get supportedTypes(){return rt(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(s=>`image/${s}`))}static get supportedTypesStr(){return rt(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,s){s.pasteEditor(tt.STAMP,{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var e;return{type:"stamp",hasAltText:!!((e=this.altTextData)!=null&&e.altText)}}static computeTelemetryFinalData(e){const s=e.get("hasAltText");return{hasAltText:s.get(!0)??0,hasNoAltText:s.get(!1)??0}}async mlGuessAltText(e=null,s=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:r,height:o}=e||this.copyCanvas(null,null,!0).imageData,h=await i.guess({name:"altText",request:{data:n,width:r,height:o,channels:n.length/(r*o)}});if(!h)throw new Error("No response from the AI service.");if(h.error)throw new Error("Error from the AI service.");if(h.cancel)return null;if(!h.output)throw new Error("No valid response from the AI service.");const l=h.output;return await this.setGuessedAltText(l),s&&!this.hasAltTextData()&&(this.altTextData={alt:l,decorative:!1}),l}remove(){var e,s;c(this,ae)&&(b(this,Mt,null),this._uiManager.imageManager.deleteId(c(this,ae)),(e=c(this,hi))==null||e.remove(),b(this,hi,null),(s=c(this,Zi))==null||s.disconnect(),b(this,Zi,null),c(this,li)&&(clearTimeout(c(this,li)),b(this,li,null))),super.remove()}rebuild(){if(!this.parent){c(this,ae)&&y(this,it,ru).call(this);return}super.rebuild(),this.div!==null&&(c(this,ae)&&c(this,hi)===null&&y(this,it,ru).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(c(this,jn)||c(this,Mt)||c(this,Ji)||c(this,Nn)||c(this,ae))}get isResizable(){return!0}render(){if(this.div)return this.div;let e,s;if(this.width&&(e=this.x,s=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),c(this,Mt)?y(this,it,Vf).call(this):y(this,it,ru).call(this),this.width&&!this.annotationElementId){const[i,n]=this.parentDimensions;this.setAt(e*i,s*n,this.width*i,this.height*n)}return this.div}copyCanvas(e,s,i=!1){var f;e||(e=224);const{width:n,height:r}=c(this,Mt),o=new xg;let h=c(this,Mt),l=n,d=r,u=null;if(s){if(n>s||r>s){const D=Math.min(s/n,s/r);l=Math.floor(n*D),d=Math.floor(r*D)}u=document.createElement("canvas");const p=u.width=Math.ceil(l*o.sx),m=u.height=Math.ceil(d*o.sy);c(this,ss)||(h=y(this,it,ou).call(this,p,m));const _=u.getContext("2d");_.filter=this._uiManager.hcmFilter;let v="white",x="#cfcfd8";this._uiManager.hcmFilter!=="none"?x="black":(f=window.matchMedia)!=null&&f.call(window,"(prefers-color-scheme: dark)").matches&&(v="#8f8f9d",x="#42414d");const S=15,C=S*o.sx,E=S*o.sy,k=new OffscreenCanvas(C*2,E*2),P=k.getContext("2d");P.fillStyle=v,P.fillRect(0,0,C*2,E*2),P.fillStyle=x,P.fillRect(0,0,C,E),P.fillRect(C,E,C,E),_.fillStyle=_.createPattern(k,"repeat"),_.fillRect(0,0,p,m),_.drawImage(h,0,0,h.width,h.height,0,0,p,m)}let g=null;if(i){let p,m;if(o.symmetric&&h.width<e&&h.height<e)p=h.width,m=h.height;else if(h=c(this,Mt),n>e||r>e){const x=Math.min(e/n,e/r);p=Math.floor(n*x),m=Math.floor(r*x),c(this,ss)||(h=y(this,it,ou).call(this,p,m))}const v=new OffscreenCanvas(p,m).getContext("2d",{willReadFrequently:!0});v.drawImage(h,0,0,h.width,h.height,0,0,p,m),g={width:p,height:m,data:v.getImageData(0,0,p,m).data}}return{canvas:u,width:l,height:d,imageData:g}}getImageForAltText(){return c(this,hi)}static async deserialize(e,s,i){var m;let n=null;if(e instanceof Y0){const{data:{rect:_,rotation:v,id:x,structParent:S,popupRef:C},container:E,parent:{page:{pageNumber:k}}}=e,P=E.querySelector("canvas"),D=i.imageManager.getFromCanvas(E.id,P);P.remove();const F=((m=await s._structTree.getAriaAttributes(`${bg}${x}`))==null?void 0:m.get("aria-label"))||"";n=e={annotationType:tt.STAMP,bitmapId:D.id,bitmap:D.bitmap,pageIndex:k-1,rect:_.slice(0),rotation:v,id:x,deleted:!1,accessibilityData:{decorative:!1,altText:F},isSvg:!1,structParent:S,popupRef:C}}const r=await super.deserialize(e,s,i),{rect:o,bitmap:h,bitmapUrl:l,bitmapId:d,isSvg:u,accessibilityData:g}=e;d&&i.imageManager.isValidId(d)?(b(r,ae,d),h&&b(r,Mt,h)):b(r,Ji,l),b(r,ss,u);const[f,p]=r.pageDimensions;return r.width=(o[2]-o[0])/f,r.height=(o[3]-o[1])/p,r.annotationElementId=e.id||null,g&&(r.altTextData=g),r._initialData=n,b(r,Ma,!!n),r}serialize(e=!1,s=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:tt.STAMP,bitmapId:c(this,ae),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:c(this,ss),structTreeParentId:this._structTreeParentId};if(e)return i.bitmapUrl=y(this,it,au).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:n,altText:r}=this.serializeAltText(!1);if(!n&&r&&(i.accessibilityData={type:"Figure",alt:r}),this.annotationElementId){const h=y(this,it,_v).call(this,i);if(h.isSame)return null;h.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,s===null)return i;s.stamps||(s.stamps=new Map);const o=c(this,ss)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(c(this,ae)))s.stamps.set(c(this,ae),{area:o,serialized:i}),i.bitmap=y(this,it,au).call(this,!1);else if(c(this,ss)){const h=s.stamps.get(c(this,ae));o>h.area&&(h.area=o,h.serialized.bitmap.close(),h.serialized.bitmap=y(this,it,au).call(this,!1))}return i}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}};Mt=new WeakMap,ae=new WeakMap,jn=new WeakMap,Ji=new WeakMap,Nn=new WeakMap,ka=new WeakMap,hi=new WeakMap,Zi=new WeakMap,li=new WeakMap,ss=new WeakMap,Ma=new WeakMap,it=new WeakSet,Ul=function(e,s=!1){if(!e){this.remove();return}b(this,Mt,e.bitmap),s||(b(this,ae,e.id),b(this,ss,e.isSvg)),e.file&&b(this,ka,e.file.name),y(this,it,Vf).call(this)},Yl=function(){if(b(this,jn,null),this._uiManager.enableWaiting(!1),!!c(this,hi)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&c(this,Mt)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&c(this,Mt)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},ru=function(){if(c(this,ae)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(c(this,ae)).then(i=>y(this,it,Ul).call(this,i,!0)).finally(()=>y(this,it,Yl).call(this));return}if(c(this,Ji)){const i=c(this,Ji);b(this,Ji,null),this._uiManager.enableWaiting(!0),b(this,jn,this._uiManager.imageManager.getFromUrl(i).then(n=>y(this,it,Ul).call(this,n)).finally(()=>y(this,it,Yl).call(this)));return}if(c(this,Nn)){const i=c(this,Nn);b(this,Nn,null),this._uiManager.enableWaiting(!0),b(this,jn,this._uiManager.imageManager.getFromFile(i).then(n=>y(this,it,Ul).call(this,n)).finally(()=>y(this,it,Yl).call(this)));return}const e=document.createElement("input");e.type="file",e.accept=Dl.supportedTypesStr;const s=this._uiManager._signal;b(this,jn,new Promise(i=>{e.addEventListener("change",async()=>{if(!e.files||e.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const n=await this._uiManager.imageManager.getFromFile(e.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),y(this,it,Ul).call(this,n)}i()},{signal:s}),e.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>y(this,it,Yl).call(this))),e.click()},Vf=function(){const{div:e}=this;let{width:s,height:i}=c(this,Mt);const[n,r]=this.pageDimensions,o=.75;if(this.width)s=this.width*n,i=this.height*r;else if(s>o*n||i>o*r){const u=Math.min(o*n/s,o*r/i);s*=u,i*=u}const[h,l]=this.parentDimensions;this.setDims(s*h/n,i*l/r),this._uiManager.enableWaiting(!1);const d=b(this,hi,document.createElement("canvas"));d.setAttribute("role","img"),this.addContainer(d),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),y(this,it,Gf).call(this,s,i),y(this,it,yv).call(this),c(this,Ma)||(this.parent.addUndoableEditor(this),b(this,Ma,!0)),this._reportTelemetry({action:"inserted_image"}),c(this,ka)&&d.setAttribute("aria-label",c(this,ka))},vv=function(e,s){var o;const[i,n]=this.parentDimensions;this.width=e/i,this.height=s/n,(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,c(this,li)!==null&&clearTimeout(c(this,li)),b(this,li,setTimeout(()=>{b(this,li,null),y(this,it,Gf).call(this,e,s)},200))},ou=function(e,s){const{width:i,height:n}=c(this,Mt);let r=i,o=n,h=c(this,Mt);for(;r>2*e||o>2*s;){const l=r,d=o;r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2)),o>2*s&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2));const u=new OffscreenCanvas(r,o);u.getContext("2d").drawImage(h,0,0,l,d,0,0,r,o),h=u.transferToImageBitmap()}return h},Gf=function(e,s){const i=new xg,n=Math.ceil(e*i.sx),r=Math.ceil(s*i.sy),o=c(this,hi);if(!o||o.width===n&&o.height===r)return;o.width=n,o.height=r;const h=c(this,ss)?c(this,Mt):y(this,it,ou).call(this,n,r),l=o.getContext("2d");l.filter=this._uiManager.hcmFilter,l.drawImage(h,0,0,h.width,h.height,0,0,n,r)},au=function(e){if(e){if(c(this,ss)){const n=this._uiManager.imageManager.getSvgUrl(c(this,ae));if(n)return n}const s=document.createElement("canvas");return{width:s.width,height:s.height}=c(this,Mt),s.getContext("2d").drawImage(c(this,Mt),0,0),s.toDataURL()}if(c(this,ss)){const[s,i]=this.pageDimensions,n=Math.round(this.width*s*un.PDF_TO_CSS_UNITS),r=Math.round(this.height*i*un.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(n,r);return o.getContext("2d").drawImage(c(this,Mt),0,0,c(this,Mt).width,c(this,Mt).height,0,0,n,r),o.transferToImageBitmap()}return structuredClone(c(this,Mt))},yv=function(){this._uiManager._signal&&(b(this,Zi,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&y(this,it,vv).call(this,s.width,s.height)})),c(this,Zi).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,Zi))==null||e.disconnect(),b(this,Zi,null)},{once:!0}))},_v=function(e){var l;const{rect:s,pageIndex:i,accessibilityData:{altText:n}}=this._initialData,r=e.rect.every((d,u)=>Math.abs(d-s[u])<1),o=e.pageIndex===i,h=(((l=e.accessibilityData)==null?void 0:l.alt)||"")===n;return{isSame:r&&o&&h,isSameAltText:h}},Q(Dl,"_type","stamp"),Q(Dl,"_editorType",tt.STAMP);let Gg=Dl;const js=class js{constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:d}){w(this,he);w(this,co);w(this,Oa,!1);w(this,ci,null);w(this,Bn,null);w(this,tn,null);w(this,is,new Map);w(this,Hn,!1);w(this,Da,!1);w(this,Pa,!1);w(this,ye,null);w(this,en,null);w(this,U);const u=[...c(js,Wn).values()];if(!js._initialized){js._initialized=!0;for(const g of u)g.initialize(d,t)}t.registerEditorTypes(u),b(this,U,t),this.pageIndex=e,this.div=s,b(this,co,n),b(this,ci,r),this.viewport=l,b(this,ye,h),this.drawLayer=o,this._structTree=i,c(this,U).addLayer(this)}get isEmpty(){return c(this,is).size===0}get isInvisible(){return this.isEmpty&&c(this,U).getMode()===tt.NONE}updateToolbar(t){c(this,U).updateToolbar(t)}updateMode(t=c(this,U).getMode()){switch(y(this,he,hu).call(this),t){case tt.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case tt.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case tt.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of c(js,Wn).values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){var e;return t===((e=c(this,ye))==null?void 0:e.div)}addInkEditorIfNeeded(t){if(c(this,U).getMode()!==tt.INK)return;if(!t){for(const s of c(this,is).values())if(s.isEmpty()){s.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){c(this,U).setEditingState(t)}addCommands(t){c(this,U).addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){var e;(e=c(this,ci))==null||e.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of c(this,is).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(c(this,U).removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!c(this,ci))return;const e=c(this,ci).getEditableAnnotations();for(const s of e){if(s.hide(),c(this,U).isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){var i;b(this,Pa,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const n of c(this,is).values())if(n.disableEditing(),!!n.annotationElementId){if(n.serialize()!==null){t.set(n.annotationElementId,n);continue}else e.set(n.annotationElementId,n);(i=this.getEditableAnnotation(n.annotationElementId))==null||i.show(),n.remove()}if(c(this,ci)){const n=c(this,ci).getEditableAnnotations();for(const r of n){const{id:o}=r.data;if(c(this,U).isDeletedAnnotationElement(o))continue;let h=e.get(o);if(h){h.resetAnnotationElement(r),h.show(!1),r.show();continue}h=t.get(o),h&&(c(this,U).addChangedExistingAnnotation(h),h.renderAnnotationElement(r)&&h.show(!1)),r.show()}}y(this,he,hu).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const n of c(js,Wn).values())s.remove(`${n._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),b(this,Pa,!1)}getEditableAnnotation(t){var e;return((e=c(this,ci))==null?void 0:e.getEditableAnnotation(t))||null}setActiveEditor(t){c(this,U).getActive()!==t&&c(this,U).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=c(this,ye))!=null&&t.div&&!c(this,en)){b(this,en,new AbortController);const e=c(this,U).combinedSignal(c(this,en));c(this,ye).div.addEventListener("pointerdown",y(this,he,wv).bind(this),{signal:e}),c(this,ye).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=c(this,ye))!=null&&t.div&&c(this,en)&&(c(this,en).abort(),b(this,en,null),c(this,ye).div.classList.remove("highlighting"))}enableClick(){if(c(this,Bn))return;b(this,Bn,new AbortController);const t=c(this,U).combinedSignal(c(this,Bn));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=c(this,Bn))==null||t.abort(),b(this,Bn,null)}attach(t){c(this,is).set(t.id,t);const{annotationElementId:e}=t;e&&c(this,U).isDeletedAnnotationElement(e)&&c(this,U).removeDeletedAnnotationElement(t)}detach(t){var e;c(this,is).delete(t.id),(e=c(this,co))==null||e.removePointerInTextLayer(t.contentDiv),!c(this,Pa)&&t.annotationElementId&&c(this,U).addDeletedAnnotationElement(t)}remove(t){this.detach(t),c(this,U).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,c(this,Da)||this.addInkEditorIfNeeded(!1)}changeParent(t){var e;t.parent!==this&&(t.parent&&t.annotationElementId&&(c(this,U).addDeletedAnnotationElement(t.annotationElementId),gt.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(e=t.parent)==null||e.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),c(this,U).addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),c(this,U).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var s;if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!c(this,tn)&&(t._focusEventsAllowed=!1,b(this,tn,setTimeout(()=>{b(this,tn,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:c(this,U)._signal}),e.focus())},0))),t._structTreeParentId=(s=c(this,co))==null?void 0:s.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||(t.parent=this),t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return c(this,U).getId()}combinedSignal(t){return c(this,U).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=c(this,he,Uf))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,e){c(this,U).updateToolbar(t),c(this,U).updateMode(t);const{offsetX:s,offsetY:i}=y(this,he,qf).call(this),n=this.getNextId(),r=y(this,he,Yf).call(this,{parent:this,id:n,x:s,y:i,uiManager:c(this,U),isCentered:!0,...e});r&&this.add(r)}async deserialize(t){var e;return await((e=c(js,Wn).get(t.annotationType??t.annotationEditorType))==null?void 0:e.deserialize(t,this,c(this,U)))||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=y(this,he,Yf).call(this,{parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:c(this,U),isCentered:e,...s});return n&&this.add(n),n}addNewEditor(){this.createAndAddNewEditor(y(this,he,qf).call(this),!0)}setSelected(t){c(this,U).setSelected(t)}toggleSelected(t){c(this,U).toggleSelected(t)}isSelected(t){return c(this,U).isSelected(t)}unselect(t){c(this,U).unselect(t)}pointerup(t){const{isMac:e}=Ie.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&c(this,Hn)){if(b(this,Hn,!1),!c(this,Oa)){b(this,Oa,!0);return}if(c(this,U).getMode()===tt.STAMP){c(this,U).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(c(this,U).getMode()===tt.HIGHLIGHT&&this.enableTextSelection(),c(this,Hn)){b(this,Hn,!1);return}const{isMac:e}=Ie.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;b(this,Hn,!0);const s=c(this,U).getActive();b(this,Oa,!s||s.isEmpty())}findNewParent(t,e,s){const i=c(this,U).findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}destroy(){var t,e;((t=c(this,U).getActive())==null?void 0:t.parent)===this&&(c(this,U).commitOrRemove(),c(this,U).setActiveEditor(null)),c(this,tn)&&(clearTimeout(c(this,tn)),b(this,tn,null));for(const s of c(this,is).values())(e=c(this,co))==null||e.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,c(this,is).clear(),c(this,U).removeLayer(this)}render({viewport:t}){this.viewport=t,ar(this.div,t);for(const e of c(this,U).getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){c(this,U).commitOrRemove(),y(this,he,hu).call(this);const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,ar(this.div,{rotation:s}),e!==s)for(const i of c(this,is).values())i.rotate(s);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return c(this,U).viewParameters.realScale}};co=new WeakMap,Oa=new WeakMap,ci=new WeakMap,Bn=new WeakMap,tn=new WeakMap,is=new WeakMap,Hn=new WeakMap,Da=new WeakMap,Pa=new WeakMap,ye=new WeakMap,en=new WeakMap,U=new WeakMap,Wn=new WeakMap,he=new WeakSet,wv=function(t){c(this,U).unselectAll();const{target:e}=t;if(e===c(this,ye).div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&c(this,ye).div.contains(e)){const{isMac:s}=Ie.platform;if(t.button!==0||t.ctrlKey&&s)return;c(this,U).showAllEditors("highlight",!0,!0),c(this,ye).div.classList.add("free"),this.toggleDrawing(),gd.startHighlighting(this,c(this,U).direction==="ltr",{target:c(this,ye).div,x:t.x,y:t.y}),c(this,ye).div.addEventListener("pointerup",()=>{c(this,ye).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:c(this,U)._signal}),t.preventDefault()}},Uf=function(){return c(js,Wn).get(c(this,U).getMode())},Yf=function(t){const e=c(this,he,Uf);return e?new e.prototype.constructor(t):null},qf=function(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),o=Math.min(window.innerWidth,t+s),h=Math.min(window.innerHeight,e+i),l=(n+o)/2-t,d=(r+h)/2-e,[u,g]=this.viewport.rotation%180===0?[l,d]:[d,l];return{offsetX:u,offsetY:g}},hu=function(){b(this,Da,!0);for(const t of c(this,is).values())t.isEmpty()&&t.remove();b(this,Da,!1)},Q(js,"_initialized",!1),w(js,Wn,new Map([zg,Vg,Gg,gd].map(t=>[t._editorType,t])));let Ug=js;const le=class le{constructor({pageIndex:t}){w(this,uo);w(this,di,null);w(this,Pl,0);w(this,Vt,new Map);w(this,zn,new Map);this.pageIndex=t}setParent(t){if(!c(this,di)){b(this,di,t);return}if(c(this,di)!==t){if(c(this,Vt).size>0)for(const e of c(this,Vt).values())e.remove(),t.append(e);b(this,di,t)}}static get _svgFactory(){return rt(this,"_svgFactory",new vg)}highlight(t,e,s,i=!1){const n=Pe(this,Pl)._++,r=y(this,uo,Kf).call(this,t.box);r.classList.add("highlight"),t.free&&r.classList.add("free");const o=le._svgFactory.createElement("defs");r.append(o);const h=le._svgFactory.createElement("path");o.append(h);const l=`path_p${this.pageIndex}_${n}`;h.setAttribute("id",l),h.setAttribute("d",t.toSVGPath()),i&&c(this,zn).set(n,h);const d=y(this,uo,xv).call(this,o,l),u=le._svgFactory.createElement("use");return r.append(u),r.setAttribute("fill",e),r.setAttribute("fill-opacity",s),u.setAttribute("href",`#${l}`),c(this,Vt).set(n,r),{id:n,clipPathId:`url(#${d})`}}highlightOutline(t){const e=Pe(this,Pl)._++,s=y(this,uo,Kf).call(this,t.box);s.classList.add("highlightOutline");const i=le._svgFactory.createElement("defs");s.append(i);const n=le._svgFactory.createElement("path");i.append(n);const r=`path_p${this.pageIndex}_${e}`;n.setAttribute("id",r),n.setAttribute("d",t.toSVGPath()),n.setAttribute("vector-effect","non-scaling-stroke");let o;if(t.free){s.classList.add("free");const d=le._svgFactory.createElement("mask");i.append(d),o=`mask_p${this.pageIndex}_${e}`,d.setAttribute("id",o),d.setAttribute("maskUnits","objectBoundingBox");const u=le._svgFactory.createElement("rect");d.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const g=le._svgFactory.createElement("use");d.append(g),g.setAttribute("href",`#${r}`),g.setAttribute("stroke","none"),g.setAttribute("fill","black"),g.setAttribute("fill-rule","nonzero"),g.classList.add("mask")}const h=le._svgFactory.createElement("use");s.append(h),h.setAttribute("href",`#${r}`),o&&h.setAttribute("mask",`url(#${o})`);const l=h.cloneNode();return s.append(l),h.classList.add("mainOutline"),l.classList.add("secondaryOutline"),c(this,Vt).set(e,s),e}finalizeLine(t,e){const s=c(this,zn).get(t);c(this,zn).delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){c(this,Vt).get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),c(this,zn).delete(t)}updatePath(t,e){c(this,zn).get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){var s;y(s=le,Ll,$f).call(s,c(this,Vt).get(t),e)}show(t,e){c(this,Vt).get(t).classList.toggle("hidden",!e)}rotate(t,e){c(this,Vt).get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){c(this,Vt).get(t).setAttribute("fill",e)}changeOpacity(t,e){c(this,Vt).get(t).setAttribute("fill-opacity",e)}addClass(t,e){c(this,Vt).get(t).classList.add(e)}removeClass(t,e){c(this,Vt).get(t).classList.remove(e)}getSVGRoot(t){return c(this,Vt).get(t)}remove(t){c(this,di)!==null&&(c(this,Vt).get(t).remove(),c(this,Vt).delete(t))}destroy(){b(this,di,null);for(const t of c(this,Vt).values())t.remove();c(this,Vt).clear()}};di=new WeakMap,Pl=new WeakMap,Vt=new WeakMap,zn=new WeakMap,Ll=new WeakSet,$f=function(t,{x:e=0,y:s=0,width:i=1,height:n=1}={}){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`},uo=new WeakSet,Kf=function(t){var s;const e=le._svgFactory.create(1,1,!0);return c(this,di).append(e),e.setAttribute("aria-hidden",!0),y(s=le,Ll,$f).call(s,e,t),e},xv=function(t,e){const s=le._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=le._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i},w(le,Ll);let Yg=le;$.AbortException,$.AnnotationEditorLayer,$.AnnotationEditorParamsType,$.AnnotationEditorType,$.AnnotationEditorUIManager,$.AnnotationLayer,$.AnnotationMode,$.CMapCompressionType,$.ColorPicker,$.DOMSVGFactory,$.DrawLayer,$.FeatureTest;var qx=$.GlobalWorkerOptions;$.ImageKind,$.InvalidPDFException,$.MissingPDFException,$.OPS,$.OutputScale,$.PDFDataRangeTransport,$.PDFDateString,$.PDFWorker,$.PasswordResponses,$.PermissionFlag,$.PixelsPerInch,$.RenderingCancelledException,$.TextLayer,$.UnexpectedResponseException,$.Util,$.VerbosityLevel,$.XfaLayer,$.build,$.createValidAbsoluteUrl,$.fetchData;var $x=$.getDocument;$.getFilenameFromUrl,$.getPdfFilenameFromUrl,$.getXfaPageViewport,$.isDataScheme,$.isPdfFile,$.noContextMenu,$.normalizeUnicode,$.setLayerDimensions,$.shadow,$.version;const Kx={fabric:"^6.4.3","pdfjs-dist":"^4.7.76"};function Qx(a){return new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>t(s.result)),s.addEventListener("error",e),s.readAsDataURL(a)})}const Jx=Kx["pdfjs-dist"].replace("^","");qx.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Jx}/pdf.worker.min.mjs`;async function Zx(a){const t="data:application/pdf;base64,",e=await Qx(a);if(typeof e=="string")return window.atob(e.slice(t.length))}function tS(a,t){return $x({data:a,password:t}).promise}const eS="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='20'%20cy='20'%20r='10.75'%20stroke='currentColor'%20stroke-width='2.5'/%3e%3cpath%20d='M16%2024L23.7782%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3cpath%20d='M24%2024L16.2218%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3c/svg%3e";function sS(a){return new URL(Object.assign({"../assets/close.svg":eS})[`../assets/${a}`],typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Ot&&Ot.src||new URL("pdf-canvas.umd.js",document.baseURI).href).href}function iS(a){return new Promise((t,e)=>{const s=window.URL.createObjectURL(a),i=new Image;i.src=s,i.addEventListener("load",async()=>{window.URL.revokeObjectURL(s),t(await nS(i))}),i.addEventListener("error",n=>{window.URL.revokeObjectURL(s),e(n)})})}function nS(a){return new Promise(t=>{const e=document.createElement("canvas"),s=e.getContext("2d"),{naturalWidth:i,naturalHeight:n}=a;e.width=i,e.height=n,s==null||s.drawImage(a,0,0,i,n),t(e.toDataURL("image/jpeg",.8))})}let K0=null;function rS(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function oS(){const a=K0??rS();return K0=a,a/72}function aS(a,t=500){if(typeof a!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,a.apply(this,s)},t)}}const hS={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},lS={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},cS={stroke:"#000",hoverStroke:"#B7EC5D",src:""},hs=new Map;function Q0(a=""){let t=0,e=null,s=null,i=1,n={...cS};function r(){if(!a||hs.has(a))return;const O=new Ku(a);return hs.set(a,O),O.on("selection:cleared",()=>D(O)),O}function o(O,R){const L=O.type;return{"application/pdf":h,"image/png":u,"image/jpeg":u}[L](O,R)??Promise.reject(new Error(`Unsupported ${L} file type.`))}async function h(O,R){const L=await Zx(O);if(!L)return;const j=Date.now(),Y={PDFId:`${O.name}-${j}`,name:O.name.replace(/.pdf/,""),updateDate:j,PDFBase64:L};try{return await l({page:1,PDFBase64:L,scale:.8,password:R}),{...Y,pages:t}}catch(X){return Promise.reject(X)}}async function l({page:O,PDFBase64:R,scale:L,password:j}){try{const G=await tS(R,j),Y=await q.toRaw(G).getPage(O),X=Y.getViewport({scale:L}),H=document.createElement("canvas"),_t=H.getContext("2d"),dt=oS()/window.devicePixelRatio;H.width=Math.floor(X.width*dt),H.height=Math.floor(X.height*dt),t=G.numPages;const _e={canvasContext:_t,viewport:X,transform:[dt,0,0,dt,0,0]};return Y.render(_e).promise.then(()=>d(H))}catch(G){return Promise.reject(G)}}function d(O){if(!hs.get(a))return;const L=1/3,j=dS(O,L);f(j,L)}async function u(O){const R=await iS(O),L=Date.now(),G={PDFId:`${O.name}${L}`,name:O.name.replace(/.png|.jpg|.jpeg/,""),updateDate:L,PDFBase64:R};return g({url:R}),{...G,pages:1}}async function g({url:O,scale:R=.5}){if(!hs.get(a))return;const j=await ge.fromURL(O);j.scale(R),f(j,R)}function f(O,R){const L=hs.get(a);L&&(L.setWidth(O.width*R),L.setHeight(O.height*R),L.backgroundImage=O,L.renderAll())}async function p(O,R){const L=hs.get(a);if(!L)return;const j=await ge.fromURL(O,{},{...hS,...R});L.add(j),_(L,j)}function m(O,R){const L=hs.get(a);if(!L)return;const j=new ue(O,{...lS,...R});L.add(j),_(L,j)}function _(O,R){R.on("selected",L=>v({canvas:O,target:L.target})),R.on("modified",L=>S(L.target)),R.on("scaling",L=>S(L.transform.target)),R.on("moving",L=>S(L.transform.target)),R.on("rotating",L=>S(L.transform.target))}async function v({canvas:O,target:R,stroke:L=n.stroke,uuid:j=Date.now()}){if((e==null?void 0:e.stroke)===`${L}-${j}`)return;const G=n.src||sS("close.svg"),{objects:Y,options:X}=await H_(G),H=Y.filter(dt=>dt!==null),_t=t_.groupSVGElements(H,X);H.forEach(dt=>{dt.stroke=L}),_t.hoverCursor="pointer",_t.stroke=`${L}-${j}`,D(O),e=_t,s=R,x(O,R,j),C(i,!0),O.add(_t)}function x(O,R,L){e&&(e.on("selected",()=>{O.remove(R),D(O)}),e.on("mouseover",()=>{v({canvas:O,target:R,stroke:n.hoverStroke,uuid:L})}),e.on("mouseout",()=>{v({canvas:O,target:R,stroke:n.stroke,uuid:L})}))}function S(O){if(!e)return;const{oCoords:R}=O;if(!R)return;const{x:L,y:j}=R.tl.touchCorner.tl,{height:G,width:Y,scaleY:X,scaleX:H}=e;e.top=j-G*X/2,e.left=L-Y*H/2,e.setCoords()}function C(O,R=!1){const L=hs.get(a);i=O,L&&(k(s,O),E(s,O),!R&&L.renderAll())}function E(O,R){!e||!O||(e.scale(1/R),S(O))}function k(O,R){O&&(O.borderScaleFactor=1/R,O.cornerSize=6*(1/R),O.touchCornerSize=24*(1/R),O.cornerStrokeColor=n.stroke,O.setCoords())}function P(O){if(!O)return;n={...n,...O};const R=hs.get(a);!e||!s||!R||v({target:s,canvas:R})}function D(O){e&&(O.remove(e),e=s=null)}function F(){const O=hs.get(a);O&&(O.discardActiveObject(),O.renderAll())}function B(){const O=hs.get(a);O&&(O.clear(),hs.delete(a))}return{createCanvas:r,loadFile:o,specifyPage:l,renderImage:g,addFabric:p,addTextFabric:m,clearActive:F,deleteCanvas:B,scaleFabric:C,setCloseSvgOptions:P}}function dS(a,t){return new ge(a,{scaleX:t,scaleY:t})}function uS(a){let t=0;const e=aS(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});q.onMounted(()=>{window.addEventListener("resize",e)}),q.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const qg=q.defineComponent({__name:"PdfCanvas",props:{file:{},page:{default:1},canvasId:{default:"PDF-canvas"},fileZoom:{default:1},fileScale:{default:1},canvasScale:{default:1},canvasClass:{default:""},isDrop:{type:Boolean,default:!1},password:{},dropTextOptions:{},dropImageOptions:{},closeSvgOptions:{}},setup(a,{expose:t}){const e=a,s=q.ref(null),i=`${e.canvasId}-${e.page-1}`,n=q.computed(()=>e.fileZoom*e.canvasScale),{createCanvas:r,specifyPage:o,addFabric:h,addTextFabric:l,renderImage:d,clearActive:u,deleteCanvas:g,scaleFabric:f,setCloseSvgOptions:p}=Q0(i);m(),uS(m);async function m(){const{file:S,page:C,fileScale:E}=e;window.requestAnimationFrame(async()=>{if(await q.nextTick(),r(),S.PDFBase64.startsWith("data:image")||S.canvas){const{canvas:k}=S,P=k?7:3,D=k!=null&&k.length?k[C-1]:S.PDFBase64;d({url:D,scale:E/P});return}await o({page:C,PDFBase64:S.PDFBase64,scale:E,password:e.password})})}function _(S){if(!e.isDrop||!S.dataTransfer)return;const{dataTransfer:C,offsetX:E,offsetY:k}=S,P=C.getData("text"),D=C.getData("image"),F={left:E-71,top:k-55};D&&v(D,F),P&&x(P,F)}function v(S,C){h(S,{...C,...e.dropImageOptions})}function x(S,C){l(S,{...C,...e.dropTextOptions})}return q.watch([()=>e.fileScale,()=>e.page,()=>e.file,()=>e.password],m),q.watch(n,S=>f(S),{immediate:!0}),q.watch(()=>e.closeSvgOptions,p,{immediate:!0}),q.onBeforeUnmount(g),t({addImage:v,addText:x,clearActive:u,deleteCanvas:g,canvasRef:s}),(S,C)=>(q.openBlock(),q.createElementBlock("div",{style:q.normalizeStyle({transform:`scale(${n.value})`}),onDragover:C[0]||(C[0]=q.withModifiers(()=>{},["stop","prevent"])),onDragenter:C[1]||(C[1]=q.withModifiers(()=>{},["stop","prevent"])),onDrop:q.withModifiers(_,["stop","prevent"])},[q.createElementVNode("canvas",{id:i,ref_key:"canvasRef",ref:s,class:q.normalizeClass(S.canvasClass)},null,2)],36))}});qg.install=function(a){a.component("PdfCanvas",qg)};const fd=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));nt.default=qg,nt.useFabric=Q0,Object.defineProperties(nt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});