@component-hook/pdf-canvas 0.1.3-alpha.1 → 0.1.3-alpha.3

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,30 +1,30 @@
1
- (function(st,U){typeof exports=="object"&&typeof module<"u"?U(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],U):(st=typeof globalThis<"u"?globalThis:st||self,U(st["pdf-canvas"]={},st.Vue))})(this,function(st,U){"use strict";var _S=Object.defineProperty;var nv=st=>{throw TypeError(st)};var wS=(st,U,Et)=>U in st?_S(st,U,{enumerable:!0,configurable:!0,writable:!0,value:Et}):st[U]=Et;var K=(st,U,Et)=>wS(st,typeof U!="symbol"?U+"":U,Et),nf=(st,U,Et)=>U.has(st)||nv("Cannot "+Et);var c=(st,U,Et)=>(nf(st,U,"read from private field"),Et?Et.call(st):U.get(st)),w=(st,U,Et)=>U.has(st)?nv("Cannot add the same private member more than once"):U instanceof WeakSet?U.add(st):U.set(st,Et),b=(st,U,Et,C)=>(nf(st,U,"write to private field"),C?C.call(st,Et):U.set(st,Et),Et),y=(st,U,Et)=>(nf(st,U,"access private method"),Et);var Je=(st,U,Et,C)=>({set _(tc){b(st,U,tc,Et)},get _(){return c(st,U,C)}});var xi,Ud,of,oh,nr,rr,zs,Si,ce,Ed,or,B,me,Sa,Ca,Yd,Aa,rv,af,Ta,Wl,Xl,hf,zl,ar,hr,He,lr,kd,ov,Ce,av,hv,qd,lv,lf,ah,cr,dr,dn,cv,dv,uv,Dd,hh,Od,is,lh,cf,Yt,un,ch,qt,Pd,gv,Eo,We,Xt,Jt,ko,Ci,Mo,bs,Do,ur,Vs,ys,gr,dh,uh,gh,Gs,Oo,gn,Us,Fd,fn,fh,fr,ph,Po,$t,gt,Ai,pr,mh,vh,bh,yh,_h,wh,xh,Sh,Ch,Ah,Th,Eh,kh,pn,Ys,Ti,Mh,j,$d,df,fv,pv,Kd,mv,vv,bv,uf,yv,gf,ff,_v,Ee,Rn,wv,xv,pf,Sv,Vl,mf,Ei,ki,_s,Mi,Xe,Fo,ws,Dh,vf,mr,xs,de,Ro,vr,Zt,br,Io,jo,ue,Oh,yr,mn,Ph,_r,Oi,qs,No,Bo,ns,Lh,Rd,tt,bf,Fh,yf,_f,Cv,Av,wf,xf,Sf,Tv,Ev,kv,Mv,Cf,Gl,wr,xr,Kt,Id,Dv,Rh,Ho,vn,Af,Tf,Ih,jh,$s,Ov,Pv,Qd,Sr,Nh,Bh,Hh,Wh,Wo,bn,pt,Xo,zo,Xh,Ef,iv,yn,Fe,zh,Vh,Cr,Pi,Gh,Uh,Ar,Vo,Go,_n,Uo,Yh,Yo,Tr,qh,$h,Er,kr,wn,qo,Li,Lv,Fv,kf,Ks,Jd,Rv,Iv,Nd,xn,Fi,rs,Ea,Zd,Mr,Hd,Dr,$o,tu,Ko,eu,Ri,Qs,Qo,Jo,Js,Or,Ul,Ss,Kh,Mf,Sn,Cn,Pr,Fr,Zo,ta,Qh,Df,Ve,ro,jv,Nv,ea,Wd,Xd,sa,Rr,Mt,Ii,Ir,Jh,Zh,ia,ji,Cs,Ni,tl,Bi,el,jr,Nr,mt,su,Of,Bv,Hv,Wv,Xv,iu,nu,Pf,sl,il,nl,rl,ol,al,hl,Lf,ll,Br,Hr,Wr,zv,Ff,cl,dl,ul,gl,fl,As,Ge,pl,Ue,na,Nt,Vv,Gv,Uv,ru,Hi,ou,au,Yv,Rf,qv,ml,An,Ts,Ae,$v,hu,Kv,Qv,If,vl,ra,Zs,Wi,oa,aa,ti,rt,Xr,zr,bl,yl,ha,la,Tn,_l,zd,Vd,wl,jf,ca,Vr,zi,xl,Ye,Sl,Rt,Re,Yl,ql,Jv,Cl,Al,Es,Gr,da,zt,Tl,ua,El,kl,ks,ga,yt,Nf,Bf,Zv,oo,tb,In,fa,Ml,En,Ur,pa,os,Dl,Ol,Yr,Ms,Te,qe,Gd,ma,qr,Vt,va,ei,Pl,et,Hf,Wf,eb,sb,ib,Xf,$l,as,ka,nb,lu,Kl,rb,ob,ab,hb,$r,Kr,Ll,Fl,Rl,Qr,si,Gi,hs,Jr,Zr,Ui,to,eo,kn,N,lb,cb,db,ub,zf,gb,Vf,fb,pb,mb,vb,bb,ao,Gf,cu,du,Ma,Uf,uu,Yi,yb,Yf,_b,wb,qf,gu,Ql,te,ee,Mn,qi,Dn,ba,ii,Il,$i,ni,Ds,jl,ht,Jl,Zl,fu,$f,xb,Sb,Cb,Kf,pu,Ab,so,ya,ri,io,Ki,Qi,Ji,$e,On,_a,wa,fe,G,Pn,se,Tb,Qf,Jf,Zf,mu,oi,Bl,Gt,Ln,Hl,tp,no,ep,Eb;var Et=typeof document<"u"?document.currentScript:null;function C(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 tc(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 A(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?tc(Object(e),!0).forEach(function(s){C(a,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):tc(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 Ls(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class sp{constructor(){C(this,"browserShadowBlurConstant",1),C(this,"DPI",96),C(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),C(this,"perfLimitSizeTotal",2097152),C(this,"maxCacheSideLimit",4096),C(this,"minCacheSideLimit",256),C(this,"disableStyleCopyPaste",!1),C(this,"enableGLFiltering",!0),C(this,"textureSize",4096),C(this,"forceGLPutImageData",!1),C(this,"cachesBoundsOfCurve",!0),C(this,"fontPaths",{}),C(this,"NUM_FRACTION_DIGITS",4)}}const ot=new class extends sp{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=A(A({},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 sp,e=(a==null?void 0:a.reduce((s,i)=>(s[i]=t[i],s),{}))||t;this.configure(e)}},ai=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 Fs extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class vu extends Fs{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class kb{}class Mb extends kb{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(),ai("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Db={};let ip;const Rs=()=>ip||(ip={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Mb,dispose(){},copyPasteData:Db}),ho=()=>Rs().document,ec=()=>Rs().window,np=()=>{var a;return Math.max((a=ot.devicePixelRatio)!==null&&a!==void 0?a:ec().devicePixelRatio,1)},Da=new class{constructor(){C(this,"charWidthsCache",{}),C(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}=ot,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},bu="6.3.0";function jn(){}const tn=Math.PI/2,hi=2*Math.PI,yu=Math.PI/180,ve=Object.freeze([1,0,0,1,0,0]),_u=16,en=.4477152502,Q="center",ct="left",ke="top",wu="bottom",Dt="right",be="none",xu=/\r?\n/,rp="moving",sc="scaling",op="rotating",Su="rotate",ap="skewing",Oa="resizing",Ob="modifyPoly",Pb="modifyPath",ic="changed",nc="scale",ye="scaleX",Ie="scaleY",lo="skewX",co="skewY",Ot="fill",_e="stroke",rc="modified",uo="json",Cu="svg",H=new class{constructor(){this[uo]=new Map,this[Cu]=new Map}has(a){return this[uo].has(a)}getClass(a){const t=this[uo].get(a);if(!t)throw new Fs("No class registered for ".concat(a));return t}setClass(a,t){t?this[uo].set(t,a):(this[uo].set(a.type,a),this[uo].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[Cu].get(a)}setSVGClass(a,t){this[Cu].set(t??a.type.toLowerCase(),a)}},oc=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 Lb{constructor(){C(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 Nn=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},cs=a=>{if(a===0)return 1;switch(Math.abs(a)/tn){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ds=a=>{if(a===0)return 0;const t=a/tn,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class k{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 k(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new k(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new k(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new k(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new k(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new k(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new k(this.x/t.x,this.y/t.y)}scalarDivide(t){return new k(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 k(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 k(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new k(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 k(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Au;const s=ds(t),i=cs(t),n=this.subtract(e);return new k(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 k(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 Au=new k(0,0),ac=a=>!!a&&Array.isArray(a._objects);function hp(a){class t extends a{constructor(){super(...arguments),C(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])&&(Nn(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Nn(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 Nn(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 Nn(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Nn(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 k(i,n),u=d.add(new k(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 lp extends Lb{_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 Pa(a){return ec().requestAnimationFrame(a)}function cp(a){return ec().cancelAnimationFrame(a)}let Fb=0;const sn=()=>Fb++,Pt=()=>{const a=ho().createElement("canvas");if(!a||a.getContext===void 0)throw new Fs("Failed to create `canvas` element");return a},dp=()=>ho().createElement("img"),Tu=(a,t,e)=>a.toDataURL("image/".concat(t),e),kt=a=>a*yu,nn=a=>a/yu,up=a=>a.every((t,e)=>t===ve[e]),ne=(a,t,e)=>new k(a).transform(t,e),Me=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 k(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},Lt=(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]],hc=(a,t)=>a.reduceRight((e,s)=>s&&e?Lt(s,e,t):s||e,void 0)||ve.concat(),gp=a=>{let[t,e]=a;return Math.atan2(e,t)},Bn=a=>{const t=gp(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:nn(t),scaleX:s,scaleY:i,skewX:nn(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},go=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function fo(){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=kt(a),i=cs(s),n=ds(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const lc=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},fp=a=>Math.tan(kt(a)),Eu=a=>[1,0,fp(a),1,0,0],ku=a=>[1,fp(a),0,1,0,0],La=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=lc(s?-t:t,i?-e:e);return n&&(o=Lt(o,Eu(n),!0)),r&&(o=Lt(o,ku(r),!0)),o},pp=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=go(t,e);s&&(i=Lt(i,fo({angle:s})));const n=La(a);return up(n)||(i=Lt(i,n)),i},Fa=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 vu("loadImage"));const n=dp();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 Fs("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()})},po=function(a){let{signal:t,reviver:e=jn}=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=>H.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)})})},Ra=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&&H.has(o.type)?po([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)})})},Hn=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in a&&(t[e]=a[e]),t),{})},Mu=(a,t)=>Object.keys(a).reduce((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e),{}),mp={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"},Du=(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),vp=(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]},bp=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},cc=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),yp=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class ut{constructor(t){if(C(this,"isUnrecognised",!1),t)if(t instanceof ut)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 mp&&(t=mp[t]),t==="transparent"?[255,255,255,0]:ut.sourceFromHex(t)||ut.sourceFromRgb(t)||ut.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]=vp(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=vp(...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(cc(t)).concat(cc(e)).concat(cc(s)).concat(cc(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(yp(this.getSource())),this}toBlackWhite(t){const[e,,,s]=yp(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof ut||(t=new ut(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 ut.fromRgba(t)}static fromRgba(t){return new ut(ut.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,bp(e[4])]}}static fromHsl(t){return ut.fromHsla(t)}static fromHsla(t){return new ut(ut.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=(ut.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=Du(d,l,s+1/3),o=Du(d,l,s),h=Du(d,l,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),bp(e[4])]}static fromHex(t){return new ut(ut.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")?nn(s):e.includes("turn")?360*s:s}}const it=(a,t)=>parseFloat(Number(a).toFixed(t)),we=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_u;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=ot.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}},Ou=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==be?[n.slice(1,4),n.slice(5,8)]:n===be?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},Ia=a=>"matrix("+a.map(t=>it(t,ot.NUM_FRACTION_DIGITS)).join(" ")+")",ja=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 ut(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,'" '):"")},Ze=a=>!!a&&a.toLive!==void 0,_p=a=>!!a&&typeof a.toObject=="function",wp=a=>!!a&&a.offsetX!==void 0&&"source"in a,xp=a=>!!a&&typeof a._renderText=="function",Wn=a=>!!a&&"multiSelectionStacking"in a;function Sp(a){const t=a&&us(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 us=a=>a.ownerDocument||null,Cp=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null};function Na(a,t){const e=a.style;e&&(typeof t=="string"?a.style.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const Ap=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))},Pu=(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 Tp(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=be,a}class Ep{constructor(t){C(this,"_originalCanvasStyle",void 0),C(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&&ho().getElementById(t)||Pt();var s;if(e.hasAttribute("data-fabric"))throw new Fs("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;Ap(s,i,t,e)}setCSSDimensions(t){Pu(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&us(t),i={left:0,top:0};if(!s)return i;const n=((e=Cp(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=Sp(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(){Rs().dispose(this.lower.el),delete this.lower}}const Rb={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...ve]};class Ba extends hp(lp){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 Ba.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 Ep(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&&(ai("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?np():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=A({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=ne(t,Me(i));i[0]=e,i[3]=e;const r=ne(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new k(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 k(-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=Pa(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Me(this.viewportTransform),i=ne({x:0,y:0},s),n=ne({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new k(o.x,r.y),bl:new k(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(cp(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=Ze(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 k(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new k(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new k(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 k(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new k(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return ne(this.getCenterPoint(),Me(this.viewportTransform))}_centerObject(t,e){t.setXY(e,Q,Q),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 A(A(A({version:bu},Hn(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 Ze(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),Ze(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,`)" >
1
+ (function(st,U){typeof exports=="object"&&typeof module<"u"?U(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],U):(st=typeof globalThis<"u"?globalThis:st||self,U(st["pdf-canvas"]={},st.Vue))})(this,function(st,U){"use strict";var CS=Object.defineProperty;var nv=st=>{throw TypeError(st)};var AS=(st,U,Et)=>U in st?CS(st,U,{enumerable:!0,configurable:!0,writable:!0,value:Et}):st[U]=Et;var K=(st,U,Et)=>AS(st,typeof U!="symbol"?U+"":U,Et),sf=(st,U,Et)=>U.has(st)||nv("Cannot "+Et);var c=(st,U,Et)=>(sf(st,U,"read from private field"),Et?Et.call(st):U.get(st)),w=(st,U,Et)=>U.has(st)?nv("Cannot add the same private member more than once"):U instanceof WeakSet?U.add(st):U.set(st,Et),b=(st,U,Et,C)=>(sf(st,U,"write to private field"),C?C.call(st,Et):U.set(st,Et),Et),y=(st,U,Et)=>(sf(st,U,"access private method"),Et);var Je=(st,U,Et,C)=>({set _(tc){b(st,U,tc,Et)},get _(){return c(st,U,C)}});var Si,Gd,rf,oh,nr,rr,zs,Ci,ce,Td,or,B,me,Sa,Ca,Ud,Aa,rv,of,Ta,Wl,Xl,af,zl,ar,hr,We,lr,Ed,ov,Ce,av,hv,Yd,lv,hf,ah,cr,dr,dn,cv,dv,uv,Md,hh,Dd,is,lh,lf,qt,un,ch,$t,Od,gv,Eo,Xe,zt,Jt,ko,Ai,Mo,bs,Do,ur,Vs,ys,gr,dh,uh,gh,Gs,Oo,gn,Us,Ld,fn,fh,fr,ph,Po,Kt,gt,Ti,pr,mh,vh,bh,yh,_h,wh,xh,Sh,Ch,Ah,Th,Eh,kh,pn,Ys,Ei,Mh,j,qd,cf,fv,pv,$d,mv,vv,bv,df,yv,uf,gf,_v,Ee,Rn,wv,xv,ff,Sv,Vl,pf,ki,Mi,_s,Di,ze,Fo,ws,Dh,mf,mr,xs,de,Ro,vr,Zt,br,Io,jo,ue,Oh,yr,mn,Ph,_r,Pi,qs,No,Bo,ns,Lh,Fd,tt,vf,Fh,bf,yf,Cv,Av,_f,wf,xf,Tv,Ev,kv,Mv,Sf,Gl,wr,xr,Qt,Rd,Dv,Rh,Ho,vn,Cf,Af,Ih,jh,$s,Ov,Pv,Kd,Sr,Nh,Bh,Hh,Wh,Wo,bn,pt,Xo,zo,Xh,Tf,iv,yn,Fe,zh,Vh,Cr,Li,Gh,Uh,Ar,Vo,Go,_n,Uo,Yh,Yo,Tr,qh,$h,Er,kr,wn,qo,Fi,Lv,Fv,Ef,Ks,Qd,Rv,Iv,jd,xn,Ri,rs,Ea,Jd,Mr,Bd,Dr,$o,Zd,Ko,tu,Ii,Qs,Qo,Jo,Js,Or,Ul,Ss,Kh,kf,Sn,Cn,Pr,Fr,Zo,ta,Qh,Mf,Ge,ro,jv,Nv,ea,Hd,Wd,sa,Rr,Mt,ji,Ir,Jh,Zh,ia,Ni,Cs,Bi,tl,Hi,el,jr,Nr,mt,eu,Df,Bv,Hv,Wv,Xv,su,iu,Of,sl,il,nl,rl,ol,al,hl,Pf,ll,Br,Hr,Wr,zv,Lf,cl,dl,ul,gl,fl,As,Ue,pl,Ye,na,Bt,Vv,Gv,Uv,nu,Wi,ru,ou,Yv,Ff,qv,ml,An,Ts,Ae,$v,au,Kv,Qv,Rf,vl,ra,Zs,Xi,oa,aa,ti,rt,Xr,zr,bl,yl,ha,la,Tn,_l,Xd,zd,wl,If,ca,Vr,Vi,xl,qe,Sl,Rt,Re,Yl,ql,Jv,Cl,Al,Es,Gr,da,Vt,Tl,ua,El,kl,ks,ga,yt,jf,Nf,Zv,oo,tb,In,fa,Ml,En,Ur,pa,os,Dl,Ol,Yr,Ms,Te,$e,Vd,ma,qr,Gt,va,ei,Pl,et,Bf,Hf,eb,sb,ib,Wf,$l,as,ka,nb,hu,Kl,rb,ob,ab,hb,$r,Kr,Ll,Fl,Rl,Qr,si,Ui,hs,Jr,Zr,Yi,to,eo,kn,N,lb,cb,db,ub,Xf,gb,zf,fb,pb,mb,vb,bb,ao,Vf,lu,cu,Ma,Gf,du,qi,yb,Uf,_b,wb,Yf,uu,Ql,te,ee,Mn,$i,Dn,ba,ii,Il,Ki,ni,Ds,jl,ht,Jl,Zl,gu,qf,xb,Sb,Cb,$f,fu,Ab,so,ya,ri,io,Qi,Ji,Zi,Ke,On,_a,wa,fe,G,Pn,se,Tb,Kf,Qf,Jf,pu,oi,Bl,Ut,Ln,Hl,Zf,no,tp,Eb;var Et=typeof document<"u"?document.currentScript:null;function C(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 tc(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 A(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?tc(Object(e),!0).forEach(function(s){C(a,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):tc(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 Ls(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class ep{constructor(){C(this,"browserShadowBlurConstant",1),C(this,"DPI",96),C(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),C(this,"perfLimitSizeTotal",2097152),C(this,"maxCacheSideLimit",4096),C(this,"minCacheSideLimit",256),C(this,"disableStyleCopyPaste",!1),C(this,"enableGLFiltering",!0),C(this,"textureSize",4096),C(this,"forceGLPutImageData",!1),C(this,"cachesBoundsOfCurve",!0),C(this,"fontPaths",{}),C(this,"NUM_FRACTION_DIGITS",4)}}const ot=new class extends ep{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=A(A({},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 ep,e=(a==null?void 0:a.reduce((s,i)=>(s[i]=t[i],s),{}))||t;this.configure(e)}},hi=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 Fs extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class mu extends Fs{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class kb{}class Mb extends kb{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(),hi("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Db={};let sp;const Rs=()=>sp||(sp={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Mb,dispose(){},copyPasteData:Db}),ho=()=>Rs().document,ec=()=>Rs().window,ip=()=>{var a;return Math.max((a=ot.devicePixelRatio)!==null&&a!==void 0?a:ec().devicePixelRatio,1)},Da=new class{constructor(){C(this,"charWidthsCache",{}),C(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}=ot,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},vu="6.3.0";function jn(){}const tn=Math.PI/2,li=2*Math.PI,bu=Math.PI/180,ve=Object.freeze([1,0,0,1,0,0]),yu=16,en=.4477152502,Q="center",ct="left",ke="top",_u="bottom",Dt="right",be="none",wu=/\r?\n/,np="moving",sc="scaling",rp="rotating",xu="rotate",op="skewing",Oa="resizing",Ob="modifyPoly",Pb="modifyPath",ic="changed",nc="scale",ye="scaleX",je="scaleY",lo="skewX",co="skewY",Ot="fill",_e="stroke",rc="modified",uo="json",Su="svg",H=new class{constructor(){this[uo]=new Map,this[Su]=new Map}has(a){return this[uo].has(a)}getClass(a){const t=this[uo].get(a);if(!t)throw new Fs("No class registered for ".concat(a));return t}setClass(a,t){t?this[uo].set(t,a):(this[uo].set(a.type,a),this[uo].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[Su].get(a)}setSVGClass(a,t){this[Su].set(t??a.type.toLowerCase(),a)}},oc=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 Lb{constructor(){C(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 Nn=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},cs=a=>{if(a===0)return 1;switch(Math.abs(a)/tn){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ds=a=>{if(a===0)return 0;const t=a/tn,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class k{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 k(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new k(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new k(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new k(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new k(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new k(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new k(this.x/t.x,this.y/t.y)}scalarDivide(t){return new k(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 k(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 k(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new k(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 k(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Cu;const s=ds(t),i=cs(t),n=this.subtract(e);return new k(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 k(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 Cu=new k(0,0),ac=a=>!!a&&Array.isArray(a._objects);function ap(a){class t extends a{constructor(){super(...arguments),C(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])&&(Nn(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Nn(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 Nn(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 Nn(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Nn(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 k(i,n),u=d.add(new k(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 hp extends Lb{_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 Pa(a){return ec().requestAnimationFrame(a)}function lp(a){return ec().cancelAnimationFrame(a)}let Fb=0;const sn=()=>Fb++,Pt=()=>{const a=ho().createElement("canvas");if(!a||a.getContext===void 0)throw new Fs("Failed to create `canvas` element");return a},cp=()=>ho().createElement("img"),Au=(a,t,e)=>a.toDataURL("image/".concat(t),e),kt=a=>a*bu,nn=a=>a/bu,dp=a=>a.every((t,e)=>t===ve[e]),ne=(a,t,e)=>new k(a).transform(t,e),Me=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 k(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},Lt=(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]],hc=(a,t)=>a.reduceRight((e,s)=>s&&e?Lt(s,e,t):s||e,void 0)||ve.concat(),up=a=>{let[t,e]=a;return Math.atan2(e,t)},Bn=a=>{const t=up(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:nn(t),scaleX:s,scaleY:i,skewX:nn(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},go=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function fo(){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=kt(a),i=cs(s),n=ds(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const lc=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},gp=a=>Math.tan(kt(a)),Tu=a=>[1,0,gp(a),1,0,0],Eu=a=>[1,gp(a),0,1,0,0],La=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=lc(s?-t:t,i?-e:e);return n&&(o=Lt(o,Tu(n),!0)),r&&(o=Lt(o,Eu(r),!0)),o},fp=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=go(t,e);s&&(i=Lt(i,fo({angle:s})));const n=La(a);return dp(n)||(i=Lt(i,n)),i},Fa=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 mu("loadImage"));const n=cp();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 Fs("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()})},po=function(a){let{signal:t,reviver:e=jn}=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=>H.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)})})},Ra=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&&H.has(o.type)?po([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)})})},Hn=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in a&&(t[e]=a[e]),t),{})},ku=(a,t)=>Object.keys(a).reduce((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e),{}),pp={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"},Mu=(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),mp=(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]},vp=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},cc=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),bp=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class ut{constructor(t){if(C(this,"isUnrecognised",!1),t)if(t instanceof ut)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 pp&&(t=pp[t]),t==="transparent"?[255,255,255,0]:ut.sourceFromHex(t)||ut.sourceFromRgb(t)||ut.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]=mp(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=mp(...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(cc(t)).concat(cc(e)).concat(cc(s)).concat(cc(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(bp(this.getSource())),this}toBlackWhite(t){const[e,,,s]=bp(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof ut||(t=new ut(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 ut.fromRgba(t)}static fromRgba(t){return new ut(ut.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,vp(e[4])]}}static fromHsl(t){return ut.fromHsla(t)}static fromHsla(t){return new ut(ut.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=(ut.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=Mu(d,l,s+1/3),o=Mu(d,l,s),h=Mu(d,l,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),vp(e[4])]}static fromHex(t){return new ut(ut.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")?nn(s):e.includes("turn")?360*s:s}}const it=(a,t)=>parseFloat(Number(a).toFixed(t)),we=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:yu;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=ot.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}},Du=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==be?[n.slice(1,4),n.slice(5,8)]:n===be?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},Ia=a=>"matrix("+a.map(t=>it(t,ot.NUM_FRACTION_DIGITS)).join(" ")+")",ja=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 ut(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,'" '):"")},Ze=a=>!!a&&a.toLive!==void 0,yp=a=>!!a&&typeof a.toObject=="function",_p=a=>!!a&&a.offsetX!==void 0&&"source"in a,wp=a=>!!a&&typeof a._renderText=="function",Wn=a=>!!a&&"multiSelectionStacking"in a;function xp(a){const t=a&&us(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 us=a=>a.ownerDocument||null,Sp=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null};function Na(a,t){const e=a.style;e&&(typeof t=="string"?a.style.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const Cp=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))},Ou=(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 Ap(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=be,a}class Tp{constructor(t){C(this,"_originalCanvasStyle",void 0),C(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&&ho().getElementById(t)||Pt();var s;if(e.hasAttribute("data-fabric"))throw new Fs("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;Cp(s,i,t,e)}setCSSDimensions(t){Ou(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&us(t),i={left:0,top:0};if(!s)return i;const n=((e=Sp(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=xp(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(){Rs().dispose(this.lower.el),delete this.lower}}const Rb={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...ve]};class Ba extends ap(hp){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 Ba.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 Tp(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&&(hi("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?ip():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=A({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=ne(t,Me(i));i[0]=e,i[3]=e;const r=ne(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new k(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 k(-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=Pa(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Me(this.viewportTransform),i=ne({x:0,y:0},s),n=ne({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new k(o.x,r.y),bl:new k(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(lp(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=Ze(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 k(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new k(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new k(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 k(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new k(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return ne(this.getCenterPoint(),Me(this.viewportTransform))}_centerObject(t,e){t.setXY(e,Q,Q),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 A(A(A({version:vu},Hn(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 Ze(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),Ze(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
4
  `)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
5
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
6
  `,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
7
7
  `)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=ot.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(it(-h[4]/h[0],n)," ").concat(it(-h[5]/h[3],n)," ").concat(it(this.width/h[0],n)," ").concat(it(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 ",bu,`</desc>
8
+ `,"<desc>Created with Fabric.js ",vu,`</desc>
9
9
  `,`<defs>
10
10
  `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
11
11
  `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(sn()),'<clipPath id="'.concat(e.clipPathId,`" >
12
12
  `).concat(e.toClipPathSVG(t.reviver),`</clipPath>
13
- `)):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this["".concat(t,"Color")];if(Ze(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?Ia(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=ot.fontPaths;this._objects.forEach(function n(r){t.push(r),ac(r)&&r._objects.forEach(n)}),t.forEach(n=>{if(!xp(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 {
13
+ `)):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this["".concat(t,"Color")];if(Ze(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?Ia(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=ot.fontPaths;this._objects.forEach(function n(r){t.push(r),ac(r)&&r._objects.forEach(n)}),t.forEach(n=>{if(!wp(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
14
  font-family: '`.concat(n,`';
15
15
  src: url('`).concat(s[n],`');
16
16
  }
17
17
  `)).join("");return i?` <style type="text/css"><![CDATA[
18
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(Ze(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?Ia(Me(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"||!wp(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!wp(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
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(Ze(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?Ia(Me(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"||!_p(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!_p(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
20
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 Fs("`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([po(n,{reviver:e,signal:s}),Ra({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=Pt();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 Tu(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=Pt(),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}),oc.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," }>")}}C(Ba,"ownDefaults",Rb);const Ib=["touchstart","touchmove","touchend"],kp=a=>{const t=Sp(a.target),e=function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s}(a);return new k(e.clientX+t.left,e.clientY+t.top)},dc=a=>Ib.includes(a.type)||a.pointerType==="touch",Lu=a=>{a.preventDefault(),a.stopPropagation()},Is=a=>{if(a.length===0)return{left:0,top:0,width:0,height:0};const{min:t,max:e}=a.reduce((i,n)=>{let{min:r,max:o}=i;return{min:r.min(n),max:o.max(n)}},{min:new k(a[0]),max:new k(a[0])}),s=e.subtract(t);return{left:t.x,top:t.y,width:s.x,height:s.y}},jb=["translateX","translateY","scaleX","scaleY"],Mp=(a,t)=>mo(a,Lt(t,a.calcOwnMatrix())),mo=(a,t)=>{const e=Bn(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=xt(e,jb),h=new k(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,Q,Q)},Dp=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},Fu=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}),uc=(a,t,e)=>{const s=a/2,i=t/2,n=[new k(-s,-i),new k(s,-i),new k(-s,i),new k(s,i)].map(o=>o.transform(e)),r=Is(n);return new k(r.width,r.height)},Ha=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ve;return Lt(Me(arguments.length>1&&arguments[1]!==void 0?arguments[1]:ve),a)},Xn=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ve,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ve;return a.transform(Ha(t,e))},Op=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ve,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ve;return a.transform(Ha(t,e),!0)},Ru=(a,t,e)=>{const s=Ha(t,e);return mo(a,Lt(s,a.calcOwnMatrix())),s},Pp=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),A(A({},t),{},{target:s})),s.fire(a,t)},Nb={left:-.5,top:-.5,center:0,bottom:.5,right:.5},It=a=>typeof a=="string"?Nb[a]:a-.5,gc="not-allowed";function Lp(a){return It(a.originX)===It(Q)&&It(a.originY)===It(Q)}function Fp(a){return .5-It(a)}const gs=(a,t)=>a[t],Rp=(a,t,e,s)=>({e:a,transform:t,pointer:new k(e,s)});function Ip(a,t){const e=a.getTotalAngle()+nn(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Iu(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(_,Q,Q,p,m):new k(g.left,g.top);return(g.angle?f.rotate(-kt(g.angle),_):f).subtract(v)}(r,new k(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 Bb=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!gs(i,"lockMovementX")&&i.left!==o,d=!gs(i,"lockMovementY")&&i.top!==h;return l&&i.set(ct,o),d&&i.set(ke,h),(l||d)&&Pp(rp,Rp(a,t,e,s)),l||d};class jp{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):be,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=ja(Ot,this.fill);return[ja(_e,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(Ia(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(sn()),_='<clipPath id="'.concat(h.clipPathId,`" >
21
+ `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new Fs("`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([po(n,{reviver:e,signal:s}),Ra({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=Pt();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 Au(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=Pt(),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}),oc.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," }>")}}C(Ba,"ownDefaults",Rb);const Ib=["touchstart","touchmove","touchend"],Ep=a=>{const t=xp(a.target),e=function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s}(a);return new k(e.clientX+t.left,e.clientY+t.top)},dc=a=>Ib.includes(a.type)||a.pointerType==="touch",Pu=a=>{a.preventDefault(),a.stopPropagation()},Is=a=>{if(a.length===0)return{left:0,top:0,width:0,height:0};const{min:t,max:e}=a.reduce((i,n)=>{let{min:r,max:o}=i;return{min:r.min(n),max:o.max(n)}},{min:new k(a[0]),max:new k(a[0])}),s=e.subtract(t);return{left:t.x,top:t.y,width:s.x,height:s.y}},jb=["translateX","translateY","scaleX","scaleY"],kp=(a,t)=>mo(a,Lt(t,a.calcOwnMatrix())),mo=(a,t)=>{const e=Bn(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=xt(e,jb),h=new k(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,Q,Q)},Mp=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},Lu=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}),uc=(a,t,e)=>{const s=a/2,i=t/2,n=[new k(-s,-i),new k(s,-i),new k(-s,i),new k(s,i)].map(o=>o.transform(e)),r=Is(n);return new k(r.width,r.height)},Ha=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ve;return Lt(Me(arguments.length>1&&arguments[1]!==void 0?arguments[1]:ve),a)},Xn=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ve,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ve;return a.transform(Ha(t,e))},Dp=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ve,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ve;return a.transform(Ha(t,e),!0)},Fu=(a,t,e)=>{const s=Ha(t,e);return mo(a,Lt(s,a.calcOwnMatrix())),s},Op=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),A(A({},t),{},{target:s})),s.fire(a,t)},Nb={left:-.5,top:-.5,center:0,bottom:.5,right:.5},jt=a=>typeof a=="string"?Nb[a]:a-.5,gc="not-allowed";function Pp(a){return jt(a.originX)===jt(Q)&&jt(a.originY)===jt(Q)}function Lp(a){return .5-jt(a)}const gs=(a,t)=>a[t],Fp=(a,t,e,s)=>({e:a,transform:t,pointer:new k(e,s)});function Rp(a,t){const e=a.getTotalAngle()+nn(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Ru(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(_,Q,Q,p,m):new k(g.left,g.top);return(g.angle?f.rotate(-kt(g.angle),_):f).subtract(v)}(r,new k(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 Bb=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!gs(i,"lockMovementX")&&i.left!==o,d=!gs(i,"lockMovementY")&&i.top!==h;return l&&i.set(ct,o),d&&i.set(ke,h),(l||d)&&Op(np,Fp(a,t,e,s)),l||d};class Ip{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):be,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=ja(Ot,this.fill);return[ja(_e,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(Ia(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(sn()),_='<clipPath id="'.concat(h.clipPathId,`" >
22
22
  `).concat(h.toClipPathSVG(s),`</clipPath>
23
23
  `)),d&&p.push("<g ",o,this.getSvgCommons(),` >
24
24
  `),p.push("<g ",this.getSvgTransform(!1),d?"":o+this.getSvgCommons(),` >
25
25
  `);const v=[r,l,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[m]=v,Ze(g)&&p.push(g.toSVG(this)),Ze(u)&&p.push(u.toSVG(this)),f&&p.push(f.toSVG(this)),h&&p.push(_),p.push(t.join("")),p.push(`</g>
26
26
  `),d&&p.push(`</g>
27
- `),s?s(p.join("")):p.join("")}addPaintOrder(){return this.paintFirst!==Ot?' paint-order="'.concat(this.paintFirst,'" '):""}}const ju=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/hi*Math.asin(1):e/hi*Math.asin(t/a),{a,c:t,p:e,s}),Np=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*hi/e),Bp=(a,t,e,s)=>-e*Math.cos(a/s*tn)+e+t,Nu=(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,Hp=(a,t,e,s)=>e-Nu(s-a,0,e,s)+t;var Hb=Object.freeze({__proto__:null,defaultEasing:Bp,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:Hp,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}=ju(i,e,n,1.70158);return-Np(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*Hp(2*a,0,e,s)+t:.5*Nu(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}=ju(i,e,n,1.70158);return a<1?-.5*Np(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*hi/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*tn)+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:Nu,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}=ju(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*hi/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*tn)+t});const Wb=()=>!1;class Bu{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Bp,onStart:o=jn,onChange:h=jn,onComplete:l=jn,abort:d=Wb,target:u}=t;C(this,"_state","pending"),C(this,"durationProgress",0),C(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(()=>Pa(t),this.delay):Pa(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),Pa(this.tick)))}register(){oc.push(this)}unregister(){oc.remove(this)}abort(){this._state="aborted",this.unregister()}}const Xb=["startValue","endValue"];class zb extends Bu{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(A(A({},xt(t,Xb)),{},{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 Vb=["startValue","endValue"];class Gb extends Bu{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(A(A({},xt(t,Vb)),{},{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 zn=(a,t,e)=>Math.max(a,Math.min(t,e)),Ub=["startValue","endValue","easing","onChange","onComplete","abort"],Yb=(a,t,e,s)=>t+e*(1-Math.cos(a/s*tn)),Hu=a=>a&&((t,e,s)=>a(new ut(t).toRgba(),e,s));class qb extends Bu{constructor(t){let{startValue:e,endValue:s,easing:i=Yb,onChange:n,onComplete:r,abort:o}=t,h=xt(t,Ub);const l=new ut(e).getSource(),d=new ut(s).getSource();super(A(A({},h),{},{startValue:l,byValue:d.map((u,g)=>u-l[g]),easing:i,onChange:Hu(n),onComplete:Hu(r),abort:Hu(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),zn(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 Wu(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new Gb(a):new zb(a);return t.start(),t}function Wp(a){const t=new qb(a);return t.start(),t}const $b=new k(1,0),Xp=new k,Xu=(a,t)=>a.rotate(t),fc=(a,t)=>new k(t).subtract(a),pc=a=>a.distanceFrom(Xp),mc=(a,t)=>Math.atan2(vo(a,t),Vp(a,t)),zp=a=>mc($b,a),vc=a=>a.eq(Xp)?a:a.scalarDivide(pc(a)),zu=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return vc(new k(-a.y,a.x).scalarMultiply(t?1:-1))},vo=(a,t)=>a.x*t.y-a.y*t.x,Vp=(a,t)=>a.x*t.x+a.y*t.y,Vu=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=vo(t,e),i=vo(t,a),n=vo(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)};class St{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=fc(e,s),r=fc(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 k(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 St("Intersection").append(new k(t.x+_*o,t.y+_*h)):new St}if(f===0||p===0){const _=n||r||St.isPointContained(t,s,i)||St.isPointContained(e,s,i)||St.isPointContained(s,t,e)||St.isPointContained(i,t,e);return new St(_?"Coincident":void 0)}return new St("Parallel")}static intersectSegmentLine(t,e,s,i){return St.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return St.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 St,r=s.length;for(let o,h,l,d=0;d<r;d++){if(o=s[d],h=s[(d+1)%r],l=St.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 St.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new St,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=St.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 St("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 k(n.x,i.y),o=new k(i.x,n.y);return St.intersectPolygonPolygon(t,[i,r,n,o])}}class Kb extends lp{_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=A({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 k(r*e.scaleX,o*e.scaleY):uc(r,o,La(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=It(i)-It(e),l=It(n)-It(s);if(h||l){const d=this._getTransformedDimensions();r+=h*d.x,o+=l*d.y}return new k(r,o)}translateToCenterPoint(t,e,s){const i=this.translateToGivenOrigin(t,e,s,Q,Q);return this.angle?i.rotate(kt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,Q,Q,e,s);return this.angle?i.rotate(kt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?ne(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new k(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(),ct,ke)}}class Qb extends Kb{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?ne(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=ne(t,Me(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new k(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=>ne(o,r))}return n}intersectsWithRect(t,e){return St.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=St.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 St.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 Is(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(ye,t),this._set(Ie,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?nn(gp(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||ve.concat()}calcACoords(){const t=fo({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=go(e,s),n=Lt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:ne({x:-o,y:-h},n),tr:ne({x:o,y:-h},n),bl:ne({x:-o,y:h},n),br:ne({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,It(this.originX),It(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=Lt(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=pp(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new k(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}}class Gu extends Qb{isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||this.canvas===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e instanceof Gu?e.parent:void 0,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}}class Gp extends Gu{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=A(A({},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?Wp(d):Wu(d)}}function bc(a){return new RegExp("^("+a.join("|")+")\\b","i")}var Up,Yp;C(Gp,"colorProperties",[Ot,_e,"backgroundColor"]);const js=String.raw(Up||(Up=Ls(["(?:[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?)"],["(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)"]))),Uu="http://www.w3.org/2000/svg";String.raw(Yp||(Yp=Ls(["(?:s+,?s*|,s*|$)"],["(?:\\s+,?\\s*|,\\s*|$)"])));const Jb=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+js+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+js+"))?\\s+(.*)"),Zb={cx:ct,x:ct,r:"radius",cy:ke,y:ke,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"},Yu="font-size",qu="clip-path",ty=bc(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),ey=bc(["symbol","image","marker","pattern","view","svg"]),qp=bc(["symbol","g","a","svg","clipPath","defs"]),$p=new RegExp("^\\s*("+js+"+)\\s*,?\\s*("+js+"+)\\s*,?\\s*("+js+"+)\\s*,?\\s*("+js+"+)\\s*$"),Kp="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Qp=new RegExp("(?:\\s|^)"+Kp+Kp+"("+js+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class li{constructor(t){const e=typeof t=="string"?li.parseShadow(t):t;Object.assign(this,li.ownDefaults,e),this.id=sn()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Qp.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(Qp,"")||"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=Xu(new k(this.offsetX,this.offsetY),kt(-t.angle)),s=new ut(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*it((Math.abs(e.x)+this.blur)/t.width,ot.NUM_FRACTION_DIGITS)+20,n=100*it((Math.abs(e.y)+this.blur)/t.height,ot.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,`%" >
27
+ `),s?s(p.join("")):p.join("")}addPaintOrder(){return this.paintFirst!==Ot?' paint-order="'.concat(this.paintFirst,'" '):""}}const Iu=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/li*Math.asin(1):e/li*Math.asin(t/a),{a,c:t,p:e,s}),jp=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*li/e),Np=(a,t,e,s)=>-e*Math.cos(a/s*tn)+e+t,ju=(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,Bp=(a,t,e,s)=>e-ju(s-a,0,e,s)+t;var Hb=Object.freeze({__proto__:null,defaultEasing:Np,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:Bp,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}=Iu(i,e,n,1.70158);return-jp(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*Bp(2*a,0,e,s)+t:.5*ju(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}=Iu(i,e,n,1.70158);return a<1?-.5*jp(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*li/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*tn)+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:ju,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}=Iu(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*li/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*tn)+t});const Wb=()=>!1;class Nu{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Np,onStart:o=jn,onChange:h=jn,onComplete:l=jn,abort:d=Wb,target:u}=t;C(this,"_state","pending"),C(this,"durationProgress",0),C(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(()=>Pa(t),this.delay):Pa(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),Pa(this.tick)))}register(){oc.push(this)}unregister(){oc.remove(this)}abort(){this._state="aborted",this.unregister()}}const Xb=["startValue","endValue"];class zb extends Nu{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(A(A({},xt(t,Xb)),{},{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 Vb=["startValue","endValue"];class Gb extends Nu{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(A(A({},xt(t,Vb)),{},{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 zn=(a,t,e)=>Math.max(a,Math.min(t,e)),Ub=["startValue","endValue","easing","onChange","onComplete","abort"],Yb=(a,t,e,s)=>t+e*(1-Math.cos(a/s*tn)),Bu=a=>a&&((t,e,s)=>a(new ut(t).toRgba(),e,s));class qb extends Nu{constructor(t){let{startValue:e,endValue:s,easing:i=Yb,onChange:n,onComplete:r,abort:o}=t,h=xt(t,Ub);const l=new ut(e).getSource(),d=new ut(s).getSource();super(A(A({},h),{},{startValue:l,byValue:d.map((u,g)=>u-l[g]),easing:i,onChange:Bu(n),onComplete:Bu(r),abort:Bu(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),zn(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 Hu(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new Gb(a):new zb(a);return t.start(),t}function Hp(a){const t=new qb(a);return t.start(),t}const $b=new k(1,0),Wp=new k,Wu=(a,t)=>a.rotate(t),fc=(a,t)=>new k(t).subtract(a),pc=a=>a.distanceFrom(Wp),mc=(a,t)=>Math.atan2(vo(a,t),zp(a,t)),Xp=a=>mc($b,a),vc=a=>a.eq(Wp)?a:a.scalarDivide(pc(a)),Xu=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return vc(new k(-a.y,a.x).scalarMultiply(t?1:-1))},vo=(a,t)=>a.x*t.y-a.y*t.x,zp=(a,t)=>a.x*t.x+a.y*t.y,zu=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=vo(t,e),i=vo(t,a),n=vo(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)};class St{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=fc(e,s),r=fc(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 k(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 St("Intersection").append(new k(t.x+_*o,t.y+_*h)):new St}if(f===0||p===0){const _=n||r||St.isPointContained(t,s,i)||St.isPointContained(e,s,i)||St.isPointContained(s,t,e)||St.isPointContained(i,t,e);return new St(_?"Coincident":void 0)}return new St("Parallel")}static intersectSegmentLine(t,e,s,i){return St.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return St.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 St,r=s.length;for(let o,h,l,d=0;d<r;d++){if(o=s[d],h=s[(d+1)%r],l=St.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 St.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new St,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=St.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 St("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 k(n.x,i.y),o=new k(i.x,n.y);return St.intersectPolygonPolygon(t,[i,r,n,o])}}class Kb extends hp{_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=A({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 k(r*e.scaleX,o*e.scaleY):uc(r,o,La(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=jt(i)-jt(e),l=jt(n)-jt(s);if(h||l){const d=this._getTransformedDimensions();r+=h*d.x,o+=l*d.y}return new k(r,o)}translateToCenterPoint(t,e,s){const i=this.translateToGivenOrigin(t,e,s,Q,Q);return this.angle?i.rotate(kt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,Q,Q,e,s);return this.angle?i.rotate(kt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?ne(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new k(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(),ct,ke)}}class Qb extends Kb{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?ne(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=ne(t,Me(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new k(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=>ne(o,r))}return n}intersectsWithRect(t,e){return St.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=St.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 St.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 Is(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(ye,t),this._set(je,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?nn(up(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||ve.concat()}calcACoords(){const t=fo({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=go(e,s),n=Lt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:ne({x:-o,y:-h},n),tr:ne({x:o,y:-h},n),bl:ne({x:-o,y:h},n),br:ne({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,jt(this.originX),jt(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=Lt(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=fp(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new k(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}}class Vu extends Qb{isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||this.canvas===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e instanceof Vu?e.parent:void 0,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}}class Vp extends Vu{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=A(A({},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?Hp(d):Hu(d)}}function bc(a){return new RegExp("^("+a.join("|")+")\\b","i")}var Gp,Up;C(Vp,"colorProperties",[Ot,_e,"backgroundColor"]);const js=String.raw(Gp||(Gp=Ls(["(?:[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?)"],["(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)"]))),Gu="http://www.w3.org/2000/svg";String.raw(Up||(Up=Ls(["(?:s+,?s*|,s*|$)"],["(?:\\s+,?\\s*|,\\s*|$)"])));const Jb=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+js+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+js+"))?\\s+(.*)"),Zb={cx:ct,x:ct,r:"radius",cy:ke,y:ke,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"},Uu="font-size",Yu="clip-path",ty=bc(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),ey=bc(["symbol","image","marker","pattern","view","svg"]),Yp=bc(["symbol","g","a","svg","clipPath","defs"]),qp=new RegExp("^\\s*("+js+"+)\\s*,?\\s*("+js+"+)\\s*,?\\s*("+js+"+)\\s*,?\\s*("+js+"+)\\s*$"),$p="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Kp=new RegExp("(?:\\s|^)"+$p+$p+"("+js+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class ci{constructor(t){const e=typeof t=="string"?ci.parseShadow(t):t;Object.assign(this,ci.ownDefaults,e),this.id=sn()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Kp.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(Kp,"")||"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=Wu(new k(this.offsetX,this.offsetY),kt(-t.angle)),s=new ut(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*it((Math.abs(e.x)+this.blur)/t.width,ot.NUM_FRACTION_DIGITS)+20,n=100*it((Math.abs(e.y)+this.blur)/t.height,ot.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
28
  <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(it(this.blur?this.blur/2:0,ot.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
29
29
  <feOffset dx="`).concat(it(e.x,ot.NUM_FRACTION_DIGITS),'" dy="').concat(it(e.y,ot.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
30
30
  <feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
@@ -34,44 +34,44 @@ Resulting to default behavior: removing object from previous canvas and adding t
34
34
  <feMergeNode in="SourceGraphic"></feMergeNode>
35
35
  </feMerge>
36
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=li.ownDefaults;return this.includeDefaultValues?t:Mu(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}C(li,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),C(li,"type","shadow"),H.setClass(li,"shadow");const sy=[ke,ct,ye,Ie,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",lo,co],ci=[Ot,_e,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],iy={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:ct,originY:ke,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:Ot,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},ny=["type"],ry=["extraParam"];let Vn=class rf extends Gp{static getDefaults(){return rf.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){ai("warn","Setting type has no effect",t)}constructor(t){super(),C(this,"_cacheContext",null),Object.assign(this,rf.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Pt(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=ot.maxCacheSideLimit,n=ot.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=ot.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=Da.limitDimsByArea(r),l=zn(n,o,i),d=zn(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=ot.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 xp(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])}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=ot.NUM_FRACTION_DIGITS,s=this.clipPath&&!this.clipPath.excludeFromExport?A(A({},this.clipPath.toObject(t)),{},{inverted:this.clipPath.inverted,absolutePositioned:this.clipPath.absolutePositioned}):null,i=A(A({},Hn(this,t)),{},{type:this.constructor.type,version:bu,originX:this.originX,originY:this.originY,left:it(this.left,e),top:it(this.top,e),width:it(this.width,e),height:it(this.height,e),fill:_p(this.fill)?this.fill.toObject():this.fill,stroke:_p(this.stroke)?this.stroke.toObject():this.stroke,strokeWidth:it(this.strokeWidth,e),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:it(this.strokeMiterLimit,e),scaleX:it(this.scaleX,e),scaleY:it(this.scaleY,e),angle:it(this.angle,e),flipX:this.flipX,flipY:this.flipY,opacity:it(this.opacity,e),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:it(this.skewX,e),skewY:it(this.skewY,e)},s?{clipPath:s}:null);return this.includeDefaultValues?i:this._removeDefaultValues(i)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Mu(t,(i,n)=>{if(n===ct||n===ke||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,">")}getObjectScaling(){if(!this.group)return new k(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Bn(this.calcTransformMatrix());return new k(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!==ye&&t!==Ie||(e=this._constrainScale(e)),t===ye&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof li||(e=new li(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===_e&&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=Me(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,Ze(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&&(Ze(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)||ve,o=n*i,h=r*i,l=e.nonScaling?new k(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*ot.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(!Ze(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===_e?(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=Pt(),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 k(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(H.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Fu(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?np():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(x=>new Ba(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Dp(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Ru(this,this.getViewportTransform()),this.setCoords();const l=Pt(),d=this.getBoundingRect(),u=this.shadow,g=new k;if(u){const x=u.blur,S=u.nonScaling?new k(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 k(m.width/2,m.height/2),Q,Q);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 Tu(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=Q,this.originY=Q,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(){oc.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Rs().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}static _fromObject(t){let e=xt(t,ny),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=xt(s,ry);return Ra(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)}};C(Vn,"stateProperties",sy),C(Vn,"cacheProperties",ci),C(Vn,"ownDefaults",iy),C(Vn,"type","FabricObject"),H.setClass(Vn),H.setClass(Vn,"object");const bo=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Pp(a,A(A({},Rp(s,i,n,r)),e)),o};function yo(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 Jp=bo(Oa,yo((a,t,e,s)=>{const i=Iu(t,t.originX,t.originY,e,s);if(It(t.originX)===It(Q)||It(t.originX)===It(Dt)&&i.x<0||It(t.originX)===It(ct)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=Lp(t)?2:1,h=n.width,l=Math.ceil(Math.abs(i.x*o/n.scaleX)-r);return n.set("width",Math.max(l,0)),h!==n.width}return!1}));function oy(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?_e:Ot,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,hi,!1),a[h](),l&&a.stroke(),a.restore()}function ay(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?_e:Ot,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(kt(g)),a["".concat(h,"Rect")](-d,-u,n,r),l&&a.strokeRect(-d,-u,n,r),a.restore()}class fs{constructor(t){C(this,"visible",!0),C(this,"actionName",nc),C(this,"angle",0),C(this,"x",0),C(this,"y",0),C(this,"offsetX",0),C(this,"offsetY",0),C(this,"sizeX",0),C(this,"sizeY",0),C(this,"touchSizeX",0),C(this,"touchSizeY",0),C(this,"cursorStyle","crosshair"),C(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)&&St.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 k(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=hc([go(s,i),fo({angle:t}),lc((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new k(-.5,-.5).transform(o),tr:new k(.5,-.5).transform(o),br:new k(.5,.5).transform(o),bl:new k(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?oy.call(this,t,e,s,i,n):ay.call(this,t,e,s,i,n)}}const hy=(a,t,e)=>e.lockRotation?gc:t.cursorStyle,ly=bo(op,yo((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(gs(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=nn(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 Zp(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function tm(a,t,e){const s=gs(a,"lockScalingX"),i=gs(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 cy=["e","se","s","sw","w","nw","n","ne","e"],Wa=(a,t,e)=>{const s=Zp(a,e);if(tm(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return gc;const i=Ip(e,t);return"".concat(cy[i],"-resize")};function $u(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Zp(a,n);let h,l,d,u,g,f;if(tm(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,d=t.scaleY*t.gestureScale;else{if(h=Iu(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),gs(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);Lp(t)&&(l*=2,d*=2),t.signX!==g&&r!=="y"&&(t.originX=Fp(t.originX),l*=-1,t.signX=g),t.signY!==f&&r!=="x"&&(t.originY=Fp(t.originY),d*=-1,t.signY=f)}const p=n.scaleX,m=n.scaleY;return r?(r==="x"&&n.set(ye,l),r==="y"&&n.set(Ie,d)):(!gs(n,"lockScalingX")&&n.set(ye,l),!gs(n,"lockScalingY")&&n.set(Ie,d)),p!==n.scaleX||m!==n.scaleY}const yc=bo(sc,yo((a,t,e,s)=>$u(a,t,e,s))),dy=bo(sc,yo((a,t,e,s)=>$u(a,t,e,s,{by:"x"}))),uy=bo(sc,yo((a,t,e,s)=>$u(a,t,e,s,{by:"y"}))),gy=["target","ex","ey","skewingSide"],Ku={x:{counterAxis:"y",scale:ye,skew:lo,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Ie,skew:co,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},fy=["ns","nesw","ew","nwse"],py=(a,t,e)=>{if(t.x!==0&&gs(e,"lockSkewingY")||t.y!==0&&gs(e,"lockSkewingX"))return gc;const s=Ip(e,t)%4;return"".concat(fy[s],"-resize")};function em(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:d}=Ku[a];if(gs(n,h))return!1;const{origin:u,flip:g}=Ku[r],f=It(e[u])*(n[g]?-1:1),p=-Math.sign(f)*(n[d]?-1:1),m=.5*-((n[l]===0&&Iu(e,Q,Q,s,i)[a]>0||n[l]>0?1:-1)*p)+.5;return bo(ap,yo((v,x,S,T)=>function(E,M,P){let{target:O,ex:R,ey:D,skewingSide:L}=M,F=xt(M,gy);const{skew:I}=Ku[E],X=P.subtract(new k(R,D)).divide(new k(O.scaleX,O.scaleY))[E],Y=O[I],J=F[I],W=Math.tan(kt(J)),V=E==="y"?O._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:O._getTransformedDimensions({scaleX:1,scaleY:1}).y,Qt=2*X*L/Math.max(V,1)+W,Ke=nn(Math.atan(Qt));O.set(I,Ke);const Zi=Y!==O[I];if(Zi&&E==="y"){const{skewX:Ut,scaleX:Tt}=O,Qe=O._getTransformedDimensions({skewY:Y}),ls=O._getTransformedDimensions(),pe=Ut!==0?Qe.x/ls.x:1;pe!==1&&O.set(ye,pe*Tt)}return Zi}(a,x,new k(S,T))))(t,A(A({},e),{},{[o]:m,skewingSide:p}),s,i)}const my=(a,t,e,s)=>em("x",a,t,e,s),vy=(a,t,e,s)=>em("y",a,t,e,s);function _c(a,t){return a[t.canvas.altActionKey]}const wc=(a,t,e)=>{const s=_c(a,e);return t.x===0?s?lo:Ie:t.y===0?s?co:ye:""},_o=(a,t,e)=>_c(a,e)?py(0,t,e):Wa(a,t,e),sm=(a,t,e,s)=>_c(a,t.target)?vy(a,t,e,s):dy(a,t,e,s),im=(a,t,e,s)=>_c(a,t.target)?my(a,t,e,s):uy(a,t,e,s),nm=()=>({ml:new fs({x:-.5,y:0,cursorStyleHandler:_o,actionHandler:sm,getActionName:wc}),mr:new fs({x:.5,y:0,cursorStyleHandler:_o,actionHandler:sm,getActionName:wc}),mb:new fs({x:0,y:.5,cursorStyleHandler:_o,actionHandler:im,getActionName:wc}),mt:new fs({x:0,y:-.5,cursorStyleHandler:_o,actionHandler:im,getActionName:wc}),tl:new fs({x:-.5,y:-.5,cursorStyleHandler:Wa,actionHandler:yc}),tr:new fs({x:.5,y:-.5,cursorStyleHandler:Wa,actionHandler:yc}),bl:new fs({x:-.5,y:.5,cursorStyleHandler:Wa,actionHandler:yc}),br:new fs({x:.5,y:.5,cursorStyleHandler:Wa,actionHandler:yc}),mtr:new fs({x:0,y:-.5,actionHandler:ly,cursorStyleHandler:hy,offsetY:-40,withConnection:!0,actionName:Su})}),by=()=>({mr:new fs({x:.5,y:0,actionHandler:Jp,cursorStyleHandler:_o,actionName:Oa}),ml:new fs({x:-.5,y:0,actionHandler:Jp,cursorStyleHandler:_o,actionName:Oa})}),yy=()=>A(A({},nm()),by());class Xa extends Vn{static getDefaults(){return A(A({},super.getDefaults()),Xa.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),Xa.ownDefaults),this.setOptions(t)}static createControls(){return{controls:nm()}}_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(nc))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=go(e.x,e.y),i=fo({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=Lt(s,i),r=Lt(t,n),o=Lt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Bn(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(kt(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=A({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=A({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=Lt(r,this.calcTransformMatrix()),d=Bn(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(kt(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=uc(this.width,this.height,La(e)),r=this.isStrokeAccountedForInDimensions()?Au:(this.strokeUniform?new k().scalarAdd(this.canvas?this.canvas.getZoom():1):new k(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=A({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 rm(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}C(Xa,"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 re extends Xa{}rm(re,[jp]),H.setClass(re),H.setClass(re,"object");const om=(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 am{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new k(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new k(1/this.options.scaleX,1/this.options.scaleY):new k(1,1)}createSideVector(t,e){const s=fc(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 k(t);return e.y+=e.x*Math.tan(kt(this.options.skewY)),e.x+=e.y*Math.tan(kt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const _y=new k;class wo extends am{static getOrthogonalRotationFactor(t,e){const s=e?mc(t,e):zp(t);return Math.abs(s)<tn?-1:1}constructor(t,e,s,i){super(i),C(this,"AB",void 0),C(this,"AC",void 0),C(this,"alpha",void 0),C(this,"bisector",void 0),this.A=new k(t),this.B=new k(e),this.C=new k(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=mc(this.AB,this.AC),this.bisector=vc(Xu(this.AB.eq(_y)?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=zu(i),r=wo.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%hi==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?pc(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return pc(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new k(wo.getOrthogonalRotationFactor(this.bisector),wo.getOrthogonalRotationFactor(new k(this.bisector.y,this.bisector.x)));return[new k(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new k(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{Vu(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 k(Math.tan(kt(i)),Math.tan(kt(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 k(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 k(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=>{Vu(m,t,e)&&s.push(this.applySkew(this.A).add(m))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%hi==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=vo(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 hm extends am{constructor(t,e,s){super(s),this.A=new k(t),this.T=new k(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(zu(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 k(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 wo(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new k(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(vc(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 lm=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 k(r)),n),[new k(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 hm(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new wo(n,h,l,t).project()):s.push(...new hm(n,r===0?l:h,t).project())}),s},Qu=a=>{const t={};return Object.keys(a).forEach(e=>{t[e]={},Object.keys(a[e]).forEach(s=>{t[e][s]=A({},a[e][s])})}),t},cm=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),xc=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=wy(a,s))!==!1&&t.push(e);return t},wy=(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 xy=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:cm,graphemeSplit:xc});const Sc=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)},dm=(a,t)=>{const e=t.split(`
38
- `),s=[];let i=-1,n={};a=Qu(a);for(let r=0;r<e.length;r++){const o=xc(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&&(Sc(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},um=(a,t)=>{if(!Array.isArray(a))return Qu(a);const e=t.split(xu),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=xc(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]=A({},a[n].style),i===a[n].end-1&&n++)}return s},rn=["display","transform",Ot,"fill-opacity","fill-rule","opacity",_e,"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 gm(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 Sy(a,t){let e=!0;const s=gm(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=gm(i=i.parentElement,r);return n.length===0}(a,t)),s&&e&&t.length===0}const Cy=a=>{var t;return(t=Zb[a])!==null&&t!==void 0?t:a},Ay=new RegExp("(".concat(js,")"),"gi"),fm=a=>a.replace(Ay," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var pm,mm,vm,bm,ym,_m,wm;const xe="(".concat(js,")"),Ty=String.raw(pm||(pm=Ls(["(skewX)(",")"],["(skewX)\\(","\\)"])),xe),Ey=String.raw(mm||(mm=Ls(["(skewY)(",")"],["(skewY)\\(","\\)"])),xe),ky=String.raw(vm||(vm=Ls(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),xe,xe,xe),My=String.raw(bm||(bm=Ls(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),xe,xe),Dy=String.raw(ym||(ym=Ls(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),xe,xe),Oy=String.raw(_m||(_m=Ls(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),xe,xe,xe,xe,xe,xe),Ju="(?:".concat(Oy,"|").concat(Dy,"|").concat(ky,"|").concat(My,"|").concat(Ty,"|").concat(Ey,")"),Py="(?:".concat(Ju,"*)"),Ly=String.raw(wm||(wm=Ls(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),Py),Fy=new RegExp(Ly),Ry=new RegExp(Ju),Iy=new RegExp(Ju,"g");function Cc(a){const t=[];if(!(a=fm(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!Fy.test(a))return[...ve];for(const e of a.matchAll(Iy)){const s=Ry.exec(e[0]);if(!s)continue;let i=ve;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=go(h,l);break;case Su:i=fo({angle:h},{x:l,y:d});break;case nc:i=lc(h,l);break;case lo:i=Eu(h);break;case co:i=ku(h);break;case"matrix":i=[h,l,d,u,g,f]}t.push(i)}return hc(t)}function jy(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==Ot&&a!==_e||t!==be){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===be?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?Lt(e.transformMatrix,Cc(t)):Cc(t);else if(a==="visible")r=t!==be&&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"?ct:t==="end"?Dt:Q;else if(a==="charSpacing")n=we(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(Ot),h=t.indexOf(_e);r=Ot,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=_e)}else{if(a==="href"||a==="xlink:href"||a==="font")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(we):we(t,s)}}else r="";return!i&&isNaN(n)?r:n}function Ny(a,t){const e=a.match(Jb);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=we(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function Zu(a,t){a.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function By(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?Zu(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 Hy={stroke:"strokeOpacity",fill:"fillOpacity"};function di(a,t,e){if(!a)return{};let s,i={},n=_u;a.parentNode&&qp.test(a.parentNode.nodeName)&&(i=di(a.parentElement,t,e),i.fontSize&&(s=n=we(i.fontSize)));const r=A(A(A({},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)Sy(l,g.split(" "))&&(u=A(A({},u),d[g]));return u}(a,e)),By(a));r[qu]&&a.setAttribute(qu,r[qu]),r[Yu]&&(s=we(r[Yu],n),r[Yu]="".concat(s));const o={};for(const l in r){const d=Cy(l),u=jy(d,r[l],i,s);o[d]=u}o&&o.font&&Ny(o.font,o);const h=A(A({},i),o);return qp.test(a.nodeName)?h:function(l){const d=re.getDefaults();return Object.entries(Hy).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 ut(l[g]);l[g]=p.setAlpha(it(p.getAlpha()*l[f],2)).toRgba()}),l}(h)}const Wy=["left","top","width","height","visible"],xm=["rx","ry"];class Ns extends re{static getDefaults(){return A(A({},super.getDefaults()),Ns.ownDefaults)}constructor(t){super(),Object.assign(this,Ns.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-en*r,n,i+e,n+en*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-en*o,i+e-en*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+en*r,n+s,i,n+s-en*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+en*o,i+en*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([...xm,...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=di(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,d=xt(i,Wy);return new this(A(A(A({},e),d),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}C(Ns,"type","Rect"),C(Ns,"cacheProperties",[...ci,...xm]),C(Ns,"ownDefaults",{rx:0,ry:0}),C(Ns,"ATTRIBUTE_NAMES",[...rn,"x","y","rx","ry","width","height"]),H.setClass(Ns),H.setSVGClass(Ns);const ui="initialization",Ac="added",tg="removed",Tc="imperative",Sm=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?Ha(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),d=e&&l?Op(new k(s,s),void 0,a.calcTransformMatrix()):Au,u=!e&&l?s:0,g=uc(i+u,n+u,hc([o,t.calcOwnMatrix()],!0)).add(d).scalarDivide(2);return[h.subtract(g),h.add(g)]};class Ec{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===ui||e===Tc||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==ui&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Tc&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Is(t.map(u=>Sm(i,u)).reduce((u,g)=>u.concat(g),[])),l=new k(o,h),d=new k(n,r).add(l.scalarDivide(2));if(s===ui){const u=this.getInitialSize(e,{size:l,center:d});return{center:d,relativeCorrection:new k(0,0),size:u}}return{center:d.transform(i.calcOwnMatrix()),size:l}}}C(Ec,"type","strategy");class eg extends Ec{shouldPerformLayout(t){return!0}}C(eg,"type","fit-content"),H.setClass(eg);const Xy=["strategy"],zy=["target","strategy","bubbles","prevStrategy"],Cm="layoutManager";class za{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new eg;C(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=A(A({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[rc,rp,Oa,op,sc,ap,ic,Ob,Pb].map(i=>t.on(i,n=>this.performLayout(i===rc?{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===ui||s===Ac?this.subscribeTargets(t):s===tg&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Tc&&t.deep){const n=xt(t,Xy);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(A(A({},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===ui?new k:e.getRelativeCenterPoint(),{center:o,correction:h=new k,relativeCorrection:l=new k}=n,d=r.subtract(o).add(h).transform(i===ui?ve:Me(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===ui?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*It(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*It(s.originY)}):(s.setPositionByOrigin(n,Q,Q),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,zy),{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(A(A({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Cm,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}H.setClass(za,Cm);const Vy=["type","objects","layoutManager"];class Gy extends za{performLayout(){}}class Bs extends hp(re){static getDefaults(){return A(A({},super.getDefaults()),Bs.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),C(this,"_activeObjects",[]),C(this,"__objectSelectionTracker",void 0),C(this,"__objectSelectionDisposer",void 0),Object.assign(this,Bs.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 za,this.layoutManager.performLayout({type:ui,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(ai("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(ai("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(Ac,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(Ac,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(tg,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&&mo(t,Lt(Me(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||(mo(t,Lt(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=re.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(...Me(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(A({target:this,type:Tc},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 A(A(A({},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=Ns.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",` >
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=ci.ownDefaults;return this.includeDefaultValues?t:ku(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}C(ci,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),C(ci,"type","shadow"),H.setClass(ci,"shadow");const sy=[ke,ct,ye,je,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",lo,co],di=[Ot,_e,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],iy={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:ct,originY:ke,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:Ot,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},ny=["type"],ry=["extraParam"];let Vn=class nf extends Vp{static getDefaults(){return nf.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){hi("warn","Setting type has no effect",t)}constructor(t){super(),C(this,"_cacheContext",null),Object.assign(this,nf.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Pt(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=ot.maxCacheSideLimit,n=ot.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=ot.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=Da.limitDimsByArea(r),l=zn(n,o,i),d=zn(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=ot.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 wp(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])}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=ot.NUM_FRACTION_DIGITS,s=this.clipPath&&!this.clipPath.excludeFromExport?A(A({},this.clipPath.toObject(t)),{},{inverted:this.clipPath.inverted,absolutePositioned:this.clipPath.absolutePositioned}):null,i=A(A({},Hn(this,t)),{},{type:this.constructor.type,version:vu,originX:this.originX,originY:this.originY,left:it(this.left,e),top:it(this.top,e),width:it(this.width,e),height:it(this.height,e),fill:yp(this.fill)?this.fill.toObject():this.fill,stroke:yp(this.stroke)?this.stroke.toObject():this.stroke,strokeWidth:it(this.strokeWidth,e),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:it(this.strokeMiterLimit,e),scaleX:it(this.scaleX,e),scaleY:it(this.scaleY,e),angle:it(this.angle,e),flipX:this.flipX,flipY:this.flipY,opacity:it(this.opacity,e),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:it(this.skewX,e),skewY:it(this.skewY,e)},s?{clipPath:s}:null);return this.includeDefaultValues?i:this._removeDefaultValues(i)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return ku(t,(i,n)=>{if(n===ct||n===ke||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,">")}getObjectScaling(){if(!this.group)return new k(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Bn(this.calcTransformMatrix());return new k(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!==ye&&t!==je||(e=this._constrainScale(e)),t===ye&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof ci||(e=new ci(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===_e&&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=Me(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,Ze(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&&(Ze(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)||ve,o=n*i,h=r*i,l=e.nonScaling?new k(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*ot.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(!Ze(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===_e?(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=Pt(),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 k(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(H.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Lu(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?ip():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(x=>new Ba(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Mp(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Fu(this,this.getViewportTransform()),this.setCoords();const l=Pt(),d=this.getBoundingRect(),u=this.shadow,g=new k;if(u){const x=u.blur,S=u.nonScaling?new k(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 k(m.width/2,m.height/2),Q,Q);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 Au(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=Q,this.originY=Q,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(){oc.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Rs().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}static _fromObject(t){let e=xt(t,ny),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=xt(s,ry);return Ra(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)}};C(Vn,"stateProperties",sy),C(Vn,"cacheProperties",di),C(Vn,"ownDefaults",iy),C(Vn,"type","FabricObject"),H.setClass(Vn),H.setClass(Vn,"object");const bo=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Op(a,A(A({},Fp(s,i,n,r)),e)),o};function yo(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 Qp=bo(Oa,yo((a,t,e,s)=>{const i=Ru(t,t.originX,t.originY,e,s);if(jt(t.originX)===jt(Q)||jt(t.originX)===jt(Dt)&&i.x<0||jt(t.originX)===jt(ct)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=Pp(t)?2:1,h=n.width,l=Math.ceil(Math.abs(i.x*o/n.scaleX)-r);return n.set("width",Math.max(l,0)),h!==n.width}return!1}));function oy(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?_e:Ot,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,li,!1),a[h](),l&&a.stroke(),a.restore()}function ay(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?_e:Ot,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(kt(g)),a["".concat(h,"Rect")](-d,-u,n,r),l&&a.strokeRect(-d,-u,n,r),a.restore()}class fs{constructor(t){C(this,"visible",!0),C(this,"actionName",nc),C(this,"angle",0),C(this,"x",0),C(this,"y",0),C(this,"offsetX",0),C(this,"offsetY",0),C(this,"sizeX",0),C(this,"sizeY",0),C(this,"touchSizeX",0),C(this,"touchSizeY",0),C(this,"cursorStyle","crosshair"),C(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)&&St.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 k(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=hc([go(s,i),fo({angle:t}),lc((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new k(-.5,-.5).transform(o),tr:new k(.5,-.5).transform(o),br:new k(.5,.5).transform(o),bl:new k(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?oy.call(this,t,e,s,i,n):ay.call(this,t,e,s,i,n)}}const hy=(a,t,e)=>e.lockRotation?gc:t.cursorStyle,ly=bo(rp,yo((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(gs(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=nn(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 Jp(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Zp(a,t,e){const s=gs(a,"lockScalingX"),i=gs(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 cy=["e","se","s","sw","w","nw","n","ne","e"],Wa=(a,t,e)=>{const s=Jp(a,e);if(Zp(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return gc;const i=Rp(e,t);return"".concat(cy[i],"-resize")};function qu(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Jp(a,n);let h,l,d,u,g,f;if(Zp(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,d=t.scaleY*t.gestureScale;else{if(h=Ru(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),gs(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);Pp(t)&&(l*=2,d*=2),t.signX!==g&&r!=="y"&&(t.originX=Lp(t.originX),l*=-1,t.signX=g),t.signY!==f&&r!=="x"&&(t.originY=Lp(t.originY),d*=-1,t.signY=f)}const p=n.scaleX,m=n.scaleY;return r?(r==="x"&&n.set(ye,l),r==="y"&&n.set(je,d)):(!gs(n,"lockScalingX")&&n.set(ye,l),!gs(n,"lockScalingY")&&n.set(je,d)),p!==n.scaleX||m!==n.scaleY}const yc=bo(sc,yo((a,t,e,s)=>qu(a,t,e,s))),dy=bo(sc,yo((a,t,e,s)=>qu(a,t,e,s,{by:"x"}))),uy=bo(sc,yo((a,t,e,s)=>qu(a,t,e,s,{by:"y"}))),gy=["target","ex","ey","skewingSide"],$u={x:{counterAxis:"y",scale:ye,skew:lo,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:je,skew:co,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},fy=["ns","nesw","ew","nwse"],py=(a,t,e)=>{if(t.x!==0&&gs(e,"lockSkewingY")||t.y!==0&&gs(e,"lockSkewingX"))return gc;const s=Rp(e,t)%4;return"".concat(fy[s],"-resize")};function tm(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:d}=$u[a];if(gs(n,h))return!1;const{origin:u,flip:g}=$u[r],f=jt(e[u])*(n[g]?-1:1),p=-Math.sign(f)*(n[d]?-1:1),m=.5*-((n[l]===0&&Ru(e,Q,Q,s,i)[a]>0||n[l]>0?1:-1)*p)+.5;return bo(op,yo((v,x,S,T)=>function(E,M,P){let{target:O,ex:R,ey:D,skewingSide:L}=M,F=xt(M,gy);const{skew:I}=$u[E],X=P.subtract(new k(R,D)).divide(new k(O.scaleX,O.scaleY))[E],Y=O[I],J=F[I],W=Math.tan(kt(J)),V=E==="y"?O._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:O._getTransformedDimensions({scaleX:1,scaleY:1}).y,It=2*X*L/Math.max(V,1)+W,Ie=nn(Math.atan(It));O.set(I,Ie);const ai=Y!==O[I];if(ai&&E==="y"){const{skewX:Yt,scaleX:Tt}=O,Qe=O._getTransformedDimensions({skewY:Y}),ls=O._getTransformedDimensions(),pe=Yt!==0?Qe.x/ls.x:1;pe!==1&&O.set(ye,pe*Tt)}return ai}(a,x,new k(S,T))))(t,A(A({},e),{},{[o]:m,skewingSide:p}),s,i)}const my=(a,t,e,s)=>tm("x",a,t,e,s),vy=(a,t,e,s)=>tm("y",a,t,e,s);function _c(a,t){return a[t.canvas.altActionKey]}const wc=(a,t,e)=>{const s=_c(a,e);return t.x===0?s?lo:je:t.y===0?s?co:ye:""},_o=(a,t,e)=>_c(a,e)?py(0,t,e):Wa(a,t,e),em=(a,t,e,s)=>_c(a,t.target)?vy(a,t,e,s):dy(a,t,e,s),sm=(a,t,e,s)=>_c(a,t.target)?my(a,t,e,s):uy(a,t,e,s),im=()=>({ml:new fs({x:-.5,y:0,cursorStyleHandler:_o,actionHandler:em,getActionName:wc}),mr:new fs({x:.5,y:0,cursorStyleHandler:_o,actionHandler:em,getActionName:wc}),mb:new fs({x:0,y:.5,cursorStyleHandler:_o,actionHandler:sm,getActionName:wc}),mt:new fs({x:0,y:-.5,cursorStyleHandler:_o,actionHandler:sm,getActionName:wc}),tl:new fs({x:-.5,y:-.5,cursorStyleHandler:Wa,actionHandler:yc}),tr:new fs({x:.5,y:-.5,cursorStyleHandler:Wa,actionHandler:yc}),bl:new fs({x:-.5,y:.5,cursorStyleHandler:Wa,actionHandler:yc}),br:new fs({x:.5,y:.5,cursorStyleHandler:Wa,actionHandler:yc}),mtr:new fs({x:0,y:-.5,actionHandler:ly,cursorStyleHandler:hy,offsetY:-40,withConnection:!0,actionName:xu})}),by=()=>({mr:new fs({x:.5,y:0,actionHandler:Qp,cursorStyleHandler:_o,actionName:Oa}),ml:new fs({x:-.5,y:0,actionHandler:Qp,cursorStyleHandler:_o,actionName:Oa})}),yy=()=>A(A({},im()),by());class Xa extends Vn{static getDefaults(){return A(A({},super.getDefaults()),Xa.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),Xa.ownDefaults),this.setOptions(t)}static createControls(){return{controls:im()}}_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(nc))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=go(e.x,e.y),i=fo({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=Lt(s,i),r=Lt(t,n),o=Lt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Bn(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(kt(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=A({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=A({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=Lt(r,this.calcTransformMatrix()),d=Bn(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(kt(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=uc(this.width,this.height,La(e)),r=this.isStrokeAccountedForInDimensions()?Cu:(this.strokeUniform?new k().scalarAdd(this.canvas?this.canvas.getZoom():1):new k(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=A({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 nm(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}C(Xa,"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 re extends Xa{}nm(re,[Ip]),H.setClass(re),H.setClass(re,"object");const rm=(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 om{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new k(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new k(1/this.options.scaleX,1/this.options.scaleY):new k(1,1)}createSideVector(t,e){const s=fc(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 k(t);return e.y+=e.x*Math.tan(kt(this.options.skewY)),e.x+=e.y*Math.tan(kt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const _y=new k;class wo extends om{static getOrthogonalRotationFactor(t,e){const s=e?mc(t,e):Xp(t);return Math.abs(s)<tn?-1:1}constructor(t,e,s,i){super(i),C(this,"AB",void 0),C(this,"AC",void 0),C(this,"alpha",void 0),C(this,"bisector",void 0),this.A=new k(t),this.B=new k(e),this.C=new k(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=mc(this.AB,this.AC),this.bisector=vc(Wu(this.AB.eq(_y)?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=Xu(i),r=wo.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%li==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?pc(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return pc(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new k(wo.getOrthogonalRotationFactor(this.bisector),wo.getOrthogonalRotationFactor(new k(this.bisector.y,this.bisector.x)));return[new k(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new k(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{zu(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 k(Math.tan(kt(i)),Math.tan(kt(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 k(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 k(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=>{zu(m,t,e)&&s.push(this.applySkew(this.A).add(m))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%li==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=vo(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 am extends om{constructor(t,e,s){super(s),this.A=new k(t),this.T=new k(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(Xu(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 k(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 wo(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new k(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(vc(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 hm=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 k(r)),n),[new k(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 am(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new wo(n,h,l,t).project()):s.push(...new am(n,r===0?l:h,t).project())}),s},Ku=a=>{const t={};return Object.keys(a).forEach(e=>{t[e]={},Object.keys(a[e]).forEach(s=>{t[e][s]=A({},a[e][s])})}),t},lm=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),xc=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=wy(a,s))!==!1&&t.push(e);return t},wy=(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 xy=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:lm,graphemeSplit:xc});const Sc=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)},cm=(a,t)=>{const e=t.split(`
38
+ `),s=[];let i=-1,n={};a=Ku(a);for(let r=0;r<e.length;r++){const o=xc(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&&(Sc(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},dm=(a,t)=>{if(!Array.isArray(a))return Ku(a);const e=t.split(wu),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=xc(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]=A({},a[n].style),i===a[n].end-1&&n++)}return s},rn=["display","transform",Ot,"fill-opacity","fill-rule","opacity",_e,"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 um(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 Sy(a,t){let e=!0;const s=um(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=um(i=i.parentElement,r);return n.length===0}(a,t)),s&&e&&t.length===0}const Cy=a=>{var t;return(t=Zb[a])!==null&&t!==void 0?t:a},Ay=new RegExp("(".concat(js,")"),"gi"),gm=a=>a.replace(Ay," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var fm,pm,mm,vm,bm,ym,_m;const xe="(".concat(js,")"),Ty=String.raw(fm||(fm=Ls(["(skewX)(",")"],["(skewX)\\(","\\)"])),xe),Ey=String.raw(pm||(pm=Ls(["(skewY)(",")"],["(skewY)\\(","\\)"])),xe),ky=String.raw(mm||(mm=Ls(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),xe,xe,xe),My=String.raw(vm||(vm=Ls(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),xe,xe),Dy=String.raw(bm||(bm=Ls(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),xe,xe),Oy=String.raw(ym||(ym=Ls(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),xe,xe,xe,xe,xe,xe),Qu="(?:".concat(Oy,"|").concat(Dy,"|").concat(ky,"|").concat(My,"|").concat(Ty,"|").concat(Ey,")"),Py="(?:".concat(Qu,"*)"),Ly=String.raw(_m||(_m=Ls(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),Py),Fy=new RegExp(Ly),Ry=new RegExp(Qu),Iy=new RegExp(Qu,"g");function Cc(a){const t=[];if(!(a=gm(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!Fy.test(a))return[...ve];for(const e of a.matchAll(Iy)){const s=Ry.exec(e[0]);if(!s)continue;let i=ve;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=go(h,l);break;case xu:i=fo({angle:h},{x:l,y:d});break;case nc:i=lc(h,l);break;case lo:i=Tu(h);break;case co:i=Eu(h);break;case"matrix":i=[h,l,d,u,g,f]}t.push(i)}return hc(t)}function jy(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==Ot&&a!==_e||t!==be){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===be?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?Lt(e.transformMatrix,Cc(t)):Cc(t);else if(a==="visible")r=t!==be&&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"?ct:t==="end"?Dt:Q;else if(a==="charSpacing")n=we(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(Ot),h=t.indexOf(_e);r=Ot,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=_e)}else{if(a==="href"||a==="xlink:href"||a==="font")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(we):we(t,s)}}else r="";return!i&&isNaN(n)?r:n}function Ny(a,t){const e=a.match(Jb);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=we(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function Ju(a,t){a.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function By(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?Ju(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 Hy={stroke:"strokeOpacity",fill:"fillOpacity"};function ui(a,t,e){if(!a)return{};let s,i={},n=yu;a.parentNode&&Yp.test(a.parentNode.nodeName)&&(i=ui(a.parentElement,t,e),i.fontSize&&(s=n=we(i.fontSize)));const r=A(A(A({},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)Sy(l,g.split(" "))&&(u=A(A({},u),d[g]));return u}(a,e)),By(a));r[Yu]&&a.setAttribute(Yu,r[Yu]),r[Uu]&&(s=we(r[Uu],n),r[Uu]="".concat(s));const o={};for(const l in r){const d=Cy(l),u=jy(d,r[l],i,s);o[d]=u}o&&o.font&&Ny(o.font,o);const h=A(A({},i),o);return Yp.test(a.nodeName)?h:function(l){const d=re.getDefaults();return Object.entries(Hy).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 ut(l[g]);l[g]=p.setAlpha(it(p.getAlpha()*l[f],2)).toRgba()}),l}(h)}const Wy=["left","top","width","height","visible"],wm=["rx","ry"];class Ns extends re{static getDefaults(){return A(A({},super.getDefaults()),Ns.ownDefaults)}constructor(t){super(),Object.assign(this,Ns.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-en*r,n,i+e,n+en*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-en*o,i+e-en*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+en*r,n+s,i,n+s-en*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+en*o,i+en*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([...wm,...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=ui(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,d=xt(i,Wy);return new this(A(A(A({},e),d),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}C(Ns,"type","Rect"),C(Ns,"cacheProperties",[...di,...wm]),C(Ns,"ownDefaults",{rx:0,ry:0}),C(Ns,"ATTRIBUTE_NAMES",[...rn,"x","y","rx","ry","width","height"]),H.setClass(Ns),H.setSVGClass(Ns);const gi="initialization",Ac="added",Zu="removed",Tc="imperative",xm=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?Ha(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),d=e&&l?Dp(new k(s,s),void 0,a.calcTransformMatrix()):Cu,u=!e&&l?s:0,g=uc(i+u,n+u,hc([o,t.calcOwnMatrix()],!0)).add(d).scalarDivide(2);return[h.subtract(g),h.add(g)]};class Ec{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===gi||e===Tc||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==gi&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Tc&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Is(t.map(u=>xm(i,u)).reduce((u,g)=>u.concat(g),[])),l=new k(o,h),d=new k(n,r).add(l.scalarDivide(2));if(s===gi){const u=this.getInitialSize(e,{size:l,center:d});return{center:d,relativeCorrection:new k(0,0),size:u}}return{center:d.transform(i.calcOwnMatrix()),size:l}}}C(Ec,"type","strategy");class tg extends Ec{shouldPerformLayout(t){return!0}}C(tg,"type","fit-content"),H.setClass(tg);const Xy=["strategy"],zy=["target","strategy","bubbles","prevStrategy"],Sm="layoutManager";class za{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new tg;C(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=A(A({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[rc,np,Oa,rp,sc,op,ic,Ob,Pb].map(i=>t.on(i,n=>this.performLayout(i===rc?{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===gi||s===Ac?this.subscribeTargets(t):s===Zu&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Tc&&t.deep){const n=xt(t,Xy);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(A(A({},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===gi?new k:e.getRelativeCenterPoint(),{center:o,correction:h=new k,relativeCorrection:l=new k}=n,d=r.subtract(o).add(h).transform(i===gi?ve:Me(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===gi?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*jt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*jt(s.originY)}):(s.setPositionByOrigin(n,Q,Q),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,zy),{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(A(A({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Sm,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}H.setClass(za,Sm);const Vy=["type","objects","layoutManager"];class Gy extends za{performLayout(){}}class Bs extends ap(re){static getDefaults(){return A(A({},super.getDefaults()),Bs.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),C(this,"_activeObjects",[]),C(this,"__objectSelectionTracker",void 0),C(this,"__objectSelectionDisposer",void 0),Object.assign(this,Bs.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 za,this.layoutManager.performLayout({type:gi,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(hi("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(hi("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(Ac,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(Ac,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Zu,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&&mo(t,Lt(Me(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||(mo(t,Lt(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=re.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(...Me(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(A({target:this,type:Tc},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 A(A(A({},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=Ns.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
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,Vy);return Promise.all([po(i,e),Ra(r,e)]).then(o=>{let[h,l]=o;const d=new this(h,A(A(A({},r),l),{},{layoutManager:new Gy}));if(n){const u=H.getClass(n.type),g=H.getClass(n.strategy);d.layoutManager=new u(new g)}else d.layoutManager=new za;return d.layoutManager.subscribeTargets({type:ui,target:d,targets:d.getObjects()}),d.setCoords(),d})}}C(Bs,"type","Group"),C(Bs,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),H.setClass(Bs);const Am=(a,t)=>Math.min(t.width/a.width,t.height/a.height),Tm=(a,t)=>Math.max(t.width/a.width,t.height/a.height);var Em;const vt="(".concat(js,")"),Uy="(M) (?:".concat(vt," ").concat(vt," ?)+"),Yy="(L) (?:".concat(vt," ").concat(vt," ?)+"),qy="(H) (?:".concat(vt," ?)+"),$y="(V) (?:".concat(vt," ?)+"),Ky=String.raw(Em||(Em=Ls(["(Z)s*"],["(Z)\\s*"]))),Qy="(C) (?:".concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ?)+"),Jy="(S) (?:".concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ?)+"),Zy="(Q) (?:".concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ?)+"),t_="(T) (?:".concat(vt," ").concat(vt," ?)+"),e_="(A) (?:".concat(vt," ").concat(vt," ").concat(vt," ([01]) ?([01]) ").concat(vt," ").concat(vt," ?)+"),km="(?:(?:".concat(Uy,")")+"|(?:".concat(Yy,")")+"|(?:".concat(qy,")")+"|(?:".concat($y,")")+"|(?:".concat(Ky,")")+"|(?:".concat(Qy,")")+"|(?:".concat(Jy,")")+"|(?:".concat(Zy,")")+"|(?:".concat(t_,")")+"|(?:".concat(e_,"))"),s_={m:"l",M:"L"},i_=(a,t,e,s,i,n,r,o,h,l,d)=>{const u=cs(a),g=ds(a),f=cs(t),p=ds(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,_]},Mm=(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 sg(a,t,e,s,i,n,r,o){let h;if(ot.cachesBoundsOfCurve&&(h=[...arguments].join(),Da.boundsOfCurveCache[h]))return Da.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 T=0;T<2;++T){if(T>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 R=-m/f;0<R&&R<1&&u.push(R);continue}const E=f*f-4*m*p;if(E<0)continue;const M=l(E),P=(-f+M)/(2*p);0<P&&P<1&&u.push(P);const O=(-f-M)/(2*p);0<O&&O<1&&u.push(O)}let _=u.length;const v=_,x=Om(a,t,e,s,i,n,r,o);for(;_--;){const{x:T,y:E}=x(u[_]);g[0][_]=T,g[1][_]=E}g[0][v]=a,g[1][v]=t,g[0][v+1]=r,g[1][v+1]=o;const S=[new k(Math.min(...g[0]),Math.min(...g[1])),new k(Math.max(...g[0]),Math.max(...g[1]))];return ot.cachesBoundsOfCurve&&(Da.boundsOfCurveCache[h]=S),S}const n_=(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,T=0,E=0;const M=Math.PI,P=x*yu,O=ds(P),R=cs(P),D=.5*(-R*g-O*f),L=.5*(-R*f+O*g),F=p**2,I=m**2,X=L**2,Y=D**2,J=F*I-F*X-I*Y;let W=Math.abs(p),V=Math.abs(m);if(J<0){const Fn=Math.sqrt(1-J/(F*I));W*=Fn,V*=Fn}else E=(_===v?-1:1)*Math.sqrt(J/(F*X+I*Y));const Qt=E*W*L/V,Ke=-E*V*D/W,Zi=R*Qt-O*Ke+.5*g,Ut=O*Qt+R*Ke+.5*f;let Tt=Mm(1,0,(D-Qt)/W,(L-Ke)/V),Qe=Mm((D-Qt)/W,(L-Ke)/V,(-D-Qt)/W,(-L-Ke)/V);v===0&&Qe>0?Qe-=2*M:v===1&&Qe<0&&(Qe+=2*M);const ls=Math.ceil(Math.abs(Qe/M*2)),pe=[],wt=Qe/ls,Ps=8/3*Math.sin(wt/4)*Math.sin(wt/4)/Math.sin(wt/2);let xa=Tt+wt;for(let Fn=0;Fn<ls;Fn++)pe[Fn]=i_(Tt,xa,R,O,W,V,Zi,Ut,Ps,S,T),S=pe[Fn][5],T=pe[Fn][6],Tt=xa,xa+=wt;return pe})(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},Dm=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":n_(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},kc=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),Om=(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 k(r*l+i*d+e*u+a*g,o*l+n*d+s*u+t*g)},Pm=a=>a**2,Lm=a=>2*a*(1-a),Fm=a=>(1-a)**2,r_=(a,t,e,s,i,n,r,o)=>h=>{const l=Pm(h),d=Lm(h),u=Fm(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)},o_=(a,t,e,s,i,n)=>r=>{const o=Pm(r),h=Lm(r),l=Fm(r);return new k(i*o+e*h+a*l,n*o+s*h+t*l)},a_=(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)},Rm=(a,t,e)=>{let s=new k(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=kc(s.x,s.y,r.x,r.y),s=r}return i},h_=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=A({},n),o=.01,h=0;const l=a.iterator,d=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=kc(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return A(A({},r),{},{angle:d(h)})},ig=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=kc(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=Om(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=d,e.iterator=t,e.angleFinder=r_(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=Rm(t,i,n),i=l[5],n=l[6];break;case"Q":t=o_(i,n,l[1],l[2],l[3],l[4]),e=d,e.iterator=t,e.angleFinder=a_(i,n,l[1],l[2],l[3],l[4]),e.length=Rm(t,i,n),i=l[3],n=l[4];break;case"Z":e=d,e.destX=r,e.destY=o,e.length=kc(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},Im=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ig(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 A(A({},new k(i.x,i.y).lerp(new k(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return A(A({},new k(i.x,i.y).lerp(new k(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return h_(i,t)}},l_=new RegExp(km,"gi"),c_=new RegExp(km,"i"),jm=a=>{a=fm(a);const t=[];for(let[e]of a.matchAll(l_)){const s=[];let i;do{if(i=c_.exec(e),!i)break;const n=i.filter(o=>o);n.shift();const r=n.map(o=>{const h=Number.parseFloat(o);return Number.isNaN(h)?o:h});if(s.push(r),n.length<=1)break;n.shift(),e=e.replace(new RegExp("".concat(n.join(" ?")," ?$")),"")}while(i);s.reverse().forEach((n,r)=>{const o=s_[n[0]];r>0&&(o=="l"||o=="L")&&(n[0]=o),t.push(n)})}return t},d_=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new k(a[0]),s=new k(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},Nm=(a,t)=>a.map(e=>e.map((s,i)=>i===0||t===void 0?s:it(s,t)).join(" ")).join(" "),u_=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function Bm(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||jn,s=new(ec()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=jn};if(i&&i.aborted)throw new vu("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=jn)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const Mc=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=Bn(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(ye,i),s.set(Ie,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,Q,Q)};var g_=Object.freeze({__proto__:null,addTransformToObject:Mp,animate:Wu,animateColor:Wp,applyTransformToObject:mo,calcAngleBetweenVectors:mc,calcDimensionsMatrix:La,calcPlaneChangeMatrix:Ha,calcVectorRotation:zp,cancelAnimFrame:cp,capValue:zn,composeMatrix:pp,copyCanvasElement:a=>{var t;const e=Pt();return e.width=a.width,e.height=a.height,(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:cs,createCanvasElement:Pt,createImage:dp,createRotateMatrix:fo,createScaleMatrix:lc,createSkewXMatrix:Eu,createSkewYMatrix:ku,createTranslateMatrix:go,createVector:fc,crossProduct:vo,degreesToRadians:kt,dotProduct:Vp,ease:Hb,enlivenObjectEnlivables:Ra,enlivenObjects:po,findScaleToCover:Tm,findScaleToFit:Am,getBoundsOfCurve:sg,getOrthonormalVector:zu,getPathSegmentsInfo:ig,getPointOnPath:Im,getPointer:kp,getRandomInt:u_,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-tn;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 k(cs(r),ds(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:d_,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:vc,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new Bs(a,t),hasStyleChanged:Sc,invertTransform:Me,isBetweenVectors:Vu,isIdentityMatrix:up,isTouchEvent:dc,isTransparent:om,joinPath:Nm,loadImage:Fa,magnitude:pc,makeBoundingBoxFromPoints:Is,makePathSimpler:Dm,matrixToSVG:Ia,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),Ru(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 Bs([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:Lt,multiplyTransformMatrixArray:hc,parsePath:jm,parsePreserveAspectRatioAttribute:Ou,parseUnit:we,pick:Hn,projectStrokeOnPoints:lm,qrDecompose:Bn,radiansToDegrees:nn,removeFromArray:Nn,removeTransformFromObject:(a,t)=>{const e=Me(t),s=Lt(e,a.calcOwnMatrix());mo(a,s)},removeTransformMatrixForSvgParsing:Mc,request:Bm,requestAnimFrame:Pa,resetObjectTransform:Dp,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:Xu,saveObjectTransform:Fu,sendObjectToPlane:Ru,sendPointToPlane:Xn,sendVectorToPlane:Op,setStyle:Na,sin:ds,sizeAfterTransform:uc,string:xy,stylesFromArray:um,stylesToArray:dm,toDataURL:Tu,toFixed:it,transformPath:(a,t,e)=>(e&&(t=Lt(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}=ne({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i})),transformPoint:ne});class f_ extends Ep{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),C(this,"upper",void 0),C(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});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=Pt();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=ho().createElement("div");return t.setAttribute("data-fabric","wrapper"),Na(t,{position:"relative"}),Tp(t),t}applyCanvasStyle(t,e){let{allowTouchScrolling:s}=e;Na(t,{position:"absolute",left:"0",top:"0"}),function(i,n){const r=n?"manipulation":be;Na(i,{"touch-action":r,"-ms-touch-action":r})}(t,s),Tp(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;Ap(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Pu(this.upper.el,t),Pu(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(),Rs().dispose(this.upper.el),delete this.upper,delete this.container}}class Dc extends Ba{constructor(){super(...arguments),C(this,"targets",[]),C(this,"_hoveredTargets",[]),C(this,"_objectsToRender",void 0),C(this,"_currentTransform",null),C(this,"_groupSelector",null),C(this,"contextTopDirty",!1)}static getDefaults(){return A(A({},super.getDefaults()),Dc.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 f_(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 om(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===nc||e===ye||e===Ie||e===Oa?i=this.centeredScaling||t.centeredScaling:e===Su&&(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=Dt:["mr","tr","br"].includes(e)&&(s.x=ct),["tl","mt","tr"].includes(e)?s.y=wu:["bl","mb","br"].includes(e)&&(s.y=ke)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?Xn(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):Bb,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:Q,y:Q}: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:kt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:d,original:A(A({},Fu(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 k(e,s).transform(this.viewportTransform),o=new k(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,re.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,dc(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=cs(d)*n,g=ds(d)*n,f=u+g,p=u-g;s=[new k(r.x-p,r.y-f),new k(o.x+f,o.y-p),new k(h.x+p,h.y+f),new k(l.x-f,l.y+p)]}return St.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,Xn(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(ac(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&&ac(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!ac(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=kp(t),r=i.width||0,o=i.height||0;r&&o||(ke in i&&wu in i&&(o=Math.abs(i.top-i.bottom)),Dt in i&&ct 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=Xn(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new k(1,1):new k(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=Pt(),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 Wn(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,Wn(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),Wn(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(rc,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;Wn(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&&Wn(e)&&this._activeObject===e){const s=Hn(t,["angle","flipX","flipY",ct,ye,Ie,lo,co,ke]);return Mp(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}C(Dc,"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 p_{constructor(t){C(this,"targets",[]),C(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),Nn(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 m_=["target","oldTarget","fireCanvas","e"],je={passive:!1},xo=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},on=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)},ts=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)},v_={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 ng extends Dc{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),C(this,"_isClick",void 0),C(this,"textEditingManager",new p_(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(on,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Cp(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,je),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,je)}removeListeners(){this.addOrRemove(ts,"remove");const t=this._getEventPrefix(),e=us(this.upperCanvasEl);ts(e,"".concat(t,"up"),this._onMouseUp),ts(e,"touchend",this._onTouchEnd,je),ts(e,"".concat(t,"move"),this._onMouseMove,je),ts(e,"touchmove",this._onMouseMove,je)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=A({e:t},xo(this,t));this.fire("mouse:out",A(A({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",A({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",A(A({},s),{},{target:i})),i&&i.fire("mouseout",A({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",A({e:t},xo(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 on(this.upperCanvasEl,"drag",this._onDragProgress)}Lu(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!==be,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};ts(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",A({e:t,target:e,subTargets:s,dragSource:this._dragSource},xo(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&&Lu(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=us(e);on(i,"touchend",this._onTouchEnd,je),on(i,"touchmove",this._onMouseMove,je),ts(e,"".concat(s,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();ts(e,"".concat(s,"move"),this._onMouseMove,je);const i=us(e);on(i,"".concat(s,"up"),this._onMouseUp),on(i,"".concat(s,"move"),this._onMouseMove,je)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=us(this.upperCanvasEl);ts(s,"touchend",this._onTouchEnd,je),ts(s,"touchmove",this._onMouseMove,je),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{on(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=us(this.upperCanvasEl);ts(i,"".concat(s,"up"),this._onMouseUp),ts(i,"".concat(s,"move"),this._onMouseMove,je),on(e,"".concat(s,"move"),this._onMouseMove,je)}}_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),dc(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=A(A({e:t,target:s,subTargets:i},xo(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),dc(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=Xn(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",A(A({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",A(A({},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,m_);const{targetIn:h,targetOut:l,canvasIn:d,canvasOut:u}=v_[t],g=i!==s;if(i&&g){const f=A(A({},o),{},{e:r,target:i,nextTarget:s},xo(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&g){const f=A(A({},o),{},{e:r,target:s,previousTarget:i},xo(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?Xn(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=Wn(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=Wn(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(H.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 k(e,s),o=r.add(new k(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=H.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 Hm={x1:0,y1:0,x2:0,y2:0},b_=A(A({},Hm),{},{r1:0,r2:0}),So=(a,t)=>isNaN(a)&&typeof t=="number"?t:a,y_=/^(\d+\.\d+)%|(\d+)%$/;function Wm(a){return a&&y_.test(a)}function Xm(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(Wm(a)?100:1):NaN;return zn(0,So(e,t),1)}const __=/\s*;\s*/,w_=/\s*:\s*/;function x_(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(__);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(w_).map(d=>d.trim());h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}const n=new ut(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Xm(a.getAttribute("offset"),0),color:n.toRgb(),opacity:So(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function S_(a,t){const e=[],s=a.getElementsByTagName("stop"),i=Xm(t,1);for(let n=s.length;n--;)e.push(x_(s[n],i));return e}function zm(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Vm(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function ps(a,t){return a.getAttribute(t)}function C_(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"&&Wm(d)&&(i*=.01,o==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(i*=n),l!=="y1"&&l!=="y2"||(i*=r)))),h[l]=i,h},{})}(zm(a)==="linear"?function(e){return{x1:ps(e,"x1")||0,y1:ps(e,"y1")||0,x2:ps(e,"x2")||"100%",y2:ps(e,"y2")||0}}(a):function(e){return{x1:ps(e,"fx")||ps(e,"cx")||"50%",y1:ps(e,"fy")||ps(e,"cy")||"50%",r1:0,x2:ps(e,"cx")||"50%",y2:ps(e,"cy")||"50%",r2:ps(e,"r")||"50%"}}(a),A(A({},t),{},{gradientUnits:Vm(a)}))}class Va{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:A(A({},e==="radial"?b_:Hm),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(sn()):sn()})}addColorStop(t){for(const e in t){const s=new ut(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return A(A({},Hn(this,t)),{},{type:this.type,coords:A({},this.coords),colorStops:this.colorStops.map(e=>A({},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():ve.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(u=>A({},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(Ia(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,`">
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,Vy);return Promise.all([po(i,e),Ra(r,e)]).then(o=>{let[h,l]=o;const d=new this(h,A(A(A({},r),l),{},{layoutManager:new Gy}));if(n){const u=H.getClass(n.type),g=H.getClass(n.strategy);d.layoutManager=new u(new g)}else d.layoutManager=new za;return d.layoutManager.subscribeTargets({type:gi,target:d,targets:d.getObjects()}),d.setCoords(),d})}}C(Bs,"type","Group"),C(Bs,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),H.setClass(Bs);const Cm=(a,t)=>Math.min(t.width/a.width,t.height/a.height),Am=(a,t)=>Math.max(t.width/a.width,t.height/a.height);var Tm;const vt="(".concat(js,")"),Uy="(M) (?:".concat(vt," ").concat(vt," ?)+"),Yy="(L) (?:".concat(vt," ").concat(vt," ?)+"),qy="(H) (?:".concat(vt," ?)+"),$y="(V) (?:".concat(vt," ?)+"),Ky=String.raw(Tm||(Tm=Ls(["(Z)s*"],["(Z)\\s*"]))),Qy="(C) (?:".concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ?)+"),Jy="(S) (?:".concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ?)+"),Zy="(Q) (?:".concat(vt," ").concat(vt," ").concat(vt," ").concat(vt," ?)+"),t_="(T) (?:".concat(vt," ").concat(vt," ?)+"),e_="(A) (?:".concat(vt," ").concat(vt," ").concat(vt," ([01]) ?([01]) ").concat(vt," ").concat(vt," ?)+"),Em="(?:(?:".concat(Uy,")")+"|(?:".concat(Yy,")")+"|(?:".concat(qy,")")+"|(?:".concat($y,")")+"|(?:".concat(Ky,")")+"|(?:".concat(Qy,")")+"|(?:".concat(Jy,")")+"|(?:".concat(Zy,")")+"|(?:".concat(t_,")")+"|(?:".concat(e_,"))"),s_={m:"l",M:"L"},i_=(a,t,e,s,i,n,r,o,h,l,d)=>{const u=cs(a),g=ds(a),f=cs(t),p=ds(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,_]},km=(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 eg(a,t,e,s,i,n,r,o){let h;if(ot.cachesBoundsOfCurve&&(h=[...arguments].join(),Da.boundsOfCurveCache[h]))return Da.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 T=0;T<2;++T){if(T>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 R=-m/f;0<R&&R<1&&u.push(R);continue}const E=f*f-4*m*p;if(E<0)continue;const M=l(E),P=(-f+M)/(2*p);0<P&&P<1&&u.push(P);const O=(-f-M)/(2*p);0<O&&O<1&&u.push(O)}let _=u.length;const v=_,x=Dm(a,t,e,s,i,n,r,o);for(;_--;){const{x:T,y:E}=x(u[_]);g[0][_]=T,g[1][_]=E}g[0][v]=a,g[1][v]=t,g[0][v+1]=r,g[1][v+1]=o;const S=[new k(Math.min(...g[0]),Math.min(...g[1])),new k(Math.max(...g[0]),Math.max(...g[1]))];return ot.cachesBoundsOfCurve&&(Da.boundsOfCurveCache[h]=S),S}const n_=(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,T=0,E=0;const M=Math.PI,P=x*bu,O=ds(P),R=cs(P),D=.5*(-R*g-O*f),L=.5*(-R*f+O*g),F=p**2,I=m**2,X=L**2,Y=D**2,J=F*I-F*X-I*Y;let W=Math.abs(p),V=Math.abs(m);if(J<0){const Fn=Math.sqrt(1-J/(F*I));W*=Fn,V*=Fn}else E=(_===v?-1:1)*Math.sqrt(J/(F*X+I*Y));const It=E*W*L/V,Ie=-E*V*D/W,ai=R*It-O*Ie+.5*g,Yt=O*It+R*Ie+.5*f;let Tt=km(1,0,(D-It)/W,(L-Ie)/V),Qe=km((D-It)/W,(L-Ie)/V,(-D-It)/W,(-L-Ie)/V);v===0&&Qe>0?Qe-=2*M:v===1&&Qe<0&&(Qe+=2*M);const ls=Math.ceil(Math.abs(Qe/M*2)),pe=[],wt=Qe/ls,Ps=8/3*Math.sin(wt/4)*Math.sin(wt/4)/Math.sin(wt/2);let xa=Tt+wt;for(let Fn=0;Fn<ls;Fn++)pe[Fn]=i_(Tt,xa,R,O,W,V,ai,Yt,Ps,S,T),S=pe[Fn][5],T=pe[Fn][6],Tt=xa,xa+=wt;return pe})(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},Mm=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":n_(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},kc=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),Dm=(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 k(r*l+i*d+e*u+a*g,o*l+n*d+s*u+t*g)},Om=a=>a**2,Pm=a=>2*a*(1-a),Lm=a=>(1-a)**2,r_=(a,t,e,s,i,n,r,o)=>h=>{const l=Om(h),d=Pm(h),u=Lm(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)},o_=(a,t,e,s,i,n)=>r=>{const o=Om(r),h=Pm(r),l=Lm(r);return new k(i*o+e*h+a*l,n*o+s*h+t*l)},a_=(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)},Fm=(a,t,e)=>{let s=new k(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=kc(s.x,s.y,r.x,r.y),s=r}return i},h_=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=A({},n),o=.01,h=0;const l=a.iterator,d=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=kc(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return A(A({},r),{},{angle:d(h)})},sg=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=kc(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=Dm(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=d,e.iterator=t,e.angleFinder=r_(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=Fm(t,i,n),i=l[5],n=l[6];break;case"Q":t=o_(i,n,l[1],l[2],l[3],l[4]),e=d,e.iterator=t,e.angleFinder=a_(i,n,l[1],l[2],l[3],l[4]),e.length=Fm(t,i,n),i=l[3],n=l[4];break;case"Z":e=d,e.destX=r,e.destY=o,e.length=kc(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},Rm=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sg(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 A(A({},new k(i.x,i.y).lerp(new k(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return A(A({},new k(i.x,i.y).lerp(new k(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return h_(i,t)}},l_=new RegExp(Em,"gi"),c_=new RegExp(Em,"i"),Im=a=>{a=gm(a);const t=[];for(let[e]of a.matchAll(l_)){const s=[];let i;do{if(i=c_.exec(e),!i)break;const n=i.filter(o=>o);n.shift();const r=n.map(o=>{const h=Number.parseFloat(o);return Number.isNaN(h)?o:h});if(s.push(r),n.length<=1)break;n.shift(),e=e.replace(new RegExp("".concat(n.join(" ?")," ?$")),"")}while(i);s.reverse().forEach((n,r)=>{const o=s_[n[0]];r>0&&(o=="l"||o=="L")&&(n[0]=o),t.push(n)})}return t},d_=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new k(a[0]),s=new k(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},jm=(a,t)=>a.map(e=>e.map((s,i)=>i===0||t===void 0?s:it(s,t)).join(" ")).join(" "),u_=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function Nm(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||jn,s=new(ec()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=jn};if(i&&i.aborted)throw new mu("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=jn)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const Mc=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=Bn(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(ye,i),s.set(je,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,Q,Q)};var g_=Object.freeze({__proto__:null,addTransformToObject:kp,animate:Hu,animateColor:Hp,applyTransformToObject:mo,calcAngleBetweenVectors:mc,calcDimensionsMatrix:La,calcPlaneChangeMatrix:Ha,calcVectorRotation:Xp,cancelAnimFrame:lp,capValue:zn,composeMatrix:fp,copyCanvasElement:a=>{var t;const e=Pt();return e.width=a.width,e.height=a.height,(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:cs,createCanvasElement:Pt,createImage:cp,createRotateMatrix:fo,createScaleMatrix:lc,createSkewXMatrix:Tu,createSkewYMatrix:Eu,createTranslateMatrix:go,createVector:fc,crossProduct:vo,degreesToRadians:kt,dotProduct:zp,ease:Hb,enlivenObjectEnlivables:Ra,enlivenObjects:po,findScaleToCover:Am,findScaleToFit:Cm,getBoundsOfCurve:eg,getOrthonormalVector:Xu,getPathSegmentsInfo:sg,getPointOnPath:Rm,getPointer:Ep,getRandomInt:u_,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-tn;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 k(cs(r),ds(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:d_,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:vc,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new Bs(a,t),hasStyleChanged:Sc,invertTransform:Me,isBetweenVectors:zu,isIdentityMatrix:dp,isTouchEvent:dc,isTransparent:rm,joinPath:jm,loadImage:Fa,magnitude:pc,makeBoundingBoxFromPoints:Is,makePathSimpler:Mm,matrixToSVG:Ia,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),Fu(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 Bs([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:Lt,multiplyTransformMatrixArray:hc,parsePath:Im,parsePreserveAspectRatioAttribute:Du,parseUnit:we,pick:Hn,projectStrokeOnPoints:hm,qrDecompose:Bn,radiansToDegrees:nn,removeFromArray:Nn,removeTransformFromObject:(a,t)=>{const e=Me(t),s=Lt(e,a.calcOwnMatrix());mo(a,s)},removeTransformMatrixForSvgParsing:Mc,request:Nm,requestAnimFrame:Pa,resetObjectTransform:Mp,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:Wu,saveObjectTransform:Lu,sendObjectToPlane:Fu,sendPointToPlane:Xn,sendVectorToPlane:Dp,setStyle:Na,sin:ds,sizeAfterTransform:uc,string:xy,stylesFromArray:dm,stylesToArray:cm,toDataURL:Au,toFixed:it,transformPath:(a,t,e)=>(e&&(t=Lt(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}=ne({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i})),transformPoint:ne});class f_ extends Tp{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),C(this,"upper",void 0),C(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});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=Pt();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=ho().createElement("div");return t.setAttribute("data-fabric","wrapper"),Na(t,{position:"relative"}),Ap(t),t}applyCanvasStyle(t,e){let{allowTouchScrolling:s}=e;Na(t,{position:"absolute",left:"0",top:"0"}),function(i,n){const r=n?"manipulation":be;Na(i,{"touch-action":r,"-ms-touch-action":r})}(t,s),Ap(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;Cp(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Ou(this.upper.el,t),Ou(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(),Rs().dispose(this.upper.el),delete this.upper,delete this.container}}class Dc extends Ba{constructor(){super(...arguments),C(this,"targets",[]),C(this,"_hoveredTargets",[]),C(this,"_objectsToRender",void 0),C(this,"_currentTransform",null),C(this,"_groupSelector",null),C(this,"contextTopDirty",!1)}static getDefaults(){return A(A({},super.getDefaults()),Dc.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 f_(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 rm(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===nc||e===ye||e===je||e===Oa?i=this.centeredScaling||t.centeredScaling:e===xu&&(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=Dt:["mr","tr","br"].includes(e)&&(s.x=ct),["tl","mt","tr"].includes(e)?s.y=_u:["bl","mb","br"].includes(e)&&(s.y=ke)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?Xn(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):Bb,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:Q,y:Q}: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:kt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:d,original:A(A({},Lu(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 k(e,s).transform(this.viewportTransform),o=new k(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,re.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,dc(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=cs(d)*n,g=ds(d)*n,f=u+g,p=u-g;s=[new k(r.x-p,r.y-f),new k(o.x+f,o.y-p),new k(h.x+p,h.y+f),new k(l.x-f,l.y+p)]}return St.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,Xn(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(ac(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&&ac(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!ac(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=Ep(t),r=i.width||0,o=i.height||0;r&&o||(ke in i&&_u in i&&(o=Math.abs(i.top-i.bottom)),Dt in i&&ct 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=Xn(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new k(1,1):new k(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=Pt(),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 Wn(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,Wn(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),Wn(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(rc,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;Wn(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&&Wn(e)&&this._activeObject===e){const s=Hn(t,["angle","flipX","flipY",ct,ye,je,lo,co,ke]);return kp(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}C(Dc,"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 p_{constructor(t){C(this,"targets",[]),C(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),Nn(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 m_=["target","oldTarget","fireCanvas","e"],Ne={passive:!1},xo=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},on=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)},ts=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)},v_={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 ig extends Dc{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),C(this,"_isClick",void 0),C(this,"textEditingManager",new p_(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(on,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Sp(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,Ne),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,Ne)}removeListeners(){this.addOrRemove(ts,"remove");const t=this._getEventPrefix(),e=us(this.upperCanvasEl);ts(e,"".concat(t,"up"),this._onMouseUp),ts(e,"touchend",this._onTouchEnd,Ne),ts(e,"".concat(t,"move"),this._onMouseMove,Ne),ts(e,"touchmove",this._onMouseMove,Ne)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=A({e:t},xo(this,t));this.fire("mouse:out",A(A({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",A({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",A(A({},s),{},{target:i})),i&&i.fire("mouseout",A({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",A({e:t},xo(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 on(this.upperCanvasEl,"drag",this._onDragProgress)}Pu(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!==be,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};ts(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",A({e:t,target:e,subTargets:s,dragSource:this._dragSource},xo(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&&Pu(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=us(e);on(i,"touchend",this._onTouchEnd,Ne),on(i,"touchmove",this._onMouseMove,Ne),ts(e,"".concat(s,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();ts(e,"".concat(s,"move"),this._onMouseMove,Ne);const i=us(e);on(i,"".concat(s,"up"),this._onMouseUp),on(i,"".concat(s,"move"),this._onMouseMove,Ne)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=us(this.upperCanvasEl);ts(s,"touchend",this._onTouchEnd,Ne),ts(s,"touchmove",this._onMouseMove,Ne),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{on(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=us(this.upperCanvasEl);ts(i,"".concat(s,"up"),this._onMouseUp),ts(i,"".concat(s,"move"),this._onMouseMove,Ne),on(e,"".concat(s,"move"),this._onMouseMove,Ne)}}_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),dc(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=A(A({e:t,target:s,subTargets:i},xo(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),dc(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=Xn(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",A(A({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",A(A({},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,m_);const{targetIn:h,targetOut:l,canvasIn:d,canvasOut:u}=v_[t],g=i!==s;if(i&&g){const f=A(A({},o),{},{e:r,target:i,nextTarget:s},xo(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&g){const f=A(A({},o),{},{e:r,target:s,previousTarget:i},xo(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?Xn(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=Wn(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=Wn(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(H.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 k(e,s),o=r.add(new k(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=H.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 Bm={x1:0,y1:0,x2:0,y2:0},b_=A(A({},Bm),{},{r1:0,r2:0}),So=(a,t)=>isNaN(a)&&typeof t=="number"?t:a,y_=/^(\d+\.\d+)%|(\d+)%$/;function Hm(a){return a&&y_.test(a)}function Wm(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(Hm(a)?100:1):NaN;return zn(0,So(e,t),1)}const __=/\s*;\s*/,w_=/\s*:\s*/;function x_(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(__);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(w_).map(d=>d.trim());h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}const n=new ut(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Wm(a.getAttribute("offset"),0),color:n.toRgb(),opacity:So(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function S_(a,t){const e=[],s=a.getElementsByTagName("stop"),i=Wm(t,1);for(let n=s.length;n--;)e.push(x_(s[n],i));return e}function Xm(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function zm(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function ps(a,t){return a.getAttribute(t)}function C_(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"&&Hm(d)&&(i*=.01,o==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(i*=n),l!=="y1"&&l!=="y2"||(i*=r)))),h[l]=i,h},{})}(Xm(a)==="linear"?function(e){return{x1:ps(e,"x1")||0,y1:ps(e,"y1")||0,x2:ps(e,"x2")||"100%",y2:ps(e,"y2")||0}}(a):function(e){return{x1:ps(e,"fx")||ps(e,"cx")||"50%",y1:ps(e,"fy")||ps(e,"cy")||"50%",r1:0,x2:ps(e,"cx")||"50%",y2:ps(e,"cy")||"50%",r2:ps(e,"r")||"50%"}}(a),A(A({},t),{},{gradientUnits:zm(a)}))}class Va{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:A(A({},e==="radial"?b_:Bm),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(sn()):sn()})}addColorStop(t){for(const e in t){const s=new ut(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return A(A({},Hn(this,t)),{},{type:this.type,coords:A({},this.coords),colorStops:this.colorStops.map(e=>A({},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():ve.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(u=>A({},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(Ia(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
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
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(T=>{T.offset+=S*(1-T.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
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 ut(d).setAlpha(u).toRgba():d)}),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(A(A({},t),{},{colorStops:e?e.map(i=>A({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=Vm(t),n=e._findCenterFromElement();return new this(A({id:t.getAttribute("id")||void 0,type:zm(t),coords:C_(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:S_(t,s.opacity),gradientUnits:i,gradientTransform:Cc(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}C(Va,"type","Gradient"),H.setClass(Va,"gradient"),H.setClass(Va,"linear"),H.setClass(Va,"radial");const A_=["type","source","patternTransform"];class rg{get type(){return"pattern"}set type(t){ai("warn","Setting type has no effect",t)}constructor(t){C(this,"repeat","repeat"),C(this,"offsetX",0),C(this,"offsetY",0),C(this,"crossOrigin",""),this.id=sn(),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 A(A({},Hn(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:it(this.offsetX,ot.NUM_FRACTION_DIGITS),offsetY:it(this.offsetY,ot.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=So(this.offsetX/e,0),h=So(this.offsetY/s,0),l=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):So(i.width/e,0),d=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):So(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,A_);const o=await Fa(i,A(A({},e),{},{crossOrigin:r.crossOrigin}));return new this(A(A({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}C(rg,"type","Pattern"),H.setClass(rg),H.setClass(rg,"pattern");const T_=["path","left","top"],E_=["d"];class Gn extends re{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=xt(e,T_);super(),Object.assign(this,Gn.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(ct,i),typeof n=="number"&&this.set(ke,n)}_setPath(t,e){this.path=Dm(Array.isArray(t)?t:jm(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new k(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 A(A({},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=Nm(this.path,ot.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
- `)]}_getOffsetTransform(){const t=ot.NUM_FRACTION_DIGITS;return" translate(".concat(it(-this.pathOffset.x,t),", ").concat(it(-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,Q,Q)}_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(new k(e,s),new k(i,n));break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...sg(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(...sg(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 Is(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return A(A({},t),{},{pathOffset:new k(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=di(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,A(A(A({},xt(i,E_)),e),{},{left:void 0,top:void 0}))}}C(Gn,"type","Path"),C(Gn,"cacheProperties",[...ci,"path","fillRule"]),C(Gn,"ATTRIBUTE_NAMES",[...rn,"d"]),H.setClass(Gn),H.setSVGClass(Gn);const k_=["left","top","radius"],Gm=["radius","startAngle","endAngle","counterClockwise"];class gi extends re{static getDefaults(){return A(A({},super.getDefaults()),gi.ownDefaults)}constructor(t){super(),Object.assign(this,gi.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,kt(this.startAngle),kt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(ye)}getRadiusY(){return this.get("radius")*this.get(Ie)}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([...Gm,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
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 ut(d).setAlpha(u).toRgba():d)}),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(A(A({},t),{},{colorStops:e?e.map(i=>A({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=zm(t),n=e._findCenterFromElement();return new this(A({id:t.getAttribute("id")||void 0,type:Xm(t),coords:C_(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:S_(t,s.opacity),gradientUnits:i,gradientTransform:Cc(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}C(Va,"type","Gradient"),H.setClass(Va,"gradient"),H.setClass(Va,"linear"),H.setClass(Va,"radial");const A_=["type","source","patternTransform"];class ng{get type(){return"pattern"}set type(t){hi("warn","Setting type has no effect",t)}constructor(t){C(this,"repeat","repeat"),C(this,"offsetX",0),C(this,"offsetY",0),C(this,"crossOrigin",""),this.id=sn(),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 A(A({},Hn(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:it(this.offsetX,ot.NUM_FRACTION_DIGITS),offsetY:it(this.offsetY,ot.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=So(this.offsetX/e,0),h=So(this.offsetY/s,0),l=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):So(i.width/e,0),d=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):So(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,A_);const o=await Fa(i,A(A({},e),{},{crossOrigin:r.crossOrigin}));return new this(A(A({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}C(ng,"type","Pattern"),H.setClass(ng),H.setClass(ng,"pattern");const T_=["path","left","top"],E_=["d"];class Gn extends re{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=xt(e,T_);super(),Object.assign(this,Gn.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(ct,i),typeof n=="number"&&this.set(ke,n)}_setPath(t,e){this.path=Mm(Array.isArray(t)?t:Im(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new k(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 A(A({},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=jm(this.path,ot.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
+ `)]}_getOffsetTransform(){const t=ot.NUM_FRACTION_DIGITS;return" translate(".concat(it(-this.pathOffset.x,t),", ").concat(it(-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,Q,Q)}_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(new k(e,s),new k(i,n));break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...eg(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(...eg(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 Is(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return A(A({},t),{},{pathOffset:new k(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=ui(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,A(A(A({},xt(i,E_)),e),{},{left:void 0,top:void 0}))}}C(Gn,"type","Path"),C(Gn,"cacheProperties",[...di,"path","fillRule"]),C(Gn,"ATTRIBUTE_NAMES",[...rn,"d"]),H.setClass(Gn),H.setSVGClass(Gn);const k_=["left","top","radius"],Vm=["radius","startAngle","endAngle","counterClockwise"];class fi extends re{static getDefaults(){return A(A({},super.getDefaults()),fi.ownDefaults)}constructor(t){super(),Object.assign(this,fi.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,kt(this.startAngle),kt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(ye)}getRadiusY(){return this.get("radius")*this.get(je)}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([...Vm,...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
48
  `];{const{radius:e}=this,s=kt(this.startAngle),i=kt(this.endAngle),n=cs(s)*e,r=ds(s)*e,o=cs(i)*e,h=ds(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=di(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(A(A({},xt(i,k_)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}C(gi,"type","Circle"),C(gi,"cacheProperties",[...ci,...Gm]),C(gi,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),C(gi,"ATTRIBUTE_NAMES",["cx","cy","r",...rn]),H.setClass(gi),H.setSVGClass(gi);const M_=["x1","y1","x2","y2"],D_=["x1","y1","x2","y2"],og=["x1","x2","y1","y2"];class Un extends re{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,Un.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(ct,r),typeof o=="number"&&this.set(ke,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}=Is([{x:t,y:e},{x:s,y:i}]),l=new k(n+o/2,r+h/2);this.setPositionByOrigin(l,Q,Q)}_set(t,e){return super._set(t,e),og.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;Ze(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 k((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return A(A({},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=di(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,D_);return this._fromObject(A(A({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}C(Un,"type","Line"),C(Un,"cacheProperties",[...ci,...og]),C(Un,"ATTRIBUTE_NAMES",rn.concat(og)),H.setClass(Un),H.setSVGClass(Un);class Yn extends re{static getDefaults(){return A(A({},super.getDefaults()),Yn.ownDefaults)}constructor(t){super(),Object.assign(this,Yn.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),'" />']}}C(Yn,"type","Triangle"),C(Yn,"ownDefaults",{width:100,height:100}),H.setClass(Yn),H.setSVGClass(Yn);const Um=["rx","ry"];class fi extends re{static getDefaults(){return A(A({},super.getDefaults()),fi.ownDefaults)}constructor(t){super(),Object.assign(this,fi.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(ye)}getRy(){return this.get("ry")*this.get(Ie)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Um,...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,hi,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=di(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function O_(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}C(fi,"type","Ellipse"),C(fi,"cacheProperties",[...ci,...Um]),C(fi,"ownDefaults",{rx:0,ry:0}),C(fi,"ATTRIBUTE_NAMES",[...rn,"cx","cy","rx","ry"]),H.setClass(fi),H.setSVGClass(fi);const P_=["left","top"],Ym={exactBoundingBox:!1};class ms extends re{static getDefaults(){return A(A({},super.getDefaults()),ms.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),C(this,"strokeDiff",void 0),Object.assign(this,ms.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(ct,s),typeof i=="number"&&this.set(ke,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return lm(this.points,t,this.isOpen())}_calcDimensions(t){t=A({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 k,strokeOffset:new k,strokeDiff:new k};const s=Is(e),i=La(A(A({},t),{},{scaleX:1,scaleY:1})),n=Is(this.points.map(l=>ne(l,i,!0))),r=new k(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(kt(this.skewX)),h-=o*Math.tan(kt(this.skewY))),A(A({},s),{},{pathOffset:new k(o,h),strokeOffset:new k(n.left,n.top).subtract(new k(s.left,s.top)).multiply(r),strokeDiff:new k(s.width,s.height).subtract(new k(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Is(this.points);return new k(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 k(e+i/2,s+n/2),Q,Q)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new k(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 k((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new k((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new k(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===ye||t===Ie)&&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 A(A({},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=ot.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(it(this.points[n].x-e,i),",",it(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(O_(t.getAttribute("points")),A(A({},xt(di(t,this.ATTRIBUTE_NAMES,s),P_)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}C(ms,"ownDefaults",Ym),C(ms,"type","Polyline"),C(ms,"layoutProperties",[lo,co,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),C(ms,"cacheProperties",[...ci,"points"]),C(ms,"ATTRIBUTE_NAMES",[...rn]),H.setClass(ms),H.setSVGClass(ms);class Oc extends ms{isOpen(){return!1}}C(Oc,"ownDefaults",Ym),C(Oc,"type","Polygon"),H.setClass(Oc),H.setSVGClass(Oc);const qm=["fontSize","fontWeight","fontFamily","fontStyle"],$m=["underline","overline","linethrough"],Km=[...qm,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],Qm=[...Km,...$m,"textBackgroundColor","direction"],L_=[...qm,...$m,_e,"strokeWidth",Ot,"deltaY","textBackgroundColor"],F_={_reNewline:xu,_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:ct,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:ct,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},Hs="justify",Pc="justify-left",Ga="justify-right",Ua="justify-center";class Jm extends re{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=Mu(A(A({},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 A(A({},Hn(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]}}C(Jm,"_styleProperties",L_);const R_=/ +/g,I_=/"/g;function ag(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]:ot.NUM_FRACTION_DIGITS;const g=ja(Ot,n,!1),[f,p,m,_]=[o,h,l,d].map(v=>it(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 j_=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let hg;class oe extends Jm{static getDefaults(){return A(A({},super.getDefaults()),oe.ownDefaults)}constructor(t,e){super(),C(this,"__charBounds",[]),Object.assign(this,oe.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=ig(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(Hs)&&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===Hs||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===_e?(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 Q:t.textBaseline="middle";break;case"ascender":t.textBaseline=ke;break;case"descender":t.textBaseline=wu}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=Da.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(!hg){const m=Pt();m.width=m.height=0,hg=m.getContext("2d")}return hg}();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===Dt,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 ct:d=n?u-i:0;break;case Q:d=(u-i)/2;break;case Dt: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=Im(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===Dt?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(Ot))&&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(Hs),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="",T=0;if(e.save(),f!==this.direction&&(e.canvas.setAttribute("dir",u?"ltr":"rtl"),e.direction=u?"ltr":"rtl",e.textAlign=u?ct:Dt),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,M=s.length-1;E<=M;E++)v=E===M||this.charSpacing||l,S+=s[E],_=this.__charBounds[r][E],T===0?(i+=g*(_.kernedWidth-_.width),T+=_.width):T+=_.kernedWidth,h&&!v&&this._reSpaceAndTab.test(s[E])&&(v=!0),v||(p=p||this.getCompleteStyleDeclaration(r,E),m=this.getCompleteStyleDeclaration(r,E+1),v=Sc(p,m,!1)),v&&(l?(e.save(),e.translate(_.renderLeft,_.renderTop),e.rotate(_.angle),this._renderChar(t,e,r,E,S,-T/2,0),e.restore()):(x=i,this._renderChar(t,e,r,E,S,x,n)),S="",p=m,i+=g*T,T=0);e.restore()}_applyPatternGradientTransformText(t){const e=Pt(),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 Ze(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===Hs||i===Ua&&!r||i===Ga&&!r||i===Pc&&!r?0:(i===Q&&(o=s/2),i===Dt&&(o=s),i===Ua&&(o=s/2),i===Ga&&(o=s),n==="rtl"&&(i===Dt||i===Hs||i===Ga?o=0:i===ct||i===Pc?o=-s:i!==Q&&i!==Ua||(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,Ot);const T=s+g*(1-this._fontSizeFraction);let E=this.getHeightOfChar(h,0),M=this.getValueOfPropertyAt(h,0,"deltaY");for(let O=0,R=u.length;O<R;O++){const D=this.__charBounds[h][O];p=this.getValueOfPropertyAt(h,O,e),m=this.getValueOfPropertyAt(h,O,Ot);const L=this.getHeightOfChar(h,O),F=this.getValueOfPropertyAt(h,O,"deltaY");if(n&&p&&m)t.save(),t.fillStyle=S,t.translate(D.renderLeft,D.renderTop),t.rotate(D.angle),t.fillRect(-D.kernedWidth/2,o*L+F,D.kernedWidth,this.fontSize/15),t.restore();else if((p!==x||m!==S||L!==E||F!==M)&&v>0){let I=i+f+_;this.direction==="rtl"&&(I=this.width-I-v),x&&S&&(t.fillStyle=S,t.fillRect(I,T+o*E+M,v,this.fontSize/15)),_=D.left,v=D.width,x=p,S=m,E=L,M=F}else v+=D.kernedWidth}let P=i+f+_;this.direction==="rtl"&&(P=this.width-P-v),t.fillStyle=m,p&&m&&t.fillRect(P,T+o*E+M,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(",")||oe.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 xc(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 A(A({},super.toObject([...Qm,...t])),{},{styles:dm(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=di(t,oe.ATTRIBUTE_NAMES,s),n=A(A({},e),i),{textAnchor:r=ct,textDecoration:o="",dx:h=0,dy:l=0,top:d=0,left:u=0,fontSize:g=_u,strokeWidth:f=1}=n,p=xt(n,j_),m=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),A({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===Q&&(S=m.getScaledWidth()/2),r===Dt&&(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(A(A({},t),{},{styles:um(t.styles||{},t.text)}),{extraParam:"text"})}}C(oe,"textLayoutProperties",Km),C(oe,"cacheProperties",[...ci,...Qm]),C(oe,"ownDefaults",F_),C(oe,"type","Text"),C(oe,"genericFonts",["sans-serif","serif","cursive","fantasy","monospace"]),C(oe,"ATTRIBUTE_NAMES",rn.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),rm(oe,[class extends jp{_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(I_,"'"),'" '):"",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(...ag(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(R_)),n=i?'style="'.concat(i,'"'):"",r=t.deltaY,o=r?' dy="'.concat(it(r,ot.NUM_FRACTION_DIGITS),'" '):"";return'<tspan x="'.concat(it(e,ot.NUM_FRACTION_DIGITS),'" y="').concat(it(s,ot.NUM_FRACTION_DIGITS),'" ').concat(o).concat(n,">").concat(cm(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Hs),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=Sc(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(...ag(l,e+h,s,o,n)),h=u,o=g,l=r):o+=f}r&&a.push(...ag(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?ja(_e,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?ja(Ot,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter(t=>a[t.replace("-","")]).join(" ")}}]),H.setClass(oe),H.setSVGClass(oe);class N_{constructor(t){C(this,"target",void 0),C(this,"__mouseDownInPlace",!1),C(this,"__dragStartFired",!1),C(this,"__isDraggingOver",!1),C(this,"__dragStartSelection",void 0),C(this,"__dragImageDisposer",void 0),C(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 k(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),d=new k(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 k(f.left,f.top)),m=o.viewportTransform,_=p.add(u).transform(m,!0),v=r.backgroundColor,x=Qu(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 T=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=v,r.styles=x,r.dirty=!0,Na(T,{position:"fixed",left:"".concat(-T.width,"px"),border:be,width:"".concat(T.width/g,"px"),height:"".concat(T.height/g,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{T.remove()},us(t.target||this.target.hiddenTextarea).body.appendChild(T),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(T,_.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=A({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(ic,{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)||be;h===be?(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(ic,{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 Zm=/[ \n\.,;!\?\-]/;class B_ extends oe{constructor(){super(...arguments),C(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 Wu({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||!xu.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!Zm.test(n);)i+=e,n=s[i];return e===-1&&Zm.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;us(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 k(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new k(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(rc),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:A({},i[s-1])}:l?this.styles[t+s]={0:A({},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?A({},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]=A({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=A({},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=ct:this._selectionDirection===Dt&&(this._selectionDirection=ct,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Dt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Dt:this._selectionDirection===ct&&(this._selectionDirection=Dt,this.selectionStart=e),this.selectionEnd=s)}}class H_ extends B_{initHiddenTextarea(){const t=this.canvas&&us(this.canvas.getElement())||ho(),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(ic),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}=Rs();e&&v.join("")===x.copiedText&&!ot.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}=Rs();t.copiedText=this.getSelectedText(),ot.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===Dt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=zn(0,this.selectionStart,i),this.selectionEnd=zn(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===ct?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=ct,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Dt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=ct,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===ct&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Dt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Dt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const lg=a=>!!a.button;class W_ extends H_{constructor(){super(...arguments),C(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 N_(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),Lu(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&&!lg(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&&!lg(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||lg(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(Me(this.calcTransformMatrix())).add(new k(-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 Lc="moveCursorUp",Fc="moveCursorDown",Rc="moveCursorLeft",Ic="moveCursorRight",jc="exitEditing",X_=A({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:jc,27:jc,33:Lc,34:Fc,35:Ic,36:Rc,37:Rc,38:Lc,39:Ic,40:Fc},keysMapRtl:{9:jc,27:jc,33:Lc,34:Fc,35:Rc,36:Ic,37:Ic,38:Lc,39:Rc,40:Fc},ctrlKeysMapDown:{65:"selectAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class pi extends W_{static getDefaults(){return A(A({},super.getDefaults()),pi.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,A(A({},pi.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 ng&&this.canvas.textEditingManager.remove(this),e instanceof ng&&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===Dt||this.textAlign===Hs||this.textAlign===Ga?h.left*=-1:this.textAlign===ct||this.textAlign===Pc?h.left=r-(s>0?s:0):this.textAlign!==Q&&this.textAlign!==Ua||(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,Ot),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(Hs),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,T=m,E=0;const M=x-v;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",T=1,E=m):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Dt||this.textAlign===Hs||this.textAlign===Ga?S=this.width-S-M:this.textAlign===ct||this.textAlign===Pc?S=s.left+p-x:this.textAlign!==Q&&this.textAlign!==Ua||(S=s.left+p-x)),t.fillRect(S,s.top+s.topOffset+E,M,T),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,Ot)}_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()}}C(pi,"ownDefaults",X_),C(pi,"type","IText"),H.setClass(pi),H.setClass(pi,"i-text");class qn extends pi{static getDefaults(){return A(A({},super.getDefaults()),qn.ownDefaults)}constructor(t,e){super(t,A(A({},qn.ownDefaults),e))}static createControls(){return{controls:yy()}}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(Hs)&&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:T}=v[x];f+=S.length,u+=p+T-o,u>_&&!m?(l.push(g),g=[],u=T,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])}}C(qn,"type","Textbox"),C(qn,"textLayoutProperties",[...pi.textLayoutProperties,"width"]),C(qn,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),H.setClass(qn);class t0 extends Ec{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}=Is(Sm(s,i)),h=new k(r,o);if(i.absolutePositioned)return{center:Xn(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 k,correction:u=new k}=this.calcBoundingBox(e,t)||{};return{center:d.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}C(t0,"type","clip-path"),H.setClass(t0);class e0 extends Ec{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new k(s.width||i.x,s.height||i.y)}}C(e0,"type","fixed"),H.setClass(e0);class z_ extends za{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 $n extends Bs{static getDefaults(){return A(A({},super.getDefaults()),$n.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,$n.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new z_})}_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))?(ai("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===tg?s.forEach(i=>{i._onAfterObjectsChange(Ac,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=A(A({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()}}C($n,"type","ActiveSelection"),C($n,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),H.setClass($n),H.setClass($n,"activeSelection");class V_{constructor(){C(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 s0{constructor(){let{tileSize:t=ot.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};C(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),C(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=Pt();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 cg;function G_(){const{WebGLProbe:a}=Rs();return a.queryWebGL(Pt()),ot.enableGLFiltering&&a.isSupported(ot.textureSize)?new s0({tileSize:ot.textureSize}):new V_}function dg(){return!cg&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(cg=G_()),cg}const U_=["filters","resizeFilter","src","crossOrigin","type"],i0=["cropX","cropY"];class ae extends re{static getDefaults(){return A(A({},super.getDefaults()),ae.ownDefaults)}constructor(t,e){super(),C(this,"_lastScaleX",1),C(this,"_lastScaleY",1),C(this,"_filterScalingX",1),C(this,"_filterScalingY",1),this.filters=[],Object.assign(this,ae.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(sn()),this.setElement(typeof t=="string"?(this.canvas&&us(this.canvas.getElement())||ho()).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(ae.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=dg(!1);e instanceof s0&&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&&Rs().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())}),A(A({},super.toObject([...i0,...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=sn();n.push('<clipPath id="imageCrop_'+l+`">
49
+ `]}}static async fromElement(t,e,s){const i=ui(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(A(A({},xt(i,k_)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}C(fi,"type","Circle"),C(fi,"cacheProperties",[...di,...Vm]),C(fi,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),C(fi,"ATTRIBUTE_NAMES",["cx","cy","r",...rn]),H.setClass(fi),H.setSVGClass(fi);const M_=["x1","y1","x2","y2"],D_=["x1","y1","x2","y2"],rg=["x1","x2","y1","y2"];class Un extends re{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,Un.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(ct,r),typeof o=="number"&&this.set(ke,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}=Is([{x:t,y:e},{x:s,y:i}]),l=new k(n+o/2,r+h/2);this.setPositionByOrigin(l,Q,Q)}_set(t,e){return super._set(t,e),rg.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;Ze(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 k((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return A(A({},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=ui(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,D_);return this._fromObject(A(A({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}C(Un,"type","Line"),C(Un,"cacheProperties",[...di,...rg]),C(Un,"ATTRIBUTE_NAMES",rn.concat(rg)),H.setClass(Un),H.setSVGClass(Un);class Yn extends re{static getDefaults(){return A(A({},super.getDefaults()),Yn.ownDefaults)}constructor(t){super(),Object.assign(this,Yn.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),'" />']}}C(Yn,"type","Triangle"),C(Yn,"ownDefaults",{width:100,height:100}),H.setClass(Yn),H.setSVGClass(Yn);const Gm=["rx","ry"];class pi extends re{static getDefaults(){return A(A({},super.getDefaults()),pi.ownDefaults)}constructor(t){super(),Object.assign(this,pi.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(ye)}getRy(){return this.get("ry")*this.get(je)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Gm,...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,li,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=ui(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function O_(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}C(pi,"type","Ellipse"),C(pi,"cacheProperties",[...di,...Gm]),C(pi,"ownDefaults",{rx:0,ry:0}),C(pi,"ATTRIBUTE_NAMES",[...rn,"cx","cy","rx","ry"]),H.setClass(pi),H.setSVGClass(pi);const P_=["left","top"],Um={exactBoundingBox:!1};class ms extends re{static getDefaults(){return A(A({},super.getDefaults()),ms.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),C(this,"strokeDiff",void 0),Object.assign(this,ms.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(ct,s),typeof i=="number"&&this.set(ke,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return hm(this.points,t,this.isOpen())}_calcDimensions(t){t=A({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 k,strokeOffset:new k,strokeDiff:new k};const s=Is(e),i=La(A(A({},t),{},{scaleX:1,scaleY:1})),n=Is(this.points.map(l=>ne(l,i,!0))),r=new k(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(kt(this.skewX)),h-=o*Math.tan(kt(this.skewY))),A(A({},s),{},{pathOffset:new k(o,h),strokeOffset:new k(n.left,n.top).subtract(new k(s.left,s.top)).multiply(r),strokeDiff:new k(s.width,s.height).subtract(new k(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Is(this.points);return new k(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 k(e+i/2,s+n/2),Q,Q)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new k(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 k((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new k((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new k(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===ye||t===je)&&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 A(A({},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=ot.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(it(this.points[n].x-e,i),",",it(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(O_(t.getAttribute("points")),A(A({},xt(ui(t,this.ATTRIBUTE_NAMES,s),P_)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}C(ms,"ownDefaults",Um),C(ms,"type","Polyline"),C(ms,"layoutProperties",[lo,co,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),C(ms,"cacheProperties",[...di,"points"]),C(ms,"ATTRIBUTE_NAMES",[...rn]),H.setClass(ms),H.setSVGClass(ms);class Oc extends ms{isOpen(){return!1}}C(Oc,"ownDefaults",Um),C(Oc,"type","Polygon"),H.setClass(Oc),H.setSVGClass(Oc);const Ym=["fontSize","fontWeight","fontFamily","fontStyle"],qm=["underline","overline","linethrough"],$m=[...Ym,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],Km=[...$m,...qm,"textBackgroundColor","direction"],L_=[...Ym,...qm,_e,"strokeWidth",Ot,"deltaY","textBackgroundColor"],F_={_reNewline:wu,_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:ct,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:ct,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},Hs="justify",Pc="justify-left",Ga="justify-right",Ua="justify-center";class Qm extends re{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=ku(A(A({},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 A(A({},Hn(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]}}C(Qm,"_styleProperties",L_);const R_=/ +/g,I_=/"/g;function og(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]:ot.NUM_FRACTION_DIGITS;const g=ja(Ot,n,!1),[f,p,m,_]=[o,h,l,d].map(v=>it(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 j_=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let ag;class oe extends Qm{static getDefaults(){return A(A({},super.getDefaults()),oe.ownDefaults)}constructor(t,e){super(),C(this,"__charBounds",[]),Object.assign(this,oe.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=sg(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(Hs)&&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===Hs||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===_e?(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 Q:t.textBaseline="middle";break;case"ascender":t.textBaseline=ke;break;case"descender":t.textBaseline=_u}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=Da.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(!ag){const m=Pt();m.width=m.height=0,ag=m.getContext("2d")}return ag}();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===Dt,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 ct:d=n?u-i:0;break;case Q:d=(u-i)/2;break;case Dt: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=Rm(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===Dt?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(Ot))&&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(Hs),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="",T=0;if(e.save(),f!==this.direction&&(e.canvas.setAttribute("dir",u?"ltr":"rtl"),e.direction=u?"ltr":"rtl",e.textAlign=u?ct:Dt),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,M=s.length-1;E<=M;E++)v=E===M||this.charSpacing||l,S+=s[E],_=this.__charBounds[r][E],T===0?(i+=g*(_.kernedWidth-_.width),T+=_.width):T+=_.kernedWidth,h&&!v&&this._reSpaceAndTab.test(s[E])&&(v=!0),v||(p=p||this.getCompleteStyleDeclaration(r,E),m=this.getCompleteStyleDeclaration(r,E+1),v=Sc(p,m,!1)),v&&(l?(e.save(),e.translate(_.renderLeft,_.renderTop),e.rotate(_.angle),this._renderChar(t,e,r,E,S,-T/2,0),e.restore()):(x=i,this._renderChar(t,e,r,E,S,x,n)),S="",p=m,i+=g*T,T=0);e.restore()}_applyPatternGradientTransformText(t){const e=Pt(),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 Ze(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===Hs||i===Ua&&!r||i===Ga&&!r||i===Pc&&!r?0:(i===Q&&(o=s/2),i===Dt&&(o=s),i===Ua&&(o=s/2),i===Ga&&(o=s),n==="rtl"&&(i===Dt||i===Hs||i===Ga?o=0:i===ct||i===Pc?o=-s:i!==Q&&i!==Ua||(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,Ot);const T=s+g*(1-this._fontSizeFraction);let E=this.getHeightOfChar(h,0),M=this.getValueOfPropertyAt(h,0,"deltaY");for(let O=0,R=u.length;O<R;O++){const D=this.__charBounds[h][O];p=this.getValueOfPropertyAt(h,O,e),m=this.getValueOfPropertyAt(h,O,Ot);const L=this.getHeightOfChar(h,O),F=this.getValueOfPropertyAt(h,O,"deltaY");if(n&&p&&m)t.save(),t.fillStyle=S,t.translate(D.renderLeft,D.renderTop),t.rotate(D.angle),t.fillRect(-D.kernedWidth/2,o*L+F,D.kernedWidth,this.fontSize/15),t.restore();else if((p!==x||m!==S||L!==E||F!==M)&&v>0){let I=i+f+_;this.direction==="rtl"&&(I=this.width-I-v),x&&S&&(t.fillStyle=S,t.fillRect(I,T+o*E+M,v,this.fontSize/15)),_=D.left,v=D.width,x=p,S=m,E=L,M=F}else v+=D.kernedWidth}let P=i+f+_;this.direction==="rtl"&&(P=this.width-P-v),t.fillStyle=m,p&&m&&t.fillRect(P,T+o*E+M,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(",")||oe.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 xc(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 A(A({},super.toObject([...Km,...t])),{},{styles:cm(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=ui(t,oe.ATTRIBUTE_NAMES,s),n=A(A({},e),i),{textAnchor:r=ct,textDecoration:o="",dx:h=0,dy:l=0,top:d=0,left:u=0,fontSize:g=yu,strokeWidth:f=1}=n,p=xt(n,j_),m=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),A({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===Q&&(S=m.getScaledWidth()/2),r===Dt&&(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(A(A({},t),{},{styles:dm(t.styles||{},t.text)}),{extraParam:"text"})}}C(oe,"textLayoutProperties",$m),C(oe,"cacheProperties",[...di,...Km]),C(oe,"ownDefaults",F_),C(oe,"type","Text"),C(oe,"genericFonts",["sans-serif","serif","cursive","fantasy","monospace"]),C(oe,"ATTRIBUTE_NAMES",rn.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),nm(oe,[class extends Ip{_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(I_,"'"),'" '):"",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(...og(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(R_)),n=i?'style="'.concat(i,'"'):"",r=t.deltaY,o=r?' dy="'.concat(it(r,ot.NUM_FRACTION_DIGITS),'" '):"";return'<tspan x="'.concat(it(e,ot.NUM_FRACTION_DIGITS),'" y="').concat(it(s,ot.NUM_FRACTION_DIGITS),'" ').concat(o).concat(n,">").concat(lm(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Hs),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=Sc(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(...og(l,e+h,s,o,n)),h=u,o=g,l=r):o+=f}r&&a.push(...og(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?ja(_e,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?ja(Ot,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter(t=>a[t.replace("-","")]).join(" ")}}]),H.setClass(oe),H.setSVGClass(oe);class N_{constructor(t){C(this,"target",void 0),C(this,"__mouseDownInPlace",!1),C(this,"__dragStartFired",!1),C(this,"__isDraggingOver",!1),C(this,"__dragStartSelection",void 0),C(this,"__dragImageDisposer",void 0),C(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 k(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),d=new k(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 k(f.left,f.top)),m=o.viewportTransform,_=p.add(u).transform(m,!0),v=r.backgroundColor,x=Ku(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 T=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=v,r.styles=x,r.dirty=!0,Na(T,{position:"fixed",left:"".concat(-T.width,"px"),border:be,width:"".concat(T.width/g,"px"),height:"".concat(T.height/g,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{T.remove()},us(t.target||this.target.hiddenTextarea).body.appendChild(T),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(T,_.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=A({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(ic,{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)||be;h===be?(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(ic,{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 Jm=/[ \n\.,;!\?\-]/;class B_ extends oe{constructor(){super(...arguments),C(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 Hu({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||!wu.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!Jm.test(n);)i+=e,n=s[i];return e===-1&&Jm.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;us(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 k(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new k(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(rc),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:A({},i[s-1])}:l?this.styles[t+s]={0:A({},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?A({},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]=A({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=A({},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=ct:this._selectionDirection===Dt&&(this._selectionDirection=ct,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Dt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Dt:this._selectionDirection===ct&&(this._selectionDirection=Dt,this.selectionStart=e),this.selectionEnd=s)}}class H_ extends B_{initHiddenTextarea(){const t=this.canvas&&us(this.canvas.getElement())||ho(),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(ic),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}=Rs();e&&v.join("")===x.copiedText&&!ot.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}=Rs();t.copiedText=this.getSelectedText(),ot.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===Dt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=zn(0,this.selectionStart,i),this.selectionEnd=zn(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===ct?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=ct,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Dt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=ct,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===ct&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Dt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Dt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const hg=a=>!!a.button;class W_ extends H_{constructor(){super(...arguments),C(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 N_(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),Pu(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&&!hg(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&&!hg(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||hg(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(Me(this.calcTransformMatrix())).add(new k(-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 Lc="moveCursorUp",Fc="moveCursorDown",Rc="moveCursorLeft",Ic="moveCursorRight",jc="exitEditing",X_=A({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:jc,27:jc,33:Lc,34:Fc,35:Ic,36:Rc,37:Rc,38:Lc,39:Ic,40:Fc},keysMapRtl:{9:jc,27:jc,33:Lc,34:Fc,35:Rc,36:Ic,37:Ic,38:Lc,39:Rc,40:Fc},ctrlKeysMapDown:{65:"selectAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class mi extends W_{static getDefaults(){return A(A({},super.getDefaults()),mi.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,A(A({},mi.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 ig&&this.canvas.textEditingManager.remove(this),e instanceof ig&&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===Dt||this.textAlign===Hs||this.textAlign===Ga?h.left*=-1:this.textAlign===ct||this.textAlign===Pc?h.left=r-(s>0?s:0):this.textAlign!==Q&&this.textAlign!==Ua||(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,Ot),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(Hs),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,T=m,E=0;const M=x-v;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",T=1,E=m):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Dt||this.textAlign===Hs||this.textAlign===Ga?S=this.width-S-M:this.textAlign===ct||this.textAlign===Pc?S=s.left+p-x:this.textAlign!==Q&&this.textAlign!==Ua||(S=s.left+p-x)),t.fillRect(S,s.top+s.topOffset+E,M,T),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,Ot)}_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()}}C(mi,"ownDefaults",X_),C(mi,"type","IText"),H.setClass(mi),H.setClass(mi,"i-text");class qn extends mi{static getDefaults(){return A(A({},super.getDefaults()),qn.ownDefaults)}constructor(t,e){super(t,A(A({},qn.ownDefaults),e))}static createControls(){return{controls:yy()}}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(Hs)&&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:T}=v[x];f+=S.length,u+=p+T-o,u>_&&!m?(l.push(g),g=[],u=T,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])}}C(qn,"type","Textbox"),C(qn,"textLayoutProperties",[...mi.textLayoutProperties,"width"]),C(qn,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),H.setClass(qn);class Zm extends Ec{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}=Is(xm(s,i)),h=new k(r,o);if(i.absolutePositioned)return{center:Xn(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 k,correction:u=new k}=this.calcBoundingBox(e,t)||{};return{center:d.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}C(Zm,"type","clip-path"),H.setClass(Zm);class t0 extends Ec{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new k(s.width||i.x,s.height||i.y)}}C(t0,"type","fixed"),H.setClass(t0);class z_ extends za{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 $n extends Bs{static getDefaults(){return A(A({},super.getDefaults()),$n.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,$n.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new z_})}_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))?(hi("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===Zu?s.forEach(i=>{i._onAfterObjectsChange(Ac,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=A(A({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()}}C($n,"type","ActiveSelection"),C($n,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),H.setClass($n),H.setClass($n,"activeSelection");class V_{constructor(){C(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 e0{constructor(){let{tileSize:t=ot.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};C(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),C(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=Pt();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 lg;function G_(){const{WebGLProbe:a}=Rs();return a.queryWebGL(Pt()),ot.enableGLFiltering&&a.isSupported(ot.textureSize)?new e0({tileSize:ot.textureSize}):new V_}function cg(){return!lg&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(lg=G_()),lg}const U_=["filters","resizeFilter","src","crossOrigin","type"],s0=["cropX","cropY"];class ae extends re{static getDefaults(){return A(A({},super.getDefaults()),ae.ownDefaults)}constructor(t,e){super(),C(this,"_lastScaleX",1),C(this,"_lastScaleY",1),C(this,"_filterScalingX",1),C(this,"_filterScalingY",1),this.filters=[],Object.assign(this,ae.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(sn()),this.setElement(typeof t=="string"?(this.canvas&&us(this.canvas.getElement())||ho()).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(ae.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=cg(!1);e instanceof e0&&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&&Rs().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())}),A(A({},super.toObject([...s0,...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=sn();n.push('<clipPath id="imageCrop_'+l+`">
58
58
  `,' <rect x="'+s+'" y="'+i+'" width="'+this.width+'" height="'+this.height+`" />
59
59
  `,`</clipPath>
60
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
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!==Ot?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 Fa(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=Pt(),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,dg().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=Pt();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);dg().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=Ou(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===be&&t.alignY===be?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=Am(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=Tm(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,U_);return Promise.all([Fa(n,A(A({},e),{},{crossOrigin:r})),s&&po(s,e),i&&po([i],e),Ra(h,e)]).then(l=>{let[d,u=[],[g]=[],f={}]=l;return new this(d,A(A({},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 Fa(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=di(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"],e,i).catch(n=>(ai("log","Unable to parse Image",n),null))}}function ug(a){if(!ey.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&&$p.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("+we(d||"0")+" "+we(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=we(h),v.height=we(l),v;const x=t.match($p);r=-parseFloat(x[1]),o=-parseFloat(x[2]);const S=parseFloat(x[3]),T=parseFloat(x[4]);v.minX=r,v.minY=o,v.viewBoxWidth=S,v.viewBoxHeight=T,f?(v.width=S,v.height=T):(v.width=we(h),v.height=we(l),i=v.width/S,n=v.height/T);const E=Ou(a.getAttribute("preserveAspectRatio")||"");if(E.alignX!==be&&(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-T*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("+we(d||"0")+" "+we(u||"0")+") "),e=p+" matrix("+i+" 0 0 "+n+" "+(r*i+m)+" "+(o*n+_)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(Uu,"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}C(ae,"type","Image"),C(ae,"cacheProperties",[...ci,...i0]),C(ae,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),C(ae,"CSS_CANVAS","canvas-img"),C(ae,"ATTRIBUTE_NAMES",[...rn,"x","y","width","height","preserveAspectRatio","xlink:href","crossOrigin","image-rendering"]),H.setClass(ae),H.setSVGClass(ae);const Nc=a=>a.tagName.replace("svg:",""),Y_=bc(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function n0(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 q_=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],gg="xlink:href";function r0(a,t){var e;const s=((e=t.getAttribute(gg))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(gg)&&r0(a,i),i&&(q_.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(gg)}const $_=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function K_(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]=A(A({},i[d]||{}),h))})})}return i}const o0=a=>H.getSVGClass(Nc(a).toLowerCase());class Q_{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=n0(r,$_),h={};let l=o.length;for(;l--;){const d=o[l];d.getAttribute("xlink:href")&&r0(r,d);const u=d.getAttribute("id");u&&(h[u]=d)}return h}(i),this.cssRules=K_(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=o0(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,Ot),this.resolveGradient(s,t,_e),s instanceof ae&&s._originalElement?Mc(s,s.parsePreserveAspectRatioAttribute()):Mc(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=Va.fromElement(i,t,A(A({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e){const s=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(s){const i=Me(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=Cc("".concat(r.getAttribute("transform")||""," ").concat(n.getAttribute("originalTransform")||""));n.setAttribute("transform","matrix(".concat(o.join(","),")"));const h=await Promise.all(s.map(v=>o0(v).fromElement(v,this.options,this.cssRules).then(x=>(Mc(x),x.fillRule=x.clipRule,delete x.clipRule,x)))),l=h.length===1?h[0]:new Bs(h),d=Lt(i,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,r);const{scaleX:u,scaleY:g,angle:f,skewX:p,translateX:m,translateY:_}=Bn(d);l.set({flipX:!1,flipY:!1}),l.set({scaleX:u,scaleY:g,angle:f,skewX:p,skewY:0}),l.setPositionByOrigin(new k(m,_),Q,Q),t.clipPath=l}else delete t.clipPath}}const a0=a=>ty.test(Nc(a)),fg=()=>({objects:[],elements:[],options:{},allElements:[]});async function J_(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return ai("log",new vu("parseSVGDocument")),fg();const i=a.documentElement;(function(d){const u=n0(d,["use","svg:use"]),g=["x","y","xlink:href","href","transform"];for(const f of u){const p=f.attributes,m={};for(const R of p)R.value&&(m[R.name]=R.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,T={};for(const R of S)R.value&&(T[R.name]=R.value);const{x:E=0,y:M=0,transform:P=""}=m,O="".concat(P," ").concat(T.transform||""," translate(").concat(E,", ").concat(M,")");if(ug(x),/^svg$/i.test(x.nodeName)){const R=x.ownerDocument.createElementNS(Uu,"g");Object.entries(T).forEach(D=>{let[L,F]=D;return R.setAttributeNS(Uu,L,F)}),R.append(...x.childNodes),x=R}for(const R of p){if(!R)continue;const{name:D,value:L}=R;if(!g.includes(D))if(D==="style"){const F={};Zu(L,F),Object.entries(T).forEach(X=>{let[Y,J]=X;F[Y]=J}),Zu(T.style||"",F);const I=Object.entries(F).map(X=>X.join(":")).join(";");x.setAttribute(D,I)}else!T[D]&&x.setAttribute(D,L)}x.setAttribute("transform",O),x.setAttribute("instantiated_by_use","1"),x.removeAttribute("id"),f.parentNode.replaceChild(x,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=A(A({},ug(i)),{},{crossOrigin:e,signal:s}),o=n.filter(d=>(ug(d),a0(d)&&!function(u){let g=u;for(;g&&(g=g.parentElement);)if(g&&g.nodeName&&Y_.test(Nc(g))&&!g.getAttribute("instantiated_by_use"))return!0;return!1}(d)));if(!o||o&&!o.length)return A(A({},fg()),{},{options:r,allElements:n});const h={};return n.filter(d=>Nc(d)==="clipPath").forEach(d=>{d.setAttribute("originalTransform",d.getAttribute("transform")||"");const u=d.getAttribute("id");h[u]=Array.from(d.getElementsByTagName("*")).filter(g=>a0(g))}),{objects:await new Q_(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function Z_(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{Bm(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>J_(s,t,e)).catch(()=>fg())}const Bc=a=>a.webgl!==void 0,pg="precision highp float",tw=`
63
- `.concat(pg,`;
62
+ `)],this.fill=l}return n=this.paintFirst!==Ot?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 Fa(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=Pt(),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,cg().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=Pt();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);cg().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=Du(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===be&&t.alignY===be?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=Cm(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=Am(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,U_);return Promise.all([Fa(n,A(A({},e),{},{crossOrigin:r})),s&&po(s,e),i&&po([i],e),Ra(h,e)]).then(l=>{let[d,u=[],[g]=[],f={}]=l;return new this(d,A(A({},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 Fa(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=ui(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"],e,i).catch(n=>(hi("log","Unable to parse Image",n),null))}}function dg(a){if(!ey.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&&qp.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("+we(d||"0")+" "+we(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=we(h),v.height=we(l),v;const x=t.match(qp);r=-parseFloat(x[1]),o=-parseFloat(x[2]);const S=parseFloat(x[3]),T=parseFloat(x[4]);v.minX=r,v.minY=o,v.viewBoxWidth=S,v.viewBoxHeight=T,f?(v.width=S,v.height=T):(v.width=we(h),v.height=we(l),i=v.width/S,n=v.height/T);const E=Du(a.getAttribute("preserveAspectRatio")||"");if(E.alignX!==be&&(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-T*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("+we(d||"0")+" "+we(u||"0")+") "),e=p+" matrix("+i+" 0 0 "+n+" "+(r*i+m)+" "+(o*n+_)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(Gu,"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}C(ae,"type","Image"),C(ae,"cacheProperties",[...di,...s0]),C(ae,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),C(ae,"CSS_CANVAS","canvas-img"),C(ae,"ATTRIBUTE_NAMES",[...rn,"x","y","width","height","preserveAspectRatio","xlink:href","crossOrigin","image-rendering"]),H.setClass(ae),H.setSVGClass(ae);const Nc=a=>a.tagName.replace("svg:",""),Y_=bc(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function i0(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 q_=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],ug="xlink:href";function n0(a,t){var e;const s=((e=t.getAttribute(ug))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(ug)&&n0(a,i),i&&(q_.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(ug)}const $_=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function K_(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]=A(A({},i[d]||{}),h))})})}return i}const r0=a=>H.getSVGClass(Nc(a).toLowerCase());class Q_{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=i0(r,$_),h={};let l=o.length;for(;l--;){const d=o[l];d.getAttribute("xlink:href")&&n0(r,d);const u=d.getAttribute("id");u&&(h[u]=d)}return h}(i),this.cssRules=K_(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=r0(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,Ot),this.resolveGradient(s,t,_e),s instanceof ae&&s._originalElement?Mc(s,s.parsePreserveAspectRatioAttribute()):Mc(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=Va.fromElement(i,t,A(A({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e){const s=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(s){const i=Me(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=Cc("".concat(r.getAttribute("transform")||""," ").concat(n.getAttribute("originalTransform")||""));n.setAttribute("transform","matrix(".concat(o.join(","),")"));const h=await Promise.all(s.map(v=>r0(v).fromElement(v,this.options,this.cssRules).then(x=>(Mc(x),x.fillRule=x.clipRule,delete x.clipRule,x)))),l=h.length===1?h[0]:new Bs(h),d=Lt(i,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,r);const{scaleX:u,scaleY:g,angle:f,skewX:p,translateX:m,translateY:_}=Bn(d);l.set({flipX:!1,flipY:!1}),l.set({scaleX:u,scaleY:g,angle:f,skewX:p,skewY:0}),l.setPositionByOrigin(new k(m,_),Q,Q),t.clipPath=l}else delete t.clipPath}}const o0=a=>ty.test(Nc(a)),gg=()=>({objects:[],elements:[],options:{},allElements:[]});async function J_(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return hi("log",new mu("parseSVGDocument")),gg();const i=a.documentElement;(function(d){const u=i0(d,["use","svg:use"]),g=["x","y","xlink:href","href","transform"];for(const f of u){const p=f.attributes,m={};for(const R of p)R.value&&(m[R.name]=R.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,T={};for(const R of S)R.value&&(T[R.name]=R.value);const{x:E=0,y:M=0,transform:P=""}=m,O="".concat(P," ").concat(T.transform||""," translate(").concat(E,", ").concat(M,")");if(dg(x),/^svg$/i.test(x.nodeName)){const R=x.ownerDocument.createElementNS(Gu,"g");Object.entries(T).forEach(D=>{let[L,F]=D;return R.setAttributeNS(Gu,L,F)}),R.append(...x.childNodes),x=R}for(const R of p){if(!R)continue;const{name:D,value:L}=R;if(!g.includes(D))if(D==="style"){const F={};Ju(L,F),Object.entries(T).forEach(X=>{let[Y,J]=X;F[Y]=J}),Ju(T.style||"",F);const I=Object.entries(F).map(X=>X.join(":")).join(";");x.setAttribute(D,I)}else!T[D]&&x.setAttribute(D,L)}x.setAttribute("transform",O),x.setAttribute("instantiated_by_use","1"),x.removeAttribute("id"),f.parentNode.replaceChild(x,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=A(A({},dg(i)),{},{crossOrigin:e,signal:s}),o=n.filter(d=>(dg(d),o0(d)&&!function(u){let g=u;for(;g&&(g=g.parentElement);)if(g&&g.nodeName&&Y_.test(Nc(g))&&!g.getAttribute("instantiated_by_use"))return!0;return!1}(d)));if(!o||o&&!o.length)return A(A({},gg()),{},{options:r,allElements:n});const h={};return n.filter(d=>Nc(d)==="clipPath").forEach(d=>{d.setAttribute("originalTransform",d.getAttribute("transform")||"");const u=d.getAttribute("id");h[u]=Array.from(d.getElementsByTagName("*")).filter(g=>o0(g))}),{objects:await new Q_(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function Z_(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{Nm(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>J_(s,t,e)).catch(()=>gg())}const Bc=a=>a.webgl!==void 0,fg="precision highp float",tw=`
63
+ `.concat(fg,`;
64
64
  varying vec2 vTexCoord;
65
65
  uniform sampler2D uTexture;
66
66
  void main() {
67
67
  gl_FragColor = texture2D(uTexture, vTexCoord);
68
- }`),ew=["type"],sw=["type"],iw=new RegExp(pg,"g");class Bt{get type(){return this.constructor.type}constructor(){let t=xt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ew);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return tw}getVertexSource(){return`
68
+ }`),ew=["type"],sw=["type"],iw=new RegExp(fg,"g");class Ht{get type(){return this.constructor.type}constructor(){let t=xt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ew);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return tw}getVertexSource(){return`
69
69
  attribute vec2 aPosition;
70
70
  varying vec2 vTexCoord;
71
71
  void main() {
72
72
  vTexCoord = aPosition;
73
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"}}=Rs();i!=="highp"&&(e=e.replace(iw,pg.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 Fs("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Fs("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 Fs("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 Fs('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){Bc(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=Pt();e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}}toObject(){const t=Object.keys(this.constructor.defaults);return A({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,sw))}}C(Bt,"type","BaseFilter"),C(Bt,"uniformLocations",[]);const nw={multiply:`gl_FragColor.rgb *= uColor.rgb;
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"}}=Rs();i!=="highp"&&(e=e.replace(iw,fg.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 Fs("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Fs("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 Fs("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 Fs('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){Bc(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=Pt();e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}}toObject(){const t=Object.keys(this.constructor.defaults);return A({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,sw))}}C(Ht,"type","BaseFilter"),C(Ht,"uniformLocations",[]);const nw={multiply:`gl_FragColor.rgb *= uColor.rgb;
75
75
  `,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
76
76
  `,add:`gl_FragColor.rgb += uColor.rgb;
77
77
  `,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
@@ -98,7 +98,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
98
98
  `,tint:`
99
99
  gl_FragColor.rgb *= (1.0 - uColor.a);
100
100
  gl_FragColor.rgb += uColor.rgb;
101
- `};class Hc extends Bt{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
101
+ `};class Hc extends Ht{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
102
102
  precision highp float;
103
103
  uniform sampler2D uTexture;
104
104
  uniform vec4 uColor;
@@ -136,7 +136,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
136
136
  color.a = color2.a;
137
137
  gl_FragColor = color;
138
138
  }
139
- `},ow=["type","image"];class Wc extends Bt{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return rw[this.mode]}getVertexSource(){return`
139
+ `},ow=["type","image"];class Wc extends Ht{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return rw[this.mode]}getVertexSource(){return`
140
140
  attribute vec2 aPosition;
141
141
  varying vec2 vTexCoord;
142
142
  varying vec2 vTexCoord2;
@@ -146,7 +146,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
146
146
  vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
147
147
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
148
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=Pt());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 A(A({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=xt(t,ow);return ae.fromObject(i,e).then(r=>new this(A(A({},n),{},{image:r})))}}C(Wc,"type","BlendImage"),C(Wc,"defaults",{mode:"multiply",alpha:1}),C(Wc,"uniformLocations",["uTransformMatrix","uImage"]),H.setClass(Wc);class Xc extends Bt{getFragmentSource(){return`
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=Pt());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 A(A({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=xt(t,ow);return ae.fromObject(i,e).then(r=>new this(A(A({},n),{},{image:r})))}}C(Wc,"type","BlendImage"),C(Wc,"defaults",{mode:"multiply",alpha:1}),C(Wc,"uniformLocations",["uTransformMatrix","uImage"]),H.setClass(Wc);class Xc extends Ht{getFragmentSource(){return`
150
150
  precision highp float;
151
151
  uniform sampler2D uTexture;
152
152
  uniform vec2 uDelta;
@@ -169,7 +169,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
169
169
  }
170
170
  gl_FragColor = color / total;
171
171
  }
172
- `}applyTo(t){Bc(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=Pt(),i.blurLayer2=Pt());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}}C(Xc,"type","Blur"),C(Xc,"defaults",{blur:0}),C(Xc,"uniformLocations",["uDelta"]),H.setClass(Xc);class zc extends Bt{getFragmentSource(){return`
172
+ `}applyTo(t){Bc(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=Pt(),i.blurLayer2=Pt());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}}C(Xc,"type","Blur"),C(Xc,"defaults",{blur:0}),C(Xc,"uniformLocations",["uDelta"]),H.setClass(Xc);class zc extends Ht{getFragmentSource(){return`
173
173
  precision highp float;
174
174
  uniform sampler2D uTexture;
175
175
  uniform float uBrightness;
@@ -179,7 +179,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
179
179
  color.rgb += uBrightness;
180
180
  gl_FragColor = color;
181
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)}}C(zc,"type","Brightness"),C(zc,"defaults",{brightness:0}),C(zc,"uniformLocations",["uBrightness"]),H.setClass(zc);class Co extends Bt{getFragmentSource(){return`
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)}}C(zc,"type","Brightness"),C(zc,"defaults",{brightness:0}),C(zc,"uniformLocations",["uBrightness"]),H.setClass(zc);class Co extends Ht{getFragmentSource(){return`
183
183
  precision highp float;
184
184
  uniform sampler2D uTexture;
185
185
  varying vec2 vTexCoord;
@@ -190,7 +190,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
190
190
  color *= uColorMatrix;
191
191
  color += uConstants;
192
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 A(A({},super.toObject()),{},{matrix:[...this.matrix]})}}function Kn(a,t){var e;const s=(C(e=class extends Co{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),C(e,"defaults",{colorsOnly:!1,matrix:t}),e);return H.setClass(s,a),s}C(Co,"type","ColorMatrix"),C(Co,"defaults",{matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0}),C(Co,"uniformLocations",["uColorMatrix","uConstants"]),H.setClass(Co),Kn("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),Kn("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),Kn("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),Kn("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),Kn("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),Kn("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),Kn("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 h0 extends Bt{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){Bc(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=>H.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}C(h0,"type","Composed"),H.setClass(h0);class Vc extends Bt{getFragmentSource(){return`
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 A(A({},super.toObject()),{},{matrix:[...this.matrix]})}}function Kn(a,t){var e;const s=(C(e=class extends Co{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),C(e,"defaults",{colorsOnly:!1,matrix:t}),e);return H.setClass(s,a),s}C(Co,"type","ColorMatrix"),C(Co,"defaults",{matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0}),C(Co,"uniformLocations",["uColorMatrix","uConstants"]),H.setClass(Co),Kn("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),Kn("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),Kn("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),Kn("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),Kn("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),Kn("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),Kn("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 a0 extends Ht{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){Bc(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=>H.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}C(a0,"type","Composed"),H.setClass(a0);class Vc extends Ht{getFragmentSource(){return`
194
194
  precision highp float;
195
195
  uniform sampler2D uTexture;
196
196
  uniform float uContrast;
@@ -344,7 +344,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
344
344
  gl_FragColor = color;
345
345
  gl_FragColor.a = alpha;
346
346
  }
347
- `};class Gc extends Bt{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return aw[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,T,E,M,P,O;for(M=0;M<h;M++)for(E=0;E<o;E++){for(_=4*(M*o+E),g=0,f=0,p=0,m=0,O=0;O<n;O++)for(P=0;P<n;P++)x=M+O-r,v=E+P-r,x<0||x>=h||v<0||v>=o||(S=4*(x*o+v),T=i[O*n+P],g+=s[S]*T,f+=s[S+1]*T,p+=s[S+2]*T,u||(m+=s[S+3]*T));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 A(A({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}C(Gc,"type","Convolute"),C(Gc,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),C(Gc,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),H.setClass(Gc);const l0="Gamma";class Uc extends Bt{getFragmentSource(){return`
347
+ `};class Gc extends Ht{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return aw[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,T,E,M,P,O;for(M=0;M<h;M++)for(E=0;E<o;E++){for(_=4*(M*o+E),g=0,f=0,p=0,m=0,O=0;O<n;O++)for(P=0;P<n;P++)x=M+O-r,v=E+P-r,x<0||x>=h||v<0||v>=o||(S=4*(x*o+v),T=i[O*n+P],g+=s[S]*T,f+=s[S+1]*T,p+=s[S+2]*T,u||(m+=s[S+3]*T));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 A(A({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}C(Gc,"type","Convolute"),C(Gc,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),C(Gc,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),H.setClass(Gc);const h0="Gamma";class Uc extends Ht{getFragmentSource(){return`
348
348
  precision highp float;
349
349
  uniform sampler2D uTexture;
350
350
  uniform vec3 uGamma;
@@ -358,7 +358,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
358
358
  gl_FragColor = color;
359
359
  gl_FragColor.rgb *= color.a;
360
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:l0,gamma:this.gamma.concat()}}}C(Uc,"type",l0),C(Uc,"defaults",{gamma:[1,1,1]}),C(Uc,"uniformLocations",["uGamma"]),H.setClass(Uc);const hw={average:`
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:h0,gamma:this.gamma.concat()}}}C(Uc,"type",h0),C(Uc,"defaults",{gamma:[1,1,1]}),C(Uc,"uniformLocations",["uGamma"]),H.setClass(Uc);const hw={average:`
362
362
  precision highp float;
363
363
  uniform sampler2D uTexture;
364
364
  varying vec2 vTexCoord;
@@ -387,7 +387,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
387
387
  float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
388
388
  gl_FragColor = vec4(average, average, average, col.a);
389
389
  }
390
- `};class Yc extends Bt{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 hw[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}C(Yc,"type","Grayscale"),C(Yc,"defaults",{mode:"average"}),C(Yc,"uniformLocations",["uMode"]),H.setClass(Yc);class mg extends Co{calculateMatrix(){const t=this.rotation*Math.PI,e=cs(t),s=ds(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}}}C(mg,"type","HueRotation"),C(mg,"defaults",{rotation:0}),H.setClass(mg);class qc extends Bt{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`
390
+ `};class Yc extends Ht{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 hw[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}C(Yc,"type","Grayscale"),C(Yc,"defaults",{mode:"average"}),C(Yc,"uniformLocations",["uMode"]),H.setClass(Yc);class pg extends Co{calculateMatrix(){const t=this.rotation*Math.PI,e=cs(t),s=ds(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}}}C(pg,"type","HueRotation"),C(pg,"defaults",{rotation:0}),H.setClass(pg);class qc extends Ht{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
391
  precision highp float;
392
392
  uniform sampler2D uTexture;
393
393
  uniform int uInvert;
@@ -405,7 +405,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
405
405
  gl_FragColor = color;
406
406
  }
407
407
  }
408
- `}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}C(qc,"type","Invert"),C(qc,"defaults",{alpha:!1,invert:!0}),C(qc,"uniformLocations",["uInvert","uAlpha"]),H.setClass(qc);class $c extends Bt{getFragmentSource(){return`
408
+ `}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}C(qc,"type","Invert"),C(qc,"defaults",{alpha:!1,invert:!0}),C(qc,"uniformLocations",["uInvert","uAlpha"]),H.setClass(qc);class $c extends Ht{getFragmentSource(){return`
409
409
  precision highp float;
410
410
  uniform sampler2D uTexture;
411
411
  uniform float uStepH;
@@ -420,7 +420,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
420
420
  color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
421
421
  gl_FragColor = color;
422
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}}C($c,"type","Noise"),C($c,"defaults",{noise:0}),C($c,"uniformLocations",["uNoise","uSeed"]),H.setClass($c);class Kc extends Bt{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`
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}}C($c,"type","Noise"),C($c,"defaults",{noise:0}),C($c,"uniformLocations",["uNoise","uSeed"]),H.setClass($c);class Kc extends Ht{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
424
  precision highp float;
425
425
  uniform sampler2D uTexture;
426
426
  uniform float uBlocksize;
@@ -438,7 +438,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
438
438
  vec4 color = texture2D(uTexture, squareCoords);
439
439
  gl_FragColor = color;
440
440
  }
441
- `}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}C(Kc,"type","Pixelate"),C(Kc,"defaults",{blocksize:4}),C(Kc,"uniformLocations",["uBlocksize"]),H.setClass(Kc);class Qc extends Bt{getFragmentSource(){return`
441
+ `}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}C(Kc,"type","Pixelate"),C(Kc,"defaults",{blocksize:4}),C(Kc,"uniformLocations",["uBlocksize"]),H.setClass(Kc);class Qc extends Ht{getFragmentSource(){return`
442
442
  precision highp float;
443
443
  uniform sampler2D uTexture;
444
444
  uniform vec4 uLow;
@@ -450,7 +450,7 @@ void main() {
450
450
  gl_FragColor.a = 0.0;
451
451
  }
452
452
  }
453
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new ut(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 ut(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)}}C(Qc,"type","RemoveColor"),C(Qc,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),C(Qc,"uniformLocations",["uLow","uHigh"]),H.setClass(Qc);class Jc extends Bt{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`
453
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new ut(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 ut(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)}}C(Qc,"type","RemoveColor"),C(Qc,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),C(Qc,"uniformLocations",["uLow","uHigh"]),H.setClass(Qc);class Jc extends Ht{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
454
  precision highp float;
455
455
  uniform sampler2D uTexture;
456
456
  uniform vec2 uDelta;
@@ -466,7 +466,7 @@ void main() {
466
466
  `),`
467
467
  gl_FragColor = color / sum;
468
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){Bc(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=Pt());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(T){let E,M,P,O,R,D,L,F,I,X,Y;for(v.x=(T+.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),R=0,D=0,L=0,F=0,I=0,M=x.x-p;M<=x.x+p;M++)if(!(M<0||M>=e)){X=Math.floor(1e3*Math.abs(M-v.x)),_[X]||(_[X]={});for(let J=x.y-m;J<=x.y+m;J++)J<0||J>=s||(Y=Math.floor(1e3*Math.abs(J-v.y)),_[X][Y]||(_[X][Y]=l(Math.sqrt(Math.pow(X*g,2)+Math.pow(Y*f,2))/1e3)),P=_[X][Y],P>0&&(O=4*(J*e+M),R+=P,D+=P*r[O],L+=P*r[O+1],F+=P*r[O+2],I+=P*r[O+3]))}O=4*(E*i+T),h[O]=D/R,h[O+1]=L/R,h[O+2]=F/R,h[O+3]=I/R}return++T<i?S(T):o}(0)}bilinearFiltering(t,e,s,i,n){let r,o,h,l,d,u,g,f,p,m,_,v,x,S=0;const T=this.rcpScaleX,E=this.rcpScaleY,M=4*(e-1),P=t.imageData.data,O=t.ctx.createImageData(i,n),R=O.data;for(g=0;g<n;g++)for(f=0;f<i;f++)for(d=Math.floor(T*f),u=Math.floor(E*g),p=T*f-d,m=E*g-u,x=4*(u*e+d),_=0;_<4;_++)r=P[x+_],o=P[x+4+_],h=P[x+M+_],l=P[x+M+4+_],v=r*(1-p)*(1-m)+o*p*(1-m)+h*m*(1-p)+l*p*m,R[S++]=v;return O}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,T=0,E=0,M=0;const P=(f+.5)*o;for(let O=Math.floor(f*o);O<(f+1)*o;O++){const R=Math.abs(P-(O+.5))/l,D=(p+.5)*r,L=R*R;for(let F=Math.floor(p*r);F<(p+1)*r;F++){let I=Math.abs(D-(F+.5))/h;const X=Math.sqrt(L+I*I);X>1&&X<-1||(_=2*X*X*X-3*X*X+1,_>0&&(I=4*(F+O*e),M+=_*d[I+3],x+=_,d[I+3]<255&&(_=_*d[I+3]/250),S+=_*d[I],T+=_*d[I+1],E+=_*d[I+2],v+=_))}}g[m]=S/v,g[m+1]=T/v,g[m+2]=E/v,g[m+3]=M/x}return u}}C(Jc,"type","Resize"),C(Jc,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),C(Jc,"uniformLocations",["uDelta","uTaps"]),H.setClass(Jc);class Zc extends Bt{getFragmentSource(){return`
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){Bc(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=Pt());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(T){let E,M,P,O,R,D,L,F,I,X,Y;for(v.x=(T+.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),R=0,D=0,L=0,F=0,I=0,M=x.x-p;M<=x.x+p;M++)if(!(M<0||M>=e)){X=Math.floor(1e3*Math.abs(M-v.x)),_[X]||(_[X]={});for(let J=x.y-m;J<=x.y+m;J++)J<0||J>=s||(Y=Math.floor(1e3*Math.abs(J-v.y)),_[X][Y]||(_[X][Y]=l(Math.sqrt(Math.pow(X*g,2)+Math.pow(Y*f,2))/1e3)),P=_[X][Y],P>0&&(O=4*(J*e+M),R+=P,D+=P*r[O],L+=P*r[O+1],F+=P*r[O+2],I+=P*r[O+3]))}O=4*(E*i+T),h[O]=D/R,h[O+1]=L/R,h[O+2]=F/R,h[O+3]=I/R}return++T<i?S(T):o}(0)}bilinearFiltering(t,e,s,i,n){let r,o,h,l,d,u,g,f,p,m,_,v,x,S=0;const T=this.rcpScaleX,E=this.rcpScaleY,M=4*(e-1),P=t.imageData.data,O=t.ctx.createImageData(i,n),R=O.data;for(g=0;g<n;g++)for(f=0;f<i;f++)for(d=Math.floor(T*f),u=Math.floor(E*g),p=T*f-d,m=E*g-u,x=4*(u*e+d),_=0;_<4;_++)r=P[x+_],o=P[x+4+_],h=P[x+M+_],l=P[x+M+4+_],v=r*(1-p)*(1-m)+o*p*(1-m)+h*m*(1-p)+l*p*m,R[S++]=v;return O}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,T=0,E=0,M=0;const P=(f+.5)*o;for(let O=Math.floor(f*o);O<(f+1)*o;O++){const R=Math.abs(P-(O+.5))/l,D=(p+.5)*r,L=R*R;for(let F=Math.floor(p*r);F<(p+1)*r;F++){let I=Math.abs(D-(F+.5))/h;const X=Math.sqrt(L+I*I);X>1&&X<-1||(_=2*X*X*X-3*X*X+1,_>0&&(I=4*(F+O*e),M+=_*d[I+3],x+=_,d[I+3]<255&&(_=_*d[I+3]/250),S+=_*d[I],T+=_*d[I+1],E+=_*d[I+2],v+=_))}}g[m]=S/v,g[m+1]=T/v,g[m+2]=E/v,g[m+3]=M/x}return u}}C(Jc,"type","Resize"),C(Jc,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),C(Jc,"uniformLocations",["uDelta","uTaps"]),H.setClass(Jc);class Zc extends Ht{getFragmentSource(){return`
470
470
  precision highp float;
471
471
  uniform sampler2D uTexture;
472
472
  uniform float uSaturation;
@@ -480,7 +480,7 @@ void main() {
480
480
  color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
481
481
  gl_FragColor = color;
482
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}}C(Zc,"type","Saturation"),C(Zc,"defaults",{saturation:0}),C(Zc,"uniformLocations",["uSaturation"]),H.setClass(Zc);class td extends Bt{getFragmentSource(){return`
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}}C(Zc,"type","Saturation"),C(Zc,"defaults",{saturation:0}),C(Zc,"uniformLocations",["uSaturation"]),H.setClass(Zc);class td extends Ht{getFragmentSource(){return`
484
484
  precision highp float;
485
485
  uniform sampler2D uTexture;
486
486
  uniform float uVibrance;
@@ -495,15 +495,15 @@ void main() {
495
495
  color.b += max != color.b ? (max - color.b) * amt : 0.00;
496
496
  gl_FragColor = color;
497
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}}C(td,"type","Vibrance"),C(td,"defaults",{vibrance:0}),C(td,"uniformLocations",["uVibrance"]),H.setClass(td);var Ya={};Ya.d=(a,t)=>{for(var e in t)Ya.o(t,e)&&!Ya.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},Ya.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var $=globalThis.pdfjsLib={};Ya.d($,{AbortException:()=>Jn,AnnotationEditorLayer:()=>Kg,AnnotationEditorParamsType:()=>q,AnnotationEditorType:()=>nt,AnnotationEditorUIManager:()=>tr,AnnotationLayer:()=>nS,AnnotationMode:()=>an,CMapCompressionType:()=>yg,ColorPicker:()=>Sd,DOMSVGFactory:()=>Tg,DrawLayer:()=>Qg,FeatureTest:()=>De,GlobalWorkerOptions:()=>yi,ImageKind:()=>ed,InvalidPDFException:()=>d0,MissingPDFException:()=>Qn,OPS:()=>vs,PDFDataRangeTransport:()=>z0,PDFDateString:()=>y0,PDFWorker:()=>To,PasswordResponses:()=>uw,PermissionFlag:()=>dw,PixelsPerInch:()=>ln,RenderingCancelledException:()=>Eg,TextLayer:()=>sh,UnexpectedResponseException:()=>rd,Util:()=>z,VerbosityLevel:()=>sd,XfaLayer:()=>Y0,build:()=>Nx,createValidAbsoluteUrl:()=>mw,fetchData:()=>dd,getDocument:()=>Mx,getFilenameFromUrl:()=>Tw,getPdfFilenameFromUrl:()=>Ew,getXfaPageViewport:()=>kw,isDataScheme:()=>ud,isPdfFile:()=>kg,noContextMenu:()=>Oe,normalizeUnicode:()=>xw,setLayerDimensions:()=>Zn,shadow:()=>at,version:()=>jx});const he=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),c0=[1,0,0,1,0,0],vg=[.001,0,0,.001,0,0],lw=1e7,bg=1.35,Ne={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},an={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},cw="pdfjs_internal_editor_",nt={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},q={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},dw={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},le={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},ed={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Ht={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},qa={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},sd={ERRORS:0,WARNINGS:1,INFOS:5},yg={NONE:0,BINARY:1},vs={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},uw={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let id=sd.WARNINGS;function gw(a){Number.isInteger(a)&&(id=a)}function fw(){return id}function nd(a){id>=sd.INFOS&&console.log(`Info: ${a}`)}function Z(a){id>=sd.WARNINGS&&console.log(`Warning: ${a}`)}function ft(a){throw new Error(a)}function Wt(a,t){a||ft(t)}function pw(a){switch(a==null?void 0:a.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function mw(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=ww(a)}catch{}}const s=t?new URL(a,t):new URL(a);if(pw(s))return s}catch{}return null}function at(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const hn=function(){function t(e,s){this.constructor===t&&ft("Cannot initialize BaseException."),this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class _g extends hn{constructor(t,e){super(t,"PasswordException"),this.code=e}}class wg extends hn{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class d0 extends hn{constructor(t){super(t,"InvalidPDFException")}}class Qn extends hn{constructor(t){super(t,"MissingPDFException")}}class rd extends hn{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class vw extends hn{constructor(t){super(t,"FormatError")}}class Jn extends hn{constructor(t){super(t,"AbortException")}}function u0(a){(typeof a!="object"||(a==null?void 0:a.length)===void 0)&&ft("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 od(a){typeof a!="string"&&ft("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 bw(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function xg(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function yw(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function _w(){try{return new Function(""),!0}catch{return!1}}class De{static get isLittleEndian(){return at(this,"isLittleEndian",yw())}static get isEvalSupported(){return at(this,"isEvalSupported",_w())}static get isOffscreenCanvasSupported(){return at(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?at(this,"platform",{isMac:navigator.platform.includes("Mac")}):at(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){var t,e;return at(this,"isCSSRoundSupported",(e=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:e.call(t,"width: round(1.5px, 1px)"))}}const Sg=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class z{static makeHexColor(t,e,s){return`#${Sg[t]}${Sg[e]}${Sg[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,xi,of).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,xi,of).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}}xi=new WeakSet,Ud=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)},of=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,xi,Ud).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,xi,Ud).call(this,t,e,s,i,n,r,o,h,(-d+p)/m,g),y(this,xi,Ud).call(this,t,e,s,i,n,r,o,h,(-d-p)/m,g)},w(z,xi);function ww(a){return decodeURIComponent(escape(a))}let Cg=null,g0=null;function xw(a){return Cg||(Cg=/([\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,g0=new Map([["ſt","ſt"]])),a.replaceAll(Cg,(t,e,s)=>e?e.normalize("NFKC"):g0.get(s))}function Sw(){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 u0(a)}const f0="pdfjs_internal_id_",mi={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 ad{constructor(){this.constructor===ad&&ft("Cannot initialize BaseFilterFactory.")}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){}}const Zg=class Zg{constructor({enableHWA:t=!1}={}){w(this,oh,!1);this.constructor===Zg&&ft("Cannot initialize BaseCanvasFactory."),b(this,oh,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,oh)})}}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){ft("Abstract method `_createCanvas` called.")}};oh=new WeakMap;let hd=Zg;class ld{constructor({baseUrl:t=null,isCompressed:e=!0}){this.constructor===ld&&ft("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, 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?yg.BINARY:yg.NONE;return this._fetchData(e,s).catch(i=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}_fetchData(t,e){ft("Abstract method `_fetchData` called.")}}class cd{constructor({baseUrl:t=null}){this.constructor===cd&&ft("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, 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){ft("Abstract method `_fetchData` called.")}}class Ag{constructor(){this.constructor===Ag&&ft("Cannot initialize BaseSVGFactory.")}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){ft("Abstract method `_createSVG` called.")}}const vi="http://www.w3.org/2000/svg",ir=class ir{};K(ir,"CSS",96),K(ir,"PDF",72),K(ir,"PDF_TO_CSS_UNITS",ir.CSS/ir.PDF);let ln=ir;class Cw extends ad{constructor({docId:e,ownerDocument:s=globalThis.document}={}){super();w(this,B);w(this,nr);w(this,rr);w(this,zs);w(this,Si);w(this,ce);w(this,Ed);w(this,or,0);b(this,Si,e),b(this,ce,s)}addFilter(e){if(!e)return"none";let s=c(this,B,me).get(e);if(s)return s;const[i,n,r]=y(this,B,Yd).call(this,e),o=e.length===1?i:`${i}${n}${r}`;if(s=c(this,B,me).get(o),s)return c(this,B,me).set(e,s),s;const h=`g_${c(this,Si)}_transfer_map_${Je(this,or)._++}`,l=y(this,B,Aa).call(this,h);c(this,B,me).set(e,l),c(this,B,me).set(o,l);const d=y(this,B,Ta).call(this,h);return y(this,B,Xl).call(this,i,n,r,d),l}addHCMFilter(e,s){var p;const i=`${e}-${s}`,n="base";let r=c(this,B,Sa).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,B,Sa).set(n,r)),!e||!s))return r.url;const o=y(this,B,zl).call(this,e);e=z.makeHexColor(...o);const h=y(this,B,zl).call(this,s);if(s=z.makeHexColor(...h),c(this,B,Ca).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,Si)}_hcm_filter`,g=r.filter=y(this,B,Ta).call(this,u);y(this,B,Xl).call(this,d,d,d,g),y(this,B,af).call(this,g);const f=(m,_)=>{const v=o[m]/255,x=h[m]/255,S=new Array(_+1);for(let T=0;T<=_;T++)S[T]=v+T/_*(x-v);return S.join(",")};return y(this,B,Xl).call(this,f(0,5),f(1,5),f(2,5),g),r.url=y(this,B,Aa).call(this,u),r.url}addAlphaFilter(e){let s=c(this,B,me).get(e);if(s)return s;const[i]=y(this,B,Yd).call(this,[e]),n=`alpha_${i}`;if(s=c(this,B,me).get(n),s)return c(this,B,me).set(e,s),s;const r=`g_${c(this,Si)}_alpha_map_${Je(this,or)._++}`,o=y(this,B,Aa).call(this,r);c(this,B,me).set(e,o),c(this,B,me).set(n,o);const h=y(this,B,Ta).call(this,r);return y(this,B,hf).call(this,i,h),o}addLuminosityFilter(e){let s=c(this,B,me).get(e||"luminosity");if(s)return s;let i,n;if(e?([i]=y(this,B,Yd).call(this,[e]),n=`luminosity_${i}`):n="luminosity",s=c(this,B,me).get(n),s)return c(this,B,me).set(e,s),s;const r=`g_${c(this,Si)}_luminosity_map_${Je(this,or)._++}`,o=y(this,B,Aa).call(this,r);c(this,B,me).set(e,o),c(this,B,me).set(n,o);const h=y(this,B,Ta).call(this,r);return y(this,B,rv).call(this,h),e&&y(this,B,hf).call(this,i,h),o}addHighlightHCMFilter(e,s,i,n,r){var x;const o=`${s}-${i}-${n}-${r}`;let h=c(this,B,Sa).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,B,Sa).set(e,h)),!s||!i))return h.url;const[l,d]=[s,i].map(y(this,B,zl).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,B,zl).bind(this));g<u&&([u,g,f,p]=[g,u,p,f]),c(this,B,Ca).style.color="";const m=(S,T,E)=>{const M=new Array(256),P=(g-u)/E,O=S/255,R=(T-S)/(255*E);let D=0;for(let L=0;L<=E;L++){const F=Math.round(u+L*P),I=O+L*R;for(let X=D;X<=F;X++)M[X]=I;D=F+1}for(let L=D;L<256;L++)M[L]=M[D-1];return M.join(",")},_=`g_${c(this,Si)}_hcm_${e}_filter`,v=h.filter=y(this,B,Ta).call(this,_);return y(this,B,af).call(this,v),y(this,B,Xl).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,B,Aa).call(this,_),h.url}destroy(e=!1){e&&c(this,B,Sa).size!==0||(c(this,zs)&&(c(this,zs).parentNode.parentNode.remove(),b(this,zs,null)),c(this,rr)&&(c(this,rr).clear(),b(this,rr,null)),b(this,or,0))}}nr=new WeakMap,rr=new WeakMap,zs=new WeakMap,Si=new WeakMap,ce=new WeakMap,Ed=new WeakMap,or=new WeakMap,B=new WeakSet,me=function(){return c(this,rr)||b(this,rr,new Map)},Sa=function(){return c(this,Ed)||b(this,Ed,new Map)},Ca=function(){if(!c(this,zs)){const e=c(this,ce).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,ce).createElementNS(vi,"svg");i.setAttribute("width",0),i.setAttribute("height",0),b(this,zs,c(this,ce).createElementNS(vi,"defs")),e.append(i),i.append(c(this,zs)),c(this,ce).body.append(e)}return c(this,zs)},Yd=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(",")]},Aa=function(e){if(c(this,nr)===void 0){b(this,nr,"");const s=c(this,ce).URL;s!==c(this,ce).baseURI&&(ud(s)?Z('#createUrl: ignore "data:"-URL for performance reasons.'):b(this,nr,s.split("#",1)[0]))}return`url(${c(this,nr)}#${e})`},rv=function(e){const s=c(this,ce).createElementNS(vi,"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)},af=function(e){const s=c(this,ce).createElementNS(vi,"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)},Ta=function(e){const s=c(this,ce).createElementNS(vi,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",e),c(this,B,Ca).append(s),s},Wl=function(e,s,i){const n=c(this,ce).createElementNS(vi,s);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),e.append(n)},Xl=function(e,s,i,n){const r=c(this,ce).createElementNS(vi,"feComponentTransfer");n.append(r),y(this,B,Wl).call(this,r,"feFuncR",e),y(this,B,Wl).call(this,r,"feFuncG",s),y(this,B,Wl).call(this,r,"feFuncB",i)},hf=function(e,s){const i=c(this,ce).createElementNS(vi,"feComponentTransfer");s.append(i),y(this,B,Wl).call(this,i,"feFuncA",e)},zl=function(e){return c(this,B,Ca).style.color=e,Mg(getComputedStyle(c(this,B,Ca)).getPropertyValue("color"))};class Aw extends hd{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 dd(a,t="text"){if(Ka(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 p0 extends ld{_fetchData(t,e){return dd(t,this.isCompressed?"arraybuffer":"text").then(s=>({cMapData:s instanceof ArrayBuffer?new Uint8Array(s):od(s),compressionType:e}))}}class m0 extends cd{_fetchData(t){return dd(t,"arraybuffer").then(e=>new Uint8Array(e))}}class Tg extends Ag{_createSVG(t){return document.createElementNS(vi,t)}}class $a{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 at(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 $a({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return z.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=z.applyTransform([t[0],t[1]],this.transform),s=z.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return z.applyInverseTransform([t,e],this.transform)}}class Eg extends hn{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function ud(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function kg(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function Tw(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function Ew(a,t="document.pdf"){if(typeof a!="string")return t;if(ud(a))return Z('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 v0{constructor(){K(this,"started",Object.create(null));K(this,"times",[])}time(t){t in this.started&&Z(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||Z(`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 Ka(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function Oe(a){a.preventDefault()}let b0;class y0{static toDateObject(t){if(!t||typeof t!="string")return null;b0||(b0=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const e=b0.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 kw(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new $a({viewBox:n,scale:t,rotation:e})}function Mg(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):(Z(`Not a valid color format: "${a}"`),[0,0,0])}function Mw(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,Mg(s))}t.remove()}function Ct(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function bi(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 Zn(a,t,e=!1,s=!0){if(t instanceof $a){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=De.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,d=o?`round(${h}, 1px)`:`calc(${h})`,u=o?`round(${l}, 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)}const Md=class Md{constructor(t){w(this,Ce);w(this,ar,null);w(this,hr,null);w(this,He);w(this,lr,null);b(this,He,t)}render(){const t=b(this,ar,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar");const e=c(this,He)._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:e}),t.addEventListener("pointerdown",y(Md,kd,ov),{signal:e});const s=b(this,lr,document.createElement("div"));s.className="buttons",t.append(s);const i=c(this,He).toolbarPosition;if(i){const{style:n}=t,r=c(this,He)._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,Ce,lv).call(this),t}hide(){var t;c(this,ar).classList.add("hidden"),(t=c(this,hr))==null||t.hideDropdown()}show(){c(this,ar).classList.remove("hidden")}addAltTextButton(t){y(this,Ce,qd).call(this,t),c(this,lr).prepend(t,c(this,Ce,lf))}addColorPicker(t){b(this,hr,t);const e=t.renderButton();y(this,Ce,qd).call(this,e),c(this,lr).prepend(e,c(this,Ce,lf))}remove(){var t;c(this,ar).remove(),(t=c(this,hr))==null||t.destroy(),b(this,hr,null)}};ar=new WeakMap,hr=new WeakMap,He=new WeakMap,lr=new WeakMap,kd=new WeakSet,ov=function(t){t.stopPropagation()},Ce=new WeakSet,av=function(t){c(this,He)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},hv=function(t){c(this,He)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},qd=function(t){const e=c(this,He)._uiManager._signal;t.addEventListener("focusin",y(this,Ce,av).bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",y(this,Ce,hv).bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Oe,{signal:e})},lv=function(){const t=document.createElement("button");t.className="delete",t.tabIndex=0,t.setAttribute("data-l10n-id",`pdfjs-editor-remove-${c(this,He).editorType}-button`),y(this,Ce,qd).call(this,t),t.addEventListener("click",e=>{c(this,He)._uiManager.delete()},{signal:c(this,He)._uiManager._signal}),c(this,lr).append(t)},lf=function(){const t=document.createElement("div");return t.className="divider",t},w(Md,kd);let Dg=Md;class Dw{constructor(t){w(this,dn);w(this,ah,null);w(this,cr,null);w(this,dr);b(this,dr,t)}show(t,e,s){const[i,n]=y(this,dn,dv).call(this,e,s),{style:r}=c(this,cr)||b(this,cr,y(this,dn,cv).call(this));t.append(c(this,cr)),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){c(this,cr).remove()}}ah=new WeakMap,cr=new WeakMap,dr=new WeakMap,dn=new WeakSet,cv=function(){const t=b(this,cr,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",Oe,{signal:c(this,dr)._signal});const e=b(this,ah,document.createElement("div"));return e.className="buttons",t.append(e),y(this,dn,uv).call(this),t},dv=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]},uv=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,dr)._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("click",()=>{c(this,dr).highlightSelection("floating_button")},{signal:s}),c(this,ah).append(t)};function gd(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}function Ow(a){return Math.round(Math.min(255,Math.max(1,255*a))).toString(16).padStart(2,"0")}class Pw{constructor(){w(this,Dd,0)}get id(){return`${cw}${Je(this,Dd)._++}`}}Dd=new WeakMap;const tf=class tf{constructor(){w(this,lh);w(this,hh,Sw());w(this,Od,0);w(this,is,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 at(this,"_isSVGFittingCanvas",n)}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return y(this,lh,cf).call(this,`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return y(this,lh,cf).call(this,t,t)}async getFromId(t){c(this,is)||b(this,is,new Map);const e=c(this,is).get(t);return e?e.bitmap?(e.refCounter+=1,e):e.file?this.getFromFile(e.file):this.getFromUrl(e.url):null}getSvgUrl(t){const e=c(this,is).get(t);return e!=null&&e.isSvg?e.svgUrl:null}deleteId(t){c(this,is)||b(this,is,new Map);const e=c(this,is).get(t);e&&(e.refCounter-=1,e.refCounter===0&&(e.bitmap=null))}isValidId(t){return t.startsWith(`image_${c(this,hh)}_`)}};hh=new WeakMap,Od=new WeakMap,is=new WeakMap,lh=new WeakSet,cf=async function(t,e){c(this,is)||b(this,is,new Map);let s=c(this,is).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,hh)}_${Je(this,Od)._++}`,refCounter:0,isSvg:!1});let i;if(typeof e=="string"?(s.url=e,i=await dd(e,"blob")):i=s.file=e,i.type==="image/svg+xml"){const n=tf._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,is).set(t,s),s&&c(this,is).set(s.id,s),s};let Og=tf;class Lw{constructor(t=128){w(this,Yt,[]);w(this,un,!1);w(this,ch);w(this,qt,-1);b(this,ch,t)}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),c(this,un))return;const h={cmd:t,undo:e,post:s,type:n};if(c(this,qt)===-1){c(this,Yt).length>0&&(c(this,Yt).length=0),b(this,qt,0),c(this,Yt).push(h);return}if(r&&c(this,Yt)[c(this,qt)].type===n){o&&(h.undo=c(this,Yt)[c(this,qt)].undo),c(this,Yt)[c(this,qt)]=h;return}const l=c(this,qt)+1;l===c(this,ch)?c(this,Yt).splice(0,1):(b(this,qt,l),l<c(this,Yt).length&&c(this,Yt).splice(l)),c(this,Yt).push(h)}undo(){if(c(this,qt)===-1)return;b(this,un,!0);const{undo:t,post:e}=c(this,Yt)[c(this,qt)];t(),e==null||e(),b(this,un,!1),b(this,qt,c(this,qt)-1)}redo(){if(c(this,qt)<c(this,Yt).length-1){b(this,qt,c(this,qt)+1),b(this,un,!0);const{cmd:t,post:e}=c(this,Yt)[c(this,qt)];t(),e==null||e(),b(this,un,!1)}}hasSomethingToUndo(){return c(this,qt)!==-1}hasSomethingToRedo(){return c(this,qt)<c(this,Yt).length-1}destroy(){b(this,Yt,null)}}Yt=new WeakMap,un=new WeakMap,ch=new WeakMap,qt=new WeakMap;class Qa{constructor(t){w(this,Pd);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=De.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,Pd,gv).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()))}}Pd=new WeakSet,gv=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 Ld=class Ld{get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Mw(t),at(this,"_colors",t)}convert(t){const e=Mg(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 Ld._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}};K(Ld,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Pg=Ld;const Lo=class Lo{constructor(t,e,s,i,n,r,o,h,l,d){w(this,j);w(this,Eo,new AbortController);w(this,We,null);w(this,Xt,new Map);w(this,Jt,new Map);w(this,ko,null);w(this,Ci,null);w(this,Mo,null);w(this,bs,new Lw);w(this,Do,0);w(this,ur,new Set);w(this,Vs,null);w(this,ys,null);w(this,gr,new Set);w(this,dh,!1);w(this,uh,!1);w(this,gh,null);w(this,Gs,null);w(this,Oo,null);w(this,gn,!1);w(this,Us,null);w(this,Fd,new Pw);w(this,fn,!1);w(this,fh,!1);w(this,fr,null);w(this,ph,null);w(this,Po,null);w(this,$t,nt.NONE);w(this,gt,new Set);w(this,Ai,null);w(this,pr,null);w(this,mh,null);w(this,vh,this.blur.bind(this));w(this,bh,this.focus.bind(this));w(this,yh,this.copy.bind(this));w(this,_h,this.cut.bind(this));w(this,wh,this.paste.bind(this));w(this,xh,this.keydown.bind(this));w(this,Sh,this.keyup.bind(this));w(this,Ch,this.onEditingAction.bind(this));w(this,Ah,this.onPageChanging.bind(this));w(this,Th,this.onScaleChanging.bind(this));w(this,Eh,this.onRotationChanging.bind(this));w(this,kh,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});w(this,pn,[0,0]);w(this,Ys,null);w(this,Ti,null);w(this,Mh,null);this._signal=c(this,Eo).signal,b(this,Ti,t),b(this,Mh,e),b(this,ko,s),this._eventBus=i,this._eventBus._on("editingaction",c(this,Ch)),this._eventBus._on("pagechanging",c(this,Ah)),this._eventBus._on("scalechanging",c(this,Th)),this._eventBus._on("rotationchanging",c(this,Eh)),y(this,j,mv).call(this),y(this,j,_v).call(this),y(this,j,uf).call(this),b(this,Ci,n.annotationStorage),b(this,gh,n.filterFactory),b(this,pr,r),b(this,Oo,o||null),b(this,dh,h),b(this,uh,l),b(this,Po,d||null),this.viewParameters={realScale:ln.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=Lo.prototype,e=r=>c(r,Ti).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 at(this,"_keyboardManager",new Qa([[["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,Ti).contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&c(r,Ti).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;(t=c(this,Eo))==null||t.abort(),b(this,Eo,null),this._signal=null,this._eventBus._off("editingaction",c(this,Ch)),this._eventBus._off("pagechanging",c(this,Ah)),this._eventBus._off("scalechanging",c(this,Th)),this._eventBus._off("rotationchanging",c(this,Eh));for(const i of c(this,Jt).values())i.destroy();c(this,Jt).clear(),c(this,Xt).clear(),c(this,gr).clear(),b(this,We,null),c(this,gt).clear(),c(this,bs).destroy(),(e=c(this,ko))==null||e.destroy(),(s=c(this,Us))==null||s.hide(),b(this,Us,null),c(this,Gs)&&(clearTimeout(c(this,Gs)),b(this,Gs,null)),c(this,Ys)&&(clearTimeout(c(this,Ys)),b(this,Ys,null))}async mlGuess(t){var e;return((e=c(this,Po))==null?void 0:e.guess(t))||null}async isMLEnabledFor(t){var e;return!!await((e=c(this,Po))==null?void 0:e.isEnabledFor(t))}get useNewAltTextFlow(){return c(this,uh)}get hcmFilter(){return at(this,"hcmFilter",c(this,pr)?c(this,gh).addHCMFilter(c(this,pr).foreground,c(this,pr).background):"none")}get direction(){return at(this,"direction",getComputedStyle(c(this,Ti)).direction)}get highlightColors(){return at(this,"highlightColors",c(this,Oo)?new Map(c(this,Oo).split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return at(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){b(this,ph,t)}editAltText(t){var e;(e=c(this,ko))==null||e.editAltText(this,t)}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})}onPageChanging({pageNumber:t}){b(this,Do,t-1)}focusMainContainer(){c(this,Ti).focus()}findParent(t,e){for(const s of c(this,Jt).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,Mh).classList.toggle("noUserSelect",t)}addShouldRescale(t){c(this,gr).add(t)}removeShouldRescale(t){c(this,gr).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*ln.PDF_TO_CSS_UNITS;for(const e of c(this,gr))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,j,$d).call(this,e).closest(".textLayer"),d=this.getSelectionBoxes(l);if(!d)return;e.empty();const u=y(this,j,df).call(this,l),g=c(this,$t)===nt.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(nt.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&c(this,Ci)&&!c(this,Ci).has(t.id)&&c(this,Ci).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,c(this,gn)&&(b(this,gn,!1),y(this,j,Kd).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of c(this,gt))if(e.div.contains(t)){b(this,fr,[e,t]),e._focusEventsAllowed=!1;break}}focus(){if(!c(this,fr))return;const[t,e]=c(this,fr);b(this,fr,null),e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}addEditListeners(){y(this,j,uf).call(this),y(this,j,gf).call(this)}removeEditListeners(){y(this,j,yv).call(this),y(this,j,ff).call(this)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of c(this,ys))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,ys))if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){var s;if(t.preventDefault(),(s=c(this,We))==null||s.commitOrRemove(),!this.hasSelection)return;const e=[];for(const i of c(this,gt)){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()}paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of c(this,ys))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){Z(`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=i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)y(this,j,pf).call(this,h);y(this,j,mf).call(this,n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){Z(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),c(this,$t)!==nt.NONE&&!this.isEditorHandlingKeyboard&&Lo._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,c(this,gn)&&(b(this,gn,!1),y(this,j,Kd).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,j,vv).call(this),y(this,j,gf).call(this),y(this,j,Ee).call(this,{isEditing:c(this,$t)!==nt.NONE,isEmpty:y(this,j,Vl).call(this),hasSomethingToUndo:c(this,bs).hasSomethingToUndo(),hasSomethingToRedo:c(this,bs).hasSomethingToRedo(),hasSelectedEditor:!1})):(y(this,j,bv).call(this),y(this,j,ff).call(this),y(this,j,Ee).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!c(this,ys)){b(this,ys,t);for(const e of c(this,ys))y(this,j,Rn).call(this,e.defaultPropertiesToUpdate)}}getId(){return c(this,Fd).id}get currentLayer(){return c(this,Jt).get(c(this,Do))}getLayer(t){return c(this,Jt).get(t)}get currentPageIndex(){return c(this,Do)}addLayer(t){c(this,Jt).set(t.pageIndex,t),c(this,fn)?t.enable():t.disable()}removeLayer(t){c(this,Jt).delete(t.pageIndex)}updateMode(t,e=null,s=!1){if(c(this,$t)!==t){if(b(this,$t,t),t===nt.NONE){this.setEditingState(!1),y(this,j,xv).call(this);return}this.setEditingState(!0),y(this,j,wv).call(this),this.unselectAll();for(const i of c(this,Jt).values())i.updateMode(t);if(!e&&s){this.addNewEditorFromKeyboard();return}if(e){for(const i of c(this,Xt).values())if(i.annotationElementId===e){this.setSelected(i),i.enterInEditMode();break}}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==c(this,$t)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){var s;if(c(this,ys)){switch(t){case q.CREATE:this.currentLayer.addNewEditor();return;case q.HIGHLIGHT_DEFAULT_COLOR:(s=c(this,ph))==null||s.updateColor(e);break;case q.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(c(this,mh)||b(this,mh,new Map)).set(t,e),this.showAllEditors("highlight",e);break}for(const i of c(this,gt))i.updateParams(t,e);for(const i of c(this,ys))i.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){var n;for(const r of c(this,Xt).values())r.editorType===t&&r.show(e);(((n=c(this,mh))==null?void 0:n.get(q.HIGHLIGHT_SHOW_ALL))??!0)!==e&&y(this,j,Rn).call(this,[[q.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(c(this,fh)!==t){b(this,fh,t);for(const e of c(this,Jt).values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}getEditors(t){const e=[];for(const s of c(this,Xt).values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return c(this,Xt).get(t)}addEditor(t){c(this,Xt).set(t.id,t)}removeEditor(t){var e;t.div.contains(document.activeElement)&&(c(this,Gs)&&clearTimeout(c(this,Gs)),b(this,Gs,setTimeout(()=>{this.focusMainContainer(),b(this,Gs,null)},0))),c(this,Xt).delete(t.id),this.unselect(t),(!t.annotationElementId||!c(this,ur).has(t.annotationElementId))&&((e=c(this,Ci))==null||e.remove(t.id))}addDeletedAnnotationElement(t){c(this,ur).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return c(this,ur).has(t)}removeDeletedAnnotationElement(t){c(this,ur).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){c(this,We)!==t&&(b(this,We,t),t&&y(this,j,Rn).call(this,t.propertiesToUpdate))}updateUI(t){c(this,j,Sv)===t&&y(this,j,Rn).call(this,t.propertiesToUpdate)}toggleSelected(t){if(c(this,gt).has(t)){c(this,gt).delete(t),t.unselect(),y(this,j,Ee).call(this,{hasSelectedEditor:this.hasSelection});return}c(this,gt).add(t),t.select(),y(this,j,Rn).call(this,t.propertiesToUpdate),y(this,j,Ee).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const e of c(this,gt))e!==t&&e.unselect();c(this,gt).clear(),c(this,gt).add(t),t.select(),y(this,j,Rn).call(this,t.propertiesToUpdate),y(this,j,Ee).call(this,{hasSelectedEditor:!0})}isSelected(t){return c(this,gt).has(t)}get firstSelectedEditor(){return c(this,gt).values().next().value}unselect(t){t.unselect(),c(this,gt).delete(t),y(this,j,Ee).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return c(this,gt).size!==0}get isEnterHandled(){return c(this,gt).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){c(this,bs).undo(),y(this,j,Ee).call(this,{hasSomethingToUndo:c(this,bs).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:y(this,j,Vl).call(this)})}redo(){c(this,bs).redo(),y(this,j,Ee).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:c(this,bs).hasSomethingToRedo(),isEmpty:y(this,j,Vl).call(this)})}addCommands(t){c(this,bs).add(t),y(this,j,Ee).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:y(this,j,Vl).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...c(this,gt)],e=()=>{for(const i of t)i.remove()},s=()=>{for(const i of t)y(this,j,pf).call(this,i)};this.addCommands({cmd:e,undo:s,mustExec:!0})}commitOrRemove(){var t;(t=c(this,We))==null||t.commitOrRemove()}hasSomethingToControl(){return c(this,We)||this.hasSelection}selectAll(){for(const t of c(this,gt))t.commit();y(this,j,mf).call(this,c(this,Xt).values())}unselectAll(){if(!(c(this,We)&&(c(this,We).commitOrRemove(),c(this,$t)!==nt.NONE))&&this.hasSelection){for(const t of c(this,gt))t.unselect();c(this,gt).clear(),y(this,j,Ee).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;c(this,pn)[0]+=t,c(this,pn)[1]+=e;const[i,n]=c(this,pn),r=[...c(this,gt)],o=1e3;c(this,Ys)&&clearTimeout(c(this,Ys)),b(this,Ys,setTimeout(()=>{b(this,Ys,null),c(this,pn)[0]=c(this,pn)[1]=0,this.addCommands({cmd:()=>{for(const h of r)c(this,Xt).has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)c(this,Xt).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,Vs,new Map);for(const t of c(this,gt))c(this,Vs).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!c(this,Vs))return!1;this.disableUserSelect(!1);const t=c(this,Vs);b(this,Vs,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,Xt).has(i.id)){const h=c(this,Jt).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,Vs))for(const s of c(this,Vs).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,gt).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return c(this,We)===t}getActive(){return c(this,We)}getMode(){return c(this,$t)}get imageManager(){return at(this,"imageManager",new Og)}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,Mo)||b(this,Mo,new Map)).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){var e;(e=c(this,Mo))==null||e.delete(t)}renderAnnotationElement(t){var i;const e=(i=c(this,Mo))==null?void 0:i.get(t.data.id);if(!e)return;const s=c(this,Ci).getRawValue(e);s&&(c(this,$t)===nt.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}};Eo=new WeakMap,We=new WeakMap,Xt=new WeakMap,Jt=new WeakMap,ko=new WeakMap,Ci=new WeakMap,Mo=new WeakMap,bs=new WeakMap,Do=new WeakMap,ur=new WeakMap,Vs=new WeakMap,ys=new WeakMap,gr=new WeakMap,dh=new WeakMap,uh=new WeakMap,gh=new WeakMap,Gs=new WeakMap,Oo=new WeakMap,gn=new WeakMap,Us=new WeakMap,Fd=new WeakMap,fn=new WeakMap,fh=new WeakMap,fr=new WeakMap,ph=new WeakMap,Po=new WeakMap,$t=new WeakMap,gt=new WeakMap,Ai=new WeakMap,pr=new WeakMap,mh=new WeakMap,vh=new WeakMap,bh=new WeakMap,yh=new WeakMap,_h=new WeakMap,wh=new WeakMap,xh=new WeakMap,Sh=new WeakMap,Ch=new WeakMap,Ah=new WeakMap,Th=new WeakMap,Eh=new WeakMap,kh=new WeakMap,pn=new WeakMap,Ys=new WeakMap,Ti=new WeakMap,Mh=new WeakMap,j=new WeakSet,$d=function({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t},df=function(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of c(this,Jt).values())if(s.hasTextLayer(t))return s;return null},fv=function(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=y(this,j,$d).call(this,t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(c(this,Us)||b(this,Us,new Dw(this)),c(this,Us).show(s,i,this.direction==="ltr"))},pv=function(){var n,r,o;const t=document.getSelection();if(!t||t.isCollapsed){c(this,Ai)&&((n=c(this,Us))==null||n.hide(),b(this,Ai,null),y(this,j,Ee).call(this,{hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===c(this,Ai))return;const i=y(this,j,$d).call(this,t).closest(".textLayer");if(!i){c(this,Ai)&&((r=c(this,Us))==null||r.hide(),b(this,Ai,null),y(this,j,Ee).call(this,{hasSelectedText:!1}));return}if((o=c(this,Us))==null||o.hide(),b(this,Ai,e),y(this,j,Ee).call(this,{hasSelectedText:!0}),!(c(this,$t)!==nt.HIGHLIGHT&&c(this,$t)!==nt.NONE)&&(c(this,$t)===nt.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),b(this,gn,this.isShiftKeyDown),!this.isShiftKeyDown)){const h=c(this,$t)===nt.HIGHLIGHT?y(this,j,df).call(this,i):null;h==null||h.toggleDrawing();const l=this._signal,d=u=>{u.type==="pointerup"&&u.button!==0||(h==null||h.toggleDrawing(!0),window.removeEventListener("pointerup",d),window.removeEventListener("blur",d),u.type==="pointerup"&&y(this,j,Kd).call(this,"main_toolbar"))};window.addEventListener("pointerup",d,{signal:l}),window.addEventListener("blur",d,{signal:l})}},Kd=function(t=""){c(this,$t)===nt.HIGHLIGHT?this.highlightSelection(t):c(this,dh)&&y(this,j,fv).call(this)},mv=function(){document.addEventListener("selectionchange",y(this,j,pv).bind(this),{signal:this._signal})},vv=function(){const t=this._signal;window.addEventListener("focus",c(this,bh),{signal:t}),window.addEventListener("blur",c(this,vh),{signal:t})},bv=function(){window.removeEventListener("focus",c(this,bh)),window.removeEventListener("blur",c(this,vh))},uf=function(){const t=this._signal;window.addEventListener("keydown",c(this,xh),{signal:t}),window.addEventListener("keyup",c(this,Sh),{signal:t})},yv=function(){window.removeEventListener("keydown",c(this,xh)),window.removeEventListener("keyup",c(this,Sh))},gf=function(){const t=this._signal;document.addEventListener("copy",c(this,yh),{signal:t}),document.addEventListener("cut",c(this,_h),{signal:t}),document.addEventListener("paste",c(this,wh),{signal:t})},ff=function(){document.removeEventListener("copy",c(this,yh)),document.removeEventListener("cut",c(this,_h)),document.removeEventListener("paste",c(this,wh))},_v=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Ee=function(t){Object.entries(t).some(([s,i])=>c(this,kh)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(c(this,kh),t)}),c(this,$t)===nt.HIGHLIGHT&&t.hasSelectedEditor===!1&&y(this,j,Rn).call(this,[[q.HIGHLIGHT_FREE,!0]]))},Rn=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},wv=function(){if(!c(this,fn)){b(this,fn,!0);for(const t of c(this,Jt).values())t.enable();for(const t of c(this,Xt).values())t.enable()}},xv=function(){if(this.unselectAll(),c(this,fn)){b(this,fn,!1);for(const t of c(this,Jt).values())t.disable();for(const t of c(this,Xt).values())t.disable()}},pf=function(t){const e=c(this,Jt).get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},Sv=function(){let t=null;for(t of c(this,gt));return t},Vl=function(){if(c(this,Xt).size===0)return!0;if(c(this,Xt).size===1)for(const t of c(this,Xt).values())return t.isEmpty();return!1},mf=function(t){for(const e of c(this,gt))e.unselect();c(this,gt).clear();for(const e of t)e.isEmpty()||(c(this,gt).add(e),e.select());y(this,j,Ee).call(this,{hasSelectedEditor:this.hasSelection})},K(Lo,"TRANSLATE_SMALL",1),K(Lo,"TRANSLATE_BIG",10);let tr=Lo;const Di=class Di{constructor(t){w(this,Dh);w(this,Ei,"");w(this,ki,!1);w(this,_s,null);w(this,Mi,null);w(this,Xe,null);w(this,Fo,!1);w(this,ws,null);b(this,ws,t)}static initialize(t){Di._l10nPromise||(Di._l10nPromise=t)}async render(){const t=b(this,_s,document.createElement("button"));t.className="altText";const e=await Di._l10nPromise.get("pdfjs-editor-alt-text-button-label");t.textContent=e,t.setAttribute("aria-label",e),t.tabIndex="0";const s=c(this,ws)._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),c(this,ws)._uiManager.editAltText(c(this,ws))};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(b(this,Fo,!0),i(n))},{signal:s}),await y(this,Dh,vf).call(this),t}finish(){c(this,_s)&&(c(this,_s).focus({focusVisible:c(this,Fo)}),b(this,Fo,!1))}isEmpty(){return!c(this,Ei)&&!c(this,ki)}get data(){return{altText:c(this,Ei),decorative:c(this,ki)}}set data({altText:t,decorative:e}){c(this,Ei)===t&&c(this,ki)===e||(b(this,Ei,t),b(this,ki,e),y(this,Dh,vf).call(this))}toggle(t=!1){c(this,_s)&&(!t&&c(this,Xe)&&(clearTimeout(c(this,Xe)),b(this,Xe,null)),c(this,_s).disabled=!t)}destroy(){var t;(t=c(this,_s))==null||t.remove(),b(this,_s,null),b(this,Mi,null)}};Ei=new WeakMap,ki=new WeakMap,_s=new WeakMap,Mi=new WeakMap,Xe=new WeakMap,Fo=new WeakMap,ws=new WeakMap,Dh=new WeakSet,vf=async function(){var i;const t=c(this,_s);if(!t)return;if(!c(this,Ei)&&!c(this,ki)){t.classList.remove("done"),(i=c(this,Mi))==null||i.remove();return}t.classList.add("done"),Di._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(n=>{t.setAttribute("aria-label",n)});let e=c(this,Mi);if(!e){b(this,Mi,e=document.createElement("span")),e.className="tooltip",e.setAttribute("role","tooltip");const n=e.id=`alt-text-tooltip-${c(this,ws).id}`;t.setAttribute("aria-describedby",n);const r=100,o=c(this,ws)._uiManager._signal;o.addEventListener("abort",()=>{clearTimeout(c(this,Xe)),b(this,Xe,null)},{once:!0}),t.addEventListener("mouseenter",()=>{b(this,Xe,setTimeout(()=>{b(this,Xe,null),c(this,Mi).classList.add("show"),c(this,ws)._reportTelemetry({action:"alt_text_tooltip"})},r))},{signal:o}),t.addEventListener("mouseleave",()=>{var h;c(this,Xe)&&(clearTimeout(c(this,Xe)),b(this,Xe,null)),(h=c(this,Mi))==null||h.classList.remove("show")},{signal:o})}e.innerText=c(this,ki)?await Di._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):c(this,Ei),e.parentNode||t.append(e);const s=c(this,ws).getImageForAltText();s==null||s.setAttribute("aria-describedby",e.id)},K(Di,"_l10nPromise",null);let fd=Di;const bt=class bt{constructor(t){w(this,tt);w(this,mr,null);w(this,xs,null);w(this,de,null);w(this,Ro,!1);w(this,vr,!1);w(this,Zt,null);w(this,br,null);w(this,Io,this.focusin.bind(this));w(this,jo,this.focusout.bind(this));w(this,ue,null);w(this,Oh,"");w(this,yr,!1);w(this,mn,null);w(this,Ph,!1);w(this,_r,!1);w(this,Oi,!1);w(this,qs,null);w(this,No,0);w(this,Bo,0);w(this,ns,null);K(this,"_initialOptions",Object.create(null));K(this,"_isVisible",!0);K(this,"_uiManager",null);K(this,"_focusEventsAllowed",!0);K(this,"_l10nPromise",null);w(this,Lh,!1);w(this,Rd,bt._zIndex++);this.constructor===bt&&ft("Cannot initialize AnnotationEditor."),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=bt.prototype._resizeWithKeyboard,e=tr.TRANSLATE_SMALL,s=tr.TRANSLATE_BIG;return at(this,"_resizerKeyboardManager",new Qa([[["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"],bt.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return at(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Fw({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(bt._l10nPromise||(bt._l10nPromise=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map(n=>[n,t.get(n.replaceAll(/([A-Z])/g,r=>`-${r.toLowerCase()}`))]))),s!=null&&s.strings)for(const n of s.strings)bt._l10nPromise.set(n,t.get(n));if(bt._borderLineWidth!==-1)return;const i=getComputedStyle(document.documentElement);bt._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){ft("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,Rd)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):y(this,tt,Gl).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(c(this,yr)?b(this,yr,!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,tt,bf).call(this,this.parentDimensions,t,e)}translateInPage(t,e){c(this,mn)||b(this,mn,[this.x,this.y]),y(this,tt,bf).call(this,this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){c(this,mn)||b(this,mn,[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,mn)&&(c(this,mn)[0]!==this.x||c(this,mn)[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=bt,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=bt,Fh,yf).call(s,t,e,this.parentRotation)}pageTranslationToScreen(t,e){var s;return y(s=bt,Fh,yf).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,i=e*t,n=s*t;return De.isCSSRoundSupported?[Math.round(i),Math.round(n)]:[i,n]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,c(this,vr)||(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,vr)&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!c(this,vr)&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=c(this,de))==null||t.finish()}async addEditToolbar(){return c(this,ue)||c(this,_r)?c(this,ue):(b(this,ue,new Dg(this)),this.div.append(c(this,ue).render()),c(this,de)&&c(this,ue).addAltTextButton(await c(this,de).render()),c(this,ue))}removeEditToolbar(){var t;c(this,ue)&&(c(this,ue).remove(),b(this,ue,null),(t=c(this,de))==null||t.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){c(this,de)||(fd.initialize(bt._l10nPromise),b(this,de,new fd(this)),c(this,mr)&&(c(this,de).data=c(this,mr),b(this,mr,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=c(this,de))==null?void 0:t.data}set altTextData(t){c(this,de)&&(c(this,de).data=t)}hasAltText(){var t;return!((t=c(this,de))!=null&&t.isEmpty())}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,Ro)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground();const t=this._uiManager._signal;this.div.addEventListener("focusin",c(this,Io),{signal:t}),this.div.addEventListener("focusout",c(this,jo),{signal:t});const[e,s]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*s/e).toFixed(2)}%`,this.div.style.maxHeight=`${(100*e/s).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),gd(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=De.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(b(this,yr,!0),this._isDraggable){y(this,tt,Tv).call(this,t);return}y(this,tt,Sf).call(this,t)}moveInDOM(){c(this,qs)&&clearTimeout(c(this,qs)),b(this,qs,setTimeout(()=>{var t;b(this,qs,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,_r,!0)}disableEditMode(){b(this,_r,!1)}isInEditMode(){return c(this,_r)}shouldGetKeyboardEvents(){return c(this,Oi)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){var e,s;const t=this._uiManager._signal;(e=this.div)==null||e.addEventListener("focusin",c(this,Io),{signal:t}),(s=this.div)==null||s.addEventListener("focusout",c(this,jo),{signal:t})}rotate(t){}serialize(t=!1,e=null){ft("An editor must be serializable")}static deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,b(i,mr,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(){if(this.div.removeEventListener("focusin",c(this,Io)),this.div.removeEventListener("focusout",c(this,jo)),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),c(this,qs)&&(clearTimeout(c(this,qs)),b(this,qs,null)),y(this,tt,Gl).call(this),this.removeEditToolbar(),c(this,ns)){for(const t of c(this,ns).values())clearTimeout(t);b(this,ns,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(y(this,tt,Cv).call(this),c(this,Zt).classList.remove("hidden"),gd(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,br,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const e=c(this,Zt).children;if(!c(this,xs)){b(this,xs,Array.from(e));const r=y(this,tt,Ev).bind(this),o=y(this,tt,kv).bind(this),h=this._uiManager._signal;for(const l of c(this,xs)){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,tt,Mv).bind(this,d),{signal:h}),bt._l10nPromise.get(`pdfjs-editor-resizer-label-${d}`).then(u=>l.setAttribute("aria-label",u))}}const s=c(this,xs)[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,xs).length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)c(this,Zt).append(c(this,Zt).firstChild);else if(n>i)for(let o=0;o<n-i;o++)c(this,Zt).firstChild.before(c(this,Zt).lastChild);let r=0;for(const o of e){const l=c(this,xs)[r++].getAttribute("data-resizer-name");bt._l10nPromise.get(`pdfjs-editor-resizer-label-${l}`).then(d=>o.setAttribute("aria-label",d))}}y(this,tt,Cf).call(this,0),b(this,Oi,!0),c(this,Zt).firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}_resizeWithKeyboard(t,e){c(this,Oi)&&y(this,tt,xf).call(this,c(this,Oh),{movementX:t,movementY:e})}_stopResizingWithKeyboard(){y(this,tt,Gl).call(this),this.div.focus()}select(){var t,e;if(this.makeResizable(),(t=this.div)==null||t.classList.add("selectedEditor"),!c(this,ue)){this.addEditToolbar().then(()=>{var s,i;(s=this.div)!=null&&s.classList.contains("selectedEditor")&&((i=c(this,ue))==null||i.show())});return}(e=c(this,ue))==null||e.show()}unselect(){var t,e,s,i;(t=c(this,Zt))==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=c(this,ue))==null||i.hide()}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,vr,!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,ns)||b(this,ns,new Map);const{action:s}=t;let i=c(this,ns).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),c(this,ns).delete(s),c(this,ns).size===0&&b(this,ns,null)},bt._telemetryTimeout),c(this,ns).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,Ro,!1)}disable(){this.div&&(this.div.tabIndex=-1),b(this,Ro,!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.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}};mr=new WeakMap,xs=new WeakMap,de=new WeakMap,Ro=new WeakMap,vr=new WeakMap,Zt=new WeakMap,br=new WeakMap,Io=new WeakMap,jo=new WeakMap,ue=new WeakMap,Oh=new WeakMap,yr=new WeakMap,mn=new WeakMap,Ph=new WeakMap,_r=new WeakMap,Oi=new WeakMap,qs=new WeakMap,No=new WeakMap,Bo=new WeakMap,ns=new WeakMap,Lh=new WeakMap,Rd=new WeakMap,tt=new WeakSet,bf=function([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()},Fh=new WeakSet,yf=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]}},_f=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]}},Cv=function(){if(c(this,Zt))return;b(this,Zt,document.createElement("div")),c(this,Zt).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,Zt).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",y(this,tt,Av).bind(this,s),{signal:e}),i.addEventListener("contextmenu",Oe,{signal:e}),i.tabIndex=-1}this.div.prepend(c(this,Zt))},Av=function(t,e){var m;e.preventDefault();const{isMac:s}=De.platform;if(e.button!==0||e.ctrlKey&&s)return;(m=c(this,de))==null||m.toggle(!1);const i=y(this,tt,xf).bind(this,t),n=this._isDraggable;this._isDraggable=!1;const r=this._uiManager._signal,o={passive:!0,capture:!0,signal:r};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",i,o),window.addEventListener("contextmenu",Oe,{signal:r});const h=this.x,l=this.y,d=this.width,u=this.height,g=this.parent.div.style.cursor,f=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const p=()=>{var _;this.parent.togglePointerEvents(!0),(_=c(this,de))==null||_.toggle(!0),this._isDraggable=n,window.removeEventListener("pointerup",p),window.removeEventListener("blur",p),window.removeEventListener("pointermove",i,o),window.removeEventListener("contextmenu",Oe),this.parent.div.style.cursor=g,this.div.style.cursor=f,y(this,tt,wf).call(this,h,l,d,u)};window.addEventListener("pointerup",p,{signal:r}),window.addEventListener("blur",p,{signal:r})},wf=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})},xf=function(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=bt.MIN_SIZE/s,d=bt.MIN_SIZE/i,u=W=>Math.round(W*1e4)/1e4,g=y(this,tt,_f).call(this,this.rotation),f=(W,V)=>[g[0]*W+g[2]*V,g[1]*W+g[3]*V],p=y(this,tt,_f).call(this,360-this.rotation),m=(W,V)=>[p[0]*W+p[2]*V,p[1]*W+p[3]*V];let _,v,x=!1,S=!1;switch(t){case"topLeft":x=!0,_=(W,V)=>[0,0],v=(W,V)=>[W,V];break;case"topMiddle":_=(W,V)=>[W/2,0],v=(W,V)=>[W/2,V];break;case"topRight":x=!0,_=(W,V)=>[W,0],v=(W,V)=>[0,V];break;case"middleRight":S=!0,_=(W,V)=>[W,V/2],v=(W,V)=>[0,V/2];break;case"bottomRight":x=!0,_=(W,V)=>[W,V],v=(W,V)=>[0,0];break;case"bottomMiddle":_=(W,V)=>[W/2,V],v=(W,V)=>[W/2,0];break;case"bottomLeft":x=!0,_=(W,V)=>[0,V],v=(W,V)=>[W,0];break;case"middleLeft":S=!0,_=(W,V)=>[0,V/2],v=(W,V)=>[W,V/2];break}const T=_(o,h),E=v(o,h);let M=f(...E);const P=u(n+M[0]),O=u(r+M[1]);let R=1,D=1,[L,F]=this.screenToPageTranslation(e.movementX,e.movementY);if([L,F]=m(L/s,F/i),x){const W=Math.hypot(o,h);R=D=Math.max(Math.min(Math.hypot(E[0]-T[0]-L,E[1]-T[1]-F)/W,1/o,1/h),l/o,d/h)}else S?R=Math.max(l,Math.min(1,Math.abs(E[0]-T[0]-L)))/o:D=Math.max(d,Math.min(1,Math.abs(E[1]-T[1]-F)))/h;const I=u(o*R),X=u(h*D);M=f(...v(I,X));const Y=P-M[0],J=O-M[1];this.width=I,this.height=X,this.x=Y,this.y=J,this.setDims(s*I,i*X),this.fixAndSetPosition()},Sf=function(t){const{isMac:e}=De.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)},Tv=function(t){const e=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let s,i;const n=this._uiManager._signal;e&&(this.div.classList.add("moving"),s={passive:!0,capture:!0,signal:n},b(this,No,t.clientX),b(this,Bo,t.clientY),i=o=>{const{clientX:h,clientY:l}=o,[d,u]=this.screenToPageTranslation(h-c(this,No),l-c(this,Bo));b(this,No,h),b(this,Bo,l),this._uiManager.dragSelectedEditors(d,u)},window.addEventListener("pointermove",i,s));const r=()=>{window.removeEventListener("pointerup",r),window.removeEventListener("blur",r),e&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",i,s)),b(this,yr,!1),this._uiManager.endDragSession()||y(this,tt,Sf).call(this,t)};window.addEventListener("pointerup",r,{signal:n}),window.addEventListener("blur",r,{signal:n})},Ev=function(t){bt._resizerKeyboardManager.exec(this,t)},kv=function(t){var e;c(this,Oi)&&((e=t.relatedTarget)==null?void 0:e.parentNode)!==c(this,Zt)&&y(this,tt,Gl).call(this)},Mv=function(t){b(this,Oh,c(this,Oi)?t:"")},Cf=function(t){if(c(this,xs))for(const e of c(this,xs))e.tabIndex=t},Gl=function(){if(b(this,Oi,!1),y(this,tt,Cf).call(this,-1),c(this,br)){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=c(this,br);y(this,tt,wf).call(this,t,e,s,i),b(this,br,null)}},w(bt,Fh),K(bt,"_borderLineWidth",-1),K(bt,"_colorManager",new Pg),K(bt,"_zIndex",1),K(bt,"_telemetryTimeout",1e3);let dt=bt;class Fw extends dt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}const _0=3285377520,es=4294901760,Ws=65535;class w0{constructor(t){this.h1=t?t&4294967295:_0,this.h2=t?t&4294967295:_0}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&Ws,p=g&Ws;for(let m=0;m<i;m++)m&1?(o=r[m],o=o*u&es|o*f&Ws,o=o<<15|o>>>17,o=o*g&es|o*p&Ws,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[m],h=h*u&es|h*f&Ws,h=h<<15|h>>>17,h=h*g&es|h*p&Ws,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&es|o*f&Ws,o=o<<15|o>>>17,o=o*g&es|o*p&Ws,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&es|t*36045&Ws,e=e*4283543511&es|((e<<16|t>>>16)*2950163797&es)>>>16,t^=e>>>1,t=t*444984403&es|t*60499&Ws,e=e*3301882366&es|((e<<16|t>>>16)*3120437893&es)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Lg=Object.freeze({map:null,hash:"",transfer:void 0});class Fg{constructor(){w(this,Id);w(this,wr,!1);w(this,xr,null);w(this,Kt,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=c(this,Kt).get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return c(this,Kt).get(t)}remove(t){if(c(this,Kt).delete(t),c(this,Kt).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of c(this,Kt).values())if(e instanceof dt)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=c(this,Kt).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,Kt).set(t,e);i&&y(this,Id,Dv).call(this),e instanceof dt&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return c(this,Kt).has(t)}getAll(){return c(this,Kt).size>0?xg(c(this,Kt)):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return c(this,Kt).size}resetModified(){c(this,wr)&&(b(this,wr,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new x0(this)}get serializable(){if(c(this,Kt).size===0)return Lg;const t=new Map,e=new w0,s=[],i=Object.create(null);let n=!1;for(const[r,o]of c(this,Kt)){const h=o instanceof dt?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}:Lg}get editorStats(){let t=null;const e=new Map;for(const s of c(this,Kt).values()){if(!(s instanceof dt))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,xr,null)}get modifiedIds(){if(c(this,xr))return c(this,xr);const t=[];for(const e of c(this,Kt).values())!(e instanceof dt)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return b(this,xr,{ids:new Set(t),hash:t.join(",")})}}wr=new WeakMap,xr=new WeakMap,Kt=new WeakMap,Id=new WeakSet,Dv=function(){c(this,wr)||(b(this,wr,!0),typeof this.onSetModified=="function"&&this.onSetModified())};class x0 extends Fg{constructor(e){super();w(this,Rh);const{map:s,hash:i,transfer:n}=e.serializable,r=structuredClone(s,n?{transfer:n}:null);b(this,Rh,{map:r,hash:i,transfer:n})}get print(){ft("Should not call PrintAnnotationStorage.print")}get serializable(){return c(this,Rh)}get modifiedIds(){return at(this,"modifiedIds",{ids:new Set,hash:""})}}Rh=new WeakMap;class Rw{constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){w(this,Ho,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,Ho).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||c(this,Ho).has(t.loadedName))){if(Wt(!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,Ho).add(s),e==null||e(t)}catch{Z(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}ft("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 Z(`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 at(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(he||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),at(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(Wt(!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 at(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(T,E){return T.charCodeAt(E)<<24|T.charCodeAt(E+1)<<16|T.charCodeAt(E+2)<<8|T.charCodeAt(E+3)&255}function i(T,E,M,P){const O=T.substring(0,E),R=T.substring(E+M);return O+P+R}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(T,E){if(++l>30){Z("Load test font never loaded."),E();return}if(h.font="30px "+T,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){E();return}setTimeout(d.bind(null,T,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,bw(_));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 T of[t.loadedName,u]){const E=this._document.createElement("span");E.textContent="Hi",E.style.fontFamily=T,S.append(E)}this._document.body.append(S),d(u,()=>{S.remove(),e.complete()})}}Ho=new WeakMap;class Iw{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=u0(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){Z(`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 mi.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 mi.MOVE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.moveTo(o,h)),n+=2}break;case mi.LINE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.lineTo(o,h)),n+=2}break;case mi.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 mi.RESTORE:i.push(o=>o.restore());break;case mi.SAVE:i.push(o=>o.save());break;case mi.SCALE:Wt(i.length===2,"Scale command is only valid at the third position.");break;case mi.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 mi.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(he){var Rg=Promise.withResolvers(),Ja=null;(async()=>{const t=await Promise.resolve().then(()=>Td),e=await Promise.resolve().then(()=>Td),s=await Promise.resolve().then(()=>Td),i=await Promise.resolve().then(()=>Td);let n,r;return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:n,path2d:r}))})().then(t=>{Ja=t,Rg.resolve()},t=>{Z(`loadPackages: ${t}`),Ja=new Map,Rg.resolve()})}class Xs{static get promise(){return Rg.promise}static get(t){return Ja==null?void 0:Ja.get(t)}}const S0=function(a){return Xs.get("fs").promises.readFile(a).then(e=>new Uint8Array(e))};class jw extends ad{}class Nw extends hd{_createCanvas(t,e){return Xs.get("canvas").createCanvas(t,e)}}class Bw extends ld{_fetchData(t,e){return S0(t).then(s=>({cMapData:s,compressionType:e}))}}class Hw extends cd{_fetchData(t){return S0(t)}}const Se={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Ig(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 Za{constructor(){this.constructor===Za&&ft("Cannot initialize BaseShadingPattern.")}getPattern(){ft("Abstract method `getPattern` called.")}}class Ww extends Za{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===Se.STROKE||i===Se.FILL){const r=e.current.getClippedPathBoundingBox(i,Ct(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,!0),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=z.transform(s,[1,0,0,1,r[0],r[1]]),d.transform(...e.baseTransform),this.matrix&&d.transform(...this.matrix),Ig(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 Ig(t,this._bbox),n=this._createGradient(t);return n}}function jg(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],T=l[n+1],E=l[n+2],M=l[r],P=l[r+1],O=l[r+2],R=l[o],D=l[o+1],L=l[o+2],F=Math.round(p),I=Math.round(x);let X,Y,J,W,V,Qt,Ke,Zi;for(let Ut=F;Ut<=I;Ut++){if(Ut<_){const wt=Ut<p?0:(p-Ut)/(p-_);X=f-(f-m)*wt,Y=S-(S-M)*wt,J=T-(T-P)*wt,W=E-(E-O)*wt}else{let wt;Ut>x?wt=1:_===x?wt=0:wt=(_-Ut)/(_-x),X=m-(m-v)*wt,Y=M-(M-R)*wt,J=P-(P-D)*wt,W=O-(O-L)*wt}let Tt;Ut<p?Tt=0:Ut>x?Tt=1:Tt=(p-Ut)/(p-x),V=f-(f-v)*Tt,Qt=S-(S-R)*Tt,Ke=T-(T-D)*Tt,Zi=E-(E-L)*Tt;const Qe=Math.round(Math.min(X,V)),ls=Math.round(Math.max(X,V));let pe=u*Ut+Qe*4;for(let wt=Qe;wt<=ls;wt++)Tt=(X-wt)/(X-V),Tt<0?Tt=0:Tt>1&&(Tt=1),d[pe++]=Y-(Y-Qt)*Tt|0,d[pe++]=J-(J-Ke)*Tt|0,d[pe++]=W-(W-Zi)*Tt|0,d[pe++]=255}}function Xw(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++)jg(a,e,s[d],s[d+1],s[d+o],i[d],i[d+1],i[d+o]),jg(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)jg(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 zw extends Za{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,!1),S=x.context,T=S.createImageData(u,g);if(e){const M=T.data;for(let P=0,O=M.length;P<O;P+=4)M[P]=e[0],M[P+1]=e[1],M[P+2]=e[2],M[P+3]=255}for(const M of this._figures)Xw(T,M,m);return S.putImageData(T,2,2),{canvas:x.canvas,offsetX:o-2*f,offsetY:h-2*p,scaleX:f,scaleY:p}}getPattern(t,e,s,i){Ig(t,this._bbox);let n;if(i===Se.SHADING)n=z.singularValueDecompose2dScale(Ct(t));else if(n=z.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=z.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Se.SHADING?null:this._background,e.cachedCanvases);return i!==Se.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 Vw extends Za{getPattern(){return"hotpink"}}function Gw(a){switch(a[0]){case"RadialAxial":return new Ww(a);case"Mesh":return new zw(a);case"Dummy":return new Vw}throw new Error(`Unknown IR type: ${a[0]}`)}const C0={COLORED:1,UNCOLORED:2},jd=class jd{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 e=this.operatorList,s=this.bbox,i=this.xstep,n=this.ystep,r=this.paintType,o=this.tilingType,h=this.color,l=this.canvasGraphicsFactory;nd("TilingType: "+o);const d=s[0],u=s[1],g=s[2],f=s[3],p=z.singularValueDecompose2dScale(this.matrix),m=z.singularValueDecompose2dScale(this.baseTransform),_=[p[0]*m[0],p[1]*m[1]],v=this.getSizeAndScale(i,this.ctx.canvas.width,_[0]),x=this.getSizeAndScale(n,this.ctx.canvas.height,_[1]),S=t.cachedCanvases.getCanvas("pattern",v.size,x.size,!0),T=S.context,E=l.createCanvasGraphics(T);E.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(E,r,h);let M=d,P=u,O=g,R=f;return d<0&&(M=0,O+=Math.abs(d)),u<0&&(P=0,R+=Math.abs(u)),T.translate(-(v.scale*M),-(x.scale*P)),E.transform(v.scale,0,0,x.scale,0,0),T.save(),this.clipBbox(E,M,P,O,R),E.baseTransform=Ct(E.ctx),E.executeOperatorList(e),E.endDrawing(),{canvas:S.canvas,scaleX:v.scale,scaleY:x.scale,offsetX:M,offsetY:P}}getSizeAndScale(t,e,s){t=Math.abs(t);const i=Math.max(jd.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(Ct(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case C0.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case C0.UNCOLORED:const o=z.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new vw(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Se.SHADING&&(n=z.transform(n,e.baseTransform),this.matrix&&(n=z.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}};K(jd,"MAX_PATTERN_SIZE",3e3);let Ng=jd;function Uw({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=De.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 A0=16,T0=100,Yw=15,E0=10,k0=1e3,Pe=16;function qw(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 $w{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 pd(a,t,e,s,i,n,r,o,h,l){const[d,u,g,f,p,m]=Ct(a);if(u===0&&g===0){const x=r*d+p,S=Math.round(x),T=o*f+m,E=Math.round(T),M=(r+h)*d+p,P=Math.abs(Math.round(M)-S)||1,O=(o+l)*f+m,R=Math.abs(Math.round(O)-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,R),a.setTransform(d,u,g,f,p,m),[P,R]}if(d===0&&f===0){const x=o*g+p,S=Math.round(x),T=r*u+m,E=Math.round(T),M=(o+l)*g+p,P=Math.abs(Math.round(M)-S)||1,O=(r+h)*u+m,R=Math.abs(Math.round(O)-E)||1;return a.setTransform(0,Math.sign(u),Math.sign(g),0,S,E),a.drawImage(t,e,s,i,n,0,0,R,P),a.setTransform(d,u,g,f,p,m),[R,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 Kw(a){const{width:t,height:e}=a;if(t>k0||e>k0)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 T=r[v];do{const E=p[T];do v+=E;while(!r[v]);const M=r[v];M!==5&&M!==10?(T=M,r[v]=0):(T=M&51*T>>4,r[v]&=T>>2|T<<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 M0{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=c0,this.textMatrixScale=1,this.fontMatrix=vg,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=le.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]=z.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=z.applyTransform(e,t),i=z.applyTransform(e.slice(2),t),n=z.applyTransform([e[0],e[3]],t),r=z.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){z.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=z.bezierBoundingBox(e,s,i,n,r,o,h,l,d);d||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Se.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Se.STROKE){e||ft("Stroke bounding box must include transform.");const i=z.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=z.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=Se.FILL,e=null){return z.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function D0(a,t){if(typeof ImageData<"u"&&t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Pe,n=(e-i)/Pe,r=i===0?n:n+1,o=a.createImageData(s,Pe);let h=0,l;const d=t.data,u=o.data;let g,f,p,m;if(t.kind===ed.GRAYSCALE_1BPP){const _=d.byteLength,v=new Uint32Array(u.buffer,0,u.byteLength>>2),x=v.length,S=s+7>>3,T=4294967295,E=De.isLittleEndian?4278190080:255;for(g=0;g<r;g++){for(p=g<n?Pe:i,l=0,f=0;f<p;f++){const M=_-h;let P=0;const O=M>S?s:M*8-7,R=O&-8;let D=0,L=0;for(;P<R;P+=8)L=d[h++],v[l++]=L&128?T:E,v[l++]=L&64?T:E,v[l++]=L&32?T:E,v[l++]=L&16?T:E,v[l++]=L&8?T:E,v[l++]=L&4?T:E,v[l++]=L&2?T:E,v[l++]=L&1?T:E;for(;P<O;P++)D===0&&(L=d[h++],D=128),v[l++]=L&D?T:E,D>>=1}for(;l<x;)v[l++]=0;a.putImageData(o,0,g*Pe)}}else if(t.kind===ed.RGBA_32BPP){for(f=0,m=s*Pe*4,g=0;g<n;g++)u.set(d.subarray(h,h+m)),h+=m,a.putImageData(o,0,f),f+=Pe;g<r&&(m=s*i*4,u.set(d.subarray(h,h+m)),a.putImageData(o,0,f))}else if(t.kind===ed.RGB_24BPP)for(p=Pe,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*Pe)}else throw new Error(`bad image kind: ${t.kind}`)}function O0(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Pe,n=(e-i)/Pe,r=i===0?n:n+1,o=a.createImageData(s,Pe);let h=0;const l=t.data,d=o.data;for(let u=0;u<r;u++){const g=u<n?Pe:i;({srcPos:h}=Uw({src:l,srcPos:h,dest:d,width:s,height:g,nonBlackColor:0})),a.putImageData(o,0,u*Pe)}}function th(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 md(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),!he){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function P0(a,t){if(t)return!0;const e=z.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*ln.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const Qw=["butt","round","square"],Jw=["miter","round","bevel"],Zw={},L0={},ef=class ef{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){w(this,vn);this.ctx=t,this.current=new M0(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 $w(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(...Ct(this.compositeCtx))}this.ctx.save(),md(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=Ct(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>E0&&typeof s=="function",d=l?Date.now()+Yw: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!==vs.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>E0){if(Date.now()>d)return s(),o;u=0}}}endDrawing(){y(this,vn,Af).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,vn,Tf).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=Ct(e);let h,l,d,u;if((t.bitmap||t.data)&&t.count>1){const O=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(O),h||(h=new Map,this._cachedBitmapsMap.set(O,h));const R=h.get(l);if(R&&!r){const D=Math.round(Math.min(o[0],o[2])+o[4]),L=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:R,offsetX:D,offsetY:L}}d=R}d||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),O0(u.context,t));let g=z.transform(o,[1/s,0,0,-1/i,0,0]);g=z.transform(g,[1,0,0,1,0,-i]);const[f,p,m,_]=z.getAxialAlignedBoundingBox([0,0,s,i],g),v=Math.round(m-f)||1,x=Math.round(_-p)||1,S=this.cachedCanvases.getCanvas("fillCanvas",v,x),T=S.context,E=f,M=p;T.translate(-E,-M),T.transform(...g),d||(d=this._scaleImage(u.canvas,bi(T)),d=d.img,h&&r&&h.set(l,d)),T.imageSmoothingEnabled=P0(Ct(T),t.interpolate),pd(T,d,0,0,d.width,d.height,0,0,s,i),T.globalCompositeOperation="source-in";const P=z.transform(bi(T),[1,0,0,1,-E,-M]);return T.fillStyle=r?n.getPattern(e,this,P,Se.FILL):n,T.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(M)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Qw[t]}setLineJoin(t){this.ctx.lineJoin=Jw[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(...Ct(this.suspendedCtx)),th(this.suspendedCtx,n),qw(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(),th(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=z.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=z.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?(th(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(),th(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=Ct(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 vs.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 vs.moveTo:r=e[p++],o=e[p++],i.moveTo(r,o),u||n.updatePathMinMax(d,r,o);break;case vs.lineTo:r=e[p++],o=e[p++],i.lineTo(r,o),u||n.updatePathMinMax(d,r,o);break;case vs.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 vs.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 vs.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 vs.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,bi(e),Se.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,bi(e),Se.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=Zw}eoClip(){this.pendingClip=L0}beginText(){this.current.textMatrix=c0,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||vg,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&Z("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<A0?l=A0:e>T0&&(l=T0),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&le.FILL_STROKE_MASK,u=!!(h&le.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===le.FILL||d===le.FILL_STROKE)&&n.fill(),(d===le.STROKE||d===le.FILL_STROKE)&&n.stroke(),n.restore()):((d===le.FILL||d===le.FILL_STROKE)&&n.fillText(t,e,s),(d===le.STROKE||d===le.FILL_STROKE)&&n.strokeText(t,e,s)),u&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Ct(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 at(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===le.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 M=e.fillColor.getPattern(n,this,bi(n),Se.FILL);v=Ct(n),n.restore(),n.fillStyle=M}let x=e.lineWidth;const S=e.textMatrixScale;if(S===0||x===0){const M=e.textRenderingMode&le.FILL_STROKE_MASK;(M===le.STROKE||M===le.FILL_STROKE)&&(x=this.getSinglePixelWidth())}else x/=S;if(r!==1&&(n.scale(r,r),x/=r),n.lineWidth=x,s.isInvalidPDFjsFont){const M=[];let P=0;for(const O of t)M.push(O.unicode),P+=O.width;n.fillText(M.join(""),0,0),e.x+=P*m*d,n.restore(),this.compose();return}let T=0,E;for(E=0;E<u;++E){const M=t[E];if(typeof M=="number"){T+=f*M*i/1e3;continue}let P=!1;const O=(M.isSpace?h:0)+o,R=M.fontChar,D=M.accent;let L,F,I=M.width;if(g){const Y=M.vmetric||p,J=-(M.vmetric?Y[1]:I*.5)*m,W=Y[2]*m;I=Y?-Y[0]:I,L=J/r,F=(T+W)/r}else L=T/r,F=0;if(s.remeasure&&I>0){const Y=n.measureText(R).width*1e3/i*r;if(I<Y&&this.isFontSubpixelAAEnabled){const J=I/Y;P=!0,n.save(),n.scale(J,1),L/=J}else I!==Y&&(L+=(I-Y)/2e3*i/r)}if(this.contentVisible&&(M.isInFont||s.missingFile)){if(_&&!D)n.fillText(R,L,F);else if(this.paintChar(R,L,F,v),D){const Y=L+i*D.offset.x/r,J=F-i*D.offset.y/r;this.paintChar(D.fontChar,Y,J,v)}}const X=g?I*m-O*l:I*m+O*l;T+=X,P&&n.restore()}g?e.y-=T:e.x+=T*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||vg,g=t.length,f=s.textRenderingMode===le.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){Z(`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()),_=z.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||Ct(this.ctx),n={createCanvasGraphics:r=>new ef(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new Ng(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=z.makeHexColor(t,e,s)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=z.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=Gw(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,bi(e),Se.SHADING);const i=bi(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,d]=z.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(){ft("Should not call beginInlineImage")}beginImageData(){ft("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Ct(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(Ct(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||nd("TODO: Support non-isolated groups."),t.knockout&&Z("Knockout groups not supported.");const s=Ct(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=z.getAxialAlignedBoundingBox(t.bbox,Ct(e));const n=[0,0,e.canvas.width,e.canvas.height];i=z.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()),th(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=Ct(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=z.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,vn,Af).call(this),md(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]=z.singularValueDecompose2dScale(Ct(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),md(this.ctx)}else md(this.ctx),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.endPath()}this.current=new M0(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),y(this,vn,Tf).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=Kw(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=Ct(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=z.transform(h,[e,s,i,n,r[d],r[d+1]]),[f,p]=z.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);O0(u,g),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,bi(e),Se.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),pd(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){Z("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){Z("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(),!he){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;D0(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,bi(i));i.imageSmoothingEnabled=P0(Ct(i),t.interpolate),pd(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;D0(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),pd(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===L0?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Ct(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}};vn=new WeakSet,Af=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)},Tf=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 Ao=ef;for(const a in vs)Ao.prototype[a]!==void 0&&(Ao.prototype[vs[a]]=Ao.prototype[a]);class yi{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(yi,Ih,null),w(yi,jh,"");const vd={UNKNOWN:0,DATA:1,ERROR:2},jt={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Be(a){switch(a instanceof Error||typeof a=="object"&&a!==null||ft('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new Jn(a.message);case"MissingPDFException":return new Qn(a.message);case"PasswordException":return new _g(a.message,a.code);case"UnexpectedResponseException":return new rd(a.message,a.status);case"UnknownErrorException":return new wg(a.message,a.details);default:return new wg(a.message,a.toString())}}class eh{constructor(t,e,s){w(this,$s);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,$s,Pv).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===vd.DATA)h.resolve(n.data);else if(n.callback===vd.ERROR)h.reject(Be(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:vd.DATA,callbackId:n.callbackId,data:l})},function(l){s.postMessage({sourceName:o,targetName:h,callback:vd.ERROR,callbackId:n.callbackId,reason:Be(l)})});return}if(n.streamId){y(this,$s,Ov).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:jt.PULL,streamId:n,desiredSize:l.desiredSize}),d.promise},cancel:l=>{Wt(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:jt.CANCEL,streamId:n,reason:Be(l)}),d.promise}},s)}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}$s=new WeakSet,Ov=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:jt.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:jt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){Wt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:jt.ERROR,streamId:e,reason:Be(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:jt.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:jt.START_COMPLETE,streamId:e,reason:Be(l)})})},Pv=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 jt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Be(t.reason));break;case jt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Be(t.reason));break;case jt.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:jt.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:jt.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:jt.PULL_COMPLETE,streamId:e,reason:Be(h)})});break;case jt.ENQUEUE:if(Wt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case jt.CLOSE:if(Wt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),y(this,$s,Qd).call(this,r,e);break;case jt.ERROR:Wt(r,"error should have stream controller"),r.controller.error(Be(t.reason)),y(this,$s,Qd).call(this,r,e);break;case jt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Be(t.reason)),y(this,$s,Qd).call(this,r,e);break;case jt.CANCEL:if(!o)break;new Promise(function(h){var l;h((l=o.onCancel)==null?void 0:l.call(o,Be(t.reason)))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:jt.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:jt.CANCEL_COMPLETE,streamId:e,reason:Be(h)})}),o.sinkCapability.reject(Be(t.reason)),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}},Qd=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 tx{constructor({parsedData:t,rawData:e}){w(this,Sr);w(this,Nh);b(this,Sr,t),b(this,Nh,e)}getRaw(){return c(this,Nh)}get(t){return c(this,Sr).get(t)??null}getAll(){return xg(c(this,Sr))}has(t){return c(this,Sr).has(t)}}Sr=new WeakMap,Nh=new WeakMap;const cn=Symbol("INTERNAL");class ex{constructor(t,{name:e,intent:s,usage:i}){w(this,Bh,!1);w(this,Hh,!1);w(this,Wh,!1);w(this,Wo,!0);b(this,Bh,!!(t&Ne.DISPLAY)),b(this,Hh,!!(t&Ne.PRINT)),this.name=e,this.intent=s,this.usage=i}get visible(){if(c(this,Wh))return c(this,Wo);if(!c(this,Wo))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!==cn&&ft("Internal method `_setVisible` called."),b(this,Wh,s),b(this,Wo,e)}}Bh=new WeakMap,Hh=new WeakMap,Wh=new WeakMap,Wo=new WeakMap;class sx{constructor(t,e=Ne.DISPLAY){w(this,Xh);w(this,bn,null);w(this,pt,new Map);w(this,Xo,null);w(this,zo,null);if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,b(this,zo,t.order);for(const s of t.groups)c(this,pt).set(s.id,new ex(e,s));if(t.baseState==="OFF")for(const s of c(this,pt).values())s._setVisible(cn,!1);for(const s of t.on)c(this,pt).get(s)._setVisible(cn,!0);for(const s of t.off)c(this,pt).get(s)._setVisible(cn,!1);b(this,Xo,this.getHash())}}isVisible(t){if(c(this,pt).size===0)return!0;if(!t)return nd("Optional content group not defined."),!0;if(t.type==="OCG")return c(this,pt).has(t.id)?c(this,pt).get(t.id).visible:(Z(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return y(this,Xh,Ef).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(c(this,pt).get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(!c(this,pt).get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(!c(this,pt).get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(c(this,pt).get(e).visible)return!1}return!0}return Z(`Unknown optional content policy ${t.policy}.`),!0}return Z(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0){const s=c(this,pt).get(t);if(!s){Z(`Optional content group not found: ${t}`);return}s._setVisible(cn,!!e,!0),b(this,bn,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,pt).get(i);if(n)switch(s){case"ON":n._setVisible(cn,!0);break;case"OFF":n._setVisible(cn,!1);break;case"Toggle":n._setVisible(cn,!n.visible);break}}b(this,bn,null)}get hasInitialVisibility(){return c(this,Xo)===null||this.getHash()===c(this,Xo)}getOrder(){return c(this,pt).size?c(this,zo)?c(this,zo).slice():[...c(this,pt).keys()]:null}getGroups(){return c(this,pt).size>0?xg(c(this,pt)):null}getGroup(t){return c(this,pt).get(t)||null}getHash(){if(c(this,bn)!==null)return c(this,bn);const t=new w0;for(const[e,s]of c(this,pt))t.update(`${e}:${s.visible}`);return b(this,bn,t.hexdigest())}}bn=new WeakMap,pt=new WeakMap,Xo=new WeakMap,zo=new WeakMap,Xh=new WeakSet,Ef=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,Xh,Ef).call(this,n);else if(c(this,pt).has(n))r=c(this,pt).get(n).visible;else return Z(`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 ix{constructor(t,{disableRange:e=!1,disableStream:s=!1}){Wt(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)});Wt(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(){Wt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new nx(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new rx(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 nx{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=kg(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 rx{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 ox(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=od(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 Bg({getResponseHeader:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a("Accept-Ranges")!=="bytes"||(a("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function Hg(a){const t=a("Content-Disposition");if(t){let e=ox(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(kg(e))return e}return null}function bd(a,t){return a===404||a===0&&t.startsWith("file:")?new Qn('Missing PDF "'+t+'".'):new rd(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function F0(a){return a===200||a===206}function R0(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function I0(a){const t=new Headers;for(const e in a){const s=a[e];s!==void 0&&t.append(e,s)}return t}function j0(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(Z(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class N0{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.httpHeaders=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 Wt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new ax(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new hx(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 ax{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,this._headers=I0(this._stream.httpHeaders);const s=e.url;fetch(s,R0(this._headers,this._withCredentials,this._abortController)).then(i=>{if(!F0(i.status))throw bd(i.status,s);this._reader=i.body.getReader(),this._headersCapability.resolve();const n=h=>i.headers.get(h),{allowRangeRequests:r,suggestedLength:o}=Bg({getResponseHeader:n,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=o||this._contentLength,this._filename=Hg(n),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Jn("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:j0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}class hx{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,this._headers=I0(this._stream.httpHeaders),this._headers.append("Range",`bytes=${e}-${s-1}`);const n=i.url;fetch(n,R0(this._headers,this._withCredentials,this._abortController)).then(r=>{if(!F0(r.status))throw bd(r.status,n);this._readCapability.resolve(),this._reader=r.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:j0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}const Wg=200,Xg=206;function lx(a){const t=a.response;return typeof t!="string"?t:od(t).buffer}class cx{constructor(t,e={}){this.url=t,this.isHttp=/^https?:/i.test(t),this.httpHeaders=this.isHttp&&e.httpHeaders||Object.create(null),this.withCredentials=e.withCredentials||!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 in this.httpHeaders){const r=this.httpHeaders[n];r!==void 0&&e.setRequestHeader(n,r)}return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=Xg):i.expectedStatus=Wg,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||Wg;if(!(n===Wg&&s.expectedStatus===Xg)&&n!==s.expectedStatus){(l=s.onError)==null||l.call(s,i.status);return}const o=lx(i);if(n===Xg){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 dx{constructor(t){this._source=t,this._manager=new cx(t.url,{httpHeaders:t.httpHeaders,withCredentials:t.withCredentials}),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 Wt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new ux(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new gx(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 ux{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._headersReceivedCapability=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=r=>e.getResponseHeader(r),{allowRangeRequests:i,suggestedLength:n}=Bg({getResponseHeader:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Hg(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersReceivedCapability.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=bd(t,this._url),this._headersReceivedCapability.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._headersReceivedCapability.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._headersReceivedCapability.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 gx{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=bd(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 B0=/^file:\/\/\/[a-zA-Z]:\//;function fx(a){const t=Xs.get("url"),e=t.parse(a);return e.protocol==="file:"||e.host?e:/^[a-z]:[/\\]/i.test(a)?t.parse(`file:///${a}`):(e.host||(e.protocol="file:"),e)}class px{constructor(t){this.source=t,this.url=fx(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=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 Wt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new bx(this):new mx(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new yx(this,t,e):new vx(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 H0{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 Jn("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class W0{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)}}function yd(a,t){return{protocol:a.protocol,auth:a.auth,host:a.hostname,port:a.port,path:a.path,method:"GET",headers:t}}class mx extends H0{constructor(t){super(t);const e=s=>{if(s.statusCode===404){const o=new Qn(`Missing PDF "${this._url}".`);this._storedError=o,this._headersCapability.reject(o);return}this._headersCapability.resolve(),this._setReadableStream(s);const i=o=>this._readableStream.headers[o.toLowerCase()],{allowRangeRequests:n,suggestedLength:r}=Bg({getResponseHeader:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=r||this._contentLength,this._filename=Hg(i)};if(this._request=null,this._url.protocol==="http:"){const s=Xs.get("http");this._request=s.request(yd(this._url,t.httpHeaders),e)}else{const s=Xs.get("https");this._request=s.request(yd(this._url,t.httpHeaders),e)}this._request.on("error",s=>{this._storedError=s,this._headersCapability.reject(s)}),this._request.end()}}class vx extends W0{constructor(t,e,s){super(t),this._httpHeaders={};for(const n in t.httpHeaders){const r=t.httpHeaders[n];r!==void 0&&(this._httpHeaders[n]=r)}this._httpHeaders.Range=`bytes=${e}-${s-1}`;const i=n=>{if(n.statusCode===404){const r=new Qn(`Missing PDF "${this._url}".`);this._storedError=r;return}this._setReadableStream(n)};if(this._request=null,this._url.protocol==="http:"){const n=Xs.get("http");this._request=n.request(yd(this._url,this._httpHeaders),i)}else{const n=Xs.get("https");this._request=n.request(yd(this._url,this._httpHeaders),i)}this._request.on("error",n=>{this._storedError=n}),this._request.end()}}class bx extends H0{constructor(t){super(t);let e=decodeURIComponent(this._url.path);B0.test(this._url.href)&&(e=e.replace(/^\//,""));const s=Xs.get("fs");s.promises.lstat(e).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(e)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new Qn(`Missing PDF "${e}".`)),this._storedError=i,this._headersCapability.reject(i)})}}class yx extends W0{constructor(t,e,s){super(t);let i=decodeURIComponent(this._url.path);B0.test(this._url.href)&&(i=i.replace(/^\//,""));const n=Xs.get("fs");this._setReadableStream(n.createReadStream(i,{start:e,end:s-1}))}}const _x=1e5,Le=30,wx=.8,ge=class ge{constructor({textContentSource:t,container:e,viewport:s}){w(this,Li);w(this,yn,Promise.withResolvers());w(this,Fe,null);w(this,zh,!1);w(this,Vh,!!((iv=globalThis.FontInspector)!=null&&iv.enabled));w(this,Cr,null);w(this,Pi,null);w(this,Gh,0);w(this,Uh,0);w(this,Ar,null);w(this,Vo,null);w(this,Go,0);w(this,_n,0);w(this,Uo,Object.create(null));w(this,Yh,[]);w(this,Yo,null);w(this,Tr,[]);w(this,qh,new WeakMap);w(this,$h,null);var h;if(t instanceof ReadableStream)b(this,Yo,t);else if(typeof t=="object")b(this,Yo,new ReadableStream({start(l){l.enqueue(t),l.close()}}));else throw new Error('No "textContentSource" parameter specified.');b(this,Fe,b(this,Vo,e)),b(this,_n,s.scale*(globalThis.devicePixelRatio||1)),b(this,Go,s.rotation),b(this,Pi,{prevFontSize:null,prevFontFamily:null,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=ge,Ks,Rv).call(h),Zn(e,s),c(this,yn).promise.catch(()=>{}).then(()=>{c(ge,qo).delete(this),b(this,Pi,null),b(this,Uo,null)})}render(){const t=()=>{c(this,Ar).read().then(({value:e,done:s})=>{if(s){c(this,yn).resolve();return}c(this,Cr)??b(this,Cr,e.lang),Object.assign(c(this,Uo),e.styles),y(this,Li,Lv).call(this,e.items),t()},c(this,yn).reject)};return b(this,Ar,c(this,Yo).getReader()),c(ge,qo).add(this),t(),c(this,yn).promise}update({viewport:t,onBefore:e=null}){var n;const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==c(this,Go)&&(e==null||e(),b(this,Go,i),Zn(c(this,Vo),{rotation:i})),s!==c(this,_n)){e==null||e(),b(this,_n,s);const r={prevFontSize:null,prevFontFamily:null,div:null,properties:null,ctx:y(n=ge,Ks,Jd).call(n,c(this,Cr))};for(const o of c(this,Tr))r.properties=c(this,qh).get(o),r.div=o,y(this,Li,kf).call(this,r)}}cancel(){var e;const t=new Jn("TextLayer task cancelled.");(e=c(this,Ar))==null||e.cancel(t).catch(()=>{}),b(this,Ar,null),c(this,yn).reject(t)}get textDivs(){return c(this,Tr)}get textContentItemsStr(){return c(this,Yh)}static cleanup(){if(!(c(this,qo).size>0)){c(this,Er).clear();for(const{canvas:t}of c(this,kr).values())t.remove();c(this,kr).clear()}}};yn=new WeakMap,Fe=new WeakMap,zh=new WeakMap,Vh=new WeakMap,Cr=new WeakMap,Pi=new WeakMap,Gh=new WeakMap,Uh=new WeakMap,Ar=new WeakMap,Vo=new WeakMap,Go=new WeakMap,_n=new WeakMap,Uo=new WeakMap,Yh=new WeakMap,Yo=new WeakMap,Tr=new WeakMap,qh=new WeakMap,$h=new WeakMap,Er=new WeakMap,kr=new WeakMap,wn=new WeakMap,qo=new WeakMap,Li=new WeakSet,Lv=function(t){var i,n;if(c(this,zh))return;(n=c(this,Pi)).ctx??(n.ctx=y(i=ge,Ks,Jd).call(i,c(this,Cr)));const e=c(this,Tr),s=c(this,Yh);for(const r of t){if(e.length>_x){Z("Ignoring additional textDivs for performance reasons."),b(this,zh,!0);return}if(r.str===void 0){if(r.type==="beginMarkedContentProps"||r.type==="beginMarkedContent"){const o=c(this,Fe);b(this,Fe,document.createElement("span")),c(this,Fe).classList.add("markedContent"),r.id!==null&&c(this,Fe).setAttribute("id",`${r.id}`),o.append(c(this,Fe))}else r.type==="endMarkedContent"&&b(this,Fe,c(this,Fe).parentNode);continue}s.push(r.str),y(this,Li,Fv).call(this,r)}},Fv=function(t){var m;const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};c(this,Tr).push(e);const i=z.transform(c(this,$h),t.transform);let n=Math.atan2(i[1],i[0]);const r=c(this,Uo)[t.fontName];r.vertical&&(n+=Math.PI/2);const o=c(this,Vh)&&r.fontSubstitution||r.fontFamily,h=Math.hypot(i[2],i[3]),l=h*y(m=ge,Ks,Iv).call(m,o,c(this,Cr));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,Fe)===c(this,Vo)?(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(ge,wn)*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,Pi).div=e,c(this,Pi).properties=s,y(this,Li,kf).call(this,c(this,Pi)),s.hasText&&c(this,Fe).append(e),s.hasEOL){const _=document.createElement("br");_.setAttribute("role","presentation"),c(this,Fe).append(_)}},kf=function(t){const{div:e,properties:s,ctx:i,prevFontSize:n,prevFontFamily:r}=t,{style:o}=e;let h="";if(c(ge,wn)>1&&(h=`scale(${1/c(ge,wn)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:l}=o,{canvasWidth:d,fontSize:u}=s;(n!==u||r!==l)&&(i.font=`${u*c(this,_n)}px ${l}`,t.prevFontSize=u,t.prevFontFamily=l);const{width:g}=i.measureText(e.textContent);g>0&&(h=`scaleX(${d*c(this,_n)/g}) ${h}`)}s.angle!==0&&(h=`rotate(${s.angle}deg) ${h}`),h.length>0&&(o.transform=h)},Ks=new WeakSet,Jd=function(t=null){let e=c(this,kr).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,kr).set(t,e)}return e},Rv=function(){if(c(this,wn)!==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,wn,t.getBoundingClientRect().height),t.remove()},Iv=function(t,e){const s=c(this,Er).get(t);if(s)return s;const i=y(this,Ks,Jd).call(this,e),n=i.font;i.canvas.width=i.canvas.height=Le,i.font=`${Le}px ${t}`;const r=i.measureText("");let o=r.fontBoundingBoxAscent,h=Math.abs(r.fontBoundingBoxDescent);if(o){const u=o/(o+h);return c(this,Er).set(t,u),i.canvas.width=i.canvas.height=0,i.font=n,u}i.strokeStyle="red",i.clearRect(0,0,Le,Le),i.strokeText("g",0,0);let l=i.getImageData(0,0,Le,Le).data;h=0;for(let u=l.length-1-3;u>=0;u-=4)if(l[u]>0){h=Math.ceil(u/4/Le);break}i.clearRect(0,0,Le,Le),i.strokeText("A",0,Le),l=i.getImageData(0,0,Le,Le).data,o=0;for(let u=0,g=l.length;u<g;u+=4)if(l[u]>0){o=Le-Math.floor(u/4/Le);break}i.canvas.width=i.canvas.height=0,i.font=n;const d=o?o/(o+h):wx;return c(this,Er).set(t,d),d},w(ge,Ks),w(ge,Er,new Map),w(ge,kr,new Map),w(ge,wn,null),w(ge,qo,new Set);let sh=ge;class ih{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(ih.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 xx=65536,Sx=100,Cx=5e3,Ax=he?Nw:Aw,Tx=he?Bw:p0,Ex=he?jw:Cw,kx=he?Hw:m0;function Mx(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new zg,{docId:e}=t,s=a.url?Dx(a.url):null,i=a.data?Ox(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof z0?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:xx;let d=a.worker instanceof To?a.worker:null;const u=a.verbosity,g=typeof a.docBaseUrl=="string"&&!ud(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,p=a.cMapPacked!==!1,m=a.CMapReaderFactory||Tx,_=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,v=a.StandardFontDataFactory||kx,x=a.stopAtErrors!==!0,S=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,T=a.isEvalSupported!==!1,E=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!he,M=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,P=typeof a.disableFontFace=="boolean"?a.disableFontFace:he,O=a.fontExtraProperties===!0,R=a.enableXfa===!0,D=a.ownerDocument||globalThis.document,L=a.disableRange===!0,F=a.disableStream===!0,I=a.disableAutoFetch===!0,X=a.pdfBug===!0,Y=a.enableHWA===!0,J=h?h.length:a.length??NaN,W=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!he&&!P,V=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:m===p0&&v===m0&&f&&_&&Ka(f,document.baseURI)&&Ka(_,document.baseURI),Qt=a.canvasFactory||new Ax({ownerDocument:D,enableHWA:Y}),Ke=a.filterFactory||new Ex({docId:e,ownerDocument:D}),Zi=null;gw(u);const Ut={canvasFactory:Qt,filterFactory:Ke};if(V||(Ut.cMapReaderFactory=new m({baseUrl:f,isCompressed:p}),Ut.standardFontDataFactory=new v({baseUrl:_})),!d){const ls={verbosity:u,port:yi.workerPort};d=ls.port?To.fromPort(ls):new To(ls),t._worker=d}const Tt={docId:e,apiVersion:"4.5.136",data:i,password:o,disableAutoFetch:I,rangeChunkSize:l,length:J,docBaseUrl:g,enableXfa:R,evaluatorOptions:{maxImageSize:S,disableFontFace:P,ignoreErrors:x,isEvalSupported:T,isOffscreenCanvasSupported:E,canvasMaxAreaInBytes:M,fontExtraProperties:O,useSystemFonts:W,cMapUrl:V?f:null,standardFontDataUrl:V?_:null}},Qe={disableFontFace:P,fontExtraProperties:O,ownerDocument:D,pdfBug:X,styleElement:Zi,loadingParams:{disableAutoFetch:I,enableXfa:R}};return d.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const ls=d.messageHandler.sendWithPromise("GetDocRequest",Tt,i?[i.buffer]:null);let pe;if(h)pe=new ix(h,{disableRange:L,disableStream:F});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");pe=(Ps=>he?function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype}()&&Ka(Ps.url)?new N0(Ps):new px(Ps):Ka(Ps.url)?new N0(Ps):new dx(Ps))({url:s,length:J,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:L,disableStream:F})}return ls.then(wt=>{if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const Ps=new eh(e,wt,d.port),xa=new Rx(Ps,t,pe,Qe,Ut);t._transport=xa,Ps.send("Ready",null)})}).catch(t._capability.reject),t}function Dx(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(he&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Ox(a){if(he&&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 od(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 X0(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 Bd=class Bd{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Je(Bd,Nd)._++}`,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)}};Nd=new WeakMap,w(Bd,Nd,0);let zg=Bd;class z0{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){ft("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Px{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return at(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 Lx{constructor(t,e,s,i=!1){w(this,rs);w(this,xn,null);w(this,Fi,!1);this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new v0:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new V0,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 $a({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 at(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=an.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:d=null,isEditing:u=!1}){var T,E;(T=this._stats)==null||T.time("Overall");const g=this._transport.getRenderingIntent(s,i,d,u),{renderingIntent:f,cacheKey:p}=g;b(this,Fi,!1),y(this,rs,Zd).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&Ne.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=M=>{var P;m.renderTasks.delete(x),(this._maybeCleanupAfterRender||_)&&b(this,Fi,!0),y(this,rs,Ea).call(this,!_),M?(x.capability.reject(M),this._abortOperatorList({intentState:m,reason:M instanceof Error?M:new Error(M)})):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 Vg({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(([M,P])=>{var O;if(this.destroyed){v();return}if((O=this._stats)==null||O.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:M,optionalContentConfig:P}),x.operatorListChanged()}).catch(v),S}getOperatorList({intent:t="display",annotationMode:e=an.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=>ih.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,Fi,!1),y(this,rs,Zd).call(this),Promise.all(t)}cleanup(t=!1){b(this,Fi,!0);const e=y(this,rs,Ea).call(this,!1);return t&&e&&this._stats&&(this._stats=new v0),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,rs,Ea).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,rs,Ea).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 Eg){let i=Sx;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 Jn(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}}xn=new WeakMap,Fi=new WeakMap,rs=new WeakSet,Ea=function(t=!1){if(y(this,rs,Zd).call(this),!c(this,Fi)||this.destroyed)return!1;if(t)return b(this,xn,setTimeout(()=>{b(this,xn,null),y(this,rs,Ea).call(this,!1)},Cx)),!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,Fi,!1),!0},Zd=function(){c(this,xn)&&(clearTimeout(c(this,xn)),b(this,xn,null))};class Fx{constructor(){w(this,Mr,new Set);w(this,Hd,Promise.resolve())}postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};c(this,Hd).then(()=>{for(const i of c(this,Mr))i.call(this,s)})}addEventListener(t,e){c(this,Mr).add(e)}removeEventListener(t,e){c(this,Mr).delete(e)}terminate(){c(this,Mr).clear()}}Mr=new WeakMap,Hd=new WeakMap;const _i={isWorkerDisabled:!1,fakeWorkerId:0};he&&(_i.isWorkerDisabled=!0,yi.workerSrc||(yi.workerSrc="./pdf.worker.mjs")),_i.isSameOrigin=function(a,t){let e;try{if(e=new URL(a),!e.origin||e.origin==="null")return!1}catch{return!1}const s=new URL(t,e);return e.origin===s.origin},_i.createCDNWrapper=function(a){const t=`await import("${a}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))};const ze=class ze{constructor({name:t=null,port:e=null,verbosity:s=fw()}={}){w(this,$o);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(ze,Dr))!=null&&i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(c(ze,Dr)||b(ze,Dr,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return he?Promise.all([Xs.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 eh("main","worker",t),this._messageHandler.on("ready",function(){}),y(this,$o,tu).call(this)}_initialize(){if(_i.isWorkerDisabled||c(ze,Ko,eu)){this._setupFakeWorker();return}let{workerSrc:t}=ze;try{_i.isSameOrigin(window.location.href,t)||(t=_i.createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new eh("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,$o,tu).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{nd("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){_i.isWorkerDisabled||(Z("Setting up fake worker."),_i.isWorkerDisabled=!0),ze._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Fx;this._port=e;const s=`fake${_i.fakeWorkerId++}`,i=new eh(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new eh(s,s+"_worker",e),y(this,$o,tu).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(ze,Dr))==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,Dr))==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 ze(t)}static get workerSrc(){if(yi.workerSrc)return yi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return at(this,"_setupFakeWorkerGlobal",(async()=>c(this,Ko,eu)?c(this,Ko,eu):(await import(this.workerSrc)).WorkerMessageHandler)())}};Dr=new WeakMap,$o=new WeakSet,tu=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Ko=new WeakSet,eu=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},w(ze,Ko),w(ze,Dr);let To=ze;class Rx{constructor(t,e,s,i,n){w(this,Or);w(this,Ri,new Map);w(this,Qs,new Map);w(this,Qo,new Map);w(this,Jo,new Map);w(this,Js,null);this.messageHandler=t,this.loadingTask=e,this.commonObjs=new V0,this.fontLoader=new Rw({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 at(this,"annotationStorage",new Fg)}getRenderingIntent(t,e=an.ENABLE,s=null,i=!1,n=!1){let r=Ne.DISPLAY,o=Lg;switch(t){case"any":r=Ne.ANY;break;case"display":break;case"print":r=Ne.PRINT;break;default:Z(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Ne.PRINT&&s instanceof x0?s:this.annotationStorage;switch(e){case an.DISABLE:r+=Ne.ANNOTATIONS_DISABLE;break;case an.ENABLE:break;case an.ENABLE_FORMS:r+=Ne.ANNOTATIONS_FORMS;break;case an.ENABLE_STORAGE:r+=Ne.ANNOTATIONS_STORAGE,o=h.serializable;break;default:Z(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Ne.IS_EDITING),n&&(r+=Ne.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,Js))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const i of c(this,Qs).values())t.push(i._destroy());c(this,Qs).clear(),c(this,Qo).clear(),c(this,Jo).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,Ri).clear(),this.filterFactory.destroy(),sh.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new Jn("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)=>{Wt(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}Wt(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)=>{Wt(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}Wt(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 Px(s,this))}),t.on("DocException",function(s){let i;switch(s.name){case"PasswordException":i=new _g(s.message,s.code);break;case"InvalidPDFException":i=new d0(s.message);break;case"MissingPDFException":i=new Qn(s.message);break;case"UnexpectedResponseException":i=new rd(s.message,s.status);break;case"UnknownErrorException":i=new wg(s.message,s.details);break;default:ft("DocException - expected a valid Error.")}e._capability.reject(i)}),t.on("PasswordRequest",s=>{if(b(this,Js,Promise.withResolvers()),e.onPassword){const i=n=>{n instanceof Error?c(this,Js).reject(n):c(this,Js).resolve({password:n})};try{e.onPassword(i,s.code)}catch(n){c(this,Js).reject(n)}}else c(this,Js).reject(new _g(s.message,s.code));return c(this,Js).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,Qs).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;Z(`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 Iw(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;Wt(g,"The imageRef must be defined.");for(const f of c(this,Qs).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,Qs).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)>lw&&(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&&Z("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,Qo).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,Jo).set(n.refStr,t);const r=new Lx(e,n,this,this._params.pdfBug);return c(this,Qs).set(e,r),r});return c(this,Qo).set(e,i),i}getPageIndex(t){return X0(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,Or,Ul).call(this,"GetFieldObjects")}hasJSActions(){return y(this,Or,Ul).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,Or,Ul).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,Or,Ul).call(this,"GetOptionalContentConfig").then(e=>new sx(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=c(this,Ri).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 tx(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,Ri).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,Qs).values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),c(this,Ri).clear(),this.filterFactory.destroy(!0),sh.cleanup()}}cachedPageNumber(t){if(!X0(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return c(this,Jo).get(e)??null}}Ri=new WeakMap,Qs=new WeakMap,Qo=new WeakMap,Jo=new WeakMap,Js=new WeakMap,Or=new WeakSet,Ul=function(t,e=null){const s=c(this,Ri).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return c(this,Ri).set(t,i),i};const _d=Symbol("INITIAL_DATA");class V0{constructor(){w(this,Kh);w(this,Ss,Object.create(null))}get(t,e=null){if(e){const i=y(this,Kh,Mf).call(this,t);return i.promise.then(()=>e(i.data)),null}const s=c(this,Ss)[t];if(!s||s.data===_d)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=c(this,Ss)[t];return!!e&&e.data!==_d}resolve(t,e=null){const s=y(this,Kh,Mf).call(this,t);s.data=e,s.resolve()}clear(){var t;for(const e in c(this,Ss)){const{data:s}=c(this,Ss)[e];(t=s==null?void 0:s.bitmap)==null||t.close()}b(this,Ss,Object.create(null))}*[Symbol.iterator](){for(const t in c(this,Ss)){const{data:e}=c(this,Ss)[t];e!==_d&&(yield[t,e])}}}Ss=new WeakMap,Kh=new WeakSet,Mf=function(t){var e;return(e=c(this,Ss))[t]||(e[t]={...Promise.withResolvers(),data:_d})};class Ix{constructor(t){w(this,Sn,null);b(this,Sn,t),this.onContinue=null}get promise(){return c(this,Sn).capability.promise}cancel(t=0){c(this,Sn).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=c(this,Sn).operatorList;if(!t)return!1;const{annotationCanvasMap:e}=c(this,Sn);return t.form||t.canvas&&(e==null?void 0:e.size)>0}}Sn=new WeakMap;const Lr=class Lr{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,Cn,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 Ix(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(Lr,Pr).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(Lr,Pr).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 Ao(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,Cn)&&(window.cancelAnimationFrame(c(this,Cn)),b(this,Cn,null)),c(Lr,Pr).delete(this._canvas),this.callback(t||new Eg(`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,Cn,window.requestAnimationFrame(()=>{b(this,Cn,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(Lr,Pr).delete(this._canvas),this.callback())))}};Cn=new WeakMap,Pr=new WeakMap,w(Lr,Pr,new WeakSet);let Vg=Lr;const jx="4.5.136",Nx="3a21f03b0";function G0(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function nh(a){return Math.max(0,Math.min(255,255*a))}class U0{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=nh(t),[t,t,t]}static G_HTML([t]){const e=G0(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(nh)}static RGB_HTML(t){return`#${t.map(G0).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[nh(1-Math.min(1,t+i)),nh(1-Math.min(1,s+i)),nh(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 Y0{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&&ih.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&&ih.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 rh=1e3,Bx=9,er=new WeakSet;function wi(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class Hx{static create(t){switch(t.data.annotationType){case Ht.LINK:return new q0(t);case Ht.TEXT:return new Wx(t);case Ht.WIDGET:switch(t.data.fieldType){case"Tx":return new Xx(t);case"Btn":return t.data.radioButton?new $0(t):t.data.checkBox?new Vx(t):new Gx(t);case"Ch":return new Ux(t);case"Sig":return new zx(t)}return new sr(t);case Ht.POPUP:return new Gg(t);case Ht.FREETEXT:return new K0(t);case Ht.LINE:return new qx(t);case Ht.SQUARE:return new $x(t);case Ht.CIRCLE:return new Kx(t);case Ht.POLYLINE:return new Q0(t);case Ht.CARET:return new Jx(t);case Ht.INK:return new J0(t);case Ht.POLYGON:return new Qx(t);case Ht.HIGHLIGHT:return new Zx(t);case Ht.UNDERLINE:return new tS(t);case Ht.SQUIGGLY:return new eS(t);case Ht.STRIKEOUT:return new sS(t);case Ht.STAMP:return new Z0(t);case Ht.FILEATTACHMENT:return new iS(t);default:return new Ft(t)}}}const sf=class sf{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){w(this,Qh);w(this,Fr,null);w(this,Zo,!1);w(this,ta,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 sf._hasPopupData(this.data)}updateEdited(t){var s;if(!this.container)return;c(this,Fr)||b(this,Fr,{rect:this.data.rect.slice(0)});const{rect:e}=t;e&&y(this,Qh,Df).call(this,e),(s=c(this,ta))==null||s.popup.updateEdited(t)}resetEdited(){var t;c(this,Fr)&&(y(this,Qh,Df).call(this,c(this,Fr).rect),(t=c(this,ta))==null||t.popup.resetEdited(),b(this,Fr,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 sr||(n.tabIndex=rh);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 Gg){const{rotation:m}=e;return!e.hasOwnCanvas&&m!==0&&this.setRotation(m,n),n}const{width:o,height:h}=wi(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 $0){const x=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=x}switch(e.borderStyle.style){case qa.SOLID:r.borderStyle="solid";break;case qa.DASHED:r.borderStyle="dashed";break;case qa.BEVELED:Z("Unimplemented border style: beveled");break;case qa.INSET:Z("Unimplemented border style: inset");break;case qa.UNDERLINE:r.borderBottomStyle="solid";break}const v=e.borderColor||null;v?(b(this,Zo,!0),r.borderColor=z.makeHexColor(v[0]|0,v[1]|0,v[2]|0)):r.borderWidth=0}const l=z.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}=wi(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]=U0[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:U0[`${r}_rgb`](o)})};return at(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,Zo)){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],T=t[m+3],E=d.createElement("rect"),M=(S-e)/h,P=(n-x)/l,O=(v-S)/h,R=(x-T)/l;E.setAttribute("x",M),E.setAttribute("y",P),E.setAttribute("width",O),E.setAttribute("height",R),f.append(E),o==null||o.push(`<rect vector-effect="non-scaling-stroke" x="${M}" y="${P}" width="${O}" height="${R}"/>`)}c(this,Zo)&&(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,ta,new Gg({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(){ft("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&&!er.has(l)){Z(`_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&&er.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})})}};Fr=new WeakMap,Zo=new WeakMap,ta=new WeakMap,Qh=new WeakSet,Df=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}=wi(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 Ft=sf;class q0 extends Ft{constructor(e,s=null){super(e,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});w(this,Ve);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,Ve,jv).call(this,i,e.attachment,e.attachmentDest),n=!0):e.setOCGState?(y(this,Ve,Nv).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,Ve,ro).call(this)}_bindNamedAction(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(s),!1),y(this,Ve,ro).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,Ve,ro).call(this)}_bindResetFormAction(e,s){const i=e.onclick;if(i||(e.href=this.linkService.getAnchorUrl("")),y(this,Ve,ro).call(this),!this._fieldObjects){Z('_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(!er.has(p)){Z(`_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}}}Ve=new WeakSet,ro=function(){this.container.setAttribute("data-internal-link","")},jv=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,Ve,ro).call(this)},Nv=function(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(s),!1),y(this,Ve,ro).call(this)};class Wx extends Ft{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 sr extends Ft{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 De.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":z.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Bx,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/(bg*i))||1,u=l/d;r=Math.min(i,h(u/bg))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/bg))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=z.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 Xx extends sr{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),er.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=rh,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,T=x;switch(f.inputType){case"deleteWordBackward":{const M=_.substring(0,v).match(/\w*[^\w]*$/);M&&(S-=M[0].length);break}case"deleteWordForward":{const M=_.substring(v).match(/^[^\w]*\w*/);M&&(T+=M[0].length);break}case"deleteContentBackward":v===x&&(S-=1);break;case"deleteContentForward":v===x&&(T+=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:T}})}),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 zx extends sr{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Vx extends sr{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 er.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=rh,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 $0 extends sr{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(er.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=rh,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 Gx extends q0{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 Ux extends sr{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");er.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=rh;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 Gg extends Ft{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Ft._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Yx({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=>`${f0}${s}`).join(",")),this.container}}class Yx{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,mt);w(this,ea,y(this,mt,Wv).bind(this));w(this,Wd,y(this,mt,Pf).bind(this));w(this,Xd,y(this,mt,nu).bind(this));w(this,sa,y(this,mt,iu).bind(this));w(this,Rr,null);w(this,Mt,null);w(this,Ii,null);w(this,Ir,null);w(this,Jh,null);w(this,Zh,null);w(this,ia,null);w(this,ji,!1);w(this,Cs,null);w(this,Ni,null);w(this,tl,null);w(this,Bi,null);w(this,el,null);w(this,jr,null);w(this,Nr,!1);var g;b(this,Mt,t),b(this,el,i),b(this,Ii,r),b(this,Bi,o),b(this,Zh,h),b(this,Rr,e),b(this,tl,l),b(this,ia,d),b(this,Jh,s),b(this,Ir,y0.toDateObject(n)),this.trigger=s.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",c(this,sa)),f.addEventListener("mouseenter",c(this,Xd)),f.addEventListener("mouseleave",c(this,Wd)),f.classList.add("popupTriggerArea");for(const f of s)(g=f.container)==null||g.addEventListener("keydown",c(this,ea));c(this,Mt).hidden=!0,u&&y(this,mt,iu).call(this)}render(){if(c(this,Cs))return;const t=b(this,Cs,document.createElement("div"));if(t.className="popup",c(this,Rr)){const n=t.style.outlineColor=z.makeHexColor(...c(this,Rr));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=z.makeHexColor(...c(this,Rr).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,el),t.append(e),c(this,Ir)){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),n.setAttribute("data-l10n-args",JSON.stringify({date:c(this,Ir).toLocaleDateString(),time:c(this,Ir).toLocaleTimeString()})),e.append(n)}const i=c(this,mt,su);if(i)Y0.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(c(this,Ii));t.append(n)}c(this,Mt).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,jr)||b(this,jr,{contentsObj:c(this,Ii),richText:c(this,Bi)}),t&&b(this,Ni,null),e&&(b(this,Bi,y(this,mt,Hv).call(this,e)),b(this,Ii,null)),(s=c(this,Cs))==null||s.remove(),b(this,Cs,null)}resetEdited(){var t;c(this,jr)&&({contentsObj:Je(this,Ii)._,richText:Je(this,Bi)._}=c(this,jr),b(this,jr,null),(t=c(this,Cs))==null||t.remove(),b(this,Cs,null),b(this,Ni,null))}forceHide(){b(this,Nr,this.isVisible),c(this,Nr)&&(c(this,Mt).hidden=!0)}maybeShow(){c(this,Nr)&&(c(this,Cs)||y(this,mt,nu).call(this),b(this,Nr,!1),c(this,Mt).hidden=!1)}get isVisible(){return c(this,Mt).hidden===!1}}ea=new WeakMap,Wd=new WeakMap,Xd=new WeakMap,sa=new WeakMap,Rr=new WeakMap,Mt=new WeakMap,Ii=new WeakMap,Ir=new WeakMap,Jh=new WeakMap,Zh=new WeakMap,ia=new WeakMap,ji=new WeakMap,Cs=new WeakMap,Ni=new WeakMap,tl=new WeakMap,Bi=new WeakMap,el=new WeakMap,jr=new WeakMap,Nr=new WeakMap,mt=new WeakSet,su=function(){const t=c(this,Bi),e=c(this,Ii);return t!=null&&t.str&&(!(e!=null&&e.str)||e.str===t.str)&&c(this,Bi).html||null},Of=function(){var t,e,s;return((s=(e=(t=c(this,mt,su))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.fontSize)||0},Bv=function(){var t,e,s;return((s=(e=(t=c(this,mt,su))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.color)||null},Hv=function(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:c(this,mt,Bv),fontSize:c(this,mt,Of)?`calc(${c(this,mt,Of)}px * var(--scale-factor))`:""}};for(const n of t.split(`
501
- `))e.push({name:"span",value:n,attributes:i});return s},Wv=function(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&c(this,ji))&&y(this,mt,iu).call(this)},Xv=function(){if(c(this,Ni)!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=c(this,Zh);let r=!!c(this,ia),o=r?c(this,ia):c(this,tl);for(const p of c(this,Jh))if(!o||z.intersect(p.data.rect,o)!==null){o=p.data.rect,r=!0;break}const h=z.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,Ni,[100*(u-i)/e,100*(g-n)/s]);const{style:f}=c(this,Mt);f.left=`${c(this,Ni)[0]}%`,f.top=`${c(this,Ni)[1]}%`},iu=function(){b(this,ji,!c(this,ji)),c(this,ji)?(y(this,mt,nu).call(this),c(this,Mt).addEventListener("click",c(this,sa)),c(this,Mt).addEventListener("keydown",c(this,ea))):(y(this,mt,Pf).call(this),c(this,Mt).removeEventListener("click",c(this,sa)),c(this,Mt).removeEventListener("keydown",c(this,ea)))},nu=function(){c(this,Cs)||this.render(),this.isVisible?c(this,ji)&&c(this,Mt).classList.add("focused"):(y(this,mt,Xv).call(this),c(this,Mt).hidden=!1,c(this,Mt).style.zIndex=parseInt(c(this,Mt).style.zIndex)+1e3)},Pf=function(){c(this,Mt).classList.remove("focused"),!(c(this,ji)||!this.isVisible)&&(c(this,Mt).hidden=!0,c(this,Mt).style.zIndex=parseInt(c(this,Mt).style.zIndex)-1e3)};class K0 extends Ft{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=nt.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 qx extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,sl,null)}render(){this.container.classList.add("lineAnnotation");const e=this.data,{width:s,height:i}=wi(e.rect),n=this.svgFactory.create(s,i,!0),r=b(this,sl,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,sl)}addHighlightArea(){this.container.classList.add("highlightArea")}}sl=new WeakMap;class $x extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,il,null)}render(){this.container.classList.add("squareAnnotation");const e=this.data,{width:s,height:i}=wi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,il,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,il)}addHighlightArea(){this.container.classList.add("highlightArea")}}il=new WeakMap;class Kx extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,nl,null)}render(){this.container.classList.add("circleAnnotation");const e=this.data,{width:s,height:i}=wi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,nl,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,nl)}addHighlightArea(){this.container.classList.add("highlightArea")}}nl=new WeakMap;class Q0 extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,rl,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}=wi(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,rl,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,rl)}addHighlightArea(){this.container.classList.add("highlightArea")}}rl=new WeakMap;class Qx extends Q0{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Jx extends Ft{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 J0 extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,ol,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=nt.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{width:r,height:o}=wi(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,ol).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.container}getElementsToTriggerPopup(){return c(this,ol)}addHighlightArea(){this.container.classList.add("highlightArea")}}ol=new WeakMap;class Zx extends Ft{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class tS extends Ft{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 eS extends Ft{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 sS extends Ft{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 Z0 extends Ft{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class iS extends Ft{constructor(e){var i;super(e,{isRenderable:!0});w(this,hl);w(this,al,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,hl,Lf).bind(this)),b(this,al,i);const{isMac:n}=De.platform;return e.addEventListener("keydown",r=>{r.key==="Enter"&&(n?r.metaKey:r.ctrlKey)&&y(this,hl,Lf).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),e.append(i),e}getElementsToTriggerPopup(){return c(this,al)}addHighlightArea(){this.container.classList.add("highlightArea")}}al=new WeakMap,hl=new WeakSet,Lf=function(){var e;(e=this.downloadManager)==null||e.openOrDownloadData(this.content,this.filename)};class nS{constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r}){w(this,Wr);w(this,ll,null);w(this,Br,null);w(this,Hr,new Map);this.div=t,b(this,ll,e),b(this,Br,s),this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return c(this,Hr).size>0}async render(t){var r;const{annotations:e}=t,s=this.div;Zn(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 Tg,annotationStorage:t.annotationStorage||new Fg,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===Ht.POPUP;if(h){const u=i.get(o.id);if(!u)continue;n.elements=u}else{const{width:u,height:g}=wi(o.rect);if(u<=0||g<=0)continue}n.data=o;const l=Hx.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"),y(this,Wr,zv).call(this,d,o.id),l._isEditable&&(c(this,Hr).set(l.data.id,l),(r=this._annotationEditorUIManager)==null||r.renderAnnotationElement(l))}y(this,Wr,Ff).call(this)}update({viewport:t}){const e=this.div;this.viewport=t,Zn(e,{rotation:t.rotation}),y(this,Wr,Ff).call(this),e.hidden=!1}getEditableAnnotations(){return Array.from(c(this,Hr).values())}getEditableAnnotation(t){return c(this,Hr).get(t)}}ll=new WeakMap,Br=new WeakMap,Hr=new WeakMap,Wr=new WeakSet,zv=function(t,e){var i;const s=t.firstChild||t;s.id=`${f0}${e}`,this.div.append(t),(i=c(this,ll))==null||i.moveElementInDOM(this.div,t,s,!1)},Ff=function(){if(!c(this,Br))return;const t=this.div;for(const[e,s]of c(this,Br)){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,Br).clear()};const wd=/\r\n?|\n/g,_t=class _t extends dt{constructor(e){super({...e,name:"freeTextEditor"});w(this,Nt);w(this,cl,this.editorDivBlur.bind(this));w(this,dl,this.editorDivFocus.bind(this));w(this,ul,this.editorDivInput.bind(this));w(this,gl,this.editorDivKeydown.bind(this));w(this,fl,this.editorDivPaste.bind(this));w(this,As);w(this,Ge,"");w(this,pl,`${this.id}-editor`);w(this,Ue);w(this,na,null);b(this,As,e.color||_t._defaultColor||dt._defaultLineColor),b(this,Ue,e.fontSize||_t._defaultFontSize)}static get _keyboardManager(){const e=_t.prototype,s=r=>r.isEmpty(),i=tr.TRANSLATE_SMALL,n=tr.TRANSLATE_BIG;return at(this,"_keyboardManager",new Qa([[["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){dt.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 q.FREETEXT_SIZE:_t._defaultFontSize=s;break;case q.FREETEXT_COLOR:_t._defaultColor=s;break}}updateParams(e,s){switch(e){case q.FREETEXT_SIZE:y(this,Nt,Vv).call(this,s);break;case q.FREETEXT_COLOR:y(this,Nt,Gv).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[q.FREETEXT_SIZE,_t._defaultFontSize],[q.FREETEXT_COLOR,_t._defaultColor||dt._defaultLineColor]]}get propertiesToUpdate(){return[[q.FREETEXT_SIZE,c(this,Ue)],[q.FREETEXT_COLOR,c(this,As)]]}_translateEmpty(e,s){this._uiManager.translateSelectedEditors(e,s,!0)}getInitialTranslation(){const e=this.parentScale;return[-_t._internalPadding*e,-(_t._internalPadding+c(this,Ue))*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(nt.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant");const e=this._uiManager._signal;this.editorDiv.addEventListener("keydown",c(this,gl),{signal:e}),this.editorDiv.addEventListener("focus",c(this,dl),{signal:e}),this.editorDiv.addEventListener("blur",c(this,cl),{signal:e}),this.editorDiv.addEventListener("input",c(this,ul),{signal:e}),this.editorDiv.addEventListener("paste",c(this,fl),{signal:e})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",c(this,pl)),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",c(this,gl)),this.editorDiv.removeEventListener("focus",c(this,dl)),this.editorDiv.removeEventListener("blur",c(this,cl)),this.editorDiv.removeEventListener("input",c(this,ul)),this.editorDiv.removeEventListener("paste",c(this,fl)),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,Ge),s=b(this,Ge,y(this,Nt,Uv).call(this).trimEnd());if(e===s)return;const i=n=>{if(b(this,Ge,n),!n){this.remove();return}y(this,Nt,au).call(this),this._uiManager.rebuild(this),y(this,Nt,ru).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(e)},mustExec:!1}),y(this,Nt,ru).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){_t._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,pl)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),dt._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,Ue)}px * var(--scale-factor))`,i.color=c(this,As),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),gd(this,this.div,["dblclick","keydown"]),this.width){const[n,r]=this.parentDimensions;if(this.annotationElementId){const{position:o}=c(this,na);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,Nt,au).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=_t,Hi,Rf).call(p,s.getData("text")||"").replaceAll(wd,`
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}}C(td,"type","Vibrance"),C(td,"defaults",{vibrance:0}),C(td,"uniformLocations",["uVibrance"]),H.setClass(td);var Ya={};Ya.d=(a,t)=>{for(var e in t)Ya.o(t,e)&&!Ya.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},Ya.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var $=globalThis.pdfjsLib={};Ya.d($,{AbortException:()=>Jn,AnnotationEditorLayer:()=>$g,AnnotationEditorParamsType:()=>q,AnnotationEditorType:()=>nt,AnnotationEditorUIManager:()=>tr,AnnotationLayer:()=>nS,AnnotationMode:()=>an,CMapCompressionType:()=>bg,ColorPicker:()=>Sd,DOMSVGFactory:()=>Ag,DrawLayer:()=>Kg,FeatureTest:()=>De,GlobalWorkerOptions:()=>_i,ImageKind:()=>ed,InvalidPDFException:()=>c0,MissingPDFException:()=>Qn,OPS:()=>vs,PDFDataRangeTransport:()=>X0,PDFDateString:()=>b0,PDFWorker:()=>To,PasswordResponses:()=>uw,PermissionFlag:()=>dw,PixelsPerInch:()=>ln,RenderingCancelledException:()=>Tg,TextLayer:()=>sh,UnexpectedResponseException:()=>rd,Util:()=>z,VerbosityLevel:()=>sd,XfaLayer:()=>U0,build:()=>Nx,createValidAbsoluteUrl:()=>mw,fetchData:()=>dd,getDocument:()=>Mx,getFilenameFromUrl:()=>Tw,getPdfFilenameFromUrl:()=>Ew,getXfaPageViewport:()=>kw,isDataScheme:()=>ud,isPdfFile:()=>Eg,noContextMenu:()=>Oe,normalizeUnicode:()=>xw,setLayerDimensions:()=>Zn,shadow:()=>at,version:()=>jx});const he=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),l0=[1,0,0,1,0,0],mg=[.001,0,0,.001,0,0],lw=1e7,vg=1.35,Be={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},an={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},cw="pdfjs_internal_editor_",nt={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},q={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},dw={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},le={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},ed={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Wt={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},qa={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},sd={ERRORS:0,WARNINGS:1,INFOS:5},bg={NONE:0,BINARY:1},vs={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},uw={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let id=sd.WARNINGS;function gw(a){Number.isInteger(a)&&(id=a)}function fw(){return id}function nd(a){id>=sd.INFOS&&console.log(`Info: ${a}`)}function Z(a){id>=sd.WARNINGS&&console.log(`Warning: ${a}`)}function ft(a){throw new Error(a)}function Xt(a,t){a||ft(t)}function pw(a){switch(a==null?void 0:a.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function mw(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=ww(a)}catch{}}const s=t?new URL(a,t):new URL(a);if(pw(s))return s}catch{}return null}function at(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const hn=function(){function t(e,s){this.constructor===t&&ft("Cannot initialize BaseException."),this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class yg extends hn{constructor(t,e){super(t,"PasswordException"),this.code=e}}class _g extends hn{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class c0 extends hn{constructor(t){super(t,"InvalidPDFException")}}class Qn extends hn{constructor(t){super(t,"MissingPDFException")}}class rd extends hn{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class vw extends hn{constructor(t){super(t,"FormatError")}}class Jn extends hn{constructor(t){super(t,"AbortException")}}function d0(a){(typeof a!="object"||(a==null?void 0:a.length)===void 0)&&ft("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 od(a){typeof a!="string"&&ft("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 bw(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function wg(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function yw(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function _w(){try{return new Function(""),!0}catch{return!1}}class De{static get isLittleEndian(){return at(this,"isLittleEndian",yw())}static get isEvalSupported(){return at(this,"isEvalSupported",_w())}static get isOffscreenCanvasSupported(){return at(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?at(this,"platform",{isMac:navigator.platform.includes("Mac")}):at(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){var t,e;return at(this,"isCSSRoundSupported",(e=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:e.call(t,"width: round(1.5px, 1px)"))}}const xg=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class z{static makeHexColor(t,e,s){return`#${xg[t]}${xg[e]}${xg[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,Si,rf).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,Si,rf).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}}Si=new WeakSet,Gd=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)},rf=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,Si,Gd).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,Si,Gd).call(this,t,e,s,i,n,r,o,h,(-d+p)/m,g),y(this,Si,Gd).call(this,t,e,s,i,n,r,o,h,(-d-p)/m,g)},w(z,Si);function ww(a){return decodeURIComponent(escape(a))}let Sg=null,u0=null;function xw(a){return Sg||(Sg=/([\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,u0=new Map([["ſt","ſt"]])),a.replaceAll(Sg,(t,e,s)=>e?e.normalize("NFKC"):u0.get(s))}function Sw(){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 d0(a)}const g0="pdfjs_internal_id_",vi={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 ad{constructor(){this.constructor===ad&&ft("Cannot initialize BaseFilterFactory.")}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){}}const Jg=class Jg{constructor({enableHWA:t=!1}={}){w(this,oh,!1);this.constructor===Jg&&ft("Cannot initialize BaseCanvasFactory."),b(this,oh,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,oh)})}}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){ft("Abstract method `_createCanvas` called.")}};oh=new WeakMap;let hd=Jg;class ld{constructor({baseUrl:t=null,isCompressed:e=!0}){this.constructor===ld&&ft("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, 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?bg.BINARY:bg.NONE;return this._fetchData(e,s).catch(i=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}_fetchData(t,e){ft("Abstract method `_fetchData` called.")}}class cd{constructor({baseUrl:t=null}){this.constructor===cd&&ft("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, 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){ft("Abstract method `_fetchData` called.")}}class Cg{constructor(){this.constructor===Cg&&ft("Cannot initialize BaseSVGFactory.")}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){ft("Abstract method `_createSVG` called.")}}const bi="http://www.w3.org/2000/svg",ir=class ir{};K(ir,"CSS",96),K(ir,"PDF",72),K(ir,"PDF_TO_CSS_UNITS",ir.CSS/ir.PDF);let ln=ir;class Cw extends ad{constructor({docId:e,ownerDocument:s=globalThis.document}={}){super();w(this,B);w(this,nr);w(this,rr);w(this,zs);w(this,Ci);w(this,ce);w(this,Td);w(this,or,0);b(this,Ci,e),b(this,ce,s)}addFilter(e){if(!e)return"none";let s=c(this,B,me).get(e);if(s)return s;const[i,n,r]=y(this,B,Ud).call(this,e),o=e.length===1?i:`${i}${n}${r}`;if(s=c(this,B,me).get(o),s)return c(this,B,me).set(e,s),s;const h=`g_${c(this,Ci)}_transfer_map_${Je(this,or)._++}`,l=y(this,B,Aa).call(this,h);c(this,B,me).set(e,l),c(this,B,me).set(o,l);const d=y(this,B,Ta).call(this,h);return y(this,B,Xl).call(this,i,n,r,d),l}addHCMFilter(e,s){var p;const i=`${e}-${s}`,n="base";let r=c(this,B,Sa).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,B,Sa).set(n,r)),!e||!s))return r.url;const o=y(this,B,zl).call(this,e);e=z.makeHexColor(...o);const h=y(this,B,zl).call(this,s);if(s=z.makeHexColor(...h),c(this,B,Ca).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,Ci)}_hcm_filter`,g=r.filter=y(this,B,Ta).call(this,u);y(this,B,Xl).call(this,d,d,d,g),y(this,B,of).call(this,g);const f=(m,_)=>{const v=o[m]/255,x=h[m]/255,S=new Array(_+1);for(let T=0;T<=_;T++)S[T]=v+T/_*(x-v);return S.join(",")};return y(this,B,Xl).call(this,f(0,5),f(1,5),f(2,5),g),r.url=y(this,B,Aa).call(this,u),r.url}addAlphaFilter(e){let s=c(this,B,me).get(e);if(s)return s;const[i]=y(this,B,Ud).call(this,[e]),n=`alpha_${i}`;if(s=c(this,B,me).get(n),s)return c(this,B,me).set(e,s),s;const r=`g_${c(this,Ci)}_alpha_map_${Je(this,or)._++}`,o=y(this,B,Aa).call(this,r);c(this,B,me).set(e,o),c(this,B,me).set(n,o);const h=y(this,B,Ta).call(this,r);return y(this,B,af).call(this,i,h),o}addLuminosityFilter(e){let s=c(this,B,me).get(e||"luminosity");if(s)return s;let i,n;if(e?([i]=y(this,B,Ud).call(this,[e]),n=`luminosity_${i}`):n="luminosity",s=c(this,B,me).get(n),s)return c(this,B,me).set(e,s),s;const r=`g_${c(this,Ci)}_luminosity_map_${Je(this,or)._++}`,o=y(this,B,Aa).call(this,r);c(this,B,me).set(e,o),c(this,B,me).set(n,o);const h=y(this,B,Ta).call(this,r);return y(this,B,rv).call(this,h),e&&y(this,B,af).call(this,i,h),o}addHighlightHCMFilter(e,s,i,n,r){var x;const o=`${s}-${i}-${n}-${r}`;let h=c(this,B,Sa).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,B,Sa).set(e,h)),!s||!i))return h.url;const[l,d]=[s,i].map(y(this,B,zl).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,B,zl).bind(this));g<u&&([u,g,f,p]=[g,u,p,f]),c(this,B,Ca).style.color="";const m=(S,T,E)=>{const M=new Array(256),P=(g-u)/E,O=S/255,R=(T-S)/(255*E);let D=0;for(let L=0;L<=E;L++){const F=Math.round(u+L*P),I=O+L*R;for(let X=D;X<=F;X++)M[X]=I;D=F+1}for(let L=D;L<256;L++)M[L]=M[D-1];return M.join(",")},_=`g_${c(this,Ci)}_hcm_${e}_filter`,v=h.filter=y(this,B,Ta).call(this,_);return y(this,B,of).call(this,v),y(this,B,Xl).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,B,Aa).call(this,_),h.url}destroy(e=!1){e&&c(this,B,Sa).size!==0||(c(this,zs)&&(c(this,zs).parentNode.parentNode.remove(),b(this,zs,null)),c(this,rr)&&(c(this,rr).clear(),b(this,rr,null)),b(this,or,0))}}nr=new WeakMap,rr=new WeakMap,zs=new WeakMap,Ci=new WeakMap,ce=new WeakMap,Td=new WeakMap,or=new WeakMap,B=new WeakSet,me=function(){return c(this,rr)||b(this,rr,new Map)},Sa=function(){return c(this,Td)||b(this,Td,new Map)},Ca=function(){if(!c(this,zs)){const e=c(this,ce).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,ce).createElementNS(bi,"svg");i.setAttribute("width",0),i.setAttribute("height",0),b(this,zs,c(this,ce).createElementNS(bi,"defs")),e.append(i),i.append(c(this,zs)),c(this,ce).body.append(e)}return c(this,zs)},Ud=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(",")]},Aa=function(e){if(c(this,nr)===void 0){b(this,nr,"");const s=c(this,ce).URL;s!==c(this,ce).baseURI&&(ud(s)?Z('#createUrl: ignore "data:"-URL for performance reasons.'):b(this,nr,s.split("#",1)[0]))}return`url(${c(this,nr)}#${e})`},rv=function(e){const s=c(this,ce).createElementNS(bi,"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)},of=function(e){const s=c(this,ce).createElementNS(bi,"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)},Ta=function(e){const s=c(this,ce).createElementNS(bi,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",e),c(this,B,Ca).append(s),s},Wl=function(e,s,i){const n=c(this,ce).createElementNS(bi,s);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),e.append(n)},Xl=function(e,s,i,n){const r=c(this,ce).createElementNS(bi,"feComponentTransfer");n.append(r),y(this,B,Wl).call(this,r,"feFuncR",e),y(this,B,Wl).call(this,r,"feFuncG",s),y(this,B,Wl).call(this,r,"feFuncB",i)},af=function(e,s){const i=c(this,ce).createElementNS(bi,"feComponentTransfer");s.append(i),y(this,B,Wl).call(this,i,"feFuncA",e)},zl=function(e){return c(this,B,Ca).style.color=e,kg(getComputedStyle(c(this,B,Ca)).getPropertyValue("color"))};class Aw extends hd{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 dd(a,t="text"){if(Ka(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 f0 extends ld{_fetchData(t,e){return dd(t,this.isCompressed?"arraybuffer":"text").then(s=>({cMapData:s instanceof ArrayBuffer?new Uint8Array(s):od(s),compressionType:e}))}}class p0 extends cd{_fetchData(t){return dd(t,"arraybuffer").then(e=>new Uint8Array(e))}}class Ag extends Cg{_createSVG(t){return document.createElementNS(bi,t)}}class $a{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 at(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 $a({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return z.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=z.applyTransform([t[0],t[1]],this.transform),s=z.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return z.applyInverseTransform([t,e],this.transform)}}class Tg extends hn{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function ud(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function Eg(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function Tw(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function Ew(a,t="document.pdf"){if(typeof a!="string")return t;if(ud(a))return Z('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 m0{constructor(){K(this,"started",Object.create(null));K(this,"times",[])}time(t){t in this.started&&Z(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||Z(`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 Ka(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function Oe(a){a.preventDefault()}let v0;class b0{static toDateObject(t){if(!t||typeof t!="string")return null;v0||(v0=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const e=v0.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 kw(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new $a({viewBox:n,scale:t,rotation:e})}function kg(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):(Z(`Not a valid color format: "${a}"`),[0,0,0])}function Mw(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,kg(s))}t.remove()}function Ct(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function yi(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 Zn(a,t,e=!1,s=!0){if(t instanceof $a){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=De.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,d=o?`round(${h}, 1px)`:`calc(${h})`,u=o?`round(${l}, 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)}const kd=class kd{constructor(t){w(this,Ce);w(this,ar,null);w(this,hr,null);w(this,We);w(this,lr,null);b(this,We,t)}render(){const t=b(this,ar,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar");const e=c(this,We)._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:e}),t.addEventListener("pointerdown",y(kd,Ed,ov),{signal:e});const s=b(this,lr,document.createElement("div"));s.className="buttons",t.append(s);const i=c(this,We).toolbarPosition;if(i){const{style:n}=t,r=c(this,We)._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,Ce,lv).call(this),t}hide(){var t;c(this,ar).classList.add("hidden"),(t=c(this,hr))==null||t.hideDropdown()}show(){c(this,ar).classList.remove("hidden")}addAltTextButton(t){y(this,Ce,Yd).call(this,t),c(this,lr).prepend(t,c(this,Ce,hf))}addColorPicker(t){b(this,hr,t);const e=t.renderButton();y(this,Ce,Yd).call(this,e),c(this,lr).prepend(e,c(this,Ce,hf))}remove(){var t;c(this,ar).remove(),(t=c(this,hr))==null||t.destroy(),b(this,hr,null)}};ar=new WeakMap,hr=new WeakMap,We=new WeakMap,lr=new WeakMap,Ed=new WeakSet,ov=function(t){t.stopPropagation()},Ce=new WeakSet,av=function(t){c(this,We)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},hv=function(t){c(this,We)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},Yd=function(t){const e=c(this,We)._uiManager._signal;t.addEventListener("focusin",y(this,Ce,av).bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",y(this,Ce,hv).bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Oe,{signal:e})},lv=function(){const t=document.createElement("button");t.className="delete",t.tabIndex=0,t.setAttribute("data-l10n-id",`pdfjs-editor-remove-${c(this,We).editorType}-button`),y(this,Ce,Yd).call(this,t),t.addEventListener("click",e=>{c(this,We)._uiManager.delete()},{signal:c(this,We)._uiManager._signal}),c(this,lr).append(t)},hf=function(){const t=document.createElement("div");return t.className="divider",t},w(kd,Ed);let Mg=kd;class Dw{constructor(t){w(this,dn);w(this,ah,null);w(this,cr,null);w(this,dr);b(this,dr,t)}show(t,e,s){const[i,n]=y(this,dn,dv).call(this,e,s),{style:r}=c(this,cr)||b(this,cr,y(this,dn,cv).call(this));t.append(c(this,cr)),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){c(this,cr).remove()}}ah=new WeakMap,cr=new WeakMap,dr=new WeakMap,dn=new WeakSet,cv=function(){const t=b(this,cr,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",Oe,{signal:c(this,dr)._signal});const e=b(this,ah,document.createElement("div"));return e.className="buttons",t.append(e),y(this,dn,uv).call(this),t},dv=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]},uv=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,dr)._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("click",()=>{c(this,dr).highlightSelection("floating_button")},{signal:s}),c(this,ah).append(t)};function gd(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}function Ow(a){return Math.round(Math.min(255,Math.max(1,255*a))).toString(16).padStart(2,"0")}class Pw{constructor(){w(this,Md,0)}get id(){return`${cw}${Je(this,Md)._++}`}}Md=new WeakMap;const Zg=class Zg{constructor(){w(this,lh);w(this,hh,Sw());w(this,Dd,0);w(this,is,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 at(this,"_isSVGFittingCanvas",n)}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return y(this,lh,lf).call(this,`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return y(this,lh,lf).call(this,t,t)}async getFromId(t){c(this,is)||b(this,is,new Map);const e=c(this,is).get(t);return e?e.bitmap?(e.refCounter+=1,e):e.file?this.getFromFile(e.file):this.getFromUrl(e.url):null}getSvgUrl(t){const e=c(this,is).get(t);return e!=null&&e.isSvg?e.svgUrl:null}deleteId(t){c(this,is)||b(this,is,new Map);const e=c(this,is).get(t);e&&(e.refCounter-=1,e.refCounter===0&&(e.bitmap=null))}isValidId(t){return t.startsWith(`image_${c(this,hh)}_`)}};hh=new WeakMap,Dd=new WeakMap,is=new WeakMap,lh=new WeakSet,lf=async function(t,e){c(this,is)||b(this,is,new Map);let s=c(this,is).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,hh)}_${Je(this,Dd)._++}`,refCounter:0,isSvg:!1});let i;if(typeof e=="string"?(s.url=e,i=await dd(e,"blob")):i=s.file=e,i.type==="image/svg+xml"){const n=Zg._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,is).set(t,s),s&&c(this,is).set(s.id,s),s};let Dg=Zg;class Lw{constructor(t=128){w(this,qt,[]);w(this,un,!1);w(this,ch);w(this,$t,-1);b(this,ch,t)}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),c(this,un))return;const h={cmd:t,undo:e,post:s,type:n};if(c(this,$t)===-1){c(this,qt).length>0&&(c(this,qt).length=0),b(this,$t,0),c(this,qt).push(h);return}if(r&&c(this,qt)[c(this,$t)].type===n){o&&(h.undo=c(this,qt)[c(this,$t)].undo),c(this,qt)[c(this,$t)]=h;return}const l=c(this,$t)+1;l===c(this,ch)?c(this,qt).splice(0,1):(b(this,$t,l),l<c(this,qt).length&&c(this,qt).splice(l)),c(this,qt).push(h)}undo(){if(c(this,$t)===-1)return;b(this,un,!0);const{undo:t,post:e}=c(this,qt)[c(this,$t)];t(),e==null||e(),b(this,un,!1),b(this,$t,c(this,$t)-1)}redo(){if(c(this,$t)<c(this,qt).length-1){b(this,$t,c(this,$t)+1),b(this,un,!0);const{cmd:t,post:e}=c(this,qt)[c(this,$t)];t(),e==null||e(),b(this,un,!1)}}hasSomethingToUndo(){return c(this,$t)!==-1}hasSomethingToRedo(){return c(this,$t)<c(this,qt).length-1}destroy(){b(this,qt,null)}}qt=new WeakMap,un=new WeakMap,ch=new WeakMap,$t=new WeakMap;class Qa{constructor(t){w(this,Od);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=De.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,Od,gv).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()))}}Od=new WeakSet,gv=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 Pd=class Pd{get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Mw(t),at(this,"_colors",t)}convert(t){const e=kg(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 Pd._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}};K(Pd,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Og=Pd;const Lo=class Lo{constructor(t,e,s,i,n,r,o,h,l,d){w(this,j);w(this,Eo,new AbortController);w(this,Xe,null);w(this,zt,new Map);w(this,Jt,new Map);w(this,ko,null);w(this,Ai,null);w(this,Mo,null);w(this,bs,new Lw);w(this,Do,0);w(this,ur,new Set);w(this,Vs,null);w(this,ys,null);w(this,gr,new Set);w(this,dh,!1);w(this,uh,!1);w(this,gh,null);w(this,Gs,null);w(this,Oo,null);w(this,gn,!1);w(this,Us,null);w(this,Ld,new Pw);w(this,fn,!1);w(this,fh,!1);w(this,fr,null);w(this,ph,null);w(this,Po,null);w(this,Kt,nt.NONE);w(this,gt,new Set);w(this,Ti,null);w(this,pr,null);w(this,mh,null);w(this,vh,this.blur.bind(this));w(this,bh,this.focus.bind(this));w(this,yh,this.copy.bind(this));w(this,_h,this.cut.bind(this));w(this,wh,this.paste.bind(this));w(this,xh,this.keydown.bind(this));w(this,Sh,this.keyup.bind(this));w(this,Ch,this.onEditingAction.bind(this));w(this,Ah,this.onPageChanging.bind(this));w(this,Th,this.onScaleChanging.bind(this));w(this,Eh,this.onRotationChanging.bind(this));w(this,kh,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});w(this,pn,[0,0]);w(this,Ys,null);w(this,Ei,null);w(this,Mh,null);this._signal=c(this,Eo).signal,b(this,Ei,t),b(this,Mh,e),b(this,ko,s),this._eventBus=i,this._eventBus._on("editingaction",c(this,Ch)),this._eventBus._on("pagechanging",c(this,Ah)),this._eventBus._on("scalechanging",c(this,Th)),this._eventBus._on("rotationchanging",c(this,Eh)),y(this,j,mv).call(this),y(this,j,_v).call(this),y(this,j,df).call(this),b(this,Ai,n.annotationStorage),b(this,gh,n.filterFactory),b(this,pr,r),b(this,Oo,o||null),b(this,dh,h),b(this,uh,l),b(this,Po,d||null),this.viewParameters={realScale:ln.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=Lo.prototype,e=r=>c(r,Ei).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 at(this,"_keyboardManager",new Qa([[["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,Ei).contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&c(r,Ei).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;(t=c(this,Eo))==null||t.abort(),b(this,Eo,null),this._signal=null,this._eventBus._off("editingaction",c(this,Ch)),this._eventBus._off("pagechanging",c(this,Ah)),this._eventBus._off("scalechanging",c(this,Th)),this._eventBus._off("rotationchanging",c(this,Eh));for(const i of c(this,Jt).values())i.destroy();c(this,Jt).clear(),c(this,zt).clear(),c(this,gr).clear(),b(this,Xe,null),c(this,gt).clear(),c(this,bs).destroy(),(e=c(this,ko))==null||e.destroy(),(s=c(this,Us))==null||s.hide(),b(this,Us,null),c(this,Gs)&&(clearTimeout(c(this,Gs)),b(this,Gs,null)),c(this,Ys)&&(clearTimeout(c(this,Ys)),b(this,Ys,null))}async mlGuess(t){var e;return((e=c(this,Po))==null?void 0:e.guess(t))||null}async isMLEnabledFor(t){var e;return!!await((e=c(this,Po))==null?void 0:e.isEnabledFor(t))}get useNewAltTextFlow(){return c(this,uh)}get hcmFilter(){return at(this,"hcmFilter",c(this,pr)?c(this,gh).addHCMFilter(c(this,pr).foreground,c(this,pr).background):"none")}get direction(){return at(this,"direction",getComputedStyle(c(this,Ei)).direction)}get highlightColors(){return at(this,"highlightColors",c(this,Oo)?new Map(c(this,Oo).split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return at(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){b(this,ph,t)}editAltText(t){var e;(e=c(this,ko))==null||e.editAltText(this,t)}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})}onPageChanging({pageNumber:t}){b(this,Do,t-1)}focusMainContainer(){c(this,Ei).focus()}findParent(t,e){for(const s of c(this,Jt).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,Mh).classList.toggle("noUserSelect",t)}addShouldRescale(t){c(this,gr).add(t)}removeShouldRescale(t){c(this,gr).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*ln.PDF_TO_CSS_UNITS;for(const e of c(this,gr))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,j,qd).call(this,e).closest(".textLayer"),d=this.getSelectionBoxes(l);if(!d)return;e.empty();const u=y(this,j,cf).call(this,l),g=c(this,Kt)===nt.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(nt.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&c(this,Ai)&&!c(this,Ai).has(t.id)&&c(this,Ai).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,c(this,gn)&&(b(this,gn,!1),y(this,j,$d).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of c(this,gt))if(e.div.contains(t)){b(this,fr,[e,t]),e._focusEventsAllowed=!1;break}}focus(){if(!c(this,fr))return;const[t,e]=c(this,fr);b(this,fr,null),e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}addEditListeners(){y(this,j,df).call(this),y(this,j,uf).call(this)}removeEditListeners(){y(this,j,yv).call(this),y(this,j,gf).call(this)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of c(this,ys))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,ys))if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){var s;if(t.preventDefault(),(s=c(this,Xe))==null||s.commitOrRemove(),!this.hasSelection)return;const e=[];for(const i of c(this,gt)){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()}paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of c(this,ys))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){Z(`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=i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)y(this,j,ff).call(this,h);y(this,j,pf).call(this,n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){Z(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),c(this,Kt)!==nt.NONE&&!this.isEditorHandlingKeyboard&&Lo._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,c(this,gn)&&(b(this,gn,!1),y(this,j,$d).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,j,vv).call(this),y(this,j,uf).call(this),y(this,j,Ee).call(this,{isEditing:c(this,Kt)!==nt.NONE,isEmpty:y(this,j,Vl).call(this),hasSomethingToUndo:c(this,bs).hasSomethingToUndo(),hasSomethingToRedo:c(this,bs).hasSomethingToRedo(),hasSelectedEditor:!1})):(y(this,j,bv).call(this),y(this,j,gf).call(this),y(this,j,Ee).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!c(this,ys)){b(this,ys,t);for(const e of c(this,ys))y(this,j,Rn).call(this,e.defaultPropertiesToUpdate)}}getId(){return c(this,Ld).id}get currentLayer(){return c(this,Jt).get(c(this,Do))}getLayer(t){return c(this,Jt).get(t)}get currentPageIndex(){return c(this,Do)}addLayer(t){c(this,Jt).set(t.pageIndex,t),c(this,fn)?t.enable():t.disable()}removeLayer(t){c(this,Jt).delete(t.pageIndex)}updateMode(t,e=null,s=!1){if(c(this,Kt)!==t){if(b(this,Kt,t),t===nt.NONE){this.setEditingState(!1),y(this,j,xv).call(this);return}this.setEditingState(!0),y(this,j,wv).call(this),this.unselectAll();for(const i of c(this,Jt).values())i.updateMode(t);if(!e&&s){this.addNewEditorFromKeyboard();return}if(e){for(const i of c(this,zt).values())if(i.annotationElementId===e){this.setSelected(i),i.enterInEditMode();break}}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==c(this,Kt)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){var s;if(c(this,ys)){switch(t){case q.CREATE:this.currentLayer.addNewEditor();return;case q.HIGHLIGHT_DEFAULT_COLOR:(s=c(this,ph))==null||s.updateColor(e);break;case q.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(c(this,mh)||b(this,mh,new Map)).set(t,e),this.showAllEditors("highlight",e);break}for(const i of c(this,gt))i.updateParams(t,e);for(const i of c(this,ys))i.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){var n;for(const r of c(this,zt).values())r.editorType===t&&r.show(e);(((n=c(this,mh))==null?void 0:n.get(q.HIGHLIGHT_SHOW_ALL))??!0)!==e&&y(this,j,Rn).call(this,[[q.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(c(this,fh)!==t){b(this,fh,t);for(const e of c(this,Jt).values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}getEditors(t){const e=[];for(const s of c(this,zt).values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return c(this,zt).get(t)}addEditor(t){c(this,zt).set(t.id,t)}removeEditor(t){var e;t.div.contains(document.activeElement)&&(c(this,Gs)&&clearTimeout(c(this,Gs)),b(this,Gs,setTimeout(()=>{this.focusMainContainer(),b(this,Gs,null)},0))),c(this,zt).delete(t.id),this.unselect(t),(!t.annotationElementId||!c(this,ur).has(t.annotationElementId))&&((e=c(this,Ai))==null||e.remove(t.id))}addDeletedAnnotationElement(t){c(this,ur).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return c(this,ur).has(t)}removeDeletedAnnotationElement(t){c(this,ur).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){c(this,Xe)!==t&&(b(this,Xe,t),t&&y(this,j,Rn).call(this,t.propertiesToUpdate))}updateUI(t){c(this,j,Sv)===t&&y(this,j,Rn).call(this,t.propertiesToUpdate)}toggleSelected(t){if(c(this,gt).has(t)){c(this,gt).delete(t),t.unselect(),y(this,j,Ee).call(this,{hasSelectedEditor:this.hasSelection});return}c(this,gt).add(t),t.select(),y(this,j,Rn).call(this,t.propertiesToUpdate),y(this,j,Ee).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const e of c(this,gt))e!==t&&e.unselect();c(this,gt).clear(),c(this,gt).add(t),t.select(),y(this,j,Rn).call(this,t.propertiesToUpdate),y(this,j,Ee).call(this,{hasSelectedEditor:!0})}isSelected(t){return c(this,gt).has(t)}get firstSelectedEditor(){return c(this,gt).values().next().value}unselect(t){t.unselect(),c(this,gt).delete(t),y(this,j,Ee).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return c(this,gt).size!==0}get isEnterHandled(){return c(this,gt).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){c(this,bs).undo(),y(this,j,Ee).call(this,{hasSomethingToUndo:c(this,bs).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:y(this,j,Vl).call(this)})}redo(){c(this,bs).redo(),y(this,j,Ee).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:c(this,bs).hasSomethingToRedo(),isEmpty:y(this,j,Vl).call(this)})}addCommands(t){c(this,bs).add(t),y(this,j,Ee).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:y(this,j,Vl).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...c(this,gt)],e=()=>{for(const i of t)i.remove()},s=()=>{for(const i of t)y(this,j,ff).call(this,i)};this.addCommands({cmd:e,undo:s,mustExec:!0})}commitOrRemove(){var t;(t=c(this,Xe))==null||t.commitOrRemove()}hasSomethingToControl(){return c(this,Xe)||this.hasSelection}selectAll(){for(const t of c(this,gt))t.commit();y(this,j,pf).call(this,c(this,zt).values())}unselectAll(){if(!(c(this,Xe)&&(c(this,Xe).commitOrRemove(),c(this,Kt)!==nt.NONE))&&this.hasSelection){for(const t of c(this,gt))t.unselect();c(this,gt).clear(),y(this,j,Ee).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;c(this,pn)[0]+=t,c(this,pn)[1]+=e;const[i,n]=c(this,pn),r=[...c(this,gt)],o=1e3;c(this,Ys)&&clearTimeout(c(this,Ys)),b(this,Ys,setTimeout(()=>{b(this,Ys,null),c(this,pn)[0]=c(this,pn)[1]=0,this.addCommands({cmd:()=>{for(const h of r)c(this,zt).has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)c(this,zt).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,Vs,new Map);for(const t of c(this,gt))c(this,Vs).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!c(this,Vs))return!1;this.disableUserSelect(!1);const t=c(this,Vs);b(this,Vs,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,zt).has(i.id)){const h=c(this,Jt).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,Vs))for(const s of c(this,Vs).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,gt).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return c(this,Xe)===t}getActive(){return c(this,Xe)}getMode(){return c(this,Kt)}get imageManager(){return at(this,"imageManager",new Dg)}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,Mo)||b(this,Mo,new Map)).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){var e;(e=c(this,Mo))==null||e.delete(t)}renderAnnotationElement(t){var i;const e=(i=c(this,Mo))==null?void 0:i.get(t.data.id);if(!e)return;const s=c(this,Ai).getRawValue(e);s&&(c(this,Kt)===nt.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}};Eo=new WeakMap,Xe=new WeakMap,zt=new WeakMap,Jt=new WeakMap,ko=new WeakMap,Ai=new WeakMap,Mo=new WeakMap,bs=new WeakMap,Do=new WeakMap,ur=new WeakMap,Vs=new WeakMap,ys=new WeakMap,gr=new WeakMap,dh=new WeakMap,uh=new WeakMap,gh=new WeakMap,Gs=new WeakMap,Oo=new WeakMap,gn=new WeakMap,Us=new WeakMap,Ld=new WeakMap,fn=new WeakMap,fh=new WeakMap,fr=new WeakMap,ph=new WeakMap,Po=new WeakMap,Kt=new WeakMap,gt=new WeakMap,Ti=new WeakMap,pr=new WeakMap,mh=new WeakMap,vh=new WeakMap,bh=new WeakMap,yh=new WeakMap,_h=new WeakMap,wh=new WeakMap,xh=new WeakMap,Sh=new WeakMap,Ch=new WeakMap,Ah=new WeakMap,Th=new WeakMap,Eh=new WeakMap,kh=new WeakMap,pn=new WeakMap,Ys=new WeakMap,Ei=new WeakMap,Mh=new WeakMap,j=new WeakSet,qd=function({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t},cf=function(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of c(this,Jt).values())if(s.hasTextLayer(t))return s;return null},fv=function(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=y(this,j,qd).call(this,t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(c(this,Us)||b(this,Us,new Dw(this)),c(this,Us).show(s,i,this.direction==="ltr"))},pv=function(){var n,r,o;const t=document.getSelection();if(!t||t.isCollapsed){c(this,Ti)&&((n=c(this,Us))==null||n.hide(),b(this,Ti,null),y(this,j,Ee).call(this,{hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===c(this,Ti))return;const i=y(this,j,qd).call(this,t).closest(".textLayer");if(!i){c(this,Ti)&&((r=c(this,Us))==null||r.hide(),b(this,Ti,null),y(this,j,Ee).call(this,{hasSelectedText:!1}));return}if((o=c(this,Us))==null||o.hide(),b(this,Ti,e),y(this,j,Ee).call(this,{hasSelectedText:!0}),!(c(this,Kt)!==nt.HIGHLIGHT&&c(this,Kt)!==nt.NONE)&&(c(this,Kt)===nt.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),b(this,gn,this.isShiftKeyDown),!this.isShiftKeyDown)){const h=c(this,Kt)===nt.HIGHLIGHT?y(this,j,cf).call(this,i):null;h==null||h.toggleDrawing();const l=this._signal,d=u=>{u.type==="pointerup"&&u.button!==0||(h==null||h.toggleDrawing(!0),window.removeEventListener("pointerup",d),window.removeEventListener("blur",d),u.type==="pointerup"&&y(this,j,$d).call(this,"main_toolbar"))};window.addEventListener("pointerup",d,{signal:l}),window.addEventListener("blur",d,{signal:l})}},$d=function(t=""){c(this,Kt)===nt.HIGHLIGHT?this.highlightSelection(t):c(this,dh)&&y(this,j,fv).call(this)},mv=function(){document.addEventListener("selectionchange",y(this,j,pv).bind(this),{signal:this._signal})},vv=function(){const t=this._signal;window.addEventListener("focus",c(this,bh),{signal:t}),window.addEventListener("blur",c(this,vh),{signal:t})},bv=function(){window.removeEventListener("focus",c(this,bh)),window.removeEventListener("blur",c(this,vh))},df=function(){const t=this._signal;window.addEventListener("keydown",c(this,xh),{signal:t}),window.addEventListener("keyup",c(this,Sh),{signal:t})},yv=function(){window.removeEventListener("keydown",c(this,xh)),window.removeEventListener("keyup",c(this,Sh))},uf=function(){const t=this._signal;document.addEventListener("copy",c(this,yh),{signal:t}),document.addEventListener("cut",c(this,_h),{signal:t}),document.addEventListener("paste",c(this,wh),{signal:t})},gf=function(){document.removeEventListener("copy",c(this,yh)),document.removeEventListener("cut",c(this,_h)),document.removeEventListener("paste",c(this,wh))},_v=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Ee=function(t){Object.entries(t).some(([s,i])=>c(this,kh)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(c(this,kh),t)}),c(this,Kt)===nt.HIGHLIGHT&&t.hasSelectedEditor===!1&&y(this,j,Rn).call(this,[[q.HIGHLIGHT_FREE,!0]]))},Rn=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},wv=function(){if(!c(this,fn)){b(this,fn,!0);for(const t of c(this,Jt).values())t.enable();for(const t of c(this,zt).values())t.enable()}},xv=function(){if(this.unselectAll(),c(this,fn)){b(this,fn,!1);for(const t of c(this,Jt).values())t.disable();for(const t of c(this,zt).values())t.disable()}},ff=function(t){const e=c(this,Jt).get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},Sv=function(){let t=null;for(t of c(this,gt));return t},Vl=function(){if(c(this,zt).size===0)return!0;if(c(this,zt).size===1)for(const t of c(this,zt).values())return t.isEmpty();return!1},pf=function(t){for(const e of c(this,gt))e.unselect();c(this,gt).clear();for(const e of t)e.isEmpty()||(c(this,gt).add(e),e.select());y(this,j,Ee).call(this,{hasSelectedEditor:this.hasSelection})},K(Lo,"TRANSLATE_SMALL",1),K(Lo,"TRANSLATE_BIG",10);let tr=Lo;const Oi=class Oi{constructor(t){w(this,Dh);w(this,ki,"");w(this,Mi,!1);w(this,_s,null);w(this,Di,null);w(this,ze,null);w(this,Fo,!1);w(this,ws,null);b(this,ws,t)}static initialize(t){Oi._l10nPromise||(Oi._l10nPromise=t)}async render(){const t=b(this,_s,document.createElement("button"));t.className="altText";const e=await Oi._l10nPromise.get("pdfjs-editor-alt-text-button-label");t.textContent=e,t.setAttribute("aria-label",e),t.tabIndex="0";const s=c(this,ws)._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),c(this,ws)._uiManager.editAltText(c(this,ws))};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(b(this,Fo,!0),i(n))},{signal:s}),await y(this,Dh,mf).call(this),t}finish(){c(this,_s)&&(c(this,_s).focus({focusVisible:c(this,Fo)}),b(this,Fo,!1))}isEmpty(){return!c(this,ki)&&!c(this,Mi)}get data(){return{altText:c(this,ki),decorative:c(this,Mi)}}set data({altText:t,decorative:e}){c(this,ki)===t&&c(this,Mi)===e||(b(this,ki,t),b(this,Mi,e),y(this,Dh,mf).call(this))}toggle(t=!1){c(this,_s)&&(!t&&c(this,ze)&&(clearTimeout(c(this,ze)),b(this,ze,null)),c(this,_s).disabled=!t)}destroy(){var t;(t=c(this,_s))==null||t.remove(),b(this,_s,null),b(this,Di,null)}};ki=new WeakMap,Mi=new WeakMap,_s=new WeakMap,Di=new WeakMap,ze=new WeakMap,Fo=new WeakMap,ws=new WeakMap,Dh=new WeakSet,mf=async function(){var i;const t=c(this,_s);if(!t)return;if(!c(this,ki)&&!c(this,Mi)){t.classList.remove("done"),(i=c(this,Di))==null||i.remove();return}t.classList.add("done"),Oi._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(n=>{t.setAttribute("aria-label",n)});let e=c(this,Di);if(!e){b(this,Di,e=document.createElement("span")),e.className="tooltip",e.setAttribute("role","tooltip");const n=e.id=`alt-text-tooltip-${c(this,ws).id}`;t.setAttribute("aria-describedby",n);const r=100,o=c(this,ws)._uiManager._signal;o.addEventListener("abort",()=>{clearTimeout(c(this,ze)),b(this,ze,null)},{once:!0}),t.addEventListener("mouseenter",()=>{b(this,ze,setTimeout(()=>{b(this,ze,null),c(this,Di).classList.add("show"),c(this,ws)._reportTelemetry({action:"alt_text_tooltip"})},r))},{signal:o}),t.addEventListener("mouseleave",()=>{var h;c(this,ze)&&(clearTimeout(c(this,ze)),b(this,ze,null)),(h=c(this,Di))==null||h.classList.remove("show")},{signal:o})}e.innerText=c(this,Mi)?await Oi._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):c(this,ki),e.parentNode||t.append(e);const s=c(this,ws).getImageForAltText();s==null||s.setAttribute("aria-describedby",e.id)},K(Oi,"_l10nPromise",null);let fd=Oi;const bt=class bt{constructor(t){w(this,tt);w(this,mr,null);w(this,xs,null);w(this,de,null);w(this,Ro,!1);w(this,vr,!1);w(this,Zt,null);w(this,br,null);w(this,Io,this.focusin.bind(this));w(this,jo,this.focusout.bind(this));w(this,ue,null);w(this,Oh,"");w(this,yr,!1);w(this,mn,null);w(this,Ph,!1);w(this,_r,!1);w(this,Pi,!1);w(this,qs,null);w(this,No,0);w(this,Bo,0);w(this,ns,null);K(this,"_initialOptions",Object.create(null));K(this,"_isVisible",!0);K(this,"_uiManager",null);K(this,"_focusEventsAllowed",!0);K(this,"_l10nPromise",null);w(this,Lh,!1);w(this,Fd,bt._zIndex++);this.constructor===bt&&ft("Cannot initialize AnnotationEditor."),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=bt.prototype._resizeWithKeyboard,e=tr.TRANSLATE_SMALL,s=tr.TRANSLATE_BIG;return at(this,"_resizerKeyboardManager",new Qa([[["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"],bt.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return at(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Fw({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(bt._l10nPromise||(bt._l10nPromise=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map(n=>[n,t.get(n.replaceAll(/([A-Z])/g,r=>`-${r.toLowerCase()}`))]))),s!=null&&s.strings)for(const n of s.strings)bt._l10nPromise.set(n,t.get(n));if(bt._borderLineWidth!==-1)return;const i=getComputedStyle(document.documentElement);bt._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){ft("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,Fd)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):y(this,tt,Gl).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(c(this,yr)?b(this,yr,!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,tt,vf).call(this,this.parentDimensions,t,e)}translateInPage(t,e){c(this,mn)||b(this,mn,[this.x,this.y]),y(this,tt,vf).call(this,this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){c(this,mn)||b(this,mn,[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,mn)&&(c(this,mn)[0]!==this.x||c(this,mn)[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=bt,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=bt,Fh,bf).call(s,t,e,this.parentRotation)}pageTranslationToScreen(t,e){var s;return y(s=bt,Fh,bf).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,i=e*t,n=s*t;return De.isCSSRoundSupported?[Math.round(i),Math.round(n)]:[i,n]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,c(this,vr)||(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,vr)&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!c(this,vr)&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=c(this,de))==null||t.finish()}async addEditToolbar(){return c(this,ue)||c(this,_r)?c(this,ue):(b(this,ue,new Mg(this)),this.div.append(c(this,ue).render()),c(this,de)&&c(this,ue).addAltTextButton(await c(this,de).render()),c(this,ue))}removeEditToolbar(){var t;c(this,ue)&&(c(this,ue).remove(),b(this,ue,null),(t=c(this,de))==null||t.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){c(this,de)||(fd.initialize(bt._l10nPromise),b(this,de,new fd(this)),c(this,mr)&&(c(this,de).data=c(this,mr),b(this,mr,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=c(this,de))==null?void 0:t.data}set altTextData(t){c(this,de)&&(c(this,de).data=t)}hasAltText(){var t;return!((t=c(this,de))!=null&&t.isEmpty())}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,Ro)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground();const t=this._uiManager._signal;this.div.addEventListener("focusin",c(this,Io),{signal:t}),this.div.addEventListener("focusout",c(this,jo),{signal:t});const[e,s]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*s/e).toFixed(2)}%`,this.div.style.maxHeight=`${(100*e/s).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),gd(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=De.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(b(this,yr,!0),this._isDraggable){y(this,tt,Tv).call(this,t);return}y(this,tt,xf).call(this,t)}moveInDOM(){c(this,qs)&&clearTimeout(c(this,qs)),b(this,qs,setTimeout(()=>{var t;b(this,qs,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,_r,!0)}disableEditMode(){b(this,_r,!1)}isInEditMode(){return c(this,_r)}shouldGetKeyboardEvents(){return c(this,Pi)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){var e,s;const t=this._uiManager._signal;(e=this.div)==null||e.addEventListener("focusin",c(this,Io),{signal:t}),(s=this.div)==null||s.addEventListener("focusout",c(this,jo),{signal:t})}rotate(t){}serialize(t=!1,e=null){ft("An editor must be serializable")}static deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,b(i,mr,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(){if(this.div.removeEventListener("focusin",c(this,Io)),this.div.removeEventListener("focusout",c(this,jo)),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),c(this,qs)&&(clearTimeout(c(this,qs)),b(this,qs,null)),y(this,tt,Gl).call(this),this.removeEditToolbar(),c(this,ns)){for(const t of c(this,ns).values())clearTimeout(t);b(this,ns,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(y(this,tt,Cv).call(this),c(this,Zt).classList.remove("hidden"),gd(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,br,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const e=c(this,Zt).children;if(!c(this,xs)){b(this,xs,Array.from(e));const r=y(this,tt,Ev).bind(this),o=y(this,tt,kv).bind(this),h=this._uiManager._signal;for(const l of c(this,xs)){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,tt,Mv).bind(this,d),{signal:h}),bt._l10nPromise.get(`pdfjs-editor-resizer-label-${d}`).then(u=>l.setAttribute("aria-label",u))}}const s=c(this,xs)[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,xs).length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)c(this,Zt).append(c(this,Zt).firstChild);else if(n>i)for(let o=0;o<n-i;o++)c(this,Zt).firstChild.before(c(this,Zt).lastChild);let r=0;for(const o of e){const l=c(this,xs)[r++].getAttribute("data-resizer-name");bt._l10nPromise.get(`pdfjs-editor-resizer-label-${l}`).then(d=>o.setAttribute("aria-label",d))}}y(this,tt,Sf).call(this,0),b(this,Pi,!0),c(this,Zt).firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}_resizeWithKeyboard(t,e){c(this,Pi)&&y(this,tt,wf).call(this,c(this,Oh),{movementX:t,movementY:e})}_stopResizingWithKeyboard(){y(this,tt,Gl).call(this),this.div.focus()}select(){var t,e;if(this.makeResizable(),(t=this.div)==null||t.classList.add("selectedEditor"),!c(this,ue)){this.addEditToolbar().then(()=>{var s,i;(s=this.div)!=null&&s.classList.contains("selectedEditor")&&((i=c(this,ue))==null||i.show())});return}(e=c(this,ue))==null||e.show()}unselect(){var t,e,s,i;(t=c(this,Zt))==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=c(this,ue))==null||i.hide()}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,vr,!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,ns)||b(this,ns,new Map);const{action:s}=t;let i=c(this,ns).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),c(this,ns).delete(s),c(this,ns).size===0&&b(this,ns,null)},bt._telemetryTimeout),c(this,ns).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,Ro,!1)}disable(){this.div&&(this.div.tabIndex=-1),b(this,Ro,!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.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}};mr=new WeakMap,xs=new WeakMap,de=new WeakMap,Ro=new WeakMap,vr=new WeakMap,Zt=new WeakMap,br=new WeakMap,Io=new WeakMap,jo=new WeakMap,ue=new WeakMap,Oh=new WeakMap,yr=new WeakMap,mn=new WeakMap,Ph=new WeakMap,_r=new WeakMap,Pi=new WeakMap,qs=new WeakMap,No=new WeakMap,Bo=new WeakMap,ns=new WeakMap,Lh=new WeakMap,Fd=new WeakMap,tt=new WeakSet,vf=function([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()},Fh=new WeakSet,bf=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]}},yf=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]}},Cv=function(){if(c(this,Zt))return;b(this,Zt,document.createElement("div")),c(this,Zt).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,Zt).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",y(this,tt,Av).bind(this,s),{signal:e}),i.addEventListener("contextmenu",Oe,{signal:e}),i.tabIndex=-1}this.div.prepend(c(this,Zt))},Av=function(t,e){var m;e.preventDefault();const{isMac:s}=De.platform;if(e.button!==0||e.ctrlKey&&s)return;(m=c(this,de))==null||m.toggle(!1);const i=y(this,tt,wf).bind(this,t),n=this._isDraggable;this._isDraggable=!1;const r=this._uiManager._signal,o={passive:!0,capture:!0,signal:r};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",i,o),window.addEventListener("contextmenu",Oe,{signal:r});const h=this.x,l=this.y,d=this.width,u=this.height,g=this.parent.div.style.cursor,f=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const p=()=>{var _;this.parent.togglePointerEvents(!0),(_=c(this,de))==null||_.toggle(!0),this._isDraggable=n,window.removeEventListener("pointerup",p),window.removeEventListener("blur",p),window.removeEventListener("pointermove",i,o),window.removeEventListener("contextmenu",Oe),this.parent.div.style.cursor=g,this.div.style.cursor=f,y(this,tt,_f).call(this,h,l,d,u)};window.addEventListener("pointerup",p,{signal:r}),window.addEventListener("blur",p,{signal:r})},_f=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})},wf=function(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=bt.MIN_SIZE/s,d=bt.MIN_SIZE/i,u=W=>Math.round(W*1e4)/1e4,g=y(this,tt,yf).call(this,this.rotation),f=(W,V)=>[g[0]*W+g[2]*V,g[1]*W+g[3]*V],p=y(this,tt,yf).call(this,360-this.rotation),m=(W,V)=>[p[0]*W+p[2]*V,p[1]*W+p[3]*V];let _,v,x=!1,S=!1;switch(t){case"topLeft":x=!0,_=(W,V)=>[0,0],v=(W,V)=>[W,V];break;case"topMiddle":_=(W,V)=>[W/2,0],v=(W,V)=>[W/2,V];break;case"topRight":x=!0,_=(W,V)=>[W,0],v=(W,V)=>[0,V];break;case"middleRight":S=!0,_=(W,V)=>[W,V/2],v=(W,V)=>[0,V/2];break;case"bottomRight":x=!0,_=(W,V)=>[W,V],v=(W,V)=>[0,0];break;case"bottomMiddle":_=(W,V)=>[W/2,V],v=(W,V)=>[W/2,0];break;case"bottomLeft":x=!0,_=(W,V)=>[0,V],v=(W,V)=>[W,0];break;case"middleLeft":S=!0,_=(W,V)=>[0,V/2],v=(W,V)=>[W,V/2];break}const T=_(o,h),E=v(o,h);let M=f(...E);const P=u(n+M[0]),O=u(r+M[1]);let R=1,D=1,[L,F]=this.screenToPageTranslation(e.movementX,e.movementY);if([L,F]=m(L/s,F/i),x){const W=Math.hypot(o,h);R=D=Math.max(Math.min(Math.hypot(E[0]-T[0]-L,E[1]-T[1]-F)/W,1/o,1/h),l/o,d/h)}else S?R=Math.max(l,Math.min(1,Math.abs(E[0]-T[0]-L)))/o:D=Math.max(d,Math.min(1,Math.abs(E[1]-T[1]-F)))/h;const I=u(o*R),X=u(h*D);M=f(...v(I,X));const Y=P-M[0],J=O-M[1];this.width=I,this.height=X,this.x=Y,this.y=J,this.setDims(s*I,i*X),this.fixAndSetPosition()},xf=function(t){const{isMac:e}=De.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)},Tv=function(t){const e=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let s,i;const n=this._uiManager._signal;e&&(this.div.classList.add("moving"),s={passive:!0,capture:!0,signal:n},b(this,No,t.clientX),b(this,Bo,t.clientY),i=o=>{const{clientX:h,clientY:l}=o,[d,u]=this.screenToPageTranslation(h-c(this,No),l-c(this,Bo));b(this,No,h),b(this,Bo,l),this._uiManager.dragSelectedEditors(d,u)},window.addEventListener("pointermove",i,s));const r=()=>{window.removeEventListener("pointerup",r),window.removeEventListener("blur",r),e&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",i,s)),b(this,yr,!1),this._uiManager.endDragSession()||y(this,tt,xf).call(this,t)};window.addEventListener("pointerup",r,{signal:n}),window.addEventListener("blur",r,{signal:n})},Ev=function(t){bt._resizerKeyboardManager.exec(this,t)},kv=function(t){var e;c(this,Pi)&&((e=t.relatedTarget)==null?void 0:e.parentNode)!==c(this,Zt)&&y(this,tt,Gl).call(this)},Mv=function(t){b(this,Oh,c(this,Pi)?t:"")},Sf=function(t){if(c(this,xs))for(const e of c(this,xs))e.tabIndex=t},Gl=function(){if(b(this,Pi,!1),y(this,tt,Sf).call(this,-1),c(this,br)){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=c(this,br);y(this,tt,_f).call(this,t,e,s,i),b(this,br,null)}},w(bt,Fh),K(bt,"_borderLineWidth",-1),K(bt,"_colorManager",new Og),K(bt,"_zIndex",1),K(bt,"_telemetryTimeout",1e3);let dt=bt;class Fw extends dt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}const y0=3285377520,es=4294901760,Ws=65535;class _0{constructor(t){this.h1=t?t&4294967295:y0,this.h2=t?t&4294967295:y0}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&Ws,p=g&Ws;for(let m=0;m<i;m++)m&1?(o=r[m],o=o*u&es|o*f&Ws,o=o<<15|o>>>17,o=o*g&es|o*p&Ws,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[m],h=h*u&es|h*f&Ws,h=h<<15|h>>>17,h=h*g&es|h*p&Ws,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&es|o*f&Ws,o=o<<15|o>>>17,o=o*g&es|o*p&Ws,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&es|t*36045&Ws,e=e*4283543511&es|((e<<16|t>>>16)*2950163797&es)>>>16,t^=e>>>1,t=t*444984403&es|t*60499&Ws,e=e*3301882366&es|((e<<16|t>>>16)*3120437893&es)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Pg=Object.freeze({map:null,hash:"",transfer:void 0});class Lg{constructor(){w(this,Rd);w(this,wr,!1);w(this,xr,null);w(this,Qt,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=c(this,Qt).get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return c(this,Qt).get(t)}remove(t){if(c(this,Qt).delete(t),c(this,Qt).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of c(this,Qt).values())if(e instanceof dt)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=c(this,Qt).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,Qt).set(t,e);i&&y(this,Rd,Dv).call(this),e instanceof dt&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return c(this,Qt).has(t)}getAll(){return c(this,Qt).size>0?wg(c(this,Qt)):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return c(this,Qt).size}resetModified(){c(this,wr)&&(b(this,wr,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new w0(this)}get serializable(){if(c(this,Qt).size===0)return Pg;const t=new Map,e=new _0,s=[],i=Object.create(null);let n=!1;for(const[r,o]of c(this,Qt)){const h=o instanceof dt?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}:Pg}get editorStats(){let t=null;const e=new Map;for(const s of c(this,Qt).values()){if(!(s instanceof dt))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,xr,null)}get modifiedIds(){if(c(this,xr))return c(this,xr);const t=[];for(const e of c(this,Qt).values())!(e instanceof dt)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return b(this,xr,{ids:new Set(t),hash:t.join(",")})}}wr=new WeakMap,xr=new WeakMap,Qt=new WeakMap,Rd=new WeakSet,Dv=function(){c(this,wr)||(b(this,wr,!0),typeof this.onSetModified=="function"&&this.onSetModified())};class w0 extends Lg{constructor(e){super();w(this,Rh);const{map:s,hash:i,transfer:n}=e.serializable,r=structuredClone(s,n?{transfer:n}:null);b(this,Rh,{map:r,hash:i,transfer:n})}get print(){ft("Should not call PrintAnnotationStorage.print")}get serializable(){return c(this,Rh)}get modifiedIds(){return at(this,"modifiedIds",{ids:new Set,hash:""})}}Rh=new WeakMap;class Rw{constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){w(this,Ho,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,Ho).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||c(this,Ho).has(t.loadedName))){if(Xt(!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,Ho).add(s),e==null||e(t)}catch{Z(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}ft("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 Z(`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 at(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(he||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),at(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(Xt(!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 at(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(T,E){return T.charCodeAt(E)<<24|T.charCodeAt(E+1)<<16|T.charCodeAt(E+2)<<8|T.charCodeAt(E+3)&255}function i(T,E,M,P){const O=T.substring(0,E),R=T.substring(E+M);return O+P+R}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(T,E){if(++l>30){Z("Load test font never loaded."),E();return}if(h.font="30px "+T,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){E();return}setTimeout(d.bind(null,T,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,bw(_));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 T of[t.loadedName,u]){const E=this._document.createElement("span");E.textContent="Hi",E.style.fontFamily=T,S.append(E)}this._document.body.append(S),d(u,()=>{S.remove(),e.complete()})}}Ho=new WeakMap;class Iw{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=d0(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){Z(`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 vi.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 vi.MOVE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.moveTo(o,h)),n+=2}break;case vi.LINE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.lineTo(o,h)),n+=2}break;case vi.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 vi.RESTORE:i.push(o=>o.restore());break;case vi.SAVE:i.push(o=>o.save());break;case vi.SCALE:Xt(i.length===2,"Scale command is only valid at the third position.");break;case vi.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 vi.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(he){var Fg=Promise.withResolvers(),Ja=null;(async()=>{const t=await Promise.resolve().then(()=>Ad),e=await Promise.resolve().then(()=>Ad),s=await Promise.resolve().then(()=>Ad),i=await Promise.resolve().then(()=>Ad);let n,r;return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:n,path2d:r}))})().then(t=>{Ja=t,Fg.resolve()},t=>{Z(`loadPackages: ${t}`),Ja=new Map,Fg.resolve()})}class Xs{static get promise(){return Fg.promise}static get(t){return Ja==null?void 0:Ja.get(t)}}const x0=function(a){return Xs.get("fs").promises.readFile(a).then(e=>new Uint8Array(e))};class jw extends ad{}class Nw extends hd{_createCanvas(t,e){return Xs.get("canvas").createCanvas(t,e)}}class Bw extends ld{_fetchData(t,e){return x0(t).then(s=>({cMapData:s,compressionType:e}))}}class Hw extends cd{_fetchData(t){return x0(t)}}const Se={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Rg(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 Za{constructor(){this.constructor===Za&&ft("Cannot initialize BaseShadingPattern.")}getPattern(){ft("Abstract method `getPattern` called.")}}class Ww extends Za{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===Se.STROKE||i===Se.FILL){const r=e.current.getClippedPathBoundingBox(i,Ct(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,!0),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=z.transform(s,[1,0,0,1,r[0],r[1]]),d.transform(...e.baseTransform),this.matrix&&d.transform(...this.matrix),Rg(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 Rg(t,this._bbox),n=this._createGradient(t);return n}}function Ig(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],T=l[n+1],E=l[n+2],M=l[r],P=l[r+1],O=l[r+2],R=l[o],D=l[o+1],L=l[o+2],F=Math.round(p),I=Math.round(x);let X,Y,J,W,V,It,Ie,ai;for(let Yt=F;Yt<=I;Yt++){if(Yt<_){const wt=Yt<p?0:(p-Yt)/(p-_);X=f-(f-m)*wt,Y=S-(S-M)*wt,J=T-(T-P)*wt,W=E-(E-O)*wt}else{let wt;Yt>x?wt=1:_===x?wt=0:wt=(_-Yt)/(_-x),X=m-(m-v)*wt,Y=M-(M-R)*wt,J=P-(P-D)*wt,W=O-(O-L)*wt}let Tt;Yt<p?Tt=0:Yt>x?Tt=1:Tt=(p-Yt)/(p-x),V=f-(f-v)*Tt,It=S-(S-R)*Tt,Ie=T-(T-D)*Tt,ai=E-(E-L)*Tt;const Qe=Math.round(Math.min(X,V)),ls=Math.round(Math.max(X,V));let pe=u*Yt+Qe*4;for(let wt=Qe;wt<=ls;wt++)Tt=(X-wt)/(X-V),Tt<0?Tt=0:Tt>1&&(Tt=1),d[pe++]=Y-(Y-It)*Tt|0,d[pe++]=J-(J-Ie)*Tt|0,d[pe++]=W-(W-ai)*Tt|0,d[pe++]=255}}function Xw(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++)Ig(a,e,s[d],s[d+1],s[d+o],i[d],i[d+1],i[d+o]),Ig(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)Ig(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 zw extends Za{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,!1),S=x.context,T=S.createImageData(u,g);if(e){const M=T.data;for(let P=0,O=M.length;P<O;P+=4)M[P]=e[0],M[P+1]=e[1],M[P+2]=e[2],M[P+3]=255}for(const M of this._figures)Xw(T,M,m);return S.putImageData(T,2,2),{canvas:x.canvas,offsetX:o-2*f,offsetY:h-2*p,scaleX:f,scaleY:p}}getPattern(t,e,s,i){Rg(t,this._bbox);let n;if(i===Se.SHADING)n=z.singularValueDecompose2dScale(Ct(t));else if(n=z.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=z.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Se.SHADING?null:this._background,e.cachedCanvases);return i!==Se.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 Vw extends Za{getPattern(){return"hotpink"}}function Gw(a){switch(a[0]){case"RadialAxial":return new Ww(a);case"Mesh":return new zw(a);case"Dummy":return new Vw}throw new Error(`Unknown IR type: ${a[0]}`)}const S0={COLORED:1,UNCOLORED:2},Id=class Id{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 e=this.operatorList,s=this.bbox,i=this.xstep,n=this.ystep,r=this.paintType,o=this.tilingType,h=this.color,l=this.canvasGraphicsFactory;nd("TilingType: "+o);const d=s[0],u=s[1],g=s[2],f=s[3],p=z.singularValueDecompose2dScale(this.matrix),m=z.singularValueDecompose2dScale(this.baseTransform),_=[p[0]*m[0],p[1]*m[1]],v=this.getSizeAndScale(i,this.ctx.canvas.width,_[0]),x=this.getSizeAndScale(n,this.ctx.canvas.height,_[1]),S=t.cachedCanvases.getCanvas("pattern",v.size,x.size,!0),T=S.context,E=l.createCanvasGraphics(T);E.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(E,r,h);let M=d,P=u,O=g,R=f;return d<0&&(M=0,O+=Math.abs(d)),u<0&&(P=0,R+=Math.abs(u)),T.translate(-(v.scale*M),-(x.scale*P)),E.transform(v.scale,0,0,x.scale,0,0),T.save(),this.clipBbox(E,M,P,O,R),E.baseTransform=Ct(E.ctx),E.executeOperatorList(e),E.endDrawing(),{canvas:S.canvas,scaleX:v.scale,scaleY:x.scale,offsetX:M,offsetY:P}}getSizeAndScale(t,e,s){t=Math.abs(t);const i=Math.max(Id.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(Ct(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case S0.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case S0.UNCOLORED:const o=z.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new vw(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Se.SHADING&&(n=z.transform(n,e.baseTransform),this.matrix&&(n=z.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}};K(Id,"MAX_PATTERN_SIZE",3e3);let jg=Id;function Uw({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=De.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 C0=16,A0=100,Yw=15,T0=10,E0=1e3,Pe=16;function qw(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 $w{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 pd(a,t,e,s,i,n,r,o,h,l){const[d,u,g,f,p,m]=Ct(a);if(u===0&&g===0){const x=r*d+p,S=Math.round(x),T=o*f+m,E=Math.round(T),M=(r+h)*d+p,P=Math.abs(Math.round(M)-S)||1,O=(o+l)*f+m,R=Math.abs(Math.round(O)-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,R),a.setTransform(d,u,g,f,p,m),[P,R]}if(d===0&&f===0){const x=o*g+p,S=Math.round(x),T=r*u+m,E=Math.round(T),M=(o+l)*g+p,P=Math.abs(Math.round(M)-S)||1,O=(r+h)*u+m,R=Math.abs(Math.round(O)-E)||1;return a.setTransform(0,Math.sign(u),Math.sign(g),0,S,E),a.drawImage(t,e,s,i,n,0,0,R,P),a.setTransform(d,u,g,f,p,m),[R,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 Kw(a){const{width:t,height:e}=a;if(t>E0||e>E0)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 T=r[v];do{const E=p[T];do v+=E;while(!r[v]);const M=r[v];M!==5&&M!==10?(T=M,r[v]=0):(T=M&51*T>>4,r[v]&=T>>2|T<<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 k0{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=l0,this.textMatrixScale=1,this.fontMatrix=mg,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=le.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]=z.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=z.applyTransform(e,t),i=z.applyTransform(e.slice(2),t),n=z.applyTransform([e[0],e[3]],t),r=z.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){z.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=z.bezierBoundingBox(e,s,i,n,r,o,h,l,d);d||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Se.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Se.STROKE){e||ft("Stroke bounding box must include transform.");const i=z.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=z.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=Se.FILL,e=null){return z.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function M0(a,t){if(typeof ImageData<"u"&&t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Pe,n=(e-i)/Pe,r=i===0?n:n+1,o=a.createImageData(s,Pe);let h=0,l;const d=t.data,u=o.data;let g,f,p,m;if(t.kind===ed.GRAYSCALE_1BPP){const _=d.byteLength,v=new Uint32Array(u.buffer,0,u.byteLength>>2),x=v.length,S=s+7>>3,T=4294967295,E=De.isLittleEndian?4278190080:255;for(g=0;g<r;g++){for(p=g<n?Pe:i,l=0,f=0;f<p;f++){const M=_-h;let P=0;const O=M>S?s:M*8-7,R=O&-8;let D=0,L=0;for(;P<R;P+=8)L=d[h++],v[l++]=L&128?T:E,v[l++]=L&64?T:E,v[l++]=L&32?T:E,v[l++]=L&16?T:E,v[l++]=L&8?T:E,v[l++]=L&4?T:E,v[l++]=L&2?T:E,v[l++]=L&1?T:E;for(;P<O;P++)D===0&&(L=d[h++],D=128),v[l++]=L&D?T:E,D>>=1}for(;l<x;)v[l++]=0;a.putImageData(o,0,g*Pe)}}else if(t.kind===ed.RGBA_32BPP){for(f=0,m=s*Pe*4,g=0;g<n;g++)u.set(d.subarray(h,h+m)),h+=m,a.putImageData(o,0,f),f+=Pe;g<r&&(m=s*i*4,u.set(d.subarray(h,h+m)),a.putImageData(o,0,f))}else if(t.kind===ed.RGB_24BPP)for(p=Pe,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*Pe)}else throw new Error(`bad image kind: ${t.kind}`)}function D0(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Pe,n=(e-i)/Pe,r=i===0?n:n+1,o=a.createImageData(s,Pe);let h=0;const l=t.data,d=o.data;for(let u=0;u<r;u++){const g=u<n?Pe:i;({srcPos:h}=Uw({src:l,srcPos:h,dest:d,width:s,height:g,nonBlackColor:0})),a.putImageData(o,0,u*Pe)}}function th(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 md(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),!he){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function O0(a,t){if(t)return!0;const e=z.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*ln.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const Qw=["butt","round","square"],Jw=["miter","round","bevel"],Zw={},P0={},tf=class tf{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){w(this,vn);this.ctx=t,this.current=new k0(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 $w(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(...Ct(this.compositeCtx))}this.ctx.save(),md(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=Ct(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>T0&&typeof s=="function",d=l?Date.now()+Yw: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!==vs.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>T0){if(Date.now()>d)return s(),o;u=0}}}endDrawing(){y(this,vn,Cf).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,vn,Af).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=Ct(e);let h,l,d,u;if((t.bitmap||t.data)&&t.count>1){const O=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(O),h||(h=new Map,this._cachedBitmapsMap.set(O,h));const R=h.get(l);if(R&&!r){const D=Math.round(Math.min(o[0],o[2])+o[4]),L=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:R,offsetX:D,offsetY:L}}d=R}d||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),D0(u.context,t));let g=z.transform(o,[1/s,0,0,-1/i,0,0]);g=z.transform(g,[1,0,0,1,0,-i]);const[f,p,m,_]=z.getAxialAlignedBoundingBox([0,0,s,i],g),v=Math.round(m-f)||1,x=Math.round(_-p)||1,S=this.cachedCanvases.getCanvas("fillCanvas",v,x),T=S.context,E=f,M=p;T.translate(-E,-M),T.transform(...g),d||(d=this._scaleImage(u.canvas,yi(T)),d=d.img,h&&r&&h.set(l,d)),T.imageSmoothingEnabled=O0(Ct(T),t.interpolate),pd(T,d,0,0,d.width,d.height,0,0,s,i),T.globalCompositeOperation="source-in";const P=z.transform(yi(T),[1,0,0,1,-E,-M]);return T.fillStyle=r?n.getPattern(e,this,P,Se.FILL):n,T.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(M)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Qw[t]}setLineJoin(t){this.ctx.lineJoin=Jw[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(...Ct(this.suspendedCtx)),th(this.suspendedCtx,n),qw(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(),th(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=z.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=z.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?(th(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(),th(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=Ct(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 vs.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 vs.moveTo:r=e[p++],o=e[p++],i.moveTo(r,o),u||n.updatePathMinMax(d,r,o);break;case vs.lineTo:r=e[p++],o=e[p++],i.lineTo(r,o),u||n.updatePathMinMax(d,r,o);break;case vs.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 vs.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 vs.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 vs.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,yi(e),Se.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,yi(e),Se.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=Zw}eoClip(){this.pendingClip=P0}beginText(){this.current.textMatrix=l0,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||mg,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&Z("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<C0?l=C0:e>A0&&(l=A0),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&le.FILL_STROKE_MASK,u=!!(h&le.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===le.FILL||d===le.FILL_STROKE)&&n.fill(),(d===le.STROKE||d===le.FILL_STROKE)&&n.stroke(),n.restore()):((d===le.FILL||d===le.FILL_STROKE)&&n.fillText(t,e,s),(d===le.STROKE||d===le.FILL_STROKE)&&n.strokeText(t,e,s)),u&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Ct(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 at(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===le.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 M=e.fillColor.getPattern(n,this,yi(n),Se.FILL);v=Ct(n),n.restore(),n.fillStyle=M}let x=e.lineWidth;const S=e.textMatrixScale;if(S===0||x===0){const M=e.textRenderingMode&le.FILL_STROKE_MASK;(M===le.STROKE||M===le.FILL_STROKE)&&(x=this.getSinglePixelWidth())}else x/=S;if(r!==1&&(n.scale(r,r),x/=r),n.lineWidth=x,s.isInvalidPDFjsFont){const M=[];let P=0;for(const O of t)M.push(O.unicode),P+=O.width;n.fillText(M.join(""),0,0),e.x+=P*m*d,n.restore(),this.compose();return}let T=0,E;for(E=0;E<u;++E){const M=t[E];if(typeof M=="number"){T+=f*M*i/1e3;continue}let P=!1;const O=(M.isSpace?h:0)+o,R=M.fontChar,D=M.accent;let L,F,I=M.width;if(g){const Y=M.vmetric||p,J=-(M.vmetric?Y[1]:I*.5)*m,W=Y[2]*m;I=Y?-Y[0]:I,L=J/r,F=(T+W)/r}else L=T/r,F=0;if(s.remeasure&&I>0){const Y=n.measureText(R).width*1e3/i*r;if(I<Y&&this.isFontSubpixelAAEnabled){const J=I/Y;P=!0,n.save(),n.scale(J,1),L/=J}else I!==Y&&(L+=(I-Y)/2e3*i/r)}if(this.contentVisible&&(M.isInFont||s.missingFile)){if(_&&!D)n.fillText(R,L,F);else if(this.paintChar(R,L,F,v),D){const Y=L+i*D.offset.x/r,J=F-i*D.offset.y/r;this.paintChar(D.fontChar,Y,J,v)}}const X=g?I*m-O*l:I*m+O*l;T+=X,P&&n.restore()}g?e.y-=T:e.x+=T*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||mg,g=t.length,f=s.textRenderingMode===le.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){Z(`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()),_=z.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||Ct(this.ctx),n={createCanvasGraphics:r=>new tf(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new jg(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=z.makeHexColor(t,e,s)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=z.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=Gw(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,yi(e),Se.SHADING);const i=yi(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,d]=z.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(){ft("Should not call beginInlineImage")}beginImageData(){ft("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Ct(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(Ct(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||nd("TODO: Support non-isolated groups."),t.knockout&&Z("Knockout groups not supported.");const s=Ct(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=z.getAxialAlignedBoundingBox(t.bbox,Ct(e));const n=[0,0,e.canvas.width,e.canvas.height];i=z.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()),th(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=Ct(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=z.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,vn,Cf).call(this),md(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]=z.singularValueDecompose2dScale(Ct(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),md(this.ctx)}else md(this.ctx),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.endPath()}this.current=new k0(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),y(this,vn,Af).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=Kw(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=Ct(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=z.transform(h,[e,s,i,n,r[d],r[d+1]]),[f,p]=z.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);D0(u,g),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,yi(e),Se.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),pd(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){Z("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){Z("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(),!he){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;M0(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,yi(i));i.imageSmoothingEnabled=O0(Ct(i),t.interpolate),pd(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;M0(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),pd(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===P0?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Ct(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}};vn=new WeakSet,Cf=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)},Af=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 Ao=tf;for(const a in vs)Ao.prototype[a]!==void 0&&(Ao.prototype[vs[a]]=Ao.prototype[a]);class _i{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(_i,Ih,null),w(_i,jh,"");const vd={UNKNOWN:0,DATA:1,ERROR:2},Nt={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function He(a){switch(a instanceof Error||typeof a=="object"&&a!==null||ft('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new Jn(a.message);case"MissingPDFException":return new Qn(a.message);case"PasswordException":return new yg(a.message,a.code);case"UnexpectedResponseException":return new rd(a.message,a.status);case"UnknownErrorException":return new _g(a.message,a.details);default:return new _g(a.message,a.toString())}}class eh{constructor(t,e,s){w(this,$s);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,$s,Pv).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===vd.DATA)h.resolve(n.data);else if(n.callback===vd.ERROR)h.reject(He(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:vd.DATA,callbackId:n.callbackId,data:l})},function(l){s.postMessage({sourceName:o,targetName:h,callback:vd.ERROR,callbackId:n.callbackId,reason:He(l)})});return}if(n.streamId){y(this,$s,Ov).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:Nt.PULL,streamId:n,desiredSize:l.desiredSize}),d.promise},cancel:l=>{Xt(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:Nt.CANCEL,streamId:n,reason:He(l)}),d.promise}},s)}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}$s=new WeakSet,Ov=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:Nt.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Nt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){Xt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Nt.ERROR,streamId:e,reason:He(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:Nt.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Nt.START_COMPLETE,streamId:e,reason:He(l)})})},Pv=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 Nt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(He(t.reason));break;case Nt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(He(t.reason));break;case Nt.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:Nt.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:Nt.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Nt.PULL_COMPLETE,streamId:e,reason:He(h)})});break;case Nt.ENQUEUE:if(Xt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Nt.CLOSE:if(Xt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),y(this,$s,Kd).call(this,r,e);break;case Nt.ERROR:Xt(r,"error should have stream controller"),r.controller.error(He(t.reason)),y(this,$s,Kd).call(this,r,e);break;case Nt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(He(t.reason)),y(this,$s,Kd).call(this,r,e);break;case Nt.CANCEL:if(!o)break;new Promise(function(h){var l;h((l=o.onCancel)==null?void 0:l.call(o,He(t.reason)))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Nt.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Nt.CANCEL_COMPLETE,streamId:e,reason:He(h)})}),o.sinkCapability.reject(He(t.reason)),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}},Kd=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 tx{constructor({parsedData:t,rawData:e}){w(this,Sr);w(this,Nh);b(this,Sr,t),b(this,Nh,e)}getRaw(){return c(this,Nh)}get(t){return c(this,Sr).get(t)??null}getAll(){return wg(c(this,Sr))}has(t){return c(this,Sr).has(t)}}Sr=new WeakMap,Nh=new WeakMap;const cn=Symbol("INTERNAL");class ex{constructor(t,{name:e,intent:s,usage:i}){w(this,Bh,!1);w(this,Hh,!1);w(this,Wh,!1);w(this,Wo,!0);b(this,Bh,!!(t&Be.DISPLAY)),b(this,Hh,!!(t&Be.PRINT)),this.name=e,this.intent=s,this.usage=i}get visible(){if(c(this,Wh))return c(this,Wo);if(!c(this,Wo))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!==cn&&ft("Internal method `_setVisible` called."),b(this,Wh,s),b(this,Wo,e)}}Bh=new WeakMap,Hh=new WeakMap,Wh=new WeakMap,Wo=new WeakMap;class sx{constructor(t,e=Be.DISPLAY){w(this,Xh);w(this,bn,null);w(this,pt,new Map);w(this,Xo,null);w(this,zo,null);if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,b(this,zo,t.order);for(const s of t.groups)c(this,pt).set(s.id,new ex(e,s));if(t.baseState==="OFF")for(const s of c(this,pt).values())s._setVisible(cn,!1);for(const s of t.on)c(this,pt).get(s)._setVisible(cn,!0);for(const s of t.off)c(this,pt).get(s)._setVisible(cn,!1);b(this,Xo,this.getHash())}}isVisible(t){if(c(this,pt).size===0)return!0;if(!t)return nd("Optional content group not defined."),!0;if(t.type==="OCG")return c(this,pt).has(t.id)?c(this,pt).get(t.id).visible:(Z(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return y(this,Xh,Tf).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(c(this,pt).get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(!c(this,pt).get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(!c(this,pt).get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!c(this,pt).has(e))return Z(`Optional content group not found: ${e}`),!0;if(c(this,pt).get(e).visible)return!1}return!0}return Z(`Unknown optional content policy ${t.policy}.`),!0}return Z(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0){const s=c(this,pt).get(t);if(!s){Z(`Optional content group not found: ${t}`);return}s._setVisible(cn,!!e,!0),b(this,bn,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,pt).get(i);if(n)switch(s){case"ON":n._setVisible(cn,!0);break;case"OFF":n._setVisible(cn,!1);break;case"Toggle":n._setVisible(cn,!n.visible);break}}b(this,bn,null)}get hasInitialVisibility(){return c(this,Xo)===null||this.getHash()===c(this,Xo)}getOrder(){return c(this,pt).size?c(this,zo)?c(this,zo).slice():[...c(this,pt).keys()]:null}getGroups(){return c(this,pt).size>0?wg(c(this,pt)):null}getGroup(t){return c(this,pt).get(t)||null}getHash(){if(c(this,bn)!==null)return c(this,bn);const t=new _0;for(const[e,s]of c(this,pt))t.update(`${e}:${s.visible}`);return b(this,bn,t.hexdigest())}}bn=new WeakMap,pt=new WeakMap,Xo=new WeakMap,zo=new WeakMap,Xh=new WeakSet,Tf=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,Xh,Tf).call(this,n);else if(c(this,pt).has(n))r=c(this,pt).get(n).visible;else return Z(`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 ix{constructor(t,{disableRange:e=!1,disableStream:s=!1}){Xt(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)});Xt(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(){Xt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new nx(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new rx(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 nx{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Eg(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 rx{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 ox(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=od(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 Ng({getResponseHeader:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a("Accept-Ranges")!=="bytes"||(a("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function Bg(a){const t=a("Content-Disposition");if(t){let e=ox(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Eg(e))return e}return null}function bd(a,t){return a===404||a===0&&t.startsWith("file:")?new Qn('Missing PDF "'+t+'".'):new rd(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function L0(a){return a===200||a===206}function F0(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function R0(a){const t=new Headers;for(const e in a){const s=a[e];s!==void 0&&t.append(e,s)}return t}function I0(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(Z(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class j0{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.httpHeaders=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 Xt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new ax(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new hx(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 ax{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,this._headers=R0(this._stream.httpHeaders);const s=e.url;fetch(s,F0(this._headers,this._withCredentials,this._abortController)).then(i=>{if(!L0(i.status))throw bd(i.status,s);this._reader=i.body.getReader(),this._headersCapability.resolve();const n=h=>i.headers.get(h),{allowRangeRequests:r,suggestedLength:o}=Ng({getResponseHeader:n,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=o||this._contentLength,this._filename=Bg(n),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Jn("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:I0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}class hx{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,this._headers=R0(this._stream.httpHeaders),this._headers.append("Range",`bytes=${e}-${s-1}`);const n=i.url;fetch(n,F0(this._headers,this._withCredentials,this._abortController)).then(r=>{if(!L0(r.status))throw bd(r.status,n);this._readCapability.resolve(),this._reader=r.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:I0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}const Hg=200,Wg=206;function lx(a){const t=a.response;return typeof t!="string"?t:od(t).buffer}class cx{constructor(t,e={}){this.url=t,this.isHttp=/^https?:/i.test(t),this.httpHeaders=this.isHttp&&e.httpHeaders||Object.create(null),this.withCredentials=e.withCredentials||!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 in this.httpHeaders){const r=this.httpHeaders[n];r!==void 0&&e.setRequestHeader(n,r)}return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=Wg):i.expectedStatus=Hg,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||Hg;if(!(n===Hg&&s.expectedStatus===Wg)&&n!==s.expectedStatus){(l=s.onError)==null||l.call(s,i.status);return}const o=lx(i);if(n===Wg){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 dx{constructor(t){this._source=t,this._manager=new cx(t.url,{httpHeaders:t.httpHeaders,withCredentials:t.withCredentials}),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 Xt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new ux(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new gx(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 ux{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._headersReceivedCapability=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=r=>e.getResponseHeader(r),{allowRangeRequests:i,suggestedLength:n}=Ng({getResponseHeader:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=n||this._contentLength,this._filename=Bg(s),this._isRangeSupported&&this._manager.abortRequest(t),this._headersReceivedCapability.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=bd(t,this._url),this._headersReceivedCapability.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._headersReceivedCapability.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._headersReceivedCapability.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 gx{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=bd(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 N0=/^file:\/\/\/[a-zA-Z]:\//;function fx(a){const t=Xs.get("url"),e=t.parse(a);return e.protocol==="file:"||e.host?e:/^[a-z]:[/\\]/i.test(a)?t.parse(`file:///${a}`):(e.host||(e.protocol="file:"),e)}class px{constructor(t){this.source=t,this.url=fx(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=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 Xt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new bx(this):new mx(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new yx(this,t,e):new vx(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 B0{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 Jn("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class H0{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)}}function yd(a,t){return{protocol:a.protocol,auth:a.auth,host:a.hostname,port:a.port,path:a.path,method:"GET",headers:t}}class mx extends B0{constructor(t){super(t);const e=s=>{if(s.statusCode===404){const o=new Qn(`Missing PDF "${this._url}".`);this._storedError=o,this._headersCapability.reject(o);return}this._headersCapability.resolve(),this._setReadableStream(s);const i=o=>this._readableStream.headers[o.toLowerCase()],{allowRangeRequests:n,suggestedLength:r}=Ng({getResponseHeader:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=r||this._contentLength,this._filename=Bg(i)};if(this._request=null,this._url.protocol==="http:"){const s=Xs.get("http");this._request=s.request(yd(this._url,t.httpHeaders),e)}else{const s=Xs.get("https");this._request=s.request(yd(this._url,t.httpHeaders),e)}this._request.on("error",s=>{this._storedError=s,this._headersCapability.reject(s)}),this._request.end()}}class vx extends H0{constructor(t,e,s){super(t),this._httpHeaders={};for(const n in t.httpHeaders){const r=t.httpHeaders[n];r!==void 0&&(this._httpHeaders[n]=r)}this._httpHeaders.Range=`bytes=${e}-${s-1}`;const i=n=>{if(n.statusCode===404){const r=new Qn(`Missing PDF "${this._url}".`);this._storedError=r;return}this._setReadableStream(n)};if(this._request=null,this._url.protocol==="http:"){const n=Xs.get("http");this._request=n.request(yd(this._url,this._httpHeaders),i)}else{const n=Xs.get("https");this._request=n.request(yd(this._url,this._httpHeaders),i)}this._request.on("error",n=>{this._storedError=n}),this._request.end()}}class bx extends B0{constructor(t){super(t);let e=decodeURIComponent(this._url.path);N0.test(this._url.href)&&(e=e.replace(/^\//,""));const s=Xs.get("fs");s.promises.lstat(e).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(e)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new Qn(`Missing PDF "${e}".`)),this._storedError=i,this._headersCapability.reject(i)})}}class yx extends H0{constructor(t,e,s){super(t);let i=decodeURIComponent(this._url.path);N0.test(this._url.href)&&(i=i.replace(/^\//,""));const n=Xs.get("fs");this._setReadableStream(n.createReadStream(i,{start:e,end:s-1}))}}const _x=1e5,Le=30,wx=.8,ge=class ge{constructor({textContentSource:t,container:e,viewport:s}){w(this,Fi);w(this,yn,Promise.withResolvers());w(this,Fe,null);w(this,zh,!1);w(this,Vh,!!((iv=globalThis.FontInspector)!=null&&iv.enabled));w(this,Cr,null);w(this,Li,null);w(this,Gh,0);w(this,Uh,0);w(this,Ar,null);w(this,Vo,null);w(this,Go,0);w(this,_n,0);w(this,Uo,Object.create(null));w(this,Yh,[]);w(this,Yo,null);w(this,Tr,[]);w(this,qh,new WeakMap);w(this,$h,null);var h;if(t instanceof ReadableStream)b(this,Yo,t);else if(typeof t=="object")b(this,Yo,new ReadableStream({start(l){l.enqueue(t),l.close()}}));else throw new Error('No "textContentSource" parameter specified.');b(this,Fe,b(this,Vo,e)),b(this,_n,s.scale*(globalThis.devicePixelRatio||1)),b(this,Go,s.rotation),b(this,Li,{prevFontSize:null,prevFontFamily:null,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=ge,Ks,Rv).call(h),Zn(e,s),c(this,yn).promise.catch(()=>{}).then(()=>{c(ge,qo).delete(this),b(this,Li,null),b(this,Uo,null)})}render(){const t=()=>{c(this,Ar).read().then(({value:e,done:s})=>{if(s){c(this,yn).resolve();return}c(this,Cr)??b(this,Cr,e.lang),Object.assign(c(this,Uo),e.styles),y(this,Fi,Lv).call(this,e.items),t()},c(this,yn).reject)};return b(this,Ar,c(this,Yo).getReader()),c(ge,qo).add(this),t(),c(this,yn).promise}update({viewport:t,onBefore:e=null}){var n;const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==c(this,Go)&&(e==null||e(),b(this,Go,i),Zn(c(this,Vo),{rotation:i})),s!==c(this,_n)){e==null||e(),b(this,_n,s);const r={prevFontSize:null,prevFontFamily:null,div:null,properties:null,ctx:y(n=ge,Ks,Qd).call(n,c(this,Cr))};for(const o of c(this,Tr))r.properties=c(this,qh).get(o),r.div=o,y(this,Fi,Ef).call(this,r)}}cancel(){var e;const t=new Jn("TextLayer task cancelled.");(e=c(this,Ar))==null||e.cancel(t).catch(()=>{}),b(this,Ar,null),c(this,yn).reject(t)}get textDivs(){return c(this,Tr)}get textContentItemsStr(){return c(this,Yh)}static cleanup(){if(!(c(this,qo).size>0)){c(this,Er).clear();for(const{canvas:t}of c(this,kr).values())t.remove();c(this,kr).clear()}}};yn=new WeakMap,Fe=new WeakMap,zh=new WeakMap,Vh=new WeakMap,Cr=new WeakMap,Li=new WeakMap,Gh=new WeakMap,Uh=new WeakMap,Ar=new WeakMap,Vo=new WeakMap,Go=new WeakMap,_n=new WeakMap,Uo=new WeakMap,Yh=new WeakMap,Yo=new WeakMap,Tr=new WeakMap,qh=new WeakMap,$h=new WeakMap,Er=new WeakMap,kr=new WeakMap,wn=new WeakMap,qo=new WeakMap,Fi=new WeakSet,Lv=function(t){var i,n;if(c(this,zh))return;(n=c(this,Li)).ctx??(n.ctx=y(i=ge,Ks,Qd).call(i,c(this,Cr)));const e=c(this,Tr),s=c(this,Yh);for(const r of t){if(e.length>_x){Z("Ignoring additional textDivs for performance reasons."),b(this,zh,!0);return}if(r.str===void 0){if(r.type==="beginMarkedContentProps"||r.type==="beginMarkedContent"){const o=c(this,Fe);b(this,Fe,document.createElement("span")),c(this,Fe).classList.add("markedContent"),r.id!==null&&c(this,Fe).setAttribute("id",`${r.id}`),o.append(c(this,Fe))}else r.type==="endMarkedContent"&&b(this,Fe,c(this,Fe).parentNode);continue}s.push(r.str),y(this,Fi,Fv).call(this,r)}},Fv=function(t){var m;const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};c(this,Tr).push(e);const i=z.transform(c(this,$h),t.transform);let n=Math.atan2(i[1],i[0]);const r=c(this,Uo)[t.fontName];r.vertical&&(n+=Math.PI/2);const o=c(this,Vh)&&r.fontSubstitution||r.fontFamily,h=Math.hypot(i[2],i[3]),l=h*y(m=ge,Ks,Iv).call(m,o,c(this,Cr));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,Fe)===c(this,Vo)?(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(ge,wn)*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,Li).div=e,c(this,Li).properties=s,y(this,Fi,Ef).call(this,c(this,Li)),s.hasText&&c(this,Fe).append(e),s.hasEOL){const _=document.createElement("br");_.setAttribute("role","presentation"),c(this,Fe).append(_)}},Ef=function(t){const{div:e,properties:s,ctx:i,prevFontSize:n,prevFontFamily:r}=t,{style:o}=e;let h="";if(c(ge,wn)>1&&(h=`scale(${1/c(ge,wn)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:l}=o,{canvasWidth:d,fontSize:u}=s;(n!==u||r!==l)&&(i.font=`${u*c(this,_n)}px ${l}`,t.prevFontSize=u,t.prevFontFamily=l);const{width:g}=i.measureText(e.textContent);g>0&&(h=`scaleX(${d*c(this,_n)/g}) ${h}`)}s.angle!==0&&(h=`rotate(${s.angle}deg) ${h}`),h.length>0&&(o.transform=h)},Ks=new WeakSet,Qd=function(t=null){let e=c(this,kr).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,kr).set(t,e)}return e},Rv=function(){if(c(this,wn)!==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,wn,t.getBoundingClientRect().height),t.remove()},Iv=function(t,e){const s=c(this,Er).get(t);if(s)return s;const i=y(this,Ks,Qd).call(this,e),n=i.font;i.canvas.width=i.canvas.height=Le,i.font=`${Le}px ${t}`;const r=i.measureText("");let o=r.fontBoundingBoxAscent,h=Math.abs(r.fontBoundingBoxDescent);if(o){const u=o/(o+h);return c(this,Er).set(t,u),i.canvas.width=i.canvas.height=0,i.font=n,u}i.strokeStyle="red",i.clearRect(0,0,Le,Le),i.strokeText("g",0,0);let l=i.getImageData(0,0,Le,Le).data;h=0;for(let u=l.length-1-3;u>=0;u-=4)if(l[u]>0){h=Math.ceil(u/4/Le);break}i.clearRect(0,0,Le,Le),i.strokeText("A",0,Le),l=i.getImageData(0,0,Le,Le).data,o=0;for(let u=0,g=l.length;u<g;u+=4)if(l[u]>0){o=Le-Math.floor(u/4/Le);break}i.canvas.width=i.canvas.height=0,i.font=n;const d=o?o/(o+h):wx;return c(this,Er).set(t,d),d},w(ge,Ks),w(ge,Er,new Map),w(ge,kr,new Map),w(ge,wn,null),w(ge,qo,new Set);let sh=ge;class ih{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(ih.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 xx=65536,Sx=100,Cx=5e3,Ax=he?Nw:Aw,Tx=he?Bw:f0,Ex=he?jw:Cw,kx=he?Hw:p0;function Mx(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new Xg,{docId:e}=t,s=a.url?Dx(a.url):null,i=a.data?Ox(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof X0?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:xx;let d=a.worker instanceof To?a.worker:null;const u=a.verbosity,g=typeof a.docBaseUrl=="string"&&!ud(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,p=a.cMapPacked!==!1,m=a.CMapReaderFactory||Tx,_=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,v=a.StandardFontDataFactory||kx,x=a.stopAtErrors!==!0,S=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,T=a.isEvalSupported!==!1,E=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!he,M=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,P=typeof a.disableFontFace=="boolean"?a.disableFontFace:he,O=a.fontExtraProperties===!0,R=a.enableXfa===!0,D=a.ownerDocument||globalThis.document,L=a.disableRange===!0,F=a.disableStream===!0,I=a.disableAutoFetch===!0,X=a.pdfBug===!0,Y=a.enableHWA===!0,J=h?h.length:a.length??NaN,W=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!he&&!P,V=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:m===f0&&v===p0&&f&&_&&Ka(f,document.baseURI)&&Ka(_,document.baseURI),It=a.canvasFactory||new Ax({ownerDocument:D,enableHWA:Y}),Ie=a.filterFactory||new Ex({docId:e,ownerDocument:D}),ai=null;gw(u);const Yt={canvasFactory:It,filterFactory:Ie};if(V||(Yt.cMapReaderFactory=new m({baseUrl:f,isCompressed:p}),Yt.standardFontDataFactory=new v({baseUrl:_})),!d){const ls={verbosity:u,port:_i.workerPort};d=ls.port?To.fromPort(ls):new To(ls),t._worker=d}const Tt={docId:e,apiVersion:"4.5.136",data:i,password:o,disableAutoFetch:I,rangeChunkSize:l,length:J,docBaseUrl:g,enableXfa:R,evaluatorOptions:{maxImageSize:S,disableFontFace:P,ignoreErrors:x,isEvalSupported:T,isOffscreenCanvasSupported:E,canvasMaxAreaInBytes:M,fontExtraProperties:O,useSystemFonts:W,cMapUrl:V?f:null,standardFontDataUrl:V?_:null}},Qe={disableFontFace:P,fontExtraProperties:O,ownerDocument:D,pdfBug:X,styleElement:ai,loadingParams:{disableAutoFetch:I,enableXfa:R}};return d.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const ls=d.messageHandler.sendWithPromise("GetDocRequest",Tt,i?[i.buffer]:null);let pe;if(h)pe=new ix(h,{disableRange:L,disableStream:F});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");pe=(Ps=>he?function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype}()&&Ka(Ps.url)?new j0(Ps):new px(Ps):Ka(Ps.url)?new j0(Ps):new dx(Ps))({url:s,length:J,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:L,disableStream:F})}return ls.then(wt=>{if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const Ps=new eh(e,wt,d.port),xa=new Rx(Ps,t,pe,Qe,Yt);t._transport=xa,Ps.send("Ready",null)})}).catch(t._capability.reject),t}function Dx(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(he&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Ox(a){if(he&&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 od(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 W0(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 Nd=class Nd{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Je(Nd,jd)._++}`,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)}};jd=new WeakMap,w(Nd,jd,0);let Xg=Nd;class X0{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){ft("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Px{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return at(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 Lx{constructor(t,e,s,i=!1){w(this,rs);w(this,xn,null);w(this,Ri,!1);this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new m0:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new z0,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 $a({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 at(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=an.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:d=null,isEditing:u=!1}){var T,E;(T=this._stats)==null||T.time("Overall");const g=this._transport.getRenderingIntent(s,i,d,u),{renderingIntent:f,cacheKey:p}=g;b(this,Ri,!1),y(this,rs,Jd).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&Be.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=M=>{var P;m.renderTasks.delete(x),(this._maybeCleanupAfterRender||_)&&b(this,Ri,!0),y(this,rs,Ea).call(this,!_),M?(x.capability.reject(M),this._abortOperatorList({intentState:m,reason:M instanceof Error?M:new Error(M)})):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 zg({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(([M,P])=>{var O;if(this.destroyed){v();return}if((O=this._stats)==null||O.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:M,optionalContentConfig:P}),x.operatorListChanged()}).catch(v),S}getOperatorList({intent:t="display",annotationMode:e=an.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=>ih.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,Ri,!1),y(this,rs,Jd).call(this),Promise.all(t)}cleanup(t=!1){b(this,Ri,!0);const e=y(this,rs,Ea).call(this,!1);return t&&e&&this._stats&&(this._stats=new m0),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,rs,Ea).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,rs,Ea).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 Tg){let i=Sx;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 Jn(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}}xn=new WeakMap,Ri=new WeakMap,rs=new WeakSet,Ea=function(t=!1){if(y(this,rs,Jd).call(this),!c(this,Ri)||this.destroyed)return!1;if(t)return b(this,xn,setTimeout(()=>{b(this,xn,null),y(this,rs,Ea).call(this,!1)},Cx)),!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,Ri,!1),!0},Jd=function(){c(this,xn)&&(clearTimeout(c(this,xn)),b(this,xn,null))};class Fx{constructor(){w(this,Mr,new Set);w(this,Bd,Promise.resolve())}postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};c(this,Bd).then(()=>{for(const i of c(this,Mr))i.call(this,s)})}addEventListener(t,e){c(this,Mr).add(e)}removeEventListener(t,e){c(this,Mr).delete(e)}terminate(){c(this,Mr).clear()}}Mr=new WeakMap,Bd=new WeakMap;const wi={isWorkerDisabled:!1,fakeWorkerId:0};he&&(wi.isWorkerDisabled=!0,_i.workerSrc||(_i.workerSrc="./pdf.worker.mjs")),wi.isSameOrigin=function(a,t){let e;try{if(e=new URL(a),!e.origin||e.origin==="null")return!1}catch{return!1}const s=new URL(t,e);return e.origin===s.origin},wi.createCDNWrapper=function(a){const t=`await import("${a}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))};const Ve=class Ve{constructor({name:t=null,port:e=null,verbosity:s=fw()}={}){w(this,$o);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(Ve,Dr))!=null&&i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(c(Ve,Dr)||b(Ve,Dr,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return he?Promise.all([Xs.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 eh("main","worker",t),this._messageHandler.on("ready",function(){}),y(this,$o,Zd).call(this)}_initialize(){if(wi.isWorkerDisabled||c(Ve,Ko,tu)){this._setupFakeWorker();return}let{workerSrc:t}=Ve;try{wi.isSameOrigin(window.location.href,t)||(t=wi.createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new eh("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,$o,Zd).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{nd("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){wi.isWorkerDisabled||(Z("Setting up fake worker."),wi.isWorkerDisabled=!0),Ve._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Fx;this._port=e;const s=`fake${wi.fakeWorkerId++}`,i=new eh(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new eh(s,s+"_worker",e),y(this,$o,Zd).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(Ve,Dr))==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,Dr))==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 Ve(t)}static get workerSrc(){if(_i.workerSrc)return _i.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return at(this,"_setupFakeWorkerGlobal",(async()=>c(this,Ko,tu)?c(this,Ko,tu):(await import(this.workerSrc)).WorkerMessageHandler)())}};Dr=new WeakMap,$o=new WeakSet,Zd=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Ko=new WeakSet,tu=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},w(Ve,Ko),w(Ve,Dr);let To=Ve;class Rx{constructor(t,e,s,i,n){w(this,Or);w(this,Ii,new Map);w(this,Qs,new Map);w(this,Qo,new Map);w(this,Jo,new Map);w(this,Js,null);this.messageHandler=t,this.loadingTask=e,this.commonObjs=new z0,this.fontLoader=new Rw({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 at(this,"annotationStorage",new Lg)}getRenderingIntent(t,e=an.ENABLE,s=null,i=!1,n=!1){let r=Be.DISPLAY,o=Pg;switch(t){case"any":r=Be.ANY;break;case"display":break;case"print":r=Be.PRINT;break;default:Z(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Be.PRINT&&s instanceof w0?s:this.annotationStorage;switch(e){case an.DISABLE:r+=Be.ANNOTATIONS_DISABLE;break;case an.ENABLE:break;case an.ENABLE_FORMS:r+=Be.ANNOTATIONS_FORMS;break;case an.ENABLE_STORAGE:r+=Be.ANNOTATIONS_STORAGE,o=h.serializable;break;default:Z(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Be.IS_EDITING),n&&(r+=Be.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,Js))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const i of c(this,Qs).values())t.push(i._destroy());c(this,Qs).clear(),c(this,Qo).clear(),c(this,Jo).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,Ii).clear(),this.filterFactory.destroy(),sh.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new Jn("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)=>{Xt(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}Xt(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)=>{Xt(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}Xt(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 Px(s,this))}),t.on("DocException",function(s){let i;switch(s.name){case"PasswordException":i=new yg(s.message,s.code);break;case"InvalidPDFException":i=new c0(s.message);break;case"MissingPDFException":i=new Qn(s.message);break;case"UnexpectedResponseException":i=new rd(s.message,s.status);break;case"UnknownErrorException":i=new _g(s.message,s.details);break;default:ft("DocException - expected a valid Error.")}e._capability.reject(i)}),t.on("PasswordRequest",s=>{if(b(this,Js,Promise.withResolvers()),e.onPassword){const i=n=>{n instanceof Error?c(this,Js).reject(n):c(this,Js).resolve({password:n})};try{e.onPassword(i,s.code)}catch(n){c(this,Js).reject(n)}}else c(this,Js).reject(new yg(s.message,s.code));return c(this,Js).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,Qs).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;Z(`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 Iw(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;Xt(g,"The imageRef must be defined.");for(const f of c(this,Qs).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,Qs).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)>lw&&(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&&Z("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,Qo).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,Jo).set(n.refStr,t);const r=new Lx(e,n,this,this._params.pdfBug);return c(this,Qs).set(e,r),r});return c(this,Qo).set(e,i),i}getPageIndex(t){return W0(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,Or,Ul).call(this,"GetFieldObjects")}hasJSActions(){return y(this,Or,Ul).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,Or,Ul).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,Or,Ul).call(this,"GetOptionalContentConfig").then(e=>new sx(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=c(this,Ii).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 tx(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,Ii).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,Qs).values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),c(this,Ii).clear(),this.filterFactory.destroy(!0),sh.cleanup()}}cachedPageNumber(t){if(!W0(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return c(this,Jo).get(e)??null}}Ii=new WeakMap,Qs=new WeakMap,Qo=new WeakMap,Jo=new WeakMap,Js=new WeakMap,Or=new WeakSet,Ul=function(t,e=null){const s=c(this,Ii).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return c(this,Ii).set(t,i),i};const _d=Symbol("INITIAL_DATA");class z0{constructor(){w(this,Kh);w(this,Ss,Object.create(null))}get(t,e=null){if(e){const i=y(this,Kh,kf).call(this,t);return i.promise.then(()=>e(i.data)),null}const s=c(this,Ss)[t];if(!s||s.data===_d)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=c(this,Ss)[t];return!!e&&e.data!==_d}resolve(t,e=null){const s=y(this,Kh,kf).call(this,t);s.data=e,s.resolve()}clear(){var t;for(const e in c(this,Ss)){const{data:s}=c(this,Ss)[e];(t=s==null?void 0:s.bitmap)==null||t.close()}b(this,Ss,Object.create(null))}*[Symbol.iterator](){for(const t in c(this,Ss)){const{data:e}=c(this,Ss)[t];e!==_d&&(yield[t,e])}}}Ss=new WeakMap,Kh=new WeakSet,kf=function(t){var e;return(e=c(this,Ss))[t]||(e[t]={...Promise.withResolvers(),data:_d})};class Ix{constructor(t){w(this,Sn,null);b(this,Sn,t),this.onContinue=null}get promise(){return c(this,Sn).capability.promise}cancel(t=0){c(this,Sn).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=c(this,Sn).operatorList;if(!t)return!1;const{annotationCanvasMap:e}=c(this,Sn);return t.form||t.canvas&&(e==null?void 0:e.size)>0}}Sn=new WeakMap;const Lr=class Lr{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,Cn,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 Ix(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(Lr,Pr).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(Lr,Pr).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 Ao(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,Cn)&&(window.cancelAnimationFrame(c(this,Cn)),b(this,Cn,null)),c(Lr,Pr).delete(this._canvas),this.callback(t||new Tg(`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,Cn,window.requestAnimationFrame(()=>{b(this,Cn,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(Lr,Pr).delete(this._canvas),this.callback())))}};Cn=new WeakMap,Pr=new WeakMap,w(Lr,Pr,new WeakSet);let zg=Lr;const jx="4.5.136",Nx="3a21f03b0";function V0(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function nh(a){return Math.max(0,Math.min(255,255*a))}class G0{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=nh(t),[t,t,t]}static G_HTML([t]){const e=V0(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(nh)}static RGB_HTML(t){return`#${t.map(V0).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[nh(1-Math.min(1,t+i)),nh(1-Math.min(1,s+i)),nh(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 U0{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&&ih.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&&ih.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 rh=1e3,Bx=9,er=new WeakSet;function xi(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class Hx{static create(t){switch(t.data.annotationType){case Wt.LINK:return new Y0(t);case Wt.TEXT:return new Wx(t);case Wt.WIDGET:switch(t.data.fieldType){case"Tx":return new Xx(t);case"Btn":return t.data.radioButton?new q0(t):t.data.checkBox?new Vx(t):new Gx(t);case"Ch":return new Ux(t);case"Sig":return new zx(t)}return new sr(t);case Wt.POPUP:return new Vg(t);case Wt.FREETEXT:return new $0(t);case Wt.LINE:return new qx(t);case Wt.SQUARE:return new $x(t);case Wt.CIRCLE:return new Kx(t);case Wt.POLYLINE:return new K0(t);case Wt.CARET:return new Jx(t);case Wt.INK:return new Q0(t);case Wt.POLYGON:return new Qx(t);case Wt.HIGHLIGHT:return new Zx(t);case Wt.UNDERLINE:return new tS(t);case Wt.SQUIGGLY:return new eS(t);case Wt.STRIKEOUT:return new sS(t);case Wt.STAMP:return new J0(t);case Wt.FILEATTACHMENT:return new iS(t);default:return new Ft(t)}}}const ef=class ef{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){w(this,Qh);w(this,Fr,null);w(this,Zo,!1);w(this,ta,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 ef._hasPopupData(this.data)}updateEdited(t){var s;if(!this.container)return;c(this,Fr)||b(this,Fr,{rect:this.data.rect.slice(0)});const{rect:e}=t;e&&y(this,Qh,Mf).call(this,e),(s=c(this,ta))==null||s.popup.updateEdited(t)}resetEdited(){var t;c(this,Fr)&&(y(this,Qh,Mf).call(this,c(this,Fr).rect),(t=c(this,ta))==null||t.popup.resetEdited(),b(this,Fr,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 sr||(n.tabIndex=rh);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 Vg){const{rotation:m}=e;return!e.hasOwnCanvas&&m!==0&&this.setRotation(m,n),n}const{width:o,height:h}=xi(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 q0){const x=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=x}switch(e.borderStyle.style){case qa.SOLID:r.borderStyle="solid";break;case qa.DASHED:r.borderStyle="dashed";break;case qa.BEVELED:Z("Unimplemented border style: beveled");break;case qa.INSET:Z("Unimplemented border style: inset");break;case qa.UNDERLINE:r.borderBottomStyle="solid";break}const v=e.borderColor||null;v?(b(this,Zo,!0),r.borderColor=z.makeHexColor(v[0]|0,v[1]|0,v[2]|0)):r.borderWidth=0}const l=z.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}=xi(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]=G0[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:G0[`${r}_rgb`](o)})};return at(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,Zo)){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],T=t[m+3],E=d.createElement("rect"),M=(S-e)/h,P=(n-x)/l,O=(v-S)/h,R=(x-T)/l;E.setAttribute("x",M),E.setAttribute("y",P),E.setAttribute("width",O),E.setAttribute("height",R),f.append(E),o==null||o.push(`<rect vector-effect="non-scaling-stroke" x="${M}" y="${P}" width="${O}" height="${R}"/>`)}c(this,Zo)&&(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,ta,new Vg({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(){ft("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&&!er.has(l)){Z(`_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&&er.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})})}};Fr=new WeakMap,Zo=new WeakMap,ta=new WeakMap,Qh=new WeakSet,Mf=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}=xi(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 Ft=ef;class Y0 extends Ft{constructor(e,s=null){super(e,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});w(this,Ge);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,Ge,jv).call(this,i,e.attachment,e.attachmentDest),n=!0):e.setOCGState?(y(this,Ge,Nv).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,Ge,ro).call(this)}_bindNamedAction(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(s),!1),y(this,Ge,ro).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,Ge,ro).call(this)}_bindResetFormAction(e,s){const i=e.onclick;if(i||(e.href=this.linkService.getAnchorUrl("")),y(this,Ge,ro).call(this),!this._fieldObjects){Z('_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(!er.has(p)){Z(`_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}}}Ge=new WeakSet,ro=function(){this.container.setAttribute("data-internal-link","")},jv=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,Ge,ro).call(this)},Nv=function(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(s),!1),y(this,Ge,ro).call(this)};class Wx extends Ft{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 sr extends Ft{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 De.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":z.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Bx,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/(vg*i))||1,u=l/d;r=Math.min(i,h(u/vg))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/vg))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=z.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 Xx extends sr{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),er.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=rh,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,T=x;switch(f.inputType){case"deleteWordBackward":{const M=_.substring(0,v).match(/\w*[^\w]*$/);M&&(S-=M[0].length);break}case"deleteWordForward":{const M=_.substring(v).match(/^[^\w]*\w*/);M&&(T+=M[0].length);break}case"deleteContentBackward":v===x&&(S-=1);break;case"deleteContentForward":v===x&&(T+=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:T}})}),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 zx extends sr{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Vx extends sr{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 er.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=rh,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 q0 extends sr{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(er.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=rh,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 Gx extends Y0{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 Ux extends sr{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");er.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=rh;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 Vg extends Ft{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Ft._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Yx({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=>`${g0}${s}`).join(",")),this.container}}class Yx{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,mt);w(this,ea,y(this,mt,Wv).bind(this));w(this,Hd,y(this,mt,Of).bind(this));w(this,Wd,y(this,mt,iu).bind(this));w(this,sa,y(this,mt,su).bind(this));w(this,Rr,null);w(this,Mt,null);w(this,ji,null);w(this,Ir,null);w(this,Jh,null);w(this,Zh,null);w(this,ia,null);w(this,Ni,!1);w(this,Cs,null);w(this,Bi,null);w(this,tl,null);w(this,Hi,null);w(this,el,null);w(this,jr,null);w(this,Nr,!1);var g;b(this,Mt,t),b(this,el,i),b(this,ji,r),b(this,Hi,o),b(this,Zh,h),b(this,Rr,e),b(this,tl,l),b(this,ia,d),b(this,Jh,s),b(this,Ir,b0.toDateObject(n)),this.trigger=s.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",c(this,sa)),f.addEventListener("mouseenter",c(this,Wd)),f.addEventListener("mouseleave",c(this,Hd)),f.classList.add("popupTriggerArea");for(const f of s)(g=f.container)==null||g.addEventListener("keydown",c(this,ea));c(this,Mt).hidden=!0,u&&y(this,mt,su).call(this)}render(){if(c(this,Cs))return;const t=b(this,Cs,document.createElement("div"));if(t.className="popup",c(this,Rr)){const n=t.style.outlineColor=z.makeHexColor(...c(this,Rr));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=z.makeHexColor(...c(this,Rr).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,el),t.append(e),c(this,Ir)){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),n.setAttribute("data-l10n-args",JSON.stringify({date:c(this,Ir).toLocaleDateString(),time:c(this,Ir).toLocaleTimeString()})),e.append(n)}const i=c(this,mt,eu);if(i)U0.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(c(this,ji));t.append(n)}c(this,Mt).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,jr)||b(this,jr,{contentsObj:c(this,ji),richText:c(this,Hi)}),t&&b(this,Bi,null),e&&(b(this,Hi,y(this,mt,Hv).call(this,e)),b(this,ji,null)),(s=c(this,Cs))==null||s.remove(),b(this,Cs,null)}resetEdited(){var t;c(this,jr)&&({contentsObj:Je(this,ji)._,richText:Je(this,Hi)._}=c(this,jr),b(this,jr,null),(t=c(this,Cs))==null||t.remove(),b(this,Cs,null),b(this,Bi,null))}forceHide(){b(this,Nr,this.isVisible),c(this,Nr)&&(c(this,Mt).hidden=!0)}maybeShow(){c(this,Nr)&&(c(this,Cs)||y(this,mt,iu).call(this),b(this,Nr,!1),c(this,Mt).hidden=!1)}get isVisible(){return c(this,Mt).hidden===!1}}ea=new WeakMap,Hd=new WeakMap,Wd=new WeakMap,sa=new WeakMap,Rr=new WeakMap,Mt=new WeakMap,ji=new WeakMap,Ir=new WeakMap,Jh=new WeakMap,Zh=new WeakMap,ia=new WeakMap,Ni=new WeakMap,Cs=new WeakMap,Bi=new WeakMap,tl=new WeakMap,Hi=new WeakMap,el=new WeakMap,jr=new WeakMap,Nr=new WeakMap,mt=new WeakSet,eu=function(){const t=c(this,Hi),e=c(this,ji);return t!=null&&t.str&&(!(e!=null&&e.str)||e.str===t.str)&&c(this,Hi).html||null},Df=function(){var t,e,s;return((s=(e=(t=c(this,mt,eu))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.fontSize)||0},Bv=function(){var t,e,s;return((s=(e=(t=c(this,mt,eu))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.color)||null},Hv=function(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:c(this,mt,Bv),fontSize:c(this,mt,Df)?`calc(${c(this,mt,Df)}px * var(--scale-factor))`:""}};for(const n of t.split(`
501
+ `))e.push({name:"span",value:n,attributes:i});return s},Wv=function(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&c(this,Ni))&&y(this,mt,su).call(this)},Xv=function(){if(c(this,Bi)!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=c(this,Zh);let r=!!c(this,ia),o=r?c(this,ia):c(this,tl);for(const p of c(this,Jh))if(!o||z.intersect(p.data.rect,o)!==null){o=p.data.rect,r=!0;break}const h=z.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,Bi,[100*(u-i)/e,100*(g-n)/s]);const{style:f}=c(this,Mt);f.left=`${c(this,Bi)[0]}%`,f.top=`${c(this,Bi)[1]}%`},su=function(){b(this,Ni,!c(this,Ni)),c(this,Ni)?(y(this,mt,iu).call(this),c(this,Mt).addEventListener("click",c(this,sa)),c(this,Mt).addEventListener("keydown",c(this,ea))):(y(this,mt,Of).call(this),c(this,Mt).removeEventListener("click",c(this,sa)),c(this,Mt).removeEventListener("keydown",c(this,ea)))},iu=function(){c(this,Cs)||this.render(),this.isVisible?c(this,Ni)&&c(this,Mt).classList.add("focused"):(y(this,mt,Xv).call(this),c(this,Mt).hidden=!1,c(this,Mt).style.zIndex=parseInt(c(this,Mt).style.zIndex)+1e3)},Of=function(){c(this,Mt).classList.remove("focused"),!(c(this,Ni)||!this.isVisible)&&(c(this,Mt).hidden=!0,c(this,Mt).style.zIndex=parseInt(c(this,Mt).style.zIndex)-1e3)};class $0 extends Ft{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=nt.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 qx extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,sl,null)}render(){this.container.classList.add("lineAnnotation");const e=this.data,{width:s,height:i}=xi(e.rect),n=this.svgFactory.create(s,i,!0),r=b(this,sl,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,sl)}addHighlightArea(){this.container.classList.add("highlightArea")}}sl=new WeakMap;class $x extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,il,null)}render(){this.container.classList.add("squareAnnotation");const e=this.data,{width:s,height:i}=xi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,il,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,il)}addHighlightArea(){this.container.classList.add("highlightArea")}}il=new WeakMap;class Kx extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,nl,null)}render(){this.container.classList.add("circleAnnotation");const e=this.data,{width:s,height:i}=xi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,nl,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,nl)}addHighlightArea(){this.container.classList.add("highlightArea")}}nl=new WeakMap;class K0 extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,rl,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}=xi(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,rl,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,rl)}addHighlightArea(){this.container.classList.add("highlightArea")}}rl=new WeakMap;class Qx extends K0{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Jx extends Ft{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 Q0 extends Ft{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,ol,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=nt.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{width:r,height:o}=xi(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,ol).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.container}getElementsToTriggerPopup(){return c(this,ol)}addHighlightArea(){this.container.classList.add("highlightArea")}}ol=new WeakMap;class Zx extends Ft{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class tS extends Ft{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 eS extends Ft{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 sS extends Ft{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 J0 extends Ft{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class iS extends Ft{constructor(e){var i;super(e,{isRenderable:!0});w(this,hl);w(this,al,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,hl,Pf).bind(this)),b(this,al,i);const{isMac:n}=De.platform;return e.addEventListener("keydown",r=>{r.key==="Enter"&&(n?r.metaKey:r.ctrlKey)&&y(this,hl,Pf).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),e.append(i),e}getElementsToTriggerPopup(){return c(this,al)}addHighlightArea(){this.container.classList.add("highlightArea")}}al=new WeakMap,hl=new WeakSet,Pf=function(){var e;(e=this.downloadManager)==null||e.openOrDownloadData(this.content,this.filename)};class nS{constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r}){w(this,Wr);w(this,ll,null);w(this,Br,null);w(this,Hr,new Map);this.div=t,b(this,ll,e),b(this,Br,s),this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return c(this,Hr).size>0}async render(t){var r;const{annotations:e}=t,s=this.div;Zn(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 Ag,annotationStorage:t.annotationStorage||new Lg,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===Wt.POPUP;if(h){const u=i.get(o.id);if(!u)continue;n.elements=u}else{const{width:u,height:g}=xi(o.rect);if(u<=0||g<=0)continue}n.data=o;const l=Hx.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"),y(this,Wr,zv).call(this,d,o.id),l._isEditable&&(c(this,Hr).set(l.data.id,l),(r=this._annotationEditorUIManager)==null||r.renderAnnotationElement(l))}y(this,Wr,Lf).call(this)}update({viewport:t}){const e=this.div;this.viewport=t,Zn(e,{rotation:t.rotation}),y(this,Wr,Lf).call(this),e.hidden=!1}getEditableAnnotations(){return Array.from(c(this,Hr).values())}getEditableAnnotation(t){return c(this,Hr).get(t)}}ll=new WeakMap,Br=new WeakMap,Hr=new WeakMap,Wr=new WeakSet,zv=function(t,e){var i;const s=t.firstChild||t;s.id=`${g0}${e}`,this.div.append(t),(i=c(this,ll))==null||i.moveElementInDOM(this.div,t,s,!1)},Lf=function(){if(!c(this,Br))return;const t=this.div;for(const[e,s]of c(this,Br)){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,Br).clear()};const wd=/\r\n?|\n/g,_t=class _t extends dt{constructor(e){super({...e,name:"freeTextEditor"});w(this,Bt);w(this,cl,this.editorDivBlur.bind(this));w(this,dl,this.editorDivFocus.bind(this));w(this,ul,this.editorDivInput.bind(this));w(this,gl,this.editorDivKeydown.bind(this));w(this,fl,this.editorDivPaste.bind(this));w(this,As);w(this,Ue,"");w(this,pl,`${this.id}-editor`);w(this,Ye);w(this,na,null);b(this,As,e.color||_t._defaultColor||dt._defaultLineColor),b(this,Ye,e.fontSize||_t._defaultFontSize)}static get _keyboardManager(){const e=_t.prototype,s=r=>r.isEmpty(),i=tr.TRANSLATE_SMALL,n=tr.TRANSLATE_BIG;return at(this,"_keyboardManager",new Qa([[["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){dt.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 q.FREETEXT_SIZE:_t._defaultFontSize=s;break;case q.FREETEXT_COLOR:_t._defaultColor=s;break}}updateParams(e,s){switch(e){case q.FREETEXT_SIZE:y(this,Bt,Vv).call(this,s);break;case q.FREETEXT_COLOR:y(this,Bt,Gv).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[q.FREETEXT_SIZE,_t._defaultFontSize],[q.FREETEXT_COLOR,_t._defaultColor||dt._defaultLineColor]]}get propertiesToUpdate(){return[[q.FREETEXT_SIZE,c(this,Ye)],[q.FREETEXT_COLOR,c(this,As)]]}_translateEmpty(e,s){this._uiManager.translateSelectedEditors(e,s,!0)}getInitialTranslation(){const e=this.parentScale;return[-_t._internalPadding*e,-(_t._internalPadding+c(this,Ye))*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(nt.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant");const e=this._uiManager._signal;this.editorDiv.addEventListener("keydown",c(this,gl),{signal:e}),this.editorDiv.addEventListener("focus",c(this,dl),{signal:e}),this.editorDiv.addEventListener("blur",c(this,cl),{signal:e}),this.editorDiv.addEventListener("input",c(this,ul),{signal:e}),this.editorDiv.addEventListener("paste",c(this,fl),{signal:e})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",c(this,pl)),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",c(this,gl)),this.editorDiv.removeEventListener("focus",c(this,dl)),this.editorDiv.removeEventListener("blur",c(this,cl)),this.editorDiv.removeEventListener("input",c(this,ul)),this.editorDiv.removeEventListener("paste",c(this,fl)),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,Ue),s=b(this,Ue,y(this,Bt,Uv).call(this).trimEnd());if(e===s)return;const i=n=>{if(b(this,Ue,n),!n){this.remove();return}y(this,Bt,ou).call(this),this._uiManager.rebuild(this),y(this,Bt,nu).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(e)},mustExec:!1}),y(this,Bt,nu).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){_t._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,pl)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),dt._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,Ye)}px * var(--scale-factor))`,i.color=c(this,As),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),gd(this,this.div,["dblclick","keydown"]),this.width){const[n,r]=this.parentDimensions;if(this.annotationElementId){const{position:o}=c(this,na);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,Bt,ou).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=_t,Wi,Ff).call(p,s.getData("text")||"").replaceAll(wd,`
502
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(wd,"")),v!==this.editorDiv){let x=d;for(const S of this.editorDiv.childNodes){if(S===v){x=u;continue}x.push(y(m=_t,Hi,ou).call(m,S))}}d.push(h.nodeValue.slice(0,l).replaceAll(wd,""))}else if(h===this.editorDiv){let v=d,x=0;for(const S of this.editorDiv.childNodes)x++===l&&(v=u),v.push(y(_=_t,Hi,ou).call(_,S))}b(this,Ge,`${d.join(`
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(wd,"")),v!==this.editorDiv){let x=d;for(const S of this.editorDiv.childNodes){if(S===v){x=u;continue}x.push(y(m=_t,Wi,ru).call(m,S))}}d.push(h.nodeValue.slice(0,l).replaceAll(wd,""))}else if(h===this.editorDiv){let v=d,x=0;for(const S of this.editorDiv.childNodes)x++===l&&(v=u),v.push(y(_=_t,Wi,ru).call(_,S))}b(this,Ue,`${d.join(`
504
504
  `)}${n}${u.join(`
505
- `)}`),y(this,Nt,au).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 deserialize(e,s,i){var o;let n=null;if(e instanceof K0){const{data:{defaultAppearanceData:{fontSize:h,fontColor:l},rect:d,rotation:u,id:g},textContent:f,textPosition:p,parent:{page:{pageNumber:m}}}=e;if(!f||f.length===0)return null;n=e={annotationType:nt.FREETEXT,color:Array.from(l),fontSize:h,value:f.join(`
506
- `),position:p,pageIndex:m-1,rect:d.slice(0),rotation:u,id:g,deleted:!1}}const r=super.deserialize(e,s,i);return b(r,Ue,e.fontSize),b(r,As,z.makeHexColor(...e.color)),b(r,Ge,y(o=_t,Hi,Rf).call(o,e.value)),r.annotationElementId=e.id||null,b(r,na,n),r}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};const s=_t._internalPadding*this.parentScale,i=this.getRect(s,s),n=dt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:c(this,As)),r={annotationType:nt.FREETEXT,color:n,fontSize:c(this,Ue),value:y(this,Nt,Yv).call(this),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?r:this.annotationElementId&&!y(this,Nt,qv).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,Ue)}px * var(--scale-factor))`,i.color=c(this,As),s.replaceChildren();for(const r of c(this,Ge).split(`
507
- `)){const o=document.createElement("div");o.append(r?document.createTextNode(r):document.createElement("br")),s.append(o)}const n=_t._internalPadding*this.parentScale;return e.updateEdited({rect:this.getRect(n,n),popupContent:c(this,Ge)}),s}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}};cl=new WeakMap,dl=new WeakMap,ul=new WeakMap,gl=new WeakMap,fl=new WeakMap,As=new WeakMap,Ge=new WeakMap,pl=new WeakMap,Ue=new WeakMap,na=new WeakMap,Nt=new WeakSet,Vv=function(e){const s=n=>{this.editorDiv.style.fontSize=`calc(${n}px * var(--scale-factor))`,this.translate(0,-(n-c(this,Ue))*this.parentScale),b(this,Ue,n),y(this,Nt,ru).call(this)},i=c(this,Ue);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Gv=function(e){const s=n=>{b(this,As,this.editorDiv.style.color=n)},i=c(this,As);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Uv=function(){var s;const e=[];this.editorDiv.normalize();for(const i of this.editorDiv.childNodes)e.push(y(s=_t,Hi,ou).call(s,i));return e.join(`
508
- `)},ru=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()},Hi=new WeakSet,ou=function(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(wd,"")},au=function(){if(this.editorDiv.replaceChildren(),!!c(this,Ge))for(const e of c(this,Ge).split(`
509
- `)){const s=document.createElement("div");s.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(s)}},Yv=function(){return c(this,Ge).replaceAll(" "," ")},Rf=function(e){return e.replaceAll(" "," ")},qv=function(e){const{value:s,fontSize:i,color:n,pageIndex:r}=c(this,na);return this._hasBeenMoved||e.value!==s||e.fontSize!==i||e.color.some((o,h)=>o!==n[h])||e.pageIndex!==r},w(_t,Hi),K(_t,"_freeTextDefaultContent",""),K(_t,"_internalPadding",0),K(_t,"_defaultColor",null),K(_t,"_defaultFontSize",10),K(_t,"_type","freetext"),K(_t,"_editorType",nt.FREETEXT);let Ug=_t;class tv{constructor(t,e=0,s=0,i=!0){w(this,Ae);w(this,ml);w(this,An,[]);w(this,Ts,[]);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:T}of t){const E=Math.floor((v-e)/d)*d,M=Math.ceil((v+S+e)/d)*d,P=Math.floor((x-e)/d)*d,O=Math.ceil((x+T+e)/d)*d,R=[E,P,O,!0],D=[M,P,O,!1];c(this,An).push(R,D),n=Math.min(n,E),r=Math.max(r,M),o=Math.min(o,P),h=Math.max(h,O)}const u=r-n+2*s,g=h-o+2*s,f=n-s,p=o-s,m=c(this,An).at(i?-1:-2),_=[m[0],m[2]];for(const v of c(this,An)){const[x,S,T]=v;v[0]=(x-f)/u,v[1]=(S-p)/g,v[2]=(T-p)/g}b(this,ml,{x:f,y:p,width:u,height:g,lastPoint:_})}getOutlines(){c(this,An).sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of c(this,An))e[3]?(t.push(...y(this,Ae,If).call(this,e)),y(this,Ae,Kv).call(this,e)):(y(this,Ae,Qv).call(this,e),t.push(...y(this,Ae,If).call(this,e)));return y(this,Ae,$v).call(this,t)}}ml=new WeakMap,An=new WeakMap,Ts=new WeakMap,Ae=new WeakSet,$v=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 rS(i,c(this,ml))},hu=function(t){const e=c(this,Ts);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},Kv=function([,t,e]){const s=y(this,Ae,hu).call(this,t);c(this,Ts).splice(s,0,[t,e])},Qv=function([,t,e]){const s=y(this,Ae,hu).call(this,t);for(let i=s;i<c(this,Ts).length;i++){const[n,r]=c(this,Ts)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ts).splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=c(this,Ts)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ts).splice(i,1);return}}},If=function(t){const[e,s,i]=t,n=[[e,s,i]],r=y(this,Ae,hu).call(this,i);for(let o=0;o<r;o++){const[h,l]=c(this,Ts)[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 ev{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 Yg}}class rS extends ev{constructor(e,s){super();w(this,vl);w(this,ra);b(this,ra,e),b(this,vl,s)}toSVGPath(){const e=[];for(const s of c(this,ra)){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,ra)){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,vl)}}vl=new WeakMap,ra=new WeakMap;const Xi=class Xi{constructor({x:t,y:e},s,i,n,r,o=0){w(this,wl);w(this,Zs);w(this,Wi,[]);w(this,oa);w(this,aa);w(this,ti,[]);w(this,rt,new Float64Array(18));w(this,Xr);w(this,zr);w(this,bl);w(this,yl);w(this,ha);w(this,la);w(this,Tn,[]);b(this,Zs,s),b(this,la,n*i),b(this,aa,r),c(this,rt).set([NaN,NaN,NaN,NaN,t,e],6),b(this,oa,o),b(this,yl,c(Xi,_l)*i),b(this,bl,c(Xi,Vd)*i),b(this,ha,i),c(this,Tn).push(t,e)}get free(){return!0}isEmpty(){return isNaN(c(this,rt)[8])}add({x:t,y:e}){var R;b(this,Xr,t),b(this,zr,e);const[s,i,n,r]=c(this,Zs);let[o,h,l,d]=c(this,rt).subarray(8,12);const u=t-l,g=e-d,f=Math.hypot(u,g);if(f<c(this,bl))return!1;const p=f-c(this,yl),m=p/f,_=m*u,v=m*g;let x=o,S=h;o=l,h=d,l+=_,d+=v,(R=c(this,Tn))==null||R.push(t,e);const T=-v/p,E=_/p,M=T*c(this,la),P=E*c(this,la);return c(this,rt).set(c(this,rt).subarray(2,8),0),c(this,rt).set([l+M,d+P],4),c(this,rt).set(c(this,rt).subarray(14,18),12),c(this,rt).set([l-M,d-P],16),isNaN(c(this,rt)[6])?(c(this,ti).length===0&&(c(this,rt).set([o+M,h+P],2),c(this,ti).push(NaN,NaN,NaN,NaN,(o+M-s)/n,(h+P-i)/r),c(this,rt).set([o-M,h-P],14),c(this,Wi).push(NaN,NaN,NaN,NaN,(o-M-s)/n,(h-P-i)/r)),c(this,rt).set([x,S,o,h,l,d],6),!this.isEmpty()):(c(this,rt).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,rt).subarray(2,6),c(this,ti).push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+d)/2-i)/r),[o,h,x,S]=c(this,rt).subarray(14,18),c(this,Wi).push(NaN,NaN,NaN,NaN,((x+o)/2-s)/n,((S+h)/2-i)/r),!0):([x,S,o,h,l,d]=c(this,rt).subarray(0,6),c(this,ti).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,rt).subarray(12,18),c(this,Wi).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,ti),e=c(this,Wi),s=c(this,rt).subarray(4,6),i=c(this,rt).subarray(16,18),[n,r,o,h]=c(this,Zs),[l,d,u,g]=y(this,wl,jf).call(this);if(isNaN(c(this,rt)[6])&&!this.isEmpty())return`M${(c(this,rt)[2]-n)/o} ${(c(this,rt)[3]-r)/h} L${(c(this,rt)[4]-n)/o} ${(c(this,rt)[5]-r)/h} L${l} ${d} L${u} ${g} L${(c(this,rt)[16]-n)/o} ${(c(this,rt)[17]-r)/h} L${(c(this,rt)[14]-n)/o} ${(c(this,rt)[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,ti),e=c(this,Wi),s=c(this,rt),i=s.subarray(4,6),n=s.subarray(16,18),[r,o,h,l]=c(this,Zs),d=new Float64Array((((v=c(this,Tn))==null?void 0:v.length)??0)+2);for(let x=0,S=d.length-2;x<S;x+=2)d[x]=(c(this,Tn)[x]-r)/h,d[x+1]=(c(this,Tn)[x+1]-o)/l;d[d.length-2]=(c(this,Xr)-r)/h,d[d.length-1]=(c(this,zr)-o)/l;const[u,g,f,p]=y(this,wl,jf).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 Yg(x,d,c(this,Zs),c(this,ha),c(this,oa),c(this,aa))}const m=new Float64Array(c(this,ti).length+24+c(this,Wi).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 Yg(m,d,c(this,Zs),c(this,ha),c(this,oa),c(this,aa))}};Zs=new WeakMap,Wi=new WeakMap,oa=new WeakMap,aa=new WeakMap,ti=new WeakMap,rt=new WeakMap,Xr=new WeakMap,zr=new WeakMap,bl=new WeakMap,yl=new WeakMap,ha=new WeakMap,la=new WeakMap,Tn=new WeakMap,_l=new WeakMap,zd=new WeakMap,Vd=new WeakMap,wl=new WeakSet,jf=function(){const t=c(this,rt).subarray(4,6),e=c(this,rt).subarray(16,18),[s,i,n,r]=c(this,Zs);return[(c(this,Xr)+(t[0]-e[0])/2-s)/n,(c(this,zr)+(t[1]-e[1])/2-i)/r,(c(this,Xr)+(e[0]-t[0])/2-s)/n,(c(this,zr)+(e[1]-t[1])/2-i)/r]},w(Xi,_l,8),w(Xi,zd,2),w(Xi,Vd,c(Xi,_l)+c(Xi,zd));let xd=Xi;class Yg extends ev{constructor(e,s,i,n,r,o){super();w(this,Re);w(this,ca);w(this,Vr,null);w(this,zi);w(this,xl);w(this,Ye);w(this,Sl);w(this,Rt);b(this,Rt,e),b(this,Ye,s),b(this,ca,i),b(this,Sl,n),b(this,zi,r),b(this,xl,o),y(this,Re,Jv).call(this,o);const{x:h,y:l,width:d,height:u}=c(this,Vr);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,Rt)[4]} ${c(this,Rt)[5]}`];for(let s=6,i=c(this,Rt).length;s<i;s+=6){if(isNaN(c(this,Rt)[s])){e.push(`L${c(this,Rt)[s+4]} ${c(this,Rt)[s+5]}`);continue}e.push(`C${c(this,Rt)[s]} ${c(this,Rt)[s+1]} ${c(this,Rt)[s+2]} ${c(this,Rt)[s+3]} ${c(this,Rt)[s+4]} ${c(this,Rt)[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,Re,Yl).call(this,c(this,Rt),e,n,o,-h),d=y(this,Re,Yl).call(this,c(this,Ye),e,n,o,-h);break;case 90:l=y(this,Re,ql).call(this,c(this,Rt),e,s,o,h),d=y(this,Re,ql).call(this,c(this,Ye),e,s,o,h);break;case 180:l=y(this,Re,Yl).call(this,c(this,Rt),i,s,-o,h),d=y(this,Re,Yl).call(this,c(this,Ye),i,s,-o,h);break;case 270:l=y(this,Re,ql).call(this,c(this,Rt),i,n,-o,-h),d=y(this,Re,ql).call(this,c(this,Ye),i,n,-o,-h);break}return{outline:Array.from(l),points:[Array.from(d)]}}get box(){return c(this,Vr)}getNewOutline(e,s){const{x:i,y:n,width:r,height:o}=c(this,Vr),[h,l,d,u]=c(this,ca),g=r*d,f=o*u,p=i*d+h,m=n*u+l,_=new xd({x:c(this,Ye)[0]*g+p,y:c(this,Ye)[1]*f+m},c(this,ca),c(this,Sl),e,c(this,xl),s??c(this,zi));for(let v=2;v<c(this,Ye).length;v+=2)_.add({x:c(this,Ye)[v]*g+p,y:c(this,Ye)[v+1]*f+m});return _.getOutlines()}}ca=new WeakMap,Vr=new WeakMap,zi=new WeakMap,xl=new WeakMap,Ye=new WeakMap,Sl=new WeakMap,Rt=new WeakMap,Re=new WeakSet,Yl=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},ql=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},Jv=function(e){const s=c(this,Rt);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=z.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,zi),p=o-c(this,zi),m=h-r+2*c(this,zi),_=l-o+2*c(this,zi);b(this,Vr,{x:f,y:p,width:m,height:_,lastPoint:[d,u]})};const Vi=class Vi{constructor({editor:t=null,uiManager:e=null}){w(this,yt);w(this,Cl,y(this,yt,Zv).bind(this));w(this,Al,y(this,yt,tb).bind(this));w(this,Es,null);w(this,Gr,null);w(this,da);w(this,zt,null);w(this,Tl,!1);w(this,ua,!1);w(this,El,null);w(this,kl);w(this,ks,null);w(this,ga);var s;t?(b(this,ua,!1),b(this,ga,q.HIGHLIGHT_COLOR),b(this,El,t)):(b(this,ua,!0),b(this,ga,q.HIGHLIGHT_DEFAULT_COLOR)),b(this,ks,(t==null?void 0:t._uiManager)||e),b(this,kl,c(this,ks)._eventBus),b(this,da,(t==null?void 0:t.color)||((s=c(this,ks))==null?void 0:s.highlightColors.values().next().value)||"#FFFF98")}static get _keyboardManager(){return at(this,"_keyboardManager",new Qa([[["Escape","mac+Escape"],Vi.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],Vi.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],Vi.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],Vi.prototype._moveToPrevious],[["Home","mac+Home"],Vi.prototype._moveToBeginning],[["End","mac+End"],Vi.prototype._moveToEnd]]))}renderButton(){const t=b(this,Es,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,ks)._signal;t.addEventListener("click",y(this,yt,oo).bind(this),{signal:e}),t.addEventListener("keydown",c(this,Cl),{signal:e});const s=b(this,Gr,document.createElement("span"));return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=c(this,da),t.append(s),t}renderMainDropdown(){const t=b(this,zt,y(this,yt,Nf).call(this));return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}_colorSelectFromKeyboard(t){if(t.target===c(this,Es)){y(this,yt,oo).call(this,t);return}const e=t.target.getAttribute("data-color");e&&y(this,yt,Bf).call(this,e,t)}_moveToNext(t){var e,s;if(!c(this,yt,In)){y(this,yt,oo).call(this,t);return}if(t.target===c(this,Es)){(e=c(this,zt).firstChild)==null||e.focus();return}(s=t.target.nextSibling)==null||s.focus()}_moveToPrevious(t){var e,s;if(t.target===((e=c(this,zt))==null?void 0:e.firstChild)||t.target===c(this,Es)){c(this,yt,In)&&this._hideDropdownFromKeyboard();return}c(this,yt,In)||y(this,yt,oo).call(this,t),(s=t.target.previousSibling)==null||s.focus()}_moveToBeginning(t){var e;if(!c(this,yt,In)){y(this,yt,oo).call(this,t);return}(e=c(this,zt).firstChild)==null||e.focus()}_moveToEnd(t){var e;if(!c(this,yt,In)){y(this,yt,oo).call(this,t);return}(e=c(this,zt).lastChild)==null||e.focus()}hideDropdown(){var t;(t=c(this,zt))==null||t.classList.add("hidden"),window.removeEventListener("pointerdown",c(this,Al))}_hideDropdownFromKeyboard(){var t;if(!c(this,ua)){if(!c(this,yt,In)){(t=c(this,El))==null||t.unselect();return}this.hideDropdown(),c(this,Es).focus({preventScroll:!0,focusVisible:c(this,Tl)})}}updateColor(t){if(c(this,Gr)&&(c(this,Gr).style.backgroundColor=t),!c(this,zt))return;const e=c(this,ks).highlightColors.values();for(const s of c(this,zt).children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){var t,e;(t=c(this,Es))==null||t.remove(),b(this,Es,null),b(this,Gr,null),(e=c(this,zt))==null||e.remove(),b(this,zt,null)}};Cl=new WeakMap,Al=new WeakMap,Es=new WeakMap,Gr=new WeakMap,da=new WeakMap,zt=new WeakMap,Tl=new WeakMap,ua=new WeakMap,El=new WeakMap,kl=new WeakMap,ks=new WeakMap,ga=new WeakMap,yt=new WeakSet,Nf=function(){const t=document.createElement("div"),e=c(this,ks)._signal;t.addEventListener("contextmenu",Oe,{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,ks).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",`pdfjs-editor-colorpicker-${s}`);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===c(this,da)),n.addEventListener("click",y(this,yt,Bf).bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",c(this,Cl),{signal:e}),t},Bf=function(t,e){e.stopPropagation(),c(this,kl).dispatch("switchannotationeditorparams",{source:this,type:c(this,ga),value:t})},Zv=function(t){Vi._keyboardManager.exec(this,t)},oo=function(t){if(c(this,yt,In)){this.hideDropdown();return}if(b(this,Tl,t.detail===0),window.addEventListener("pointerdown",c(this,Al),{signal:c(this,ks)._signal}),c(this,zt)){c(this,zt).classList.remove("hidden");return}const e=b(this,zt,y(this,yt,Nf).call(this));c(this,Es).append(e)},tb=function(t){var e;(e=c(this,zt))!=null&&e.contains(t.target)||this.hideDropdown()},In=function(){return c(this,zt)&&!c(this,zt).classList.contains("hidden")};let Sd=Vi;const lt=class lt extends dt{constructor(e){super({...e,name:"highlightEditor"});w(this,et);w(this,fa,null);w(this,Ml,0);w(this,En);w(this,Ur,null);w(this,pa,null);w(this,os,null);w(this,Dl,null);w(this,Ol,0);w(this,Yr,null);w(this,Ms,null);w(this,Te,null);w(this,qe,!1);w(this,Gd,y(this,et,nb).bind(this));w(this,ma,null);w(this,qr);w(this,Vt,null);w(this,va,"");w(this,ei);w(this,Pl,"");this.color=e.color||lt._defaultColor,b(this,ei,e.thickness||lt._defaultThickness),b(this,qr,e.opacity||lt._defaultOpacity),b(this,En,e.boxes||null),b(this,Pl,e.methodOfCreation||""),b(this,va,e.text||""),this._isDraggable=!1,e.highlightId>-1?(b(this,qe,!0),y(this,et,Wf).call(this,e),y(this,et,$l).call(this)):(b(this,fa,e.anchorNode),b(this,Ml,e.anchorOffset),b(this,Dl,e.focusNode),b(this,Ol,e.focusOffset),y(this,et,Hf).call(this),y(this,et,$l).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const e=lt.prototype;return at(this,"_keyboardManager",new Qa([[["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,qe)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:c(this,ei),methodOfCreation:c(this,Pl)}}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;dt.initialize(e,s),lt._defaultColor||(lt._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(e,s){switch(e){case q.HIGHLIGHT_DEFAULT_COLOR:lt._defaultColor=s;break;case q.HIGHLIGHT_THICKNESS:lt._defaultThickness=s;break}}translateInPage(e,s){}get toolbarPosition(){return c(this,ma)}updateParams(e,s){switch(e){case q.HIGHLIGHT_COLOR:y(this,et,eb).call(this,s);break;case q.HIGHLIGHT_THICKNESS:y(this,et,sb).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[q.HIGHLIGHT_DEFAULT_COLOR,lt._defaultColor],[q.HIGHLIGHT_THICKNESS,lt._defaultThickness]]}get propertiesToUpdate(){return[[q.HIGHLIGHT_COLOR,this.color||lt._defaultColor],[q.HIGHLIGHT_THICKNESS,c(this,ei)||lt._defaultThickness],[q.HIGHLIGHT_FREE,c(this,qe)]]}async addEditToolbar(){const e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(b(this,pa,new Sd({editor:this})),e.addColorPicker(c(this,pa))),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,et,Kl).call(this))}getBaseTranslation(){return[0,0]}getRect(e,s){return super.getRect(e,s,y(this,et,Kl).call(this))}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){y(this,et,Xf).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(y(this,et,$l).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?y(this,et,Xf).call(this):e&&(y(this,et,$l).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,qe)?(e=(e-this.rotation+360)%360,i=y(n=lt,as,ka).call(n,c(this,Ms).box,e)):i=y(r=lt,as,ka).call(r,this,e),s.rotate(c(this,Te),e),s.rotate(c(this,Vt),e),s.updateBox(c(this,Te),i),s.updateBox(c(this,Vt),y(o=lt,as,ka).call(o,c(this,os).box,e))}render(){if(this.div)return this.div;const e=super.render();c(this,va)&&(e.setAttribute("aria-label",c(this,va)),e.setAttribute("role","mark")),c(this,qe)?e.classList.add("free"):this.div.addEventListener("keydown",c(this,Gd),{signal:this._uiManager._signal});const s=b(this,Yr,document.createElement("div"));e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=c(this,Ur);const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),gd(this,c(this,Yr),["pointerover","pointerleave"]),this.enableEditing(),e}pointerover(){this.parent.drawLayer.addClass(c(this,Vt),"hovered")}pointerleave(){this.parent.drawLayer.removeClass(c(this,Vt),"hovered")}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:y(this,et,lu).call(this,!0);break;case 1:case 3:y(this,et,lu).call(this,!1);break}}select(){var e,s;super.select(),c(this,Vt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Vt),"hovered"),(s=this.parent)==null||s.drawLayer.addClass(c(this,Vt),"selected"))}unselect(){var e;super.unselect(),c(this,Vt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Vt),"selected"),c(this,qe)||y(this,et,lu).call(this,!1))}get _mustFixPosition(){return!c(this,qe)}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.show(c(this,Te),e),this.parent.drawLayer.show(c(this,Vt),e))}static startHighlighting(e,s,{target:i,x:n,y:r}){const{x:o,y:h,width:l,height:d}=i.getBoundingClientRect(),u=_=>{y(this,as,ab).call(this,e,_)},g=e._signal,f={capture:!0,passive:!1,signal:g},p=_=>{_.preventDefault(),_.stopPropagation()},m=_=>{i.removeEventListener("pointermove",u),window.removeEventListener("blur",m),window.removeEventListener("pointerup",m),window.removeEventListener("pointerdown",p,f),window.removeEventListener("contextmenu",Oe),y(this,as,hb).call(this,e,_)};window.addEventListener("blur",m,{signal:g}),window.addEventListener("pointerup",m,{signal:g}),window.addEventListener("pointerdown",p,f),window.addEventListener("contextmenu",Oe,{signal:g}),i.addEventListener("pointermove",u,{signal:g}),this._freeHighlight=new xd({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 deserialize(e,s,i){var m;const n=super.deserialize(e,s,i),{rect:[r,o,h,l],color:d,quadPoints:u}=e;n.color=z.makeHexColor(...d),b(n,qr,e.opacity);const[g,f]=n.pageDimensions;n.width=(h-r)/g,n.height=(l-o)/f;const p=b(n,En,[]);for(let _=0;_<u.length;_+=8)p.push({x:(u[4]-h)/g,y:(l-(1-u[_+5]))/f,width:(u[_+2]-u[_])/g,height:(u[_+5]-u[_+1])/f});return y(m=n,et,Hf).call(m),n}serialize(e=!1){if(this.isEmpty()||e)return null;const s=this.getRect(0,0),i=dt._colorManager.convert(this.color);return{annotationType:nt.HIGHLIGHT,color:i,opacity:c(this,qr),thickness:c(this,ei),quadPoints:y(this,et,rb).call(this),outlines:y(this,et,ob).call(this,s),pageIndex:this.pageIndex,rect:s,rotation:y(this,et,Kl).call(this),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}};fa=new WeakMap,Ml=new WeakMap,En=new WeakMap,Ur=new WeakMap,pa=new WeakMap,os=new WeakMap,Dl=new WeakMap,Ol=new WeakMap,Yr=new WeakMap,Ms=new WeakMap,Te=new WeakMap,qe=new WeakMap,Gd=new WeakMap,ma=new WeakMap,qr=new WeakMap,Vt=new WeakMap,va=new WeakMap,ei=new WeakMap,Pl=new WeakMap,et=new WeakSet,Hf=function(){const e=new tv(c(this,En),.001);b(this,Ms,e.getOutlines()),{x:this.x,y:this.y,width:this.width,height:this.height}=c(this,Ms).box;const s=new tv(c(this,En),.0025,.001,this._uiManager.direction==="ltr");b(this,os,s.getOutlines());const{lastPoint:i}=c(this,os).box;b(this,ma,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height])},Wf=function({highlightOutlines:e,highlightId:s,clipPathId:i}){var u,g;if(b(this,Ms,e),b(this,os,e.getNewOutline(c(this,ei)/2+1.5,.0025)),s>=0)b(this,Te,s),b(this,Ur,i),this.parent.drawLayer.finalizeLine(s,e),b(this,Vt,this.parent.drawLayer.highlightOutline(c(this,os)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(c(this,Te),e),this.parent.drawLayer.updateBox(c(this,Te),y(u=lt,as,ka).call(u,c(this,Ms).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(c(this,Vt),c(this,os)),this.parent.drawLayer.updateBox(c(this,Vt),y(g=lt,as,ka).call(g,c(this,os).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,os).box;b(this,ma,[(d[0]-r)/h,(d[1]-o)/l])},eb=function(e){const s=n=>{var r,o;this.color=n,(r=this.parent)==null||r.drawLayer.changeColor(c(this,Te),n),(o=c(this,pa))==null||o.updateColor(n)},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:q.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(e)},!0)},sb=function(e){const s=c(this,ei),i=n=>{b(this,ei,n),y(this,et,ib).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:q.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:e},!0)},ib=function(e){if(!c(this,qe))return;y(this,et,Wf).call(this,{highlightOutlines:c(this,Ms).getNewOutline(e/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},Xf=function(){c(this,Te)===null||!this.parent||(this.parent.drawLayer.remove(c(this,Te)),b(this,Te,null),this.parent.drawLayer.remove(c(this,Vt)),b(this,Vt,null))},$l=function(e=this.parent){c(this,Te)===null&&({id:Je(this,Te)._,clipPathId:Je(this,Ur)._}=e.drawLayer.highlight(c(this,Ms),this.color,c(this,qr)),b(this,Vt,e.drawLayer.highlightOutline(c(this,os))),c(this,Yr)&&(c(this,Yr).style.clipPath=c(this,Ur)))},as=new WeakSet,ka=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}},nb=function(e){lt._keyboardManager.exec(this,e)},lu=function(e){if(!c(this,fa))return;const s=window.getSelection();e?s.setPosition(c(this,fa),c(this,Ml)):s.setPosition(c(this,Dl),c(this,Ol))},Kl=function(){return c(this,qe)?this.rotation:0},rb=function(){if(c(this,qe))return null;const[e,s]=this.pageDimensions,[i,n]=this.pageTranslation,r=c(this,En),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},ob=function(e){return c(this,Ms).serialize(e,y(this,et,Kl).call(this))},ab=function(e,s){this._freeHighlight.add(s)&&e.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},hb=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=""},w(lt,as),K(lt,"_defaultColor",null),K(lt,"_defaultOpacity",1),K(lt,"_defaultThickness",12),K(lt,"_l10nPromise"),K(lt,"_type","highlight"),K(lt,"_editorType",nt.HIGHLIGHT),K(lt,"_freeHighlightId",-1),K(lt,"_freeHighlight",null),K(lt,"_freeHighlightClipId","");let Cd=lt;const At=class At extends dt{constructor(e){super({...e,name:"inkEditor"});w(this,N);w(this,$r,0);w(this,Kr,0);w(this,Ll,this.canvasPointermove.bind(this));w(this,Fl,this.canvasPointerleave.bind(this));w(this,Rl,this.canvasPointerup.bind(this));w(this,Qr,this.canvasPointerdown.bind(this));w(this,si,null);w(this,Gi,new Path2D);w(this,hs,!1);w(this,Jr,!1);w(this,Zr,!1);w(this,Ui,null);w(this,to,0);w(this,eo,0);w(this,kn,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){dt.initialize(e,s)}static updateDefaultParams(e,s){switch(e){case q.INK_THICKNESS:At._defaultThickness=s;break;case q.INK_COLOR:At._defaultColor=s;break;case q.INK_OPACITY:At._defaultOpacity=s/100;break}}updateParams(e,s){switch(e){case q.INK_THICKNESS:y(this,N,lb).call(this,s);break;case q.INK_COLOR:y(this,N,cb).call(this,s);break;case q.INK_OPACITY:y(this,N,db).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[q.INK_THICKNESS,At._defaultThickness],[q.INK_COLOR,At._defaultColor||dt._defaultLineColor],[q.INK_OPACITY,Math.round(At._defaultOpacity*100)]]}get propertiesToUpdate(){return[[q.INK_THICKNESS,this.thickness||At._defaultThickness],[q.INK_COLOR,this.color||At._defaultColor||dt._defaultLineColor],[q.INK_OPACITY,Math.round(100*(this.opacity??At._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(y(this,N,cu).call(this),y(this,N,du).call(this)),this.isAttachedToDOM||(this.parent.add(this),y(this,N,Ma).call(this)),y(this,N,Ql).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,si)&&(clearTimeout(c(this,si)),b(this,si,null)),(e=c(this,Ui))==null||e.disconnect(),b(this,Ui,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,hs)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",c(this,Qr),{signal:this._uiManager._signal}))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",c(this,Qr)))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){c(this,hs)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),b(this,hs,!0),this.div.classList.add("disabled"),y(this,N,Ql).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,hs)||(this.setInForeground(),e.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),y(this,N,gb).call(this,e.offsetX,e.offsetY))}canvasPointermove(e){e.preventDefault(),y(this,N,Vf).call(this,e.offsetX,e.offsetY)}canvasPointerup(e){e.preventDefault(),y(this,N,Gf).call(this,e)}canvasPointerleave(e){y(this,N,Gf).call(this,e)}get isResizable(){return!this.isEmpty()&&c(this,hs)}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,N,ub).call(this);if(this.setAt(i,n,0,0),this.setDims(r,o),y(this,N,cu).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,Zr,!0),y(this,N,Ma).call(this),this.setDims(this.width*h,this.height*l),y(this,N,ao).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return y(this,N,du).call(this),this.div}setDimensions(e,s){const i=Math.round(e),n=Math.round(s);if(c(this,to)===i&&c(this,eo)===n)return;b(this,to,i),b(this,eo,n),this.canvas.style.visibility="hidden";const[r,o]=this.parentDimensions;this.width=e/r,this.height=s/o,this.fixAndSetPosition(),c(this,hs)&&y(this,N,Uf).call(this,e,s),y(this,N,Ma).call(this),y(this,N,ao).call(this),this.canvas.style.visibility="visible",this.fixDims()}static deserialize(e,s,i){var _,v,x;if(e instanceof J0)return null;const n=super.deserialize(e,s,i);n.thickness=e.thickness,n.color=z.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,hs,!0),b(n,to,Math.round(h)),b(n,eo,Math.round(l));const{paths:g,rect:f,rotation:p}=e;for(let{bezier:S}of g){S=y(_=At,Yi,_b).call(_,S,f,p);const T=[];n.paths.push(T);let E=d*(S[0]-u),M=d*(S[1]-u);for(let O=2,R=S.length;O<R;O+=6){const D=d*(S[O]-u),L=d*(S[O+1]-u),F=d*(S[O+2]-u),I=d*(S[O+3]-u),X=d*(S[O+4]-u),Y=d*(S[O+5]-u);T.push([[E,M],[D,L],[F,I],[X,Y]]),E=X,M=Y}const P=y(this,Yi,yb).call(this,T);n.bezierPath2D.push(P)}const m=y(v=n,N,qf).call(v);return b(n,Kr,Math.max(dt.MIN_SIZE,m[2]-m[0])),b(n,$r,Math.max(dt.MIN_SIZE,m[3]-m[1])),y(x=n,N,Uf).call(x,h,l),n}serialize(){if(this.isEmpty())return null;const e=this.getRect(0,0),s=dt._colorManager.convert(this.ctx.strokeStyle);return{annotationType:nt.INK,color:s,thickness:this.thickness,opacity:this.opacity,paths:y(this,N,wb).call(this,this.scaleFactor/this.parentScale,this.translationX,this.translationY,e),pageIndex:this.pageIndex,rect:e,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}};$r=new WeakMap,Kr=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,Rl=new WeakMap,Qr=new WeakMap,si=new WeakMap,Gi=new WeakMap,hs=new WeakMap,Jr=new WeakMap,Zr=new WeakMap,Ui=new WeakMap,to=new WeakMap,eo=new WeakMap,kn=new WeakMap,N=new WeakSet,lb=function(e){const s=n=>{this.thickness=n,y(this,N,Ql).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:q.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},cb=function(e){const s=n=>{this.color=n,y(this,N,ao).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:q.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},db=function(e){const s=n=>{this.opacity=n,y(this,N,ao).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:q.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},ub=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]}},zf=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}${Ow(i)}`},gb=function(e,s){const i=this._uiManager._signal;this.canvas.addEventListener("contextmenu",Oe,{signal:i}),this.canvas.addEventListener("pointerleave",c(this,Fl),{signal:i}),this.canvas.addEventListener("pointermove",c(this,Ll),{signal:i}),this.canvas.addEventListener("pointerup",c(this,Rl),{signal:i}),this.canvas.removeEventListener("pointerdown",c(this,Qr)),this.isEditing=!0,c(this,Zr)||(b(this,Zr,!0),y(this,N,Ma).call(this),this.thickness||(this.thickness=At._defaultThickness),this.color||(this.color=At._defaultColor||dt._defaultLineColor),this.opacity??(this.opacity=At._defaultOpacity)),this.currentPath.push([e,s]),b(this,Jr,!1),y(this,N,zf).call(this),b(this,kn,()=>{y(this,N,mb).call(this),c(this,kn)&&window.requestAnimationFrame(c(this,kn))}),window.requestAnimationFrame(c(this,kn))},Vf=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,Gi);if(r.push([e,s]),b(this,Jr,!0),r.length<=2){o.moveTo(...r[0]),o.lineTo(e,s);return}r.length===3&&(b(this,Gi,o=new Path2D),o.moveTo(...r[0])),y(this,N,vb).call(this,o,...r.at(-3),...r.at(-2),e,s)},fb=function(){if(this.currentPath.length===0)return;const e=this.currentPath.at(-1);c(this,Gi).lineTo(...e)},pb=function(e,s){b(this,kn,null),e=Math.min(Math.max(e,0),this.canvas.width),s=Math.min(Math.max(s,0),this.canvas.height),y(this,N,Vf).call(this,e,s),y(this,N,fb).call(this);let i;if(this.currentPath.length!==1)i=y(this,N,bb).call(this);else{const l=[e,s];i=[[l,l.slice(),l.slice(),l]]}const n=c(this,Gi),r=this.currentPath;this.currentPath=[],b(this,Gi,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,N,cu).call(this),y(this,N,du).call(this)),y(this,N,Ql).call(this))};this.addCommands({cmd:o,undo:h,mustExec:!0})},mb=function(){if(!c(this,Jr))return;b(this,Jr,!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,Gi)),r.restore()},vb=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)},bb=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],T=[v+2*(f-v)/3,x+2*(p-x)/3];s.push([[n,r],S,T,[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},ao=function(){if(this.isEmpty()){y(this,N,uu).call(this);return}y(this,N,zf).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,N,uu).call(this);for(const i of this.bezierPath2D)s.stroke(i)},Gf=function(e){this.canvas.removeEventListener("pointerleave",c(this,Fl)),this.canvas.removeEventListener("pointermove",c(this,Ll)),this.canvas.removeEventListener("pointerup",c(this,Rl)),this.canvas.addEventListener("pointerdown",c(this,Qr),{signal:this._uiManager._signal}),c(this,si)&&clearTimeout(c(this,si)),b(this,si,setTimeout(()=>{b(this,si,null),this.canvas.removeEventListener("contextmenu",Oe)},10)),y(this,N,pb).call(this,e.offsetX,e.offsetY),this.addToAnnotationStorage(),this.setInBackground()},cu=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")},du=function(){b(this,Ui,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&this.setDimensions(s.width,s.height)})),c(this,Ui).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,Ui))==null||e.disconnect(),b(this,Ui,null)},{once:!0})},Ma=function(){if(!c(this,Zr))return;const[e,s]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*e),this.canvas.height=Math.ceil(this.height*s),y(this,N,uu).call(this)},Uf=function(e,s){const i=y(this,N,gu).call(this),n=(e-i)/c(this,Kr),r=(s-i)/c(this,$r);this.scaleFactor=Math.min(n,r)},uu=function(){const e=y(this,N,gu).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+e,this.translationY*this.scaleFactor+e)},Yi=new WeakSet,yb=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},Yf=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},_b=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},wb=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,T]=g[m];if(v[0]===T[0]&&v[1]===T[1]&&_===1){const I=e*v[0]+h,X=e*v[1]+l;f.push(I,X),p.push(I,X);break}const E=e*v[0]+h,M=e*v[1]+l,P=e*x[0]+h,O=e*x[1]+l,R=e*S[0]+h,D=e*S[1]+l,L=e*T[0]+h,F=e*T[1]+l;m===0&&(f.push(E,M),p.push(E,M)),f.push(P,O,R,D,L,F),p.push(P,O),m===_-1&&p.push(L,F)}r.push({bezier:y(d=At,Yi,Yf).call(d,f,n,this.rotation),points:y(u=At,Yi,Yf).call(u,p,n,this.rotation)})}return r},qf=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=z.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]},gu=function(){return c(this,hs)?Math.ceil(this.thickness*this.parentScale):0},Ql=function(e=!1){if(this.isEmpty())return;if(!c(this,hs)){y(this,N,ao).call(this);return}const s=y(this,N,qf).call(this),i=y(this,N,gu).call(this);b(this,Kr,Math.max(dt.MIN_SIZE,s[2]-s[0])),b(this,$r,Math.max(dt.MIN_SIZE,s[3]-s[1]));const n=Math.ceil(i+c(this,Kr)*this.scaleFactor),r=Math.ceil(i+c(this,$r)*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,N,Ma).call(this),y(this,N,ao).call(this),b(this,to,n),b(this,eo,r),this.setDims(n,r);const u=e?i/this.scaleFactor/2:0;this.translate(l-this.translationX-u,d-this.translationY-u)},w(At,Yi),K(At,"_defaultColor",null),K(At,"_defaultOpacity",1),K(At,"_defaultThickness",1),K(At,"_type","ink"),K(At,"_editorType",nt.INK);let qg=At;const Nl=class Nl extends dt{constructor(e){super({...e,name:"stampEditor"});w(this,ht);w(this,te,null);w(this,ee,null);w(this,Mn,null);w(this,qi,null);w(this,Dn,null);w(this,ba,"");w(this,ii,null);w(this,Il,!1);w(this,$i,null);w(this,ni,null);w(this,Ds,!1);w(this,jl,!1);b(this,qi,e.bitmapUrl),b(this,Dn,e.bitmapFile)}static initialize(e,s){dt.initialize(e,s)}static get supportedTypes(){return at(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(s=>`image/${s}`))}static get supportedTypesStr(){return at(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,s){s.pasteEditor(nt.STAMP,{bitmapFile:e.getAsFile()})}remove(){var e,s;c(this,ee)&&(b(this,te,null),this._uiManager.imageManager.deleteId(c(this,ee)),(e=c(this,ii))==null||e.remove(),b(this,ii,null),(s=c(this,$i))==null||s.disconnect(),b(this,$i,null),c(this,ni)&&(clearTimeout(c(this,ni)),b(this,ni,null))),super.remove()}rebuild(){if(!this.parent){c(this,ee)&&y(this,ht,fu).call(this);return}super.rebuild(),this.div!==null&&(c(this,ee)&&c(this,ii)===null&&y(this,ht,fu).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(c(this,Mn)||c(this,te)||c(this,qi)||c(this,Dn)||c(this,ee))}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.addAltTextButton(),c(this,te)?y(this,ht,$f).call(this):y(this,ht,fu).call(this),this.width){const[i,n]=this.parentDimensions;this.setAt(e*i,s*n,this.width*i,this.height*n)}return this.div}getImageForAltText(){return c(this,ii)}static deserialize(e,s,i){if(e instanceof Z0)return null;const n=super.deserialize(e,s,i),{rect:r,bitmapUrl:o,bitmapId:h,isSvg:l,accessibilityData:d}=e;h&&i.imageManager.isValidId(h)?b(n,ee,h):b(n,qi,o),b(n,Ds,l);const[u,g]=n.pageDimensions;return n.width=(r[2]-r[0])/u,n.height=(r[3]-r[1])/g,d&&(n.altTextData=d),n}serialize(e=!1,s=null){if(this.isEmpty())return null;const i={annotationType:nt.STAMP,bitmapId:c(this,ee),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:c(this,Ds),structTreeParentId:this._structTreeParentId};if(e)return i.bitmapUrl=y(this,ht,pu).call(this,!0),i.accessibilityData=this.altTextData,i;const{decorative:n,altText:r}=this.altTextData;if(!n&&r&&(i.accessibilityData={type:"Figure",alt:r}),s===null)return i;s.stamps||(s.stamps=new Map);const o=c(this,Ds)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(c(this,ee)))s.stamps.set(c(this,ee),{area:o,serialized:i}),i.bitmap=y(this,ht,pu).call(this,!1);else if(c(this,Ds)){const h=s.stamps.get(c(this,ee));o>h.area&&(h.area=o,h.serialized.bitmap.close(),h.serialized.bitmap=y(this,ht,pu).call(this,!1))}return i}};te=new WeakMap,ee=new WeakMap,Mn=new WeakMap,qi=new WeakMap,Dn=new WeakMap,ba=new WeakMap,ii=new WeakMap,Il=new WeakMap,$i=new WeakMap,ni=new WeakMap,Ds=new WeakMap,jl=new WeakMap,ht=new WeakSet,Jl=function(e,s=!1){if(!e){this.remove();return}b(this,te,e.bitmap),s||(b(this,ee,e.id),b(this,Ds,e.isSvg)),e.file&&b(this,ba,e.file.name),y(this,ht,$f).call(this)},Zl=function(){b(this,Mn,null),this._uiManager.enableWaiting(!1),c(this,ii)&&this.div.focus()},fu=function(){if(c(this,ee)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(c(this,ee)).then(i=>y(this,ht,Jl).call(this,i,!0)).finally(()=>y(this,ht,Zl).call(this));return}if(c(this,qi)){const i=c(this,qi);b(this,qi,null),this._uiManager.enableWaiting(!0),b(this,Mn,this._uiManager.imageManager.getFromUrl(i).then(n=>y(this,ht,Jl).call(this,n)).finally(()=>y(this,ht,Zl).call(this)));return}if(c(this,Dn)){const i=c(this,Dn);b(this,Dn,null),this._uiManager.enableWaiting(!0),b(this,Mn,this._uiManager.imageManager.getFromFile(i).then(n=>y(this,ht,Jl).call(this,n)).finally(()=>y(this,ht,Zl).call(this)));return}const e=document.createElement("input");e.type="file",e.accept=Nl.supportedTypesStr;const s=this._uiManager._signal;b(this,Mn,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]);y(this,ht,Jl).call(this,n)}i()},{signal:s}),e.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>y(this,ht,Zl).call(this))),e.click()},$f=function(){const{div:e}=this;let{width:s,height:i}=c(this,te);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,ii,document.createElement("canvas"));e.append(d),e.hidden=!1,y(this,ht,Kf).call(this,s,i),y(this,ht,Ab).call(this),c(this,jl)||(this.parent.addUndoableEditor(this),b(this,jl,!0)),this._reportTelemetry({action:"inserted_image"}),c(this,ba)&&d.setAttribute("aria-label",c(this,ba))},xb=function(e,s){var o;const[i,n]=this.parentDimensions;this.width=e/i,this.height=s/n,this.setDims(e,s),(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,c(this,ni)!==null&&clearTimeout(c(this,ni)),b(this,ni,setTimeout(()=>{b(this,ni,null),y(this,ht,Kf).call(this,e,s)},200))},Sb=function(e,s){const{width:i,height:n}=c(this,te);let r=i,o=n,h=c(this,te);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},Cb=async function(e,s,i){if(c(this,Il)||(b(this,Il,!0),!await this._uiManager.isMLEnabledFor("altText")||this.hasAltText()))return;const o=new OffscreenCanvas(s,i).getContext("2d",{willReadFrequently:!0});o.drawImage(e,0,0,e.width,e.height,0,0,s,i);const h=await this._uiManager.mlGuess({service:"moz-image-to-text",request:{data:o.getImageData(0,0,s,i).data,width:s,height:i,channels:4}}),l=(h==null?void 0:h.output)||"";this.parent&&l&&!this.hasAltText()&&(this.altTextData={altText:l,decorative:!1})},Kf=function(e,s){e=Math.ceil(e),s=Math.ceil(s);const i=c(this,ii);if(!i||i.width===e&&i.height===s)return;i.width=e,i.height=s;const n=c(this,Ds)?c(this,te):y(this,ht,Sb).call(this,e,s);y(this,ht,Cb).call(this,n,e,s);const r=i.getContext("2d");r.filter=this._uiManager.hcmFilter,r.drawImage(n,0,0,n.width,n.height,0,0,e,s)},pu=function(e){if(e){if(c(this,Ds)){const n=this._uiManager.imageManager.getSvgUrl(c(this,ee));if(n)return n}const s=document.createElement("canvas");return{width:s.width,height:s.height}=c(this,te),s.getContext("2d").drawImage(c(this,te),0,0),s.toDataURL()}if(c(this,Ds)){const[s,i]=this.pageDimensions,n=Math.round(this.width*s*ln.PDF_TO_CSS_UNITS),r=Math.round(this.height*i*ln.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(n,r);return o.getContext("2d").drawImage(c(this,te),0,0,c(this,te).width,c(this,te).height,0,0,n,r),o.transferToImageBitmap()}return structuredClone(c(this,te))},Ab=function(){this._uiManager._signal&&(b(this,$i,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&y(this,ht,xb).call(this,s.width,s.height)})),c(this,$i).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,$i))==null||e.disconnect(),b(this,$i,null)},{once:!0}))},K(Nl,"_type","stamp"),K(Nl,"_editorType",nt.STAMP);let $g=Nl;const Os=class Os{constructor({uiManager:t,pageIndex:e,div:s,accessibilityManager:i,annotationLayer:n,drawLayer:r,textLayer:o,viewport:h,l10n:l}){w(this,se);w(this,so);w(this,ya,!1);w(this,ri,null);w(this,io,null);w(this,Ki,null);w(this,Qi,null);w(this,Ji,null);w(this,$e,new Map);w(this,On,!1);w(this,_a,!1);w(this,wa,!1);w(this,fe,null);w(this,G);const d=[...c(Os,Pn).values()];if(!Os._initialized){Os._initialized=!0;for(const u of d)u.initialize(l,t)}t.registerEditorTypes(d),b(this,G,t),this.pageIndex=e,this.div=s,b(this,so,i),b(this,ri,n),this.viewport=h,b(this,fe,o),this.drawLayer=r,c(this,G).addLayer(this)}get isEmpty(){return c(this,$e).size===0}get isInvisible(){return this.isEmpty&&c(this,G).getMode()===nt.NONE}updateToolbar(t){c(this,G).updateToolbar(t)}updateMode(t=c(this,G).getMode()){switch(y(this,se,mu).call(this),t){case nt.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case nt.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case nt.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(Os,Pn).values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){var e;return t===((e=c(this,fe))==null?void 0:e.div)}addInkEditorIfNeeded(t){if(c(this,G).getMode()!==nt.INK)return;if(!t){for(const s of c(this,$e).values())if(s.isEmpty()){s.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){c(this,G).setEditingState(t)}addCommands(t){c(this,G).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,ri))==null||e.div.classList.toggle("disabled",!t)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of c(this,$e).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(c(this,G).removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!c(this,ri))return;const e=c(this,ri).getEditableAnnotations();for(const s of e){if(s.hide(),c(this,G).isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){var i;b(this,wa,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const n of c(this,$e).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,ri)){const n=c(this,ri).getEditableAnnotations();for(const r of n){const{id:o}=r.data;if(c(this,G).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,G).addChangedExistingAnnotation(h),h.renderAnnotationElement(r),h.show(!1)),r.show()}}y(this,se,mu).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const n of c(Os,Pn).values())s.remove(`${n._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),b(this,wa,!1)}getEditableAnnotation(t){var e;return((e=c(this,ri))==null?void 0:e.getEditableAnnotation(t))||null}setActiveEditor(t){c(this,G).getActive()!==t&&c(this,G).setActiveEditor(t)}enableTextSelection(){var t;this.div.tabIndex=-1,(t=c(this,fe))!=null&&t.div&&!c(this,Qi)&&(b(this,Qi,y(this,se,Tb).bind(this)),c(this,fe).div.addEventListener("pointerdown",c(this,Qi),{signal:c(this,G)._signal}),c(this,fe).div.classList.add("highlighting"))}disableTextSelection(){var t;this.div.tabIndex=0,(t=c(this,fe))!=null&&t.div&&c(this,Qi)&&(c(this,fe).div.removeEventListener("pointerdown",c(this,Qi)),b(this,Qi,null),c(this,fe).div.classList.remove("highlighting"))}enableClick(){if(c(this,Ki))return;const t=c(this,G)._signal;b(this,Ki,this.pointerdown.bind(this)),b(this,io,this.pointerup.bind(this)),this.div.addEventListener("pointerdown",c(this,Ki),{signal:t}),this.div.addEventListener("pointerup",c(this,io),{signal:t})}disableClick(){c(this,Ki)&&(this.div.removeEventListener("pointerdown",c(this,Ki)),this.div.removeEventListener("pointerup",c(this,io)),b(this,Ki,null),b(this,io,null))}attach(t){c(this,$e).set(t.id,t);const{annotationElementId:e}=t;e&&c(this,G).isDeletedAnnotationElement(e)&&c(this,G).removeDeletedAnnotationElement(t)}detach(t){var e;c(this,$e).delete(t.id),(e=c(this,so))==null||e.removePointerInTextLayer(t.contentDiv),!c(this,wa)&&t.annotationElementId&&c(this,G).addDeletedAnnotationElement(t)}remove(t){this.detach(t),c(this,G).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,c(this,_a)||this.addInkEditorIfNeeded(!1)}changeParent(t){var e;t.parent!==this&&(t.parent&&t.annotationElementId&&(c(this,G).addDeletedAnnotationElement(t.annotationElementId),dt.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,G).addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),c(this,G).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var s;if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!c(this,Ji)&&(t._focusEventsAllowed=!1,b(this,Ji,setTimeout(()=>{b(this,Ji,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:c(this,G)._signal}),e.focus())},0))),t._structTreeParentId=(s=c(this,so))==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,G).getId()}get _signal(){return c(this,G)._signal}canCreateNewEmptyEditor(){var t;return(t=c(this,se,Qf))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,e){c(this,G).updateToolbar(t),c(this,G).updateMode(t);const{offsetX:s,offsetY:i}=y(this,se,Zf).call(this),n=this.getNextId(),r=y(this,se,Jf).call(this,{parent:this,id:n,x:s,y:i,uiManager:c(this,G),isCentered:!0,...e});r&&this.add(r)}deserialize(t){var e;return((e=c(Os,Pn).get(t.annotationType??t.annotationEditorType))==null?void 0:e.deserialize(t,this,c(this,G)))||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=y(this,se,Jf).call(this,{parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:c(this,G),isCentered:e,...s});return n&&this.add(n),n}addNewEditor(){this.createAndAddNewEditor(y(this,se,Zf).call(this),!0)}setSelected(t){c(this,G).setSelected(t)}toggleSelected(t){c(this,G).toggleSelected(t)}isSelected(t){return c(this,G).isSelected(t)}unselect(t){c(this,G).unselect(t)}pointerup(t){const{isMac:e}=De.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&c(this,On)){if(b(this,On,!1),!c(this,ya)){b(this,ya,!0);return}if(c(this,G).getMode()===nt.STAMP){c(this,G).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(c(this,G).getMode()===nt.HIGHLIGHT&&this.enableTextSelection(),c(this,On)){b(this,On,!1);return}const{isMac:e}=De.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;b(this,On,!0);const s=c(this,G).getActive();b(this,ya,!s||s.isEmpty())}findNewParent(t,e,s){const i=c(this,G).findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}destroy(){var t,e;((t=c(this,G).getActive())==null?void 0:t.parent)===this&&(c(this,G).commitOrRemove(),c(this,G).setActiveEditor(null)),c(this,Ji)&&(clearTimeout(c(this,Ji)),b(this,Ji,null));for(const s of c(this,$e).values())(e=c(this,so))==null||e.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,c(this,$e).clear(),c(this,G).removeLayer(this)}render({viewport:t}){this.viewport=t,Zn(this.div,t);for(const e of c(this,G).getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){c(this,G).commitOrRemove(),y(this,se,mu).call(this);const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,Zn(this.div,{rotation:s}),e!==s)for(const i of c(this,$e).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,G).viewParameters.realScale}};so=new WeakMap,ya=new WeakMap,ri=new WeakMap,io=new WeakMap,Ki=new WeakMap,Qi=new WeakMap,Ji=new WeakMap,$e=new WeakMap,On=new WeakMap,_a=new WeakMap,wa=new WeakMap,fe=new WeakMap,G=new WeakMap,Pn=new WeakMap,se=new WeakSet,Tb=function(t){c(this,G).unselectAll();const{target:e}=t;if(e===c(this,fe).div||e.classList.contains("endOfContent")&&c(this,fe).div.contains(e)){const{isMac:s}=De.platform;if(t.button!==0||t.ctrlKey&&s)return;c(this,G).showAllEditors("highlight",!0,!0),c(this,fe).div.classList.add("free"),this.toggleDrawing(),Cd.startHighlighting(this,c(this,G).direction==="ltr",t),c(this,fe).div.addEventListener("pointerup",()=>{c(this,fe).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:c(this,G)._signal}),t.preventDefault()}},Qf=function(){return c(Os,Pn).get(c(this,G).getMode())},Jf=function(t){const e=c(this,se,Qf);return e?new e.prototype.constructor(t):null},Zf=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}},mu=function(){b(this,_a,!0);for(const t of c(this,$e).values())t.isEmpty()&&t.remove();b(this,_a,!1)},K(Os,"_initialized",!1),w(Os,Pn,new Map([Ug,qg,$g,Cd].map(t=>[t._editorType,t])));let Kg=Os;const ie=class ie{constructor({pageIndex:t}){w(this,no);w(this,oi,null);w(this,Bl,0);w(this,Gt,new Map);w(this,Ln,new Map);this.pageIndex=t}setParent(t){if(!c(this,oi)){b(this,oi,t);return}if(c(this,oi)!==t){if(c(this,Gt).size>0)for(const e of c(this,Gt).values())e.remove(),t.append(e);b(this,oi,t)}}static get _svgFactory(){return at(this,"_svgFactory",new Tg)}highlight(t,e,s,i=!1){const n=Je(this,Bl)._++,r=y(this,no,ep).call(this,t.box);r.classList.add("highlight"),t.free&&r.classList.add("free");const o=ie._svgFactory.createElement("defs");r.append(o);const h=ie._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,Ln).set(n,h);const d=y(this,no,Eb).call(this,o,l),u=ie._svgFactory.createElement("use");return r.append(u),r.setAttribute("fill",e),r.setAttribute("fill-opacity",s),u.setAttribute("href",`#${l}`),c(this,Gt).set(n,r),{id:n,clipPathId:`url(#${d})`}}highlightOutline(t){const e=Je(this,Bl)._++,s=y(this,no,ep).call(this,t.box);s.classList.add("highlightOutline");const i=ie._svgFactory.createElement("defs");s.append(i);const n=ie._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=ie._svgFactory.createElement("mask");i.append(d),o=`mask_p${this.pageIndex}_${e}`,d.setAttribute("id",o),d.setAttribute("maskUnits","objectBoundingBox");const u=ie._svgFactory.createElement("rect");d.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const g=ie._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=ie._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,Gt).set(e,s),e}finalizeLine(t,e){const s=c(this,Ln).get(t);c(this,Ln).delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){c(this,Gt).get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),c(this,Ln).delete(t)}updatePath(t,e){c(this,Ln).get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){var s;y(s=ie,Hl,tp).call(s,c(this,Gt).get(t),e)}show(t,e){c(this,Gt).get(t).classList.toggle("hidden",!e)}rotate(t,e){c(this,Gt).get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){c(this,Gt).get(t).setAttribute("fill",e)}changeOpacity(t,e){c(this,Gt).get(t).setAttribute("fill-opacity",e)}addClass(t,e){c(this,Gt).get(t).classList.add(e)}removeClass(t,e){c(this,Gt).get(t).classList.remove(e)}remove(t){c(this,oi)!==null&&(c(this,Gt).get(t).remove(),c(this,Gt).delete(t))}destroy(){b(this,oi,null);for(const t of c(this,Gt).values())t.remove();c(this,Gt).clear()}};oi=new WeakMap,Bl=new WeakMap,Gt=new WeakMap,Ln=new WeakMap,Hl=new WeakSet,tp=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}%`},no=new WeakSet,ep=function(t){var s;const e=ie._svgFactory.create(1,1,!0);return c(this,oi).append(e),e.setAttribute("aria-hidden",!0),y(s=ie,Hl,tp).call(s,e,t),e},Eb=function(t,e){const s=ie._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=ie._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i},w(ie,Hl);let Qg=ie;$.AbortException,$.AnnotationEditorLayer,$.AnnotationEditorParamsType,$.AnnotationEditorType,$.AnnotationEditorUIManager,$.AnnotationLayer,$.AnnotationMode,$.CMapCompressionType,$.ColorPicker,$.DOMSVGFactory,$.DrawLayer,$.FeatureTest;var oS=$.GlobalWorkerOptions;$.ImageKind,$.InvalidPDFException,$.MissingPDFException,$.OPS,$.PDFDataRangeTransport,$.PDFDateString,$.PDFWorker,$.PasswordResponses,$.PermissionFlag,$.PixelsPerInch,$.RenderingCancelledException,$.TextLayer,$.UnexpectedResponseException,$.Util,$.VerbosityLevel,$.XfaLayer,$.build,$.createValidAbsoluteUrl,$.fetchData;var aS=$.getDocument;$.getFilenameFromUrl,$.getPdfFilenameFromUrl,$.getXfaPageViewport,$.isDataScheme,$.isPdfFile,$.noContextMenu,$.normalizeUnicode,$.setLayerDimensions,$.shadow,$.version;const hS={fabric:"^6.3.0","pdfjs-dist":"^4.5.136"};function lS(a){return new Promise((t,e)=>{const s=new FileReader;s.onload=()=>t(s.result),s.onerror=e,s.readAsDataURL(a)})}const cS=hS["pdfjs-dist"].replace("^","");oS.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${cS}/pdf.worker.min.mjs`;async function dS(a){const t="data:application/pdf;base64,",e=await lS(a);if(typeof e=="string")return window.atob(e.slice(t.length))}function uS(a,t){return aS({data:a,password:t}).promise}const gS="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 fS(a){return new URL(Object.assign({"../assets/close.svg":gS})[`../assets/${a}`],typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Et&&Et.src||new URL("pdf-canvas.umd.js",document.baseURI).href).href}function pS(a){return new Promise((t,e)=>{const s=window.URL.createObjectURL(a),i=new Image;i.src=s,i.onload=async()=>{window.URL.revokeObjectURL(s),t(await mS(i))},i.onerror=n=>{window.URL.revokeObjectURL(s),e(n)}})}function mS(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))})}const Ad=96/72,vS={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},bS={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},yS={stroke:"#000",hoverStroke:"#B7EC5D",src:""},ss=new Map;function sv(a=""){let t=0,e=null,s=null,i=1,n={...yS};function r(){if(!a||ss.has(a))return;const D=new ng(a);return ss.set(a,D),D.on("selection:cleared",()=>P(D)),D}function o(D,L){const F=D.type;return{"application/pdf":h,"image/png":g,"image/jpeg":g}[F](D,L)??Promise.reject(new Error(`Unsupported ${F} file type.`))}async function h(D,L){const F=await dS(D);if(!F)return;const I=Date.now(),Y={PDFId:`${D.name}-${I}`,name:D.name.replace(/.pdf/,""),updateDate:I,PDFBase64:F};try{return await l({page:1,PDFBase64:F,scale:.8,password:L}),{...Y,pages:t}}catch(J){return Promise.reject(J)}}async function l({page:D,PDFBase64:L,scale:F,password:I}){try{const X=await uS(L,I),Y=await U.toRaw(X).getPage(D),J=Y.getViewport({scale:F}),W=document.createElement("canvas"),V=W.getContext("2d");W.width=Math.floor(J.width*Ad),W.height=Math.floor(J.height*Ad),t=X.numPages;const Qt={canvasContext:V,viewport:J,transform:[Ad,0,0,Ad,0,0]};return Y.render(Qt).promise.then(()=>d(W))}catch(X){return Promise.reject(X)}}function d(D){if(!ss.get(a))return;const F=1/3,I=u(D,F);p(I,F)}function u(D,L){return new ae(D,{scaleX:L,scaleY:L})}async function g(D){const L=await pS(D),F=Date.now(),X={PDFId:`${D.name}${F}`,name:D.name.replace(/.png|.jpg|.jpeg/,""),updateDate:F,PDFBase64:L};return f({url:L}),{...X,pages:1}}async function f({url:D,scale:L=.5}){if(!ss.get(a))return;const I=await ae.fromURL(D);I.scale(L),p(I,L)}function p(D,L){const F=ss.get(a);F&&(F.setWidth(D.width*L),F.setHeight(D.height*L),F.backgroundImage=D,F.renderAll())}async function m(D,L){const F=ss.get(a);if(!F)return;const I=await ae.fromURL(D,{},{...vS,...L});F.add(I),v(F,I)}function _(D,L){const F=ss.get(a);if(!F)return;const I=new oe(D,{...bS,...L});F.add(I),v(F,I)}function v(D,L){L.on("selected",F=>x({canvas:D,target:F.target})),L.on("modified",F=>T(F.target)),L.on("scaling",F=>T(F.transform.target)),L.on("moving",F=>T(F.transform.target)),L.on("rotating",F=>T(F.transform.target))}async function x({canvas:D,target:L,stroke:F=n.stroke,uuid:I=Date.now()}){if((e==null?void 0:e.stroke)===`${F}-${I}`)return;const X=n.src||fS("close.svg"),{objects:Y,options:J}=await Z_(X),W=Y.filter(Qt=>Qt!==null),V=g_.groupSVGElements(W,J);W.forEach(Qt=>{Qt.stroke=F}),V.hoverCursor="pointer",V.stroke=`${F}-${I}`,P(D),e=V,s=L,S(D,L,I),E(i,!0),D.add(V)}function S(D,L,F){e&&(e.on("selected",()=>{D.remove(L),P(D)}),e.on("mouseover",()=>{x({canvas:D,target:L,stroke:n.hoverStroke,uuid:F})}),e.on("mouseout",()=>{x({canvas:D,target:L,stroke:n.stroke,uuid:F})}))}function T(D){if(!e)return;const{oCoords:L}=D;if(!L)return;const{x:F,y:I}=L.tl.touchCorner.tl,{height:X,width:Y,scaleY:J,scaleX:W}=e;e.top=I-X*J/2,e.left=F-Y*W/2,e.setCoords()}function E(D,L=!1){var F;i=D,!(!e||!s)&&(e.scale(1/D),T(s),!L&&((F=ss.get(a))==null||F.renderAll()))}function M(D){if(!D)return;n={...n,...D};const L=ss.get(a);!e||!s||!L||x({target:s,canvas:L})}function P(D){e&&(D.remove(e),e=s=null)}function O(){const D=ss.get(a);D&&(D.discardActiveObject(),D.renderAll())}function R(){const D=ss.get(a);D&&(D.clear(),ss.delete(a))}return{createCanvas:r,loadFile:o,specifyPage:l,renderImage:f,addFabric:m,addTextFabric:_,clearActive:O,deleteCanvas:R,scaleCloseFabric:E,setCloseSvgOptions:M}}const Jg=U.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=U.ref(null),i=`${e.canvasId}-${e.page-1}`,n=U.computed(()=>e.fileZoom*e.canvasScale),{createCanvas:r,specifyPage:o,addFabric:h,addTextFabric:l,renderImage:d,clearActive:u,deleteCanvas:g,scaleCloseFabric:f,setCloseSvgOptions:p}=sv(i);m();async function m(){const{file:S,page:T,fileScale:E}=e;window.requestAnimationFrame(async()=>{if(await U.nextTick(),r(),S.PDFBase64.startsWith("data:image")||S.canvas){const{canvas:M}=S,P=M?7:3,O=M!=null&&M.length?M[T-1]:S.PDFBase64;d({url:O,scale:E/P});return}await o({page:T,PDFBase64:S.PDFBase64,scale:E,password:e.password})})}function _(S){if(!e.isDrop||!S.dataTransfer)return;const{dataTransfer:T,offsetX:E,offsetY:M}=S,P=T.getData("text"),O=T.getData("image"),R={left:E-71,top:M-55};O&&v(O,R),P&&x(P,R)}function v(S,T){h(S,{...T,...e.dropImageOptions})}function x(S,T){l(S,{...T,...e.dropTextOptions})}return U.watch([()=>e.fileScale,()=>e.page,()=>e.file,()=>e.password],m),U.watch(n,S=>f(S),{immediate:!0}),U.watch(()=>e.closeSvgOptions,p,{immediate:!0}),U.onBeforeUnmount(g),t({addImage:v,addText:x,clearActive:u,deleteCanvas:g,canvasRef:s}),(S,T)=>(U.openBlock(),U.createElementBlock("div",{style:U.normalizeStyle({transform:`scale(${n.value})`}),onDragover:T[0]||(T[0]=U.withModifiers(()=>{},["stop","prevent"])),onDragenter:T[1]||(T[1]=U.withModifiers(()=>{},["stop","prevent"])),onDrop:U.withModifiers(_,["stop","prevent"])},[U.createElementVNode("canvas",{id:i,ref_key:"canvasRef",ref:s,class:U.normalizeClass(S.canvasClass)},null,2)],36))}});Jg.install=function(a){a.component("PdfCanvas",Jg)};const Td=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));st.default=Jg,st.useFabric=sv,Object.defineProperties(st,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
505
+ `)}`),y(this,Bt,ou).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 deserialize(e,s,i){var o;let n=null;if(e instanceof $0){const{data:{defaultAppearanceData:{fontSize:h,fontColor:l},rect:d,rotation:u,id:g},textContent:f,textPosition:p,parent:{page:{pageNumber:m}}}=e;if(!f||f.length===0)return null;n=e={annotationType:nt.FREETEXT,color:Array.from(l),fontSize:h,value:f.join(`
506
+ `),position:p,pageIndex:m-1,rect:d.slice(0),rotation:u,id:g,deleted:!1}}const r=super.deserialize(e,s,i);return b(r,Ye,e.fontSize),b(r,As,z.makeHexColor(...e.color)),b(r,Ue,y(o=_t,Wi,Ff).call(o,e.value)),r.annotationElementId=e.id||null,b(r,na,n),r}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};const s=_t._internalPadding*this.parentScale,i=this.getRect(s,s),n=dt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:c(this,As)),r={annotationType:nt.FREETEXT,color:n,fontSize:c(this,Ye),value:y(this,Bt,Yv).call(this),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?r:this.annotationElementId&&!y(this,Bt,qv).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,Ye)}px * var(--scale-factor))`,i.color=c(this,As),s.replaceChildren();for(const r of c(this,Ue).split(`
507
+ `)){const o=document.createElement("div");o.append(r?document.createTextNode(r):document.createElement("br")),s.append(o)}const n=_t._internalPadding*this.parentScale;return e.updateEdited({rect:this.getRect(n,n),popupContent:c(this,Ue)}),s}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}};cl=new WeakMap,dl=new WeakMap,ul=new WeakMap,gl=new WeakMap,fl=new WeakMap,As=new WeakMap,Ue=new WeakMap,pl=new WeakMap,Ye=new WeakMap,na=new WeakMap,Bt=new WeakSet,Vv=function(e){const s=n=>{this.editorDiv.style.fontSize=`calc(${n}px * var(--scale-factor))`,this.translate(0,-(n-c(this,Ye))*this.parentScale),b(this,Ye,n),y(this,Bt,nu).call(this)},i=c(this,Ye);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Gv=function(e){const s=n=>{b(this,As,this.editorDiv.style.color=n)},i=c(this,As);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Uv=function(){var s;const e=[];this.editorDiv.normalize();for(const i of this.editorDiv.childNodes)e.push(y(s=_t,Wi,ru).call(s,i));return e.join(`
508
+ `)},nu=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()},Wi=new WeakSet,ru=function(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(wd,"")},ou=function(){if(this.editorDiv.replaceChildren(),!!c(this,Ue))for(const e of c(this,Ue).split(`
509
+ `)){const s=document.createElement("div");s.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(s)}},Yv=function(){return c(this,Ue).replaceAll(" "," ")},Ff=function(e){return e.replaceAll(" "," ")},qv=function(e){const{value:s,fontSize:i,color:n,pageIndex:r}=c(this,na);return this._hasBeenMoved||e.value!==s||e.fontSize!==i||e.color.some((o,h)=>o!==n[h])||e.pageIndex!==r},w(_t,Wi),K(_t,"_freeTextDefaultContent",""),K(_t,"_internalPadding",0),K(_t,"_defaultColor",null),K(_t,"_defaultFontSize",10),K(_t,"_type","freetext"),K(_t,"_editorType",nt.FREETEXT);let Gg=_t;class Z0{constructor(t,e=0,s=0,i=!0){w(this,Ae);w(this,ml);w(this,An,[]);w(this,Ts,[]);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:T}of t){const E=Math.floor((v-e)/d)*d,M=Math.ceil((v+S+e)/d)*d,P=Math.floor((x-e)/d)*d,O=Math.ceil((x+T+e)/d)*d,R=[E,P,O,!0],D=[M,P,O,!1];c(this,An).push(R,D),n=Math.min(n,E),r=Math.max(r,M),o=Math.min(o,P),h=Math.max(h,O)}const u=r-n+2*s,g=h-o+2*s,f=n-s,p=o-s,m=c(this,An).at(i?-1:-2),_=[m[0],m[2]];for(const v of c(this,An)){const[x,S,T]=v;v[0]=(x-f)/u,v[1]=(S-p)/g,v[2]=(T-p)/g}b(this,ml,{x:f,y:p,width:u,height:g,lastPoint:_})}getOutlines(){c(this,An).sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of c(this,An))e[3]?(t.push(...y(this,Ae,Rf).call(this,e)),y(this,Ae,Kv).call(this,e)):(y(this,Ae,Qv).call(this,e),t.push(...y(this,Ae,Rf).call(this,e)));return y(this,Ae,$v).call(this,t)}}ml=new WeakMap,An=new WeakMap,Ts=new WeakMap,Ae=new WeakSet,$v=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 rS(i,c(this,ml))},au=function(t){const e=c(this,Ts);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},Kv=function([,t,e]){const s=y(this,Ae,au).call(this,t);c(this,Ts).splice(s,0,[t,e])},Qv=function([,t,e]){const s=y(this,Ae,au).call(this,t);for(let i=s;i<c(this,Ts).length;i++){const[n,r]=c(this,Ts)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ts).splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=c(this,Ts)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ts).splice(i,1);return}}},Rf=function(t){const[e,s,i]=t,n=[[e,s,i]],r=y(this,Ae,au).call(this,i);for(let o=0;o<r;o++){const[h,l]=c(this,Ts)[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 tv{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 Ug}}class rS extends tv{constructor(e,s){super();w(this,vl);w(this,ra);b(this,ra,e),b(this,vl,s)}toSVGPath(){const e=[];for(const s of c(this,ra)){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,ra)){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,vl)}}vl=new WeakMap,ra=new WeakMap;const zi=class zi{constructor({x:t,y:e},s,i,n,r,o=0){w(this,wl);w(this,Zs);w(this,Xi,[]);w(this,oa);w(this,aa);w(this,ti,[]);w(this,rt,new Float64Array(18));w(this,Xr);w(this,zr);w(this,bl);w(this,yl);w(this,ha);w(this,la);w(this,Tn,[]);b(this,Zs,s),b(this,la,n*i),b(this,aa,r),c(this,rt).set([NaN,NaN,NaN,NaN,t,e],6),b(this,oa,o),b(this,yl,c(zi,_l)*i),b(this,bl,c(zi,zd)*i),b(this,ha,i),c(this,Tn).push(t,e)}get free(){return!0}isEmpty(){return isNaN(c(this,rt)[8])}add({x:t,y:e}){var R;b(this,Xr,t),b(this,zr,e);const[s,i,n,r]=c(this,Zs);let[o,h,l,d]=c(this,rt).subarray(8,12);const u=t-l,g=e-d,f=Math.hypot(u,g);if(f<c(this,bl))return!1;const p=f-c(this,yl),m=p/f,_=m*u,v=m*g;let x=o,S=h;o=l,h=d,l+=_,d+=v,(R=c(this,Tn))==null||R.push(t,e);const T=-v/p,E=_/p,M=T*c(this,la),P=E*c(this,la);return c(this,rt).set(c(this,rt).subarray(2,8),0),c(this,rt).set([l+M,d+P],4),c(this,rt).set(c(this,rt).subarray(14,18),12),c(this,rt).set([l-M,d-P],16),isNaN(c(this,rt)[6])?(c(this,ti).length===0&&(c(this,rt).set([o+M,h+P],2),c(this,ti).push(NaN,NaN,NaN,NaN,(o+M-s)/n,(h+P-i)/r),c(this,rt).set([o-M,h-P],14),c(this,Xi).push(NaN,NaN,NaN,NaN,(o-M-s)/n,(h-P-i)/r)),c(this,rt).set([x,S,o,h,l,d],6),!this.isEmpty()):(c(this,rt).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,rt).subarray(2,6),c(this,ti).push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+d)/2-i)/r),[o,h,x,S]=c(this,rt).subarray(14,18),c(this,Xi).push(NaN,NaN,NaN,NaN,((x+o)/2-s)/n,((S+h)/2-i)/r),!0):([x,S,o,h,l,d]=c(this,rt).subarray(0,6),c(this,ti).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,rt).subarray(12,18),c(this,Xi).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,ti),e=c(this,Xi),s=c(this,rt).subarray(4,6),i=c(this,rt).subarray(16,18),[n,r,o,h]=c(this,Zs),[l,d,u,g]=y(this,wl,If).call(this);if(isNaN(c(this,rt)[6])&&!this.isEmpty())return`M${(c(this,rt)[2]-n)/o} ${(c(this,rt)[3]-r)/h} L${(c(this,rt)[4]-n)/o} ${(c(this,rt)[5]-r)/h} L${l} ${d} L${u} ${g} L${(c(this,rt)[16]-n)/o} ${(c(this,rt)[17]-r)/h} L${(c(this,rt)[14]-n)/o} ${(c(this,rt)[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,ti),e=c(this,Xi),s=c(this,rt),i=s.subarray(4,6),n=s.subarray(16,18),[r,o,h,l]=c(this,Zs),d=new Float64Array((((v=c(this,Tn))==null?void 0:v.length)??0)+2);for(let x=0,S=d.length-2;x<S;x+=2)d[x]=(c(this,Tn)[x]-r)/h,d[x+1]=(c(this,Tn)[x+1]-o)/l;d[d.length-2]=(c(this,Xr)-r)/h,d[d.length-1]=(c(this,zr)-o)/l;const[u,g,f,p]=y(this,wl,If).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 Ug(x,d,c(this,Zs),c(this,ha),c(this,oa),c(this,aa))}const m=new Float64Array(c(this,ti).length+24+c(this,Xi).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 Ug(m,d,c(this,Zs),c(this,ha),c(this,oa),c(this,aa))}};Zs=new WeakMap,Xi=new WeakMap,oa=new WeakMap,aa=new WeakMap,ti=new WeakMap,rt=new WeakMap,Xr=new WeakMap,zr=new WeakMap,bl=new WeakMap,yl=new WeakMap,ha=new WeakMap,la=new WeakMap,Tn=new WeakMap,_l=new WeakMap,Xd=new WeakMap,zd=new WeakMap,wl=new WeakSet,If=function(){const t=c(this,rt).subarray(4,6),e=c(this,rt).subarray(16,18),[s,i,n,r]=c(this,Zs);return[(c(this,Xr)+(t[0]-e[0])/2-s)/n,(c(this,zr)+(t[1]-e[1])/2-i)/r,(c(this,Xr)+(e[0]-t[0])/2-s)/n,(c(this,zr)+(e[1]-t[1])/2-i)/r]},w(zi,_l,8),w(zi,Xd,2),w(zi,zd,c(zi,_l)+c(zi,Xd));let xd=zi;class Ug extends tv{constructor(e,s,i,n,r,o){super();w(this,Re);w(this,ca);w(this,Vr,null);w(this,Vi);w(this,xl);w(this,qe);w(this,Sl);w(this,Rt);b(this,Rt,e),b(this,qe,s),b(this,ca,i),b(this,Sl,n),b(this,Vi,r),b(this,xl,o),y(this,Re,Jv).call(this,o);const{x:h,y:l,width:d,height:u}=c(this,Vr);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,Rt)[4]} ${c(this,Rt)[5]}`];for(let s=6,i=c(this,Rt).length;s<i;s+=6){if(isNaN(c(this,Rt)[s])){e.push(`L${c(this,Rt)[s+4]} ${c(this,Rt)[s+5]}`);continue}e.push(`C${c(this,Rt)[s]} ${c(this,Rt)[s+1]} ${c(this,Rt)[s+2]} ${c(this,Rt)[s+3]} ${c(this,Rt)[s+4]} ${c(this,Rt)[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,Re,Yl).call(this,c(this,Rt),e,n,o,-h),d=y(this,Re,Yl).call(this,c(this,qe),e,n,o,-h);break;case 90:l=y(this,Re,ql).call(this,c(this,Rt),e,s,o,h),d=y(this,Re,ql).call(this,c(this,qe),e,s,o,h);break;case 180:l=y(this,Re,Yl).call(this,c(this,Rt),i,s,-o,h),d=y(this,Re,Yl).call(this,c(this,qe),i,s,-o,h);break;case 270:l=y(this,Re,ql).call(this,c(this,Rt),i,n,-o,-h),d=y(this,Re,ql).call(this,c(this,qe),i,n,-o,-h);break}return{outline:Array.from(l),points:[Array.from(d)]}}get box(){return c(this,Vr)}getNewOutline(e,s){const{x:i,y:n,width:r,height:o}=c(this,Vr),[h,l,d,u]=c(this,ca),g=r*d,f=o*u,p=i*d+h,m=n*u+l,_=new xd({x:c(this,qe)[0]*g+p,y:c(this,qe)[1]*f+m},c(this,ca),c(this,Sl),e,c(this,xl),s??c(this,Vi));for(let v=2;v<c(this,qe).length;v+=2)_.add({x:c(this,qe)[v]*g+p,y:c(this,qe)[v+1]*f+m});return _.getOutlines()}}ca=new WeakMap,Vr=new WeakMap,Vi=new WeakMap,xl=new WeakMap,qe=new WeakMap,Sl=new WeakMap,Rt=new WeakMap,Re=new WeakSet,Yl=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},ql=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},Jv=function(e){const s=c(this,Rt);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=z.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,Vi),p=o-c(this,Vi),m=h-r+2*c(this,Vi),_=l-o+2*c(this,Vi);b(this,Vr,{x:f,y:p,width:m,height:_,lastPoint:[d,u]})};const Gi=class Gi{constructor({editor:t=null,uiManager:e=null}){w(this,yt);w(this,Cl,y(this,yt,Zv).bind(this));w(this,Al,y(this,yt,tb).bind(this));w(this,Es,null);w(this,Gr,null);w(this,da);w(this,Vt,null);w(this,Tl,!1);w(this,ua,!1);w(this,El,null);w(this,kl);w(this,ks,null);w(this,ga);var s;t?(b(this,ua,!1),b(this,ga,q.HIGHLIGHT_COLOR),b(this,El,t)):(b(this,ua,!0),b(this,ga,q.HIGHLIGHT_DEFAULT_COLOR)),b(this,ks,(t==null?void 0:t._uiManager)||e),b(this,kl,c(this,ks)._eventBus),b(this,da,(t==null?void 0:t.color)||((s=c(this,ks))==null?void 0:s.highlightColors.values().next().value)||"#FFFF98")}static get _keyboardManager(){return at(this,"_keyboardManager",new Qa([[["Escape","mac+Escape"],Gi.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],Gi.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],Gi.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],Gi.prototype._moveToPrevious],[["Home","mac+Home"],Gi.prototype._moveToBeginning],[["End","mac+End"],Gi.prototype._moveToEnd]]))}renderButton(){const t=b(this,Es,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,ks)._signal;t.addEventListener("click",y(this,yt,oo).bind(this),{signal:e}),t.addEventListener("keydown",c(this,Cl),{signal:e});const s=b(this,Gr,document.createElement("span"));return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=c(this,da),t.append(s),t}renderMainDropdown(){const t=b(this,Vt,y(this,yt,jf).call(this));return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}_colorSelectFromKeyboard(t){if(t.target===c(this,Es)){y(this,yt,oo).call(this,t);return}const e=t.target.getAttribute("data-color");e&&y(this,yt,Nf).call(this,e,t)}_moveToNext(t){var e,s;if(!c(this,yt,In)){y(this,yt,oo).call(this,t);return}if(t.target===c(this,Es)){(e=c(this,Vt).firstChild)==null||e.focus();return}(s=t.target.nextSibling)==null||s.focus()}_moveToPrevious(t){var e,s;if(t.target===((e=c(this,Vt))==null?void 0:e.firstChild)||t.target===c(this,Es)){c(this,yt,In)&&this._hideDropdownFromKeyboard();return}c(this,yt,In)||y(this,yt,oo).call(this,t),(s=t.target.previousSibling)==null||s.focus()}_moveToBeginning(t){var e;if(!c(this,yt,In)){y(this,yt,oo).call(this,t);return}(e=c(this,Vt).firstChild)==null||e.focus()}_moveToEnd(t){var e;if(!c(this,yt,In)){y(this,yt,oo).call(this,t);return}(e=c(this,Vt).lastChild)==null||e.focus()}hideDropdown(){var t;(t=c(this,Vt))==null||t.classList.add("hidden"),window.removeEventListener("pointerdown",c(this,Al))}_hideDropdownFromKeyboard(){var t;if(!c(this,ua)){if(!c(this,yt,In)){(t=c(this,El))==null||t.unselect();return}this.hideDropdown(),c(this,Es).focus({preventScroll:!0,focusVisible:c(this,Tl)})}}updateColor(t){if(c(this,Gr)&&(c(this,Gr).style.backgroundColor=t),!c(this,Vt))return;const e=c(this,ks).highlightColors.values();for(const s of c(this,Vt).children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){var t,e;(t=c(this,Es))==null||t.remove(),b(this,Es,null),b(this,Gr,null),(e=c(this,Vt))==null||e.remove(),b(this,Vt,null)}};Cl=new WeakMap,Al=new WeakMap,Es=new WeakMap,Gr=new WeakMap,da=new WeakMap,Vt=new WeakMap,Tl=new WeakMap,ua=new WeakMap,El=new WeakMap,kl=new WeakMap,ks=new WeakMap,ga=new WeakMap,yt=new WeakSet,jf=function(){const t=document.createElement("div"),e=c(this,ks)._signal;t.addEventListener("contextmenu",Oe,{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,ks).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",`pdfjs-editor-colorpicker-${s}`);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===c(this,da)),n.addEventListener("click",y(this,yt,Nf).bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",c(this,Cl),{signal:e}),t},Nf=function(t,e){e.stopPropagation(),c(this,kl).dispatch("switchannotationeditorparams",{source:this,type:c(this,ga),value:t})},Zv=function(t){Gi._keyboardManager.exec(this,t)},oo=function(t){if(c(this,yt,In)){this.hideDropdown();return}if(b(this,Tl,t.detail===0),window.addEventListener("pointerdown",c(this,Al),{signal:c(this,ks)._signal}),c(this,Vt)){c(this,Vt).classList.remove("hidden");return}const e=b(this,Vt,y(this,yt,jf).call(this));c(this,Es).append(e)},tb=function(t){var e;(e=c(this,Vt))!=null&&e.contains(t.target)||this.hideDropdown()},In=function(){return c(this,Vt)&&!c(this,Vt).classList.contains("hidden")};let Sd=Gi;const lt=class lt extends dt{constructor(e){super({...e,name:"highlightEditor"});w(this,et);w(this,fa,null);w(this,Ml,0);w(this,En);w(this,Ur,null);w(this,pa,null);w(this,os,null);w(this,Dl,null);w(this,Ol,0);w(this,Yr,null);w(this,Ms,null);w(this,Te,null);w(this,$e,!1);w(this,Vd,y(this,et,nb).bind(this));w(this,ma,null);w(this,qr);w(this,Gt,null);w(this,va,"");w(this,ei);w(this,Pl,"");this.color=e.color||lt._defaultColor,b(this,ei,e.thickness||lt._defaultThickness),b(this,qr,e.opacity||lt._defaultOpacity),b(this,En,e.boxes||null),b(this,Pl,e.methodOfCreation||""),b(this,va,e.text||""),this._isDraggable=!1,e.highlightId>-1?(b(this,$e,!0),y(this,et,Hf).call(this,e),y(this,et,$l).call(this)):(b(this,fa,e.anchorNode),b(this,Ml,e.anchorOffset),b(this,Dl,e.focusNode),b(this,Ol,e.focusOffset),y(this,et,Bf).call(this),y(this,et,$l).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const e=lt.prototype;return at(this,"_keyboardManager",new Qa([[["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,$e)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:c(this,ei),methodOfCreation:c(this,Pl)}}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;dt.initialize(e,s),lt._defaultColor||(lt._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(e,s){switch(e){case q.HIGHLIGHT_DEFAULT_COLOR:lt._defaultColor=s;break;case q.HIGHLIGHT_THICKNESS:lt._defaultThickness=s;break}}translateInPage(e,s){}get toolbarPosition(){return c(this,ma)}updateParams(e,s){switch(e){case q.HIGHLIGHT_COLOR:y(this,et,eb).call(this,s);break;case q.HIGHLIGHT_THICKNESS:y(this,et,sb).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[q.HIGHLIGHT_DEFAULT_COLOR,lt._defaultColor],[q.HIGHLIGHT_THICKNESS,lt._defaultThickness]]}get propertiesToUpdate(){return[[q.HIGHLIGHT_COLOR,this.color||lt._defaultColor],[q.HIGHLIGHT_THICKNESS,c(this,ei)||lt._defaultThickness],[q.HIGHLIGHT_FREE,c(this,$e)]]}async addEditToolbar(){const e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(b(this,pa,new Sd({editor:this})),e.addColorPicker(c(this,pa))),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,et,Kl).call(this))}getBaseTranslation(){return[0,0]}getRect(e,s){return super.getRect(e,s,y(this,et,Kl).call(this))}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){y(this,et,Wf).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(y(this,et,$l).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?y(this,et,Wf).call(this):e&&(y(this,et,$l).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,$e)?(e=(e-this.rotation+360)%360,i=y(n=lt,as,ka).call(n,c(this,Ms).box,e)):i=y(r=lt,as,ka).call(r,this,e),s.rotate(c(this,Te),e),s.rotate(c(this,Gt),e),s.updateBox(c(this,Te),i),s.updateBox(c(this,Gt),y(o=lt,as,ka).call(o,c(this,os).box,e))}render(){if(this.div)return this.div;const e=super.render();c(this,va)&&(e.setAttribute("aria-label",c(this,va)),e.setAttribute("role","mark")),c(this,$e)?e.classList.add("free"):this.div.addEventListener("keydown",c(this,Vd),{signal:this._uiManager._signal});const s=b(this,Yr,document.createElement("div"));e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=c(this,Ur);const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),gd(this,c(this,Yr),["pointerover","pointerleave"]),this.enableEditing(),e}pointerover(){this.parent.drawLayer.addClass(c(this,Gt),"hovered")}pointerleave(){this.parent.drawLayer.removeClass(c(this,Gt),"hovered")}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:y(this,et,hu).call(this,!0);break;case 1:case 3:y(this,et,hu).call(this,!1);break}}select(){var e,s;super.select(),c(this,Gt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Gt),"hovered"),(s=this.parent)==null||s.drawLayer.addClass(c(this,Gt),"selected"))}unselect(){var e;super.unselect(),c(this,Gt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Gt),"selected"),c(this,$e)||y(this,et,hu).call(this,!1))}get _mustFixPosition(){return!c(this,$e)}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.show(c(this,Te),e),this.parent.drawLayer.show(c(this,Gt),e))}static startHighlighting(e,s,{target:i,x:n,y:r}){const{x:o,y:h,width:l,height:d}=i.getBoundingClientRect(),u=_=>{y(this,as,ab).call(this,e,_)},g=e._signal,f={capture:!0,passive:!1,signal:g},p=_=>{_.preventDefault(),_.stopPropagation()},m=_=>{i.removeEventListener("pointermove",u),window.removeEventListener("blur",m),window.removeEventListener("pointerup",m),window.removeEventListener("pointerdown",p,f),window.removeEventListener("contextmenu",Oe),y(this,as,hb).call(this,e,_)};window.addEventListener("blur",m,{signal:g}),window.addEventListener("pointerup",m,{signal:g}),window.addEventListener("pointerdown",p,f),window.addEventListener("contextmenu",Oe,{signal:g}),i.addEventListener("pointermove",u,{signal:g}),this._freeHighlight=new xd({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 deserialize(e,s,i){var m;const n=super.deserialize(e,s,i),{rect:[r,o,h,l],color:d,quadPoints:u}=e;n.color=z.makeHexColor(...d),b(n,qr,e.opacity);const[g,f]=n.pageDimensions;n.width=(h-r)/g,n.height=(l-o)/f;const p=b(n,En,[]);for(let _=0;_<u.length;_+=8)p.push({x:(u[4]-h)/g,y:(l-(1-u[_+5]))/f,width:(u[_+2]-u[_])/g,height:(u[_+5]-u[_+1])/f});return y(m=n,et,Bf).call(m),n}serialize(e=!1){if(this.isEmpty()||e)return null;const s=this.getRect(0,0),i=dt._colorManager.convert(this.color);return{annotationType:nt.HIGHLIGHT,color:i,opacity:c(this,qr),thickness:c(this,ei),quadPoints:y(this,et,rb).call(this),outlines:y(this,et,ob).call(this,s),pageIndex:this.pageIndex,rect:s,rotation:y(this,et,Kl).call(this),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}};fa=new WeakMap,Ml=new WeakMap,En=new WeakMap,Ur=new WeakMap,pa=new WeakMap,os=new WeakMap,Dl=new WeakMap,Ol=new WeakMap,Yr=new WeakMap,Ms=new WeakMap,Te=new WeakMap,$e=new WeakMap,Vd=new WeakMap,ma=new WeakMap,qr=new WeakMap,Gt=new WeakMap,va=new WeakMap,ei=new WeakMap,Pl=new WeakMap,et=new WeakSet,Bf=function(){const e=new Z0(c(this,En),.001);b(this,Ms,e.getOutlines()),{x:this.x,y:this.y,width:this.width,height:this.height}=c(this,Ms).box;const s=new Z0(c(this,En),.0025,.001,this._uiManager.direction==="ltr");b(this,os,s.getOutlines());const{lastPoint:i}=c(this,os).box;b(this,ma,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height])},Hf=function({highlightOutlines:e,highlightId:s,clipPathId:i}){var u,g;if(b(this,Ms,e),b(this,os,e.getNewOutline(c(this,ei)/2+1.5,.0025)),s>=0)b(this,Te,s),b(this,Ur,i),this.parent.drawLayer.finalizeLine(s,e),b(this,Gt,this.parent.drawLayer.highlightOutline(c(this,os)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(c(this,Te),e),this.parent.drawLayer.updateBox(c(this,Te),y(u=lt,as,ka).call(u,c(this,Ms).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(c(this,Gt),c(this,os)),this.parent.drawLayer.updateBox(c(this,Gt),y(g=lt,as,ka).call(g,c(this,os).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,os).box;b(this,ma,[(d[0]-r)/h,(d[1]-o)/l])},eb=function(e){const s=n=>{var r,o;this.color=n,(r=this.parent)==null||r.drawLayer.changeColor(c(this,Te),n),(o=c(this,pa))==null||o.updateColor(n)},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:q.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(e)},!0)},sb=function(e){const s=c(this,ei),i=n=>{b(this,ei,n),y(this,et,ib).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:q.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:e},!0)},ib=function(e){if(!c(this,$e))return;y(this,et,Hf).call(this,{highlightOutlines:c(this,Ms).getNewOutline(e/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},Wf=function(){c(this,Te)===null||!this.parent||(this.parent.drawLayer.remove(c(this,Te)),b(this,Te,null),this.parent.drawLayer.remove(c(this,Gt)),b(this,Gt,null))},$l=function(e=this.parent){c(this,Te)===null&&({id:Je(this,Te)._,clipPathId:Je(this,Ur)._}=e.drawLayer.highlight(c(this,Ms),this.color,c(this,qr)),b(this,Gt,e.drawLayer.highlightOutline(c(this,os))),c(this,Yr)&&(c(this,Yr).style.clipPath=c(this,Ur)))},as=new WeakSet,ka=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}},nb=function(e){lt._keyboardManager.exec(this,e)},hu=function(e){if(!c(this,fa))return;const s=window.getSelection();e?s.setPosition(c(this,fa),c(this,Ml)):s.setPosition(c(this,Dl),c(this,Ol))},Kl=function(){return c(this,$e)?this.rotation:0},rb=function(){if(c(this,$e))return null;const[e,s]=this.pageDimensions,[i,n]=this.pageTranslation,r=c(this,En),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},ob=function(e){return c(this,Ms).serialize(e,y(this,et,Kl).call(this))},ab=function(e,s){this._freeHighlight.add(s)&&e.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},hb=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=""},w(lt,as),K(lt,"_defaultColor",null),K(lt,"_defaultOpacity",1),K(lt,"_defaultThickness",12),K(lt,"_l10nPromise"),K(lt,"_type","highlight"),K(lt,"_editorType",nt.HIGHLIGHT),K(lt,"_freeHighlightId",-1),K(lt,"_freeHighlight",null),K(lt,"_freeHighlightClipId","");let Cd=lt;const At=class At extends dt{constructor(e){super({...e,name:"inkEditor"});w(this,N);w(this,$r,0);w(this,Kr,0);w(this,Ll,this.canvasPointermove.bind(this));w(this,Fl,this.canvasPointerleave.bind(this));w(this,Rl,this.canvasPointerup.bind(this));w(this,Qr,this.canvasPointerdown.bind(this));w(this,si,null);w(this,Ui,new Path2D);w(this,hs,!1);w(this,Jr,!1);w(this,Zr,!1);w(this,Yi,null);w(this,to,0);w(this,eo,0);w(this,kn,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){dt.initialize(e,s)}static updateDefaultParams(e,s){switch(e){case q.INK_THICKNESS:At._defaultThickness=s;break;case q.INK_COLOR:At._defaultColor=s;break;case q.INK_OPACITY:At._defaultOpacity=s/100;break}}updateParams(e,s){switch(e){case q.INK_THICKNESS:y(this,N,lb).call(this,s);break;case q.INK_COLOR:y(this,N,cb).call(this,s);break;case q.INK_OPACITY:y(this,N,db).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[q.INK_THICKNESS,At._defaultThickness],[q.INK_COLOR,At._defaultColor||dt._defaultLineColor],[q.INK_OPACITY,Math.round(At._defaultOpacity*100)]]}get propertiesToUpdate(){return[[q.INK_THICKNESS,this.thickness||At._defaultThickness],[q.INK_COLOR,this.color||At._defaultColor||dt._defaultLineColor],[q.INK_OPACITY,Math.round(100*(this.opacity??At._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(y(this,N,lu).call(this),y(this,N,cu).call(this)),this.isAttachedToDOM||(this.parent.add(this),y(this,N,Ma).call(this)),y(this,N,Ql).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,si)&&(clearTimeout(c(this,si)),b(this,si,null)),(e=c(this,Yi))==null||e.disconnect(),b(this,Yi,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,hs)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",c(this,Qr),{signal:this._uiManager._signal}))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",c(this,Qr)))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){c(this,hs)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),b(this,hs,!0),this.div.classList.add("disabled"),y(this,N,Ql).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,hs)||(this.setInForeground(),e.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),y(this,N,gb).call(this,e.offsetX,e.offsetY))}canvasPointermove(e){e.preventDefault(),y(this,N,zf).call(this,e.offsetX,e.offsetY)}canvasPointerup(e){e.preventDefault(),y(this,N,Vf).call(this,e)}canvasPointerleave(e){y(this,N,Vf).call(this,e)}get isResizable(){return!this.isEmpty()&&c(this,hs)}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,N,ub).call(this);if(this.setAt(i,n,0,0),this.setDims(r,o),y(this,N,lu).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,Zr,!0),y(this,N,Ma).call(this),this.setDims(this.width*h,this.height*l),y(this,N,ao).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return y(this,N,cu).call(this),this.div}setDimensions(e,s){const i=Math.round(e),n=Math.round(s);if(c(this,to)===i&&c(this,eo)===n)return;b(this,to,i),b(this,eo,n),this.canvas.style.visibility="hidden";const[r,o]=this.parentDimensions;this.width=e/r,this.height=s/o,this.fixAndSetPosition(),c(this,hs)&&y(this,N,Gf).call(this,e,s),y(this,N,Ma).call(this),y(this,N,ao).call(this),this.canvas.style.visibility="visible",this.fixDims()}static deserialize(e,s,i){var _,v,x;if(e instanceof Q0)return null;const n=super.deserialize(e,s,i);n.thickness=e.thickness,n.color=z.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,hs,!0),b(n,to,Math.round(h)),b(n,eo,Math.round(l));const{paths:g,rect:f,rotation:p}=e;for(let{bezier:S}of g){S=y(_=At,qi,_b).call(_,S,f,p);const T=[];n.paths.push(T);let E=d*(S[0]-u),M=d*(S[1]-u);for(let O=2,R=S.length;O<R;O+=6){const D=d*(S[O]-u),L=d*(S[O+1]-u),F=d*(S[O+2]-u),I=d*(S[O+3]-u),X=d*(S[O+4]-u),Y=d*(S[O+5]-u);T.push([[E,M],[D,L],[F,I],[X,Y]]),E=X,M=Y}const P=y(this,qi,yb).call(this,T);n.bezierPath2D.push(P)}const m=y(v=n,N,Yf).call(v);return b(n,Kr,Math.max(dt.MIN_SIZE,m[2]-m[0])),b(n,$r,Math.max(dt.MIN_SIZE,m[3]-m[1])),y(x=n,N,Gf).call(x,h,l),n}serialize(){if(this.isEmpty())return null;const e=this.getRect(0,0),s=dt._colorManager.convert(this.ctx.strokeStyle);return{annotationType:nt.INK,color:s,thickness:this.thickness,opacity:this.opacity,paths:y(this,N,wb).call(this,this.scaleFactor/this.parentScale,this.translationX,this.translationY,e),pageIndex:this.pageIndex,rect:e,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}};$r=new WeakMap,Kr=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,Rl=new WeakMap,Qr=new WeakMap,si=new WeakMap,Ui=new WeakMap,hs=new WeakMap,Jr=new WeakMap,Zr=new WeakMap,Yi=new WeakMap,to=new WeakMap,eo=new WeakMap,kn=new WeakMap,N=new WeakSet,lb=function(e){const s=n=>{this.thickness=n,y(this,N,Ql).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:q.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},cb=function(e){const s=n=>{this.color=n,y(this,N,ao).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:q.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},db=function(e){const s=n=>{this.opacity=n,y(this,N,ao).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:q.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},ub=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]}},Xf=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}${Ow(i)}`},gb=function(e,s){const i=this._uiManager._signal;this.canvas.addEventListener("contextmenu",Oe,{signal:i}),this.canvas.addEventListener("pointerleave",c(this,Fl),{signal:i}),this.canvas.addEventListener("pointermove",c(this,Ll),{signal:i}),this.canvas.addEventListener("pointerup",c(this,Rl),{signal:i}),this.canvas.removeEventListener("pointerdown",c(this,Qr)),this.isEditing=!0,c(this,Zr)||(b(this,Zr,!0),y(this,N,Ma).call(this),this.thickness||(this.thickness=At._defaultThickness),this.color||(this.color=At._defaultColor||dt._defaultLineColor),this.opacity??(this.opacity=At._defaultOpacity)),this.currentPath.push([e,s]),b(this,Jr,!1),y(this,N,Xf).call(this),b(this,kn,()=>{y(this,N,mb).call(this),c(this,kn)&&window.requestAnimationFrame(c(this,kn))}),window.requestAnimationFrame(c(this,kn))},zf=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,Ui);if(r.push([e,s]),b(this,Jr,!0),r.length<=2){o.moveTo(...r[0]),o.lineTo(e,s);return}r.length===3&&(b(this,Ui,o=new Path2D),o.moveTo(...r[0])),y(this,N,vb).call(this,o,...r.at(-3),...r.at(-2),e,s)},fb=function(){if(this.currentPath.length===0)return;const e=this.currentPath.at(-1);c(this,Ui).lineTo(...e)},pb=function(e,s){b(this,kn,null),e=Math.min(Math.max(e,0),this.canvas.width),s=Math.min(Math.max(s,0),this.canvas.height),y(this,N,zf).call(this,e,s),y(this,N,fb).call(this);let i;if(this.currentPath.length!==1)i=y(this,N,bb).call(this);else{const l=[e,s];i=[[l,l.slice(),l.slice(),l]]}const n=c(this,Ui),r=this.currentPath;this.currentPath=[],b(this,Ui,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,N,lu).call(this),y(this,N,cu).call(this)),y(this,N,Ql).call(this))};this.addCommands({cmd:o,undo:h,mustExec:!0})},mb=function(){if(!c(this,Jr))return;b(this,Jr,!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,Ui)),r.restore()},vb=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)},bb=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],T=[v+2*(f-v)/3,x+2*(p-x)/3];s.push([[n,r],S,T,[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},ao=function(){if(this.isEmpty()){y(this,N,du).call(this);return}y(this,N,Xf).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,N,du).call(this);for(const i of this.bezierPath2D)s.stroke(i)},Vf=function(e){this.canvas.removeEventListener("pointerleave",c(this,Fl)),this.canvas.removeEventListener("pointermove",c(this,Ll)),this.canvas.removeEventListener("pointerup",c(this,Rl)),this.canvas.addEventListener("pointerdown",c(this,Qr),{signal:this._uiManager._signal}),c(this,si)&&clearTimeout(c(this,si)),b(this,si,setTimeout(()=>{b(this,si,null),this.canvas.removeEventListener("contextmenu",Oe)},10)),y(this,N,pb).call(this,e.offsetX,e.offsetY),this.addToAnnotationStorage(),this.setInBackground()},lu=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")},cu=function(){b(this,Yi,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&this.setDimensions(s.width,s.height)})),c(this,Yi).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,Yi))==null||e.disconnect(),b(this,Yi,null)},{once:!0})},Ma=function(){if(!c(this,Zr))return;const[e,s]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*e),this.canvas.height=Math.ceil(this.height*s),y(this,N,du).call(this)},Gf=function(e,s){const i=y(this,N,uu).call(this),n=(e-i)/c(this,Kr),r=(s-i)/c(this,$r);this.scaleFactor=Math.min(n,r)},du=function(){const e=y(this,N,uu).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,yb=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},Uf=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},_b=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},wb=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,T]=g[m];if(v[0]===T[0]&&v[1]===T[1]&&_===1){const I=e*v[0]+h,X=e*v[1]+l;f.push(I,X),p.push(I,X);break}const E=e*v[0]+h,M=e*v[1]+l,P=e*x[0]+h,O=e*x[1]+l,R=e*S[0]+h,D=e*S[1]+l,L=e*T[0]+h,F=e*T[1]+l;m===0&&(f.push(E,M),p.push(E,M)),f.push(P,O,R,D,L,F),p.push(P,O),m===_-1&&p.push(L,F)}r.push({bezier:y(d=At,qi,Uf).call(d,f,n,this.rotation),points:y(u=At,qi,Uf).call(u,p,n,this.rotation)})}return r},Yf=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=z.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]},uu=function(){return c(this,hs)?Math.ceil(this.thickness*this.parentScale):0},Ql=function(e=!1){if(this.isEmpty())return;if(!c(this,hs)){y(this,N,ao).call(this);return}const s=y(this,N,Yf).call(this),i=y(this,N,uu).call(this);b(this,Kr,Math.max(dt.MIN_SIZE,s[2]-s[0])),b(this,$r,Math.max(dt.MIN_SIZE,s[3]-s[1]));const n=Math.ceil(i+c(this,Kr)*this.scaleFactor),r=Math.ceil(i+c(this,$r)*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,N,Ma).call(this),y(this,N,ao).call(this),b(this,to,n),b(this,eo,r),this.setDims(n,r);const u=e?i/this.scaleFactor/2:0;this.translate(l-this.translationX-u,d-this.translationY-u)},w(At,qi),K(At,"_defaultColor",null),K(At,"_defaultOpacity",1),K(At,"_defaultThickness",1),K(At,"_type","ink"),K(At,"_editorType",nt.INK);let Yg=At;const Nl=class Nl extends dt{constructor(e){super({...e,name:"stampEditor"});w(this,ht);w(this,te,null);w(this,ee,null);w(this,Mn,null);w(this,$i,null);w(this,Dn,null);w(this,ba,"");w(this,ii,null);w(this,Il,!1);w(this,Ki,null);w(this,ni,null);w(this,Ds,!1);w(this,jl,!1);b(this,$i,e.bitmapUrl),b(this,Dn,e.bitmapFile)}static initialize(e,s){dt.initialize(e,s)}static get supportedTypes(){return at(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(s=>`image/${s}`))}static get supportedTypesStr(){return at(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,s){s.pasteEditor(nt.STAMP,{bitmapFile:e.getAsFile()})}remove(){var e,s;c(this,ee)&&(b(this,te,null),this._uiManager.imageManager.deleteId(c(this,ee)),(e=c(this,ii))==null||e.remove(),b(this,ii,null),(s=c(this,Ki))==null||s.disconnect(),b(this,Ki,null),c(this,ni)&&(clearTimeout(c(this,ni)),b(this,ni,null))),super.remove()}rebuild(){if(!this.parent){c(this,ee)&&y(this,ht,gu).call(this);return}super.rebuild(),this.div!==null&&(c(this,ee)&&c(this,ii)===null&&y(this,ht,gu).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(c(this,Mn)||c(this,te)||c(this,$i)||c(this,Dn)||c(this,ee))}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.addAltTextButton(),c(this,te)?y(this,ht,qf).call(this):y(this,ht,gu).call(this),this.width){const[i,n]=this.parentDimensions;this.setAt(e*i,s*n,this.width*i,this.height*n)}return this.div}getImageForAltText(){return c(this,ii)}static deserialize(e,s,i){if(e instanceof J0)return null;const n=super.deserialize(e,s,i),{rect:r,bitmapUrl:o,bitmapId:h,isSvg:l,accessibilityData:d}=e;h&&i.imageManager.isValidId(h)?b(n,ee,h):b(n,$i,o),b(n,Ds,l);const[u,g]=n.pageDimensions;return n.width=(r[2]-r[0])/u,n.height=(r[3]-r[1])/g,d&&(n.altTextData=d),n}serialize(e=!1,s=null){if(this.isEmpty())return null;const i={annotationType:nt.STAMP,bitmapId:c(this,ee),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:c(this,Ds),structTreeParentId:this._structTreeParentId};if(e)return i.bitmapUrl=y(this,ht,fu).call(this,!0),i.accessibilityData=this.altTextData,i;const{decorative:n,altText:r}=this.altTextData;if(!n&&r&&(i.accessibilityData={type:"Figure",alt:r}),s===null)return i;s.stamps||(s.stamps=new Map);const o=c(this,Ds)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(c(this,ee)))s.stamps.set(c(this,ee),{area:o,serialized:i}),i.bitmap=y(this,ht,fu).call(this,!1);else if(c(this,Ds)){const h=s.stamps.get(c(this,ee));o>h.area&&(h.area=o,h.serialized.bitmap.close(),h.serialized.bitmap=y(this,ht,fu).call(this,!1))}return i}};te=new WeakMap,ee=new WeakMap,Mn=new WeakMap,$i=new WeakMap,Dn=new WeakMap,ba=new WeakMap,ii=new WeakMap,Il=new WeakMap,Ki=new WeakMap,ni=new WeakMap,Ds=new WeakMap,jl=new WeakMap,ht=new WeakSet,Jl=function(e,s=!1){if(!e){this.remove();return}b(this,te,e.bitmap),s||(b(this,ee,e.id),b(this,Ds,e.isSvg)),e.file&&b(this,ba,e.file.name),y(this,ht,qf).call(this)},Zl=function(){b(this,Mn,null),this._uiManager.enableWaiting(!1),c(this,ii)&&this.div.focus()},gu=function(){if(c(this,ee)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(c(this,ee)).then(i=>y(this,ht,Jl).call(this,i,!0)).finally(()=>y(this,ht,Zl).call(this));return}if(c(this,$i)){const i=c(this,$i);b(this,$i,null),this._uiManager.enableWaiting(!0),b(this,Mn,this._uiManager.imageManager.getFromUrl(i).then(n=>y(this,ht,Jl).call(this,n)).finally(()=>y(this,ht,Zl).call(this)));return}if(c(this,Dn)){const i=c(this,Dn);b(this,Dn,null),this._uiManager.enableWaiting(!0),b(this,Mn,this._uiManager.imageManager.getFromFile(i).then(n=>y(this,ht,Jl).call(this,n)).finally(()=>y(this,ht,Zl).call(this)));return}const e=document.createElement("input");e.type="file",e.accept=Nl.supportedTypesStr;const s=this._uiManager._signal;b(this,Mn,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]);y(this,ht,Jl).call(this,n)}i()},{signal:s}),e.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>y(this,ht,Zl).call(this))),e.click()},qf=function(){const{div:e}=this;let{width:s,height:i}=c(this,te);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,ii,document.createElement("canvas"));e.append(d),e.hidden=!1,y(this,ht,$f).call(this,s,i),y(this,ht,Ab).call(this),c(this,jl)||(this.parent.addUndoableEditor(this),b(this,jl,!0)),this._reportTelemetry({action:"inserted_image"}),c(this,ba)&&d.setAttribute("aria-label",c(this,ba))},xb=function(e,s){var o;const[i,n]=this.parentDimensions;this.width=e/i,this.height=s/n,this.setDims(e,s),(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,c(this,ni)!==null&&clearTimeout(c(this,ni)),b(this,ni,setTimeout(()=>{b(this,ni,null),y(this,ht,$f).call(this,e,s)},200))},Sb=function(e,s){const{width:i,height:n}=c(this,te);let r=i,o=n,h=c(this,te);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},Cb=async function(e,s,i){if(c(this,Il)||(b(this,Il,!0),!await this._uiManager.isMLEnabledFor("altText")||this.hasAltText()))return;const o=new OffscreenCanvas(s,i).getContext("2d",{willReadFrequently:!0});o.drawImage(e,0,0,e.width,e.height,0,0,s,i);const h=await this._uiManager.mlGuess({service:"moz-image-to-text",request:{data:o.getImageData(0,0,s,i).data,width:s,height:i,channels:4}}),l=(h==null?void 0:h.output)||"";this.parent&&l&&!this.hasAltText()&&(this.altTextData={altText:l,decorative:!1})},$f=function(e,s){e=Math.ceil(e),s=Math.ceil(s);const i=c(this,ii);if(!i||i.width===e&&i.height===s)return;i.width=e,i.height=s;const n=c(this,Ds)?c(this,te):y(this,ht,Sb).call(this,e,s);y(this,ht,Cb).call(this,n,e,s);const r=i.getContext("2d");r.filter=this._uiManager.hcmFilter,r.drawImage(n,0,0,n.width,n.height,0,0,e,s)},fu=function(e){if(e){if(c(this,Ds)){const n=this._uiManager.imageManager.getSvgUrl(c(this,ee));if(n)return n}const s=document.createElement("canvas");return{width:s.width,height:s.height}=c(this,te),s.getContext("2d").drawImage(c(this,te),0,0),s.toDataURL()}if(c(this,Ds)){const[s,i]=this.pageDimensions,n=Math.round(this.width*s*ln.PDF_TO_CSS_UNITS),r=Math.round(this.height*i*ln.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(n,r);return o.getContext("2d").drawImage(c(this,te),0,0,c(this,te).width,c(this,te).height,0,0,n,r),o.transferToImageBitmap()}return structuredClone(c(this,te))},Ab=function(){this._uiManager._signal&&(b(this,Ki,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&y(this,ht,xb).call(this,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}))},K(Nl,"_type","stamp"),K(Nl,"_editorType",nt.STAMP);let qg=Nl;const Os=class Os{constructor({uiManager:t,pageIndex:e,div:s,accessibilityManager:i,annotationLayer:n,drawLayer:r,textLayer:o,viewport:h,l10n:l}){w(this,se);w(this,so);w(this,ya,!1);w(this,ri,null);w(this,io,null);w(this,Qi,null);w(this,Ji,null);w(this,Zi,null);w(this,Ke,new Map);w(this,On,!1);w(this,_a,!1);w(this,wa,!1);w(this,fe,null);w(this,G);const d=[...c(Os,Pn).values()];if(!Os._initialized){Os._initialized=!0;for(const u of d)u.initialize(l,t)}t.registerEditorTypes(d),b(this,G,t),this.pageIndex=e,this.div=s,b(this,so,i),b(this,ri,n),this.viewport=h,b(this,fe,o),this.drawLayer=r,c(this,G).addLayer(this)}get isEmpty(){return c(this,Ke).size===0}get isInvisible(){return this.isEmpty&&c(this,G).getMode()===nt.NONE}updateToolbar(t){c(this,G).updateToolbar(t)}updateMode(t=c(this,G).getMode()){switch(y(this,se,pu).call(this),t){case nt.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case nt.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case nt.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(Os,Pn).values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){var e;return t===((e=c(this,fe))==null?void 0:e.div)}addInkEditorIfNeeded(t){if(c(this,G).getMode()!==nt.INK)return;if(!t){for(const s of c(this,Ke).values())if(s.isEmpty()){s.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){c(this,G).setEditingState(t)}addCommands(t){c(this,G).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,ri))==null||e.div.classList.toggle("disabled",!t)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of c(this,Ke).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(c(this,G).removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!c(this,ri))return;const e=c(this,ri).getEditableAnnotations();for(const s of e){if(s.hide(),c(this,G).isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){var i;b(this,wa,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const n of c(this,Ke).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,ri)){const n=c(this,ri).getEditableAnnotations();for(const r of n){const{id:o}=r.data;if(c(this,G).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,G).addChangedExistingAnnotation(h),h.renderAnnotationElement(r),h.show(!1)),r.show()}}y(this,se,pu).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const n of c(Os,Pn).values())s.remove(`${n._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),b(this,wa,!1)}getEditableAnnotation(t){var e;return((e=c(this,ri))==null?void 0:e.getEditableAnnotation(t))||null}setActiveEditor(t){c(this,G).getActive()!==t&&c(this,G).setActiveEditor(t)}enableTextSelection(){var t;this.div.tabIndex=-1,(t=c(this,fe))!=null&&t.div&&!c(this,Ji)&&(b(this,Ji,y(this,se,Tb).bind(this)),c(this,fe).div.addEventListener("pointerdown",c(this,Ji),{signal:c(this,G)._signal}),c(this,fe).div.classList.add("highlighting"))}disableTextSelection(){var t;this.div.tabIndex=0,(t=c(this,fe))!=null&&t.div&&c(this,Ji)&&(c(this,fe).div.removeEventListener("pointerdown",c(this,Ji)),b(this,Ji,null),c(this,fe).div.classList.remove("highlighting"))}enableClick(){if(c(this,Qi))return;const t=c(this,G)._signal;b(this,Qi,this.pointerdown.bind(this)),b(this,io,this.pointerup.bind(this)),this.div.addEventListener("pointerdown",c(this,Qi),{signal:t}),this.div.addEventListener("pointerup",c(this,io),{signal:t})}disableClick(){c(this,Qi)&&(this.div.removeEventListener("pointerdown",c(this,Qi)),this.div.removeEventListener("pointerup",c(this,io)),b(this,Qi,null),b(this,io,null))}attach(t){c(this,Ke).set(t.id,t);const{annotationElementId:e}=t;e&&c(this,G).isDeletedAnnotationElement(e)&&c(this,G).removeDeletedAnnotationElement(t)}detach(t){var e;c(this,Ke).delete(t.id),(e=c(this,so))==null||e.removePointerInTextLayer(t.contentDiv),!c(this,wa)&&t.annotationElementId&&c(this,G).addDeletedAnnotationElement(t)}remove(t){this.detach(t),c(this,G).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,c(this,_a)||this.addInkEditorIfNeeded(!1)}changeParent(t){var e;t.parent!==this&&(t.parent&&t.annotationElementId&&(c(this,G).addDeletedAnnotationElement(t.annotationElementId),dt.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,G).addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),c(this,G).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var s;if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!c(this,Zi)&&(t._focusEventsAllowed=!1,b(this,Zi,setTimeout(()=>{b(this,Zi,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:c(this,G)._signal}),e.focus())},0))),t._structTreeParentId=(s=c(this,so))==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,G).getId()}get _signal(){return c(this,G)._signal}canCreateNewEmptyEditor(){var t;return(t=c(this,se,Kf))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,e){c(this,G).updateToolbar(t),c(this,G).updateMode(t);const{offsetX:s,offsetY:i}=y(this,se,Jf).call(this),n=this.getNextId(),r=y(this,se,Qf).call(this,{parent:this,id:n,x:s,y:i,uiManager:c(this,G),isCentered:!0,...e});r&&this.add(r)}deserialize(t){var e;return((e=c(Os,Pn).get(t.annotationType??t.annotationEditorType))==null?void 0:e.deserialize(t,this,c(this,G)))||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=y(this,se,Qf).call(this,{parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:c(this,G),isCentered:e,...s});return n&&this.add(n),n}addNewEditor(){this.createAndAddNewEditor(y(this,se,Jf).call(this),!0)}setSelected(t){c(this,G).setSelected(t)}toggleSelected(t){c(this,G).toggleSelected(t)}isSelected(t){return c(this,G).isSelected(t)}unselect(t){c(this,G).unselect(t)}pointerup(t){const{isMac:e}=De.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&c(this,On)){if(b(this,On,!1),!c(this,ya)){b(this,ya,!0);return}if(c(this,G).getMode()===nt.STAMP){c(this,G).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(c(this,G).getMode()===nt.HIGHLIGHT&&this.enableTextSelection(),c(this,On)){b(this,On,!1);return}const{isMac:e}=De.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;b(this,On,!0);const s=c(this,G).getActive();b(this,ya,!s||s.isEmpty())}findNewParent(t,e,s){const i=c(this,G).findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}destroy(){var t,e;((t=c(this,G).getActive())==null?void 0:t.parent)===this&&(c(this,G).commitOrRemove(),c(this,G).setActiveEditor(null)),c(this,Zi)&&(clearTimeout(c(this,Zi)),b(this,Zi,null));for(const s of c(this,Ke).values())(e=c(this,so))==null||e.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,c(this,Ke).clear(),c(this,G).removeLayer(this)}render({viewport:t}){this.viewport=t,Zn(this.div,t);for(const e of c(this,G).getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){c(this,G).commitOrRemove(),y(this,se,pu).call(this);const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,Zn(this.div,{rotation:s}),e!==s)for(const i of c(this,Ke).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,G).viewParameters.realScale}};so=new WeakMap,ya=new WeakMap,ri=new WeakMap,io=new WeakMap,Qi=new WeakMap,Ji=new WeakMap,Zi=new WeakMap,Ke=new WeakMap,On=new WeakMap,_a=new WeakMap,wa=new WeakMap,fe=new WeakMap,G=new WeakMap,Pn=new WeakMap,se=new WeakSet,Tb=function(t){c(this,G).unselectAll();const{target:e}=t;if(e===c(this,fe).div||e.classList.contains("endOfContent")&&c(this,fe).div.contains(e)){const{isMac:s}=De.platform;if(t.button!==0||t.ctrlKey&&s)return;c(this,G).showAllEditors("highlight",!0,!0),c(this,fe).div.classList.add("free"),this.toggleDrawing(),Cd.startHighlighting(this,c(this,G).direction==="ltr",t),c(this,fe).div.addEventListener("pointerup",()=>{c(this,fe).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:c(this,G)._signal}),t.preventDefault()}},Kf=function(){return c(Os,Pn).get(c(this,G).getMode())},Qf=function(t){const e=c(this,se,Kf);return e?new e.prototype.constructor(t):null},Jf=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}},pu=function(){b(this,_a,!0);for(const t of c(this,Ke).values())t.isEmpty()&&t.remove();b(this,_a,!1)},K(Os,"_initialized",!1),w(Os,Pn,new Map([Gg,Yg,qg,Cd].map(t=>[t._editorType,t])));let $g=Os;const ie=class ie{constructor({pageIndex:t}){w(this,no);w(this,oi,null);w(this,Bl,0);w(this,Ut,new Map);w(this,Ln,new Map);this.pageIndex=t}setParent(t){if(!c(this,oi)){b(this,oi,t);return}if(c(this,oi)!==t){if(c(this,Ut).size>0)for(const e of c(this,Ut).values())e.remove(),t.append(e);b(this,oi,t)}}static get _svgFactory(){return at(this,"_svgFactory",new Ag)}highlight(t,e,s,i=!1){const n=Je(this,Bl)._++,r=y(this,no,tp).call(this,t.box);r.classList.add("highlight"),t.free&&r.classList.add("free");const o=ie._svgFactory.createElement("defs");r.append(o);const h=ie._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,Ln).set(n,h);const d=y(this,no,Eb).call(this,o,l),u=ie._svgFactory.createElement("use");return r.append(u),r.setAttribute("fill",e),r.setAttribute("fill-opacity",s),u.setAttribute("href",`#${l}`),c(this,Ut).set(n,r),{id:n,clipPathId:`url(#${d})`}}highlightOutline(t){const e=Je(this,Bl)._++,s=y(this,no,tp).call(this,t.box);s.classList.add("highlightOutline");const i=ie._svgFactory.createElement("defs");s.append(i);const n=ie._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=ie._svgFactory.createElement("mask");i.append(d),o=`mask_p${this.pageIndex}_${e}`,d.setAttribute("id",o),d.setAttribute("maskUnits","objectBoundingBox");const u=ie._svgFactory.createElement("rect");d.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const g=ie._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=ie._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,Ut).set(e,s),e}finalizeLine(t,e){const s=c(this,Ln).get(t);c(this,Ln).delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){c(this,Ut).get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}removeFreeHighlight(t){this.remove(t),c(this,Ln).delete(t)}updatePath(t,e){c(this,Ln).get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){var s;y(s=ie,Hl,Zf).call(s,c(this,Ut).get(t),e)}show(t,e){c(this,Ut).get(t).classList.toggle("hidden",!e)}rotate(t,e){c(this,Ut).get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){c(this,Ut).get(t).setAttribute("fill",e)}changeOpacity(t,e){c(this,Ut).get(t).setAttribute("fill-opacity",e)}addClass(t,e){c(this,Ut).get(t).classList.add(e)}removeClass(t,e){c(this,Ut).get(t).classList.remove(e)}remove(t){c(this,oi)!==null&&(c(this,Ut).get(t).remove(),c(this,Ut).delete(t))}destroy(){b(this,oi,null);for(const t of c(this,Ut).values())t.remove();c(this,Ut).clear()}};oi=new WeakMap,Bl=new WeakMap,Ut=new WeakMap,Ln=new WeakMap,Hl=new WeakSet,Zf=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}%`},no=new WeakSet,tp=function(t){var s;const e=ie._svgFactory.create(1,1,!0);return c(this,oi).append(e),e.setAttribute("aria-hidden",!0),y(s=ie,Hl,Zf).call(s,e,t),e},Eb=function(t,e){const s=ie._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=ie._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i},w(ie,Hl);let Kg=ie;$.AbortException,$.AnnotationEditorLayer,$.AnnotationEditorParamsType,$.AnnotationEditorType,$.AnnotationEditorUIManager,$.AnnotationLayer,$.AnnotationMode,$.CMapCompressionType,$.ColorPicker,$.DOMSVGFactory,$.DrawLayer,$.FeatureTest;var oS=$.GlobalWorkerOptions;$.ImageKind,$.InvalidPDFException,$.MissingPDFException,$.OPS,$.PDFDataRangeTransport,$.PDFDateString,$.PDFWorker,$.PasswordResponses,$.PermissionFlag,$.PixelsPerInch,$.RenderingCancelledException,$.TextLayer,$.UnexpectedResponseException,$.Util,$.VerbosityLevel,$.XfaLayer,$.build,$.createValidAbsoluteUrl,$.fetchData;var aS=$.getDocument;$.getFilenameFromUrl,$.getPdfFilenameFromUrl,$.getXfaPageViewport,$.isDataScheme,$.isPdfFile,$.noContextMenu,$.normalizeUnicode,$.setLayerDimensions,$.shadow,$.version;const hS={fabric:"^6.3.0","pdfjs-dist":"^4.5.136"};function lS(a){return new Promise((t,e)=>{const s=new FileReader;s.onload=()=>t(s.result),s.onerror=e,s.readAsDataURL(a)})}const cS=hS["pdfjs-dist"].replace("^","");oS.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${cS}/pdf.worker.min.mjs`;async function dS(a){const t="data:application/pdf;base64,",e=await lS(a);if(typeof e=="string")return window.atob(e.slice(t.length))}function uS(a,t){return aS({data:a,password:t}).promise}const gS="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 fS(a){return new URL(Object.assign({"../assets/close.svg":gS})[`../assets/${a}`],typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Et&&Et.src||new URL("pdf-canvas.umd.js",document.baseURI).href).href}function pS(a){return new Promise((t,e)=>{const s=window.URL.createObjectURL(a),i=new Image;i.src=s,i.onload=async()=>{window.URL.revokeObjectURL(s),t(await mS(i))},i.onerror=n=>{window.URL.revokeObjectURL(s),e(n)}})}function mS(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 ev=null;function vS(){const a=document.createElement("div");a.style.width="1in",document.body.appendChild(a);const t=a.offsetWidth;return document.body.removeChild(a),t}function bS(){const a=ev??vS();return ev=a,a/72}function yS(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 _S={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},wS={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},xS={stroke:"#000",hoverStroke:"#B7EC5D",src:""},ss=new Map;function sv(a=""){let t=0,e=null,s=null,i=1,n={...xS};function r(){if(!a||ss.has(a))return;const D=new ig(a);return ss.set(a,D),D.on("selection:cleared",()=>P(D)),D}function o(D,L){const F=D.type;return{"application/pdf":h,"image/png":g,"image/jpeg":g}[F](D,L)??Promise.reject(new Error(`Unsupported ${F} file type.`))}async function h(D,L){const F=await dS(D);if(!F)return;const I=Date.now(),Y={PDFId:`${D.name}-${I}`,name:D.name.replace(/.pdf/,""),updateDate:I,PDFBase64:F};try{return await l({page:1,PDFBase64:F,scale:.8,password:L}),{...Y,pages:t}}catch(J){return Promise.reject(J)}}async function l({page:D,PDFBase64:L,scale:F,password:I}){try{const X=await uS(L,I),Y=await U.toRaw(X).getPage(D),J=Y.getViewport({scale:F}),W=document.createElement("canvas"),V=W.getContext("2d"),It=bS()/window.devicePixelRatio;W.width=Math.floor(J.width*It),W.height=Math.floor(J.height*It),t=X.numPages;const Ie={canvasContext:V,viewport:J,transform:[It,0,0,It,0,0]};return Y.render(Ie).promise.then(()=>d(W))}catch(X){return Promise.reject(X)}}function d(D){if(!ss.get(a))return;const F=1/3,I=u(D,F);p(I,F)}function u(D,L){return new ae(D,{scaleX:L,scaleY:L})}async function g(D){const L=await pS(D),F=Date.now(),X={PDFId:`${D.name}${F}`,name:D.name.replace(/.png|.jpg|.jpeg/,""),updateDate:F,PDFBase64:L};return f({url:L}),{...X,pages:1}}async function f({url:D,scale:L=.5}){if(!ss.get(a))return;const I=await ae.fromURL(D);I.scale(L),p(I,L)}function p(D,L){const F=ss.get(a);F&&(F.setWidth(D.width*L),F.setHeight(D.height*L),F.backgroundImage=D,F.renderAll())}async function m(D,L){const F=ss.get(a);if(!F)return;const I=await ae.fromURL(D,{},{..._S,...L});F.add(I),v(F,I)}function _(D,L){const F=ss.get(a);if(!F)return;const I=new oe(D,{...wS,...L});F.add(I),v(F,I)}function v(D,L){L.on("selected",F=>x({canvas:D,target:F.target})),L.on("modified",F=>T(F.target)),L.on("scaling",F=>T(F.transform.target)),L.on("moving",F=>T(F.transform.target)),L.on("rotating",F=>T(F.transform.target))}async function x({canvas:D,target:L,stroke:F=n.stroke,uuid:I=Date.now()}){if((e==null?void 0:e.stroke)===`${F}-${I}`)return;const X=n.src||fS("close.svg"),{objects:Y,options:J}=await Z_(X),W=Y.filter(It=>It!==null),V=g_.groupSVGElements(W,J);W.forEach(It=>{It.stroke=F}),V.hoverCursor="pointer",V.stroke=`${F}-${I}`,P(D),e=V,s=L,S(D,L,I),E(i,!0),D.add(V)}function S(D,L,F){e&&(e.on("selected",()=>{D.remove(L),P(D)}),e.on("mouseover",()=>{x({canvas:D,target:L,stroke:n.hoverStroke,uuid:F})}),e.on("mouseout",()=>{x({canvas:D,target:L,stroke:n.stroke,uuid:F})}))}function T(D){if(!e)return;const{oCoords:L}=D;if(!L)return;const{x:F,y:I}=L.tl.touchCorner.tl,{height:X,width:Y,scaleY:J,scaleX:W}=e;e.top=I-X*J/2,e.left=F-Y*W/2,e.setCoords()}function E(D,L=!1){var F;i=D,!(!e||!s)&&(e.scale(1/D),T(s),!L&&((F=ss.get(a))==null||F.renderAll()))}function M(D){if(!D)return;n={...n,...D};const L=ss.get(a);!e||!s||!L||x({target:s,canvas:L})}function P(D){e&&(D.remove(e),e=s=null)}function O(){const D=ss.get(a);D&&(D.discardActiveObject(),D.renderAll())}function R(){const D=ss.get(a);D&&(D.clear(),ss.delete(a))}return{createCanvas:r,loadFile:o,specifyPage:l,renderImage:f,addFabric:m,addTextFabric:_,clearActive:O,deleteCanvas:R,scaleCloseFabric:E,setCloseSvgOptions:M}}function SS(a){let t=0;const e=yS(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});U.onMounted(()=>{window.addEventListener("resize",e)}),U.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const Qg=U.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=U.ref(null),i=`${e.canvasId}-${e.page-1}`,n=U.computed(()=>e.fileZoom*e.canvasScale),{createCanvas:r,specifyPage:o,addFabric:h,addTextFabric:l,renderImage:d,clearActive:u,deleteCanvas:g,scaleCloseFabric:f,setCloseSvgOptions:p}=sv(i);m(),SS(m);async function m(){const{file:S,page:T,fileScale:E}=e;window.requestAnimationFrame(async()=>{if(await U.nextTick(),r(),S.PDFBase64.startsWith("data:image")||S.canvas){const{canvas:M}=S,P=M?7:3,O=M!=null&&M.length?M[T-1]:S.PDFBase64;d({url:O,scale:E/P});return}await o({page:T,PDFBase64:S.PDFBase64,scale:E,password:e.password})})}function _(S){if(!e.isDrop||!S.dataTransfer)return;const{dataTransfer:T,offsetX:E,offsetY:M}=S,P=T.getData("text"),O=T.getData("image"),R={left:E-71,top:M-55};O&&v(O,R),P&&x(P,R)}function v(S,T){h(S,{...T,...e.dropImageOptions})}function x(S,T){l(S,{...T,...e.dropTextOptions})}return U.watch([()=>e.fileScale,()=>e.page,()=>e.file,()=>e.password],m),U.watch(n,S=>f(S),{immediate:!0}),U.watch(()=>e.closeSvgOptions,p,{immediate:!0}),U.onBeforeUnmount(g),t({addImage:v,addText:x,clearActive:u,deleteCanvas:g,canvasRef:s}),(S,T)=>(U.openBlock(),U.createElementBlock("div",{style:U.normalizeStyle({transform:`scale(${n.value})`}),onDragover:T[0]||(T[0]=U.withModifiers(()=>{},["stop","prevent"])),onDragenter:T[1]||(T[1]=U.withModifiers(()=>{},["stop","prevent"])),onDrop:U.withModifiers(_,["stop","prevent"])},[U.createElementVNode("canvas",{id:i,ref_key:"canvasRef",ref:s,class:U.normalizeClass(S.canvasClass)},null,2)],36))}});Qg.install=function(a){a.component("PdfCanvas",Qg)};const Ad=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));st.default=Qg,st.useFabric=sv,Object.defineProperties(st,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});