@component-hook/pdf-canvas 0.2.1-alpha.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- (function(rt,Y){typeof exports=="object"&&typeof module<"u"?Y(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],Y):(rt=typeof globalThis<"u"?globalThis:rt||self,Y(rt["pdf-canvas"]={},rt.Vue))})(this,function(rt,Y){"use strict";var jS=Object.defineProperty;var rb=rt=>{throw TypeError(rt)};var NS=(rt,Y,Ct)=>Y in rt?jS(rt,Y,{enumerable:!0,configurable:!0,writable:!0,value:Ct}):rt[Y]=Ct;var q=(rt,Y,Ct)=>NS(rt,typeof Y!="symbol"?Y+"":Y,Ct),nf=(rt,Y,Ct)=>Y.has(rt)||rb("Cannot "+Ct);var c=(rt,Y,Ct)=>(nf(rt,Y,"read from private field"),Ct?Ct.call(rt):Y.get(rt)),w=(rt,Y,Ct)=>Y.has(rt)?rb("Cannot add the same private member more than once"):Y instanceof WeakSet?Y.add(rt):Y.set(rt,Ct),b=(rt,Y,Ct,A)=>(nf(rt,Y,"write to private field"),A?A.call(rt,Ct):Y.set(rt,Ct),Ct),v=(rt,Y,Ct)=>(nf(rt,Y,"access private method"),Ct);var Fe=(rt,Y,Ct,A)=>({set _(Zl){b(rt,Y,Zl,Ct)},get _(){return c(rt,Y,A)}});var Di,Bd,rf,Sh,yn,mr,ks,br,Ch,Ah,wd,ob,Me,ab,hb,Hd,lb,of,Th,vr,yr,_n,cb,db,ub,xd,Wo,Eh,me,zo,Wd,Zt,wn,kh,te,Sd,gb,Xo,qe,Yt,ne,Vo,Fi,Go,Ms,xn,Yo,_r,Ks,Os,wr,Mh,Oh,Uo,Dh,Qs,Sn,qo,Cn,Js,Ad,An,Ph,Tn,xr,Fh,Rh,ee,ft,Ri,Sr,Lh,Ih,En,Zs,Li,jh,cs,I,zd,af,fb,pb,Xd,mb,bb,vb,hf,yb,lf,cf,_b,Re,qn,wb,xb,df,Sb,Bl,uf,se,ti,Ds,Ko,ei,$e,Qo,si,Be,Ii,Cr,ii,kn,Ps,Hl,Vd,Ar,Fs,Et,Jo,Tr,re,Er,Mn,Nh,kr,On,Bh,Mr,ji,ni,Zo,ta,ds,Hh,Td,et,gf,Wh,ff,pf,Cb,Ab,mf,bf,vf,Tb,yf,Eb,kb,Mb,_f,Wl,Or,Dr,ie,Ed,Ob,zh,ea,Xh,Pr,Fr,ri,Ni,be,kd,Rr,j,_e,Ha,Wa,Gd,za,Db,wf,Xa,zl,Xl,xf,Vl,Dn,Sf,Cf,Vh,Gh,sa,us,Pb,Fb,Rb,Yd,Lr,Yh,Uh,qh,$h,ia,Pn,pt,na,ra,Kh,Af,nb,Fn,He,Qh,Jh,Ir,Bi,Zh,tl,jr,oa,aa,Rn,ha,el,la,Nr,sl,il,Br,Hr,nl,Ln,ca,Hi,Lb,Ib,Tf,Ke,Ud,Ef,jb,Nb,Od,In,Wi,gs,Va,qd,zi,Pd,Fd,Wr,zr,da,$d,ua,Kd,Xi,oi,ga,fa,ai,Xr,Gl,Rs,rl,kf,jn,Nn,Vr,Yr,pa,ma,ol,Mf,Qe,vo,Bb,Hb,ba,Rd,Ld,va,Ur,Dt,Vi,ya,al,hl,_a,Gi,Ls,Yi,ll,Ui,cl,qr,$r,mt,Qd,Of,Wb,zb,Xb,Vb,Jd,Zd,Df,dl,ul,gl,fl,pl,ml,bl,Pf,vl,Kr,Qr,yl,Jr,Gb,Ff,Is,Je,_l,Zr,Ze,Ht,Yb,Ub,qb,tu,qi,eu,su,$b,Rf,Kb,ts,js,wa,xa,hi,it,to,eo,wl,xl,Sa,Ca,Bn,Sl,Id,jd,qt,Yl,Qb,Jb,Zb,tv,ev,sv,Aa,so,Ki,Cl,es,Al,It,We,Ul,ql,iv,Tl,Hn,Ns,De,nv,iu,rv,ov,Lf,El,Ta,Bs,io,Ea,$t,kl,ka,Ml,Ol,Wn,Hs,Ma,Dl,bt,If,jf,Nf,yo,av,$n,Oa,Pl,Qi,no,Da,fs,Fl,Rl,ro,Ws,ve,Xe,Pa,Ji,Kt,Fa,ps,Ll,J,Bf,nu,hv,lv,cv,Hf,_o,ms,Ga,dv,ru,$l,uv,gv,fv,pv,mv,oo,ao,li,Zi,bs,ho,lo,co,tn,Ra,uo,go,zn,L,bv,vv,yv,_v,Wf,wv,zf,xv,Sv,Cv,Av,Tv,wo,Xf,Vf,Gf,ou,au,Ya,Yf,hu,en,Ev,Uf,kv,Mv,qf,lu,Kl,Mt,oe,Xn,sn,Vn,La,ci,nn,di,ss,Ia,nt,Ql,Jl,cu,$f,Ov,du,Kf,uu,Dv,Pv,fo,ja,ui,Gn,rn,is,Yn,Na,Ba,ye,on,G,Un,ae,Fv,Qf,Jf,Zf,gu,gi,jl,Wt,an,Nl,tp,po,ep,Rv;var Ct=typeof document<"u"?document.currentScript:null;function A(a,t,e){return(t=function(s){var i=function(n,r){if(typeof n!="object"||!n)return n;var o=n[Symbol.toPrimitive];if(o!==void 0){var h=o.call(n,r||"default");if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)}(s,"string");return typeof i=="symbol"?i:i+""}(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function Zl(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),e.push.apply(e,s)}return e}function T(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Zl(Object(e),!0).forEach(function(s){A(a,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):Zl(Object(e)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(e,s))})}return a}function wt(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 hn(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class sp{constructor(){A(this,"browserShadowBlurConstant",1),A(this,"DPI",96),A(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),A(this,"perfLimitSizeTotal",2097152),A(this,"maxCacheSideLimit",4096),A(this,"minCacheSideLimit",256),A(this,"disableStyleCopyPaste",!1),A(this,"enableGLFiltering",!0),A(this,"textureSize",4096),A(this,"forceGLPutImageData",!1),A(this,"cachesBoundsOfCurve",!1),A(this,"fontPaths",{}),A(this,"NUM_FRACTION_DIGITS",4)}}const at=new class extends 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=T(T({},this.fontPaths),a)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(a=>{delete this.fontPaths[a]})}clearFonts(){this.fontPaths={}}restoreDefaults(a){const t=new sp,e=(a==null?void 0:a.reduce((s,i)=>(s[i]=t[i],s),{}))||t;this.configure(e)}},mi=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 Xs extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class fu extends Xs{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class Lv{}class Iv extends Lv{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(),mi("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const jv={};let ip;const Vs=()=>ip||(ip={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Iv,dispose(){},copyPasteData:jv}),xo=()=>Vs().document,tc=()=>Vs().window,np=()=>{var a;return Math.max((a=at.devicePixelRatio)!==null&&a!==void 0?a:tc().devicePixelRatio,1)},Ua=new class{constructor(){A(this,"charWidthsCache",{}),A(this,"boundsOfCurveCache",{})}getFontCache(a){let{fontFamily:t,fontStyle:e,fontWeight:s}=a;t=t.toLowerCase(),this.charWidthsCache[t]||(this.charWidthsCache[t]={});const i=this.charWidthsCache[t],n="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return i[n]||(i[n]={}),i[n]}clearFontCache(a){(a=(a||"").toLowerCase())?this.charWidthsCache[a]&&delete this.charWidthsCache[a]:this.charWidthsCache={}}limitDimsByArea(a){const{perfLimitSizeTotal:t}=at,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},pu="6.5.0";function Kn(){}const ln=Math.PI/2,bi=2*Math.PI,mu=Math.PI/180,we=Object.freeze([1,0,0,1,0,0]),bu=16,cn=.4477152502,Q="center",lt="left",Le="top",vu="bottom",Ft="right",xe="none",yu=/\r?\n/,rp="moving",ec="scaling",op="rotating",_u="rotate",ap="skewing",qa="resizing",Nv="modifyPoly",Bv="modifyPath",sc="changed",ic="scale",Se="scaleX",Ve="scaleY",So="skewX",Co="skewY",jt="fill",Ce="stroke",nc="modified",Ao="json",wu="svg",N=new class{constructor(){this[Ao]=new Map,this[wu]=new Map}has(a){return this[Ao].has(a)}getClass(a){const t=this[Ao].get(a);if(!t)throw new Xs("No class registered for ".concat(a));return t}setClass(a,t){t?this[Ao].set(t,a):(this[Ao].set(a.type,a),this[Ao].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[wu].get(a)}setSVGClass(a,t){this[wu].set(t??a.type.toLowerCase(),a)}},rc=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 Hv{constructor(){A(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach(s=>{let[i,n]=s;this.on(i,n)}),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach(i=>{let[n,r]=i;s.push(this.once(n,r))}),()=>s.forEach(i=>i())}if(e){const s=this.on(t,function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()});return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach(s=>{let[i,n]=s;this._removeEventListener(i,n)}):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const Qn=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},vs=a=>{if(a===0)return 1;switch(Math.abs(a)/ln){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ys=a=>{if(a===0)return 0;const t=a/ln,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class D{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 D(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new D(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new D(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new D(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new D(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new D(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new D(this.x/t.x,this.y/t.y)}scalarDivide(t){return new D(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 D(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 D(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new D(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 D(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:xu;const s=ys(t),i=vs(t),n=this.subtract(e);return new D(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 D(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 xu=new D(0,0),oc=a=>!!a&&Array.isArray(a._objects);function hp(a){class t extends a{constructor(){super(...arguments),A(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach(o=>this._onObjectAdded(o)),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach(o=>this._onObjectAdded(o)),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return r.forEach(h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),i.push(h),this._onObjectRemoved(h))}),i}forEachObject(s){this.getObjects().forEach((i,n,r)=>s(i,n,r))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter(r=>r.isType(...i))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some(n=>n instanceof t&&n.contains(s,!0))}complexity(){return this._objects.reduce((s,i)=>s+=i.complexity?i.complexity():0,0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(Qn(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Qn(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 Qn(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 Qn(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Qn(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 D(i,n),u=d.add(new D(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 Hv{_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 $a(a){return tc().requestAnimationFrame(a)}function cp(a){return tc().cancelAnimationFrame(a)}let Wv=0;const dn=()=>Wv++,ns=()=>{const a=xo().createElement("canvas");if(!a||a.getContext===void 0)throw new Xs("Failed to create `canvas` element");return a},dp=()=>xo().createElement("img"),_s=a=>{const t=ns();return t.width=a.width,t.height=a.height,t},Su=(a,t,e)=>a.toDataURL("image/".concat(t),e),Ot=a=>a*mu,un=a=>a/mu,up=a=>a.every((t,e)=>t===we[e]),ce=(a,t,e)=>new D(a).transform(t,e),Ie=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 D(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},Rt=(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]],ac=(a,t)=>a.reduceRight((e,s)=>s&&e?Rt(s,e,t):s||e,void 0)||we.concat(),gp=a=>{let[t,e]=a;return Math.atan2(e,t)},Jn=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:un(t),scaleX:s,scaleY:i,skewX:un(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},To=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function Eo(){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=Ot(a),i=vs(s),n=ys(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const hc=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},fp=a=>Math.tan(Ot(a)),Cu=a=>[1,0,fp(a),1,0,0],Au=a=>[1,fp(a),0,1,0,0],Ka=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=hc(s?-t:t,i?-e:e);return n&&(o=Rt(o,Cu(n),!0)),r&&(o=Rt(o,Au(r),!0)),o},pp=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=To(t,e);s&&(i=Rt(i,Eo({angle:s})));const n=Ka(a);return up(n)||(i=Rt(i,n)),i},Qa=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 fu("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 Xs("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()})},ko=function(a){let{signal:t,reviver:e=Kn}=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=>N.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)})})},Ja=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&&N.has(o.type)?ko([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)})})},Zn=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in a&&(t[e]=a[e]),t),{})},Tu=(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"},Eu=(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),bp=(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)},lc=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(A(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]=bp(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=bp(...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(lc(t)).concat(lc(e)).concat(lc(s)).concat(lc(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,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=Eu(d,l,s+1/3),o=Eu(d,l,s),h=Eu(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")?un(s):e.includes("turn")?360*s:s}}const xt=(a,t)=>parseFloat(Number(a).toFixed(t)),Ae=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:bu;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=at.DPI;switch(e==null?void 0:e[0]){case"mm":return s*i/25.4;case"cm":return s*i/2.54;case"in":return s*i;case"pt":return s*i/72;case"pc":return s*i/72*12;case"em":return s*t;default:return s}},ku=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==xe?[n.slice(1,4),n.slice(5,8)]:n===xe?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},Za=a=>"matrix("+a.map(t=>xt(t,at.NUM_FRACTION_DIGITS)).join(" ")+")",th=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,'" '):"")},rs=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",tr=a=>!!a&&"multiSelectionStacking"in a;function Sp(a){const t=a&&ws(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 ws=a=>a.ownerDocument||null,Cp=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},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))},Mu=(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=xe,a}class Ep{constructor(t){A(this,"_originalCanvasStyle",void 0),A(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&xo().getElementById(t)||ns();var s;if(e.hasAttribute("data-fabric"))throw new Xs("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){Mu(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&ws(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(){Vs().dispose(this.lower.el),delete this.lower}}const zv={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...we]};class eh 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 eh.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&&(mi("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=T({width:this.width,height:this.height},t);this.elements.setDimensions(i,this.getRetinaScaling()),this.hasLostContext=!0,this.width=i.width,this.height=i.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,i=[...this.viewportTransform],n=ce(t,Ie(i));i[0]=e,i[3]=e;const r=ce(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new D(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 D(-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=$a(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Ie(this.viewportTransform),i=ce({x:0,y:0},s),n=ce({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new D(o.x,r.y),bl:new D(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=rs(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 D(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new D(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new D(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 D(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new D(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return ce(this.getCenterPoint(),Ie(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 T(T(T({version:pu},Zn(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 rs(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),rs(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(rt,Y){typeof exports=="object"&&typeof module<"u"?Y(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],Y):(rt=typeof globalThis<"u"?globalThis:rt||self,Y(rt["pdf-canvas"]={},rt.Vue))})(this,function(rt,Y){"use strict";var jS=Object.defineProperty;var nb=rt=>{throw TypeError(rt)};var NS=(rt,Y,Ct)=>Y in rt?jS(rt,Y,{enumerable:!0,configurable:!0,writable:!0,value:Ct}):rt[Y]=Ct;var q=(rt,Y,Ct)=>NS(rt,typeof Y!="symbol"?Y+"":Y,Ct),sf=(rt,Y,Ct)=>Y.has(rt)||nb("Cannot "+Ct);var c=(rt,Y,Ct)=>(sf(rt,Y,"read from private field"),Ct?Ct.call(rt):Y.get(rt)),w=(rt,Y,Ct)=>Y.has(rt)?nb("Cannot add the same private member more than once"):Y instanceof WeakSet?Y.add(rt):Y.set(rt,Ct),b=(rt,Y,Ct,A)=>(sf(rt,Y,"write to private field"),A?A.call(rt,Ct):Y.set(rt,Ct),Ct),v=(rt,Y,Ct)=>(sf(rt,Y,"access private method"),Ct);var Fe=(rt,Y,Ct,A)=>({set _(Zl){b(rt,Y,Zl,Ct)},get _(){return c(rt,Y,A)}});var Di,Bd,nf,Sh,yn,mr,ks,br,Ch,Ah,wd,rb,Me,ob,ab,Hd,hb,rf,Th,vr,yr,_n,lb,cb,db,xd,Wo,Eh,me,zo,Wd,Zt,wn,kh,te,Sd,ub,Xo,qe,Yt,ne,Vo,Fi,Go,Ms,xn,Yo,_r,Ks,Os,wr,Mh,Oh,Uo,Dh,Qs,Sn,qo,Cn,Js,Ad,An,Ph,Tn,xr,Fh,Rh,ee,ft,Ri,Sr,Lh,Ih,En,Zs,Li,jh,cs,I,zd,of,gb,fb,Xd,pb,mb,bb,af,vb,hf,lf,yb,Re,qn,_b,wb,cf,xb,Bl,df,se,ti,Ds,Ko,ei,$e,Qo,si,Be,Ii,Cr,ii,kn,Ps,Hl,Vd,Ar,Fs,Et,Jo,Tr,re,Er,Mn,Nh,kr,On,Bh,Mr,ji,ni,Zo,ta,ds,Hh,Td,et,uf,Wh,gf,ff,Sb,Cb,pf,mf,bf,Ab,vf,Tb,Eb,kb,yf,Wl,Or,Dr,ie,Ed,Mb,zh,ea,Xh,Pr,Fr,ri,Ni,be,kd,Rr,j,_e,Ha,Wa,Gd,za,Ob,_f,Xa,zl,Xl,wf,Vl,Dn,xf,Sf,Vh,Gh,sa,us,Db,Pb,Fb,Yd,Lr,Yh,Uh,qh,$h,ia,Pn,pt,na,ra,Kh,Cf,ib,Fn,He,Qh,Jh,Ir,Bi,Zh,tl,jr,oa,aa,Rn,ha,el,la,Nr,sl,il,Br,Hr,nl,Ln,ca,Hi,Rb,Lb,Af,Ke,Ud,Tf,Ib,jb,Od,In,Wi,gs,Va,qd,zi,Pd,Fd,Wr,zr,da,$d,ua,Kd,Xi,oi,ga,fa,ai,Xr,Gl,Rs,rl,Ef,jn,Nn,Vr,Yr,pa,ma,ol,kf,Qe,vo,Nb,Bb,ba,Rd,Ld,va,Ur,Dt,Vi,ya,al,hl,_a,Gi,Ls,Yi,ll,Ui,cl,qr,$r,mt,Qd,Mf,Hb,Wb,zb,Xb,Jd,Zd,Of,dl,ul,gl,fl,pl,ml,bl,Df,vl,Kr,Qr,yl,Jr,Vb,Pf,Is,Je,_l,Zr,Ze,Ht,Gb,Yb,Ub,tu,qi,eu,su,qb,Ff,$b,ts,js,wa,xa,hi,it,to,eo,wl,xl,Sa,Ca,Bn,Sl,Id,jd,qt,Yl,Kb,Qb,Jb,Zb,tv,ev,Aa,so,Ki,Cl,es,Al,It,We,Ul,ql,sv,Tl,Hn,Ns,De,iv,iu,nv,rv,Rf,El,Ta,Bs,io,Ea,$t,kl,ka,Ml,Ol,Wn,Hs,Ma,Dl,bt,Lf,If,jf,yo,ov,$n,Oa,Pl,Qi,no,Da,fs,Fl,Rl,ro,Ws,ve,Xe,Pa,Ji,Kt,Fa,ps,Ll,J,Nf,nu,av,hv,lv,Bf,_o,ms,Ga,cv,ru,$l,dv,uv,gv,fv,pv,oo,ao,li,Zi,bs,ho,lo,co,tn,Ra,uo,go,zn,L,mv,bv,vv,yv,Hf,_v,Wf,wv,xv,Sv,Cv,Av,wo,zf,Xf,Vf,ou,au,Ya,Gf,hu,en,Tv,Yf,Ev,kv,Uf,lu,Kl,Mt,oe,Xn,sn,Vn,La,ci,nn,di,ss,Ia,nt,Ql,Jl,cu,qf,Mv,du,$f,uu,Ov,Dv,fo,ja,ui,Gn,rn,is,Yn,Na,Ba,ye,on,G,Un,ae,Pv,Kf,Qf,Jf,gu,gi,jl,Wt,an,Nl,Zf,po,tp,Fv;var Ct=typeof document<"u"?document.currentScript:null;function A(a,t,e){return(t=function(s){var i=function(n,r){if(typeof n!="object"||!n)return n;var o=n[Symbol.toPrimitive];if(o!==void 0){var h=o.call(n,r||"default");if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)}(s,"string");return typeof i=="symbol"?i:i+""}(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function Zl(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),e.push.apply(e,s)}return e}function T(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Zl(Object(e),!0).forEach(function(s){A(a,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):Zl(Object(e)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(e,s))})}return a}function wt(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 hn(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class ep{constructor(){A(this,"browserShadowBlurConstant",1),A(this,"DPI",96),A(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),A(this,"perfLimitSizeTotal",2097152),A(this,"maxCacheSideLimit",4096),A(this,"minCacheSideLimit",256),A(this,"disableStyleCopyPaste",!1),A(this,"enableGLFiltering",!0),A(this,"textureSize",4096),A(this,"forceGLPutImageData",!1),A(this,"cachesBoundsOfCurve",!1),A(this,"fontPaths",{}),A(this,"NUM_FRACTION_DIGITS",4)}}const at=new class extends 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=T(T({},this.fontPaths),a)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(a=>{delete this.fontPaths[a]})}clearFonts(){this.fontPaths={}}restoreDefaults(a){const t=new ep,e=(a==null?void 0:a.reduce((s,i)=>(s[i]=t[i],s),{}))||t;this.configure(e)}},mi=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 Xs extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class fu extends Xs{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class Rv{}class Lv extends Rv{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(),mi("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Iv={};let sp;const Vs=()=>sp||(sp={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Lv,dispose(){},copyPasteData:Iv}),xo=()=>Vs().document,tc=()=>Vs().window,ip=()=>{var a;return Math.max((a=at.devicePixelRatio)!==null&&a!==void 0?a:tc().devicePixelRatio,1)},Ua=new class{constructor(){A(this,"charWidthsCache",{}),A(this,"boundsOfCurveCache",{})}getFontCache(a){let{fontFamily:t,fontStyle:e,fontWeight:s}=a;t=t.toLowerCase(),this.charWidthsCache[t]||(this.charWidthsCache[t]={});const i=this.charWidthsCache[t],n="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return i[n]||(i[n]={}),i[n]}clearFontCache(a){(a=(a||"").toLowerCase())?this.charWidthsCache[a]&&delete this.charWidthsCache[a]:this.charWidthsCache={}}limitDimsByArea(a){const{perfLimitSizeTotal:t}=at,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},pu="6.5.0";function Kn(){}const ln=Math.PI/2,bi=2*Math.PI,mu=Math.PI/180,we=Object.freeze([1,0,0,1,0,0]),bu=16,cn=.4477152502,Q="center",lt="left",Le="top",vu="bottom",Ft="right",xe="none",yu=/\r?\n/,np="moving",ec="scaling",rp="rotating",_u="rotate",op="skewing",qa="resizing",jv="modifyPoly",Nv="modifyPath",sc="changed",ic="scale",Se="scaleX",Ve="scaleY",So="skewX",Co="skewY",jt="fill",Ce="stroke",nc="modified",Ao="json",wu="svg",N=new class{constructor(){this[Ao]=new Map,this[wu]=new Map}has(a){return this[Ao].has(a)}getClass(a){const t=this[Ao].get(a);if(!t)throw new Xs("No class registered for ".concat(a));return t}setClass(a,t){t?this[Ao].set(t,a):(this[Ao].set(a.type,a),this[Ao].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[wu].get(a)}setSVGClass(a,t){this[wu].set(t??a.type.toLowerCase(),a)}},rc=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 Bv{constructor(){A(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach(s=>{let[i,n]=s;this.on(i,n)}),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach(i=>{let[n,r]=i;s.push(this.once(n,r))}),()=>s.forEach(i=>i())}if(e){const s=this.on(t,function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()});return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach(s=>{let[i,n]=s;this._removeEventListener(i,n)}):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const Qn=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},vs=a=>{if(a===0)return 1;switch(Math.abs(a)/ln){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ys=a=>{if(a===0)return 0;const t=a/ln,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class D{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 D(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new D(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new D(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new D(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new D(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new D(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new D(this.x/t.x,this.y/t.y)}scalarDivide(t){return new D(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 D(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 D(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new D(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 D(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:xu;const s=ys(t),i=vs(t),n=this.subtract(e);return new D(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 D(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 xu=new D(0,0),oc=a=>!!a&&Array.isArray(a._objects);function ap(a){class t extends a{constructor(){super(...arguments),A(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach(o=>this._onObjectAdded(o)),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach(o=>this._onObjectAdded(o)),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return r.forEach(h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),i.push(h),this._onObjectRemoved(h))}),i}forEachObject(s){this.getObjects().forEach((i,n,r)=>s(i,n,r))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter(r=>r.isType(...i))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some(n=>n instanceof t&&n.contains(s,!0))}complexity(){return this._objects.reduce((s,i)=>s+=i.complexity?i.complexity():0,0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(Qn(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Qn(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 Qn(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 Qn(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Qn(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 D(i,n),u=d.add(new D(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 Bv{_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 $a(a){return tc().requestAnimationFrame(a)}function lp(a){return tc().cancelAnimationFrame(a)}let Hv=0;const dn=()=>Hv++,ns=()=>{const a=xo().createElement("canvas");if(!a||a.getContext===void 0)throw new Xs("Failed to create `canvas` element");return a},cp=()=>xo().createElement("img"),_s=a=>{const t=ns();return t.width=a.width,t.height=a.height,t},Su=(a,t,e)=>a.toDataURL("image/".concat(t),e),Ot=a=>a*mu,un=a=>a/mu,dp=a=>a.every((t,e)=>t===we[e]),ce=(a,t,e)=>new D(a).transform(t,e),Ie=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 D(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},Rt=(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]],ac=(a,t)=>a.reduceRight((e,s)=>s&&e?Rt(s,e,t):s||e,void 0)||we.concat(),up=a=>{let[t,e]=a;return Math.atan2(e,t)},Jn=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:un(t),scaleX:s,scaleY:i,skewX:un(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},To=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function Eo(){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=Ot(a),i=vs(s),n=ys(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const hc=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},gp=a=>Math.tan(Ot(a)),Cu=a=>[1,0,gp(a),1,0,0],Au=a=>[1,gp(a),0,1,0,0],Ka=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=hc(s?-t:t,i?-e:e);return n&&(o=Rt(o,Cu(n),!0)),r&&(o=Rt(o,Au(r),!0)),o},fp=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=To(t,e);s&&(i=Rt(i,Eo({angle:s})));const n=Ka(a);return dp(n)||(i=Rt(i,n)),i},Qa=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 fu("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 Xs("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()})},ko=function(a){let{signal:t,reviver:e=Kn}=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=>N.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)})})},Ja=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&&N.has(o.type)?ko([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)})})},Zn=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in a&&(t[e]=a[e]),t),{})},Tu=(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"},Eu=(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]},bp=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},lc=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),vp=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(A(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(lc(t)).concat(lc(e)).concat(lc(s)).concat(lc(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(vp(this.getSource())),this}toBlackWhite(t){const[e,,,s]=vp(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=Eu(d,l,s+1/3),o=Eu(d,l,s),h=Eu(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")?un(s):e.includes("turn")?360*s:s}}const xt=(a,t)=>parseFloat(Number(a).toFixed(t)),Ae=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:bu;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=at.DPI;switch(e==null?void 0:e[0]){case"mm":return s*i/25.4;case"cm":return s*i/2.54;case"in":return s*i;case"pt":return s*i/72;case"pc":return s*i/72*12;case"em":return s*t;default:return s}},ku=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==xe?[n.slice(1,4),n.slice(5,8)]:n===xe?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},Za=a=>"matrix("+a.map(t=>xt(t,at.NUM_FRACTION_DIGITS)).join(" ")+")",th=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,'" '):"")},rs=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",tr=a=>!!a&&"multiSelectionStacking"in a;function xp(a){const t=a&&ws(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 ws=a=>a.ownerDocument||null,Sp=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},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))},Mu=(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=xe,a}class Tp{constructor(t){A(this,"_originalCanvasStyle",void 0),A(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&xo().getElementById(t)||ns();var s;if(e.hasAttribute("data-fabric"))throw new Xs("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){Mu(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&ws(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(){Vs().dispose(this.lower.el),delete this.lower}}const Wv={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...we]};class eh 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 eh.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&&(mi("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=T({width:this.width,height:this.height},t);this.elements.setDimensions(i,this.getRetinaScaling()),this.hasLostContext=!0,this.width=i.width,this.height=i.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,i=[...this.viewportTransform],n=ce(t,Ie(i));i[0]=e,i[3]=e;const r=ce(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new D(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 D(-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=$a(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Ie(this.viewportTransform),i=ce({x:0,y:0},s),n=ce({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new D(o.x,r.y),bl:new D(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=rs(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 D(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new D(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new D(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 D(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new D(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return ce(this.getCenterPoint(),Ie(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 T(T(T({version:pu},Zn(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 rs(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),rs(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">
@@ -10,21 +10,21 @@ Resulting to default behavior: removing object from previous canvas and adding t
10
10
  `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
11
11
  `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(dn()),'<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(rs(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?Za(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=at.fontPaths;this._objects.forEach(function n(r){t.push(r),oc(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(rs(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?Za(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=at.fontPaths;this._objects.forEach(function n(r){t.push(r),oc(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(rs(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?Za(Ie(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(rs(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?Za(Ie(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 Xs("`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([ko(n,{reviver:e,signal:s}),Ja({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=_s(this);return 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 Su(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,y=_s({width:o,height:h}),x=r?this._objects.filter(S=>r(S)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(y.getContext("2d"),x),this.viewportTransform=p,this.width=d,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=_,this.skipControlsDrawing=g,y}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),rc.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}A(eh,"ownDefaults",zv);const Xv=["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 D(e.clientX+t.left,e.clientY+t.top)},cc=a=>Xv.includes(a.type)||a.pointerType==="touch",Ou=a=>{a.preventDefault(),a.stopPropagation()},Gs=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:h}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},Vv=["translateX","translateY","scaleX","scaleY"],Mp=(a,t)=>Mo(a,Rt(t,a.calcOwnMatrix())),Mo=(a,t)=>{const e=Jn(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=wt(e,Vv),h=new D(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,Q,Q)},Op=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},Du=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}),dc=(a,t,e)=>{const s=a/2,i=t/2,n=[new D(-s,-i),new D(s,-i),new D(-s,i),new D(s,i)].map(o=>o.transform(e)),r=Gs(n);return new D(r.width,r.height)},sh=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:we;return Rt(Ie(arguments.length>1&&arguments[1]!==void 0?arguments[1]:we),a)},er=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:we,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:we;return a.transform(sh(t,e))},Dp=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:we,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:we;return a.transform(sh(t,e),!0)},Pu=(a,t,e)=>{const s=sh(t,e);return Mo(a,Rt(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),T(T({},t),{},{target:s})),s.fire(a,t)},Gv={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Nt=a=>typeof a=="string"?Gv[a]:a-.5,uc="not-allowed";function Fp(a){return Nt(a.originX)===Nt(Q)&&Nt(a.originY)===Nt(Q)}function Rp(a){return .5-Nt(a)}const xs=(a,t)=>a[t],Lp=(a,t,e,s)=>({e:a,transform:t,pointer:new D(e,s)});function Ip(a,t){const e=a.getTotalAngle()+un(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Fu(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(),y=p!==void 0&&m!==void 0?g.translateToGivenOrigin(_,Q,Q,p,m):new D(g.left,g.top);return(g.angle?f.rotate(-Ot(g.angle),_):f).subtract(y)}(r,new D(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 Yv=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!xs(i,"lockMovementX")&&i.left!==o,d=!xs(i,"lockMovementY")&&i.top!==h;return l&&i.set(lt,o),d&&i.set(Le,h),(l||d)&&Pp(rp,Lp(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(" "):xe,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=th(jt,this.fill);return[th(Ce,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(Za(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(dn()),_='<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 Xs("`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([ko(n,{reviver:e,signal:s}),Ja({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=_s(this);return 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 Su(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,y=_s({width:o,height:h}),x=r?this._objects.filter(S=>r(S)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(y.getContext("2d"),x),this.viewportTransform=p,this.width=d,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=_,this.skipControlsDrawing=g,y}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),rc.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}A(eh,"ownDefaults",Wv);const zv=["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 D(e.clientX+t.left,e.clientY+t.top)},cc=a=>zv.includes(a.type)||a.pointerType==="touch",Ou=a=>{a.preventDefault(),a.stopPropagation()},Gs=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:h}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},Xv=["translateX","translateY","scaleX","scaleY"],kp=(a,t)=>Mo(a,Rt(t,a.calcOwnMatrix())),Mo=(a,t)=>{const e=Jn(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=wt(e,Xv),h=new D(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)},Du=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}),dc=(a,t,e)=>{const s=a/2,i=t/2,n=[new D(-s,-i),new D(s,-i),new D(-s,i),new D(s,i)].map(o=>o.transform(e)),r=Gs(n);return new D(r.width,r.height)},sh=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:we;return Rt(Ie(arguments.length>1&&arguments[1]!==void 0?arguments[1]:we),a)},er=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:we,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:we;return a.transform(sh(t,e))},Op=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:we,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:we;return a.transform(sh(t,e),!0)},Pu=(a,t,e)=>{const s=sh(t,e);return Mo(a,Rt(s,a.calcOwnMatrix())),s},Dp=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),T(T({},t),{},{target:s})),s.fire(a,t)},Vv={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Nt=a=>typeof a=="string"?Vv[a]:a-.5,uc="not-allowed";function Pp(a){return Nt(a.originX)===Nt(Q)&&Nt(a.originY)===Nt(Q)}function Fp(a){return .5-Nt(a)}const xs=(a,t)=>a[t],Rp=(a,t,e,s)=>({e:a,transform:t,pointer:new D(e,s)});function Lp(a,t){const e=a.getTotalAngle()+un(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Fu(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(),y=p!==void 0&&m!==void 0?g.translateToGivenOrigin(_,Q,Q,p,m):new D(g.left,g.top);return(g.angle?f.rotate(-Ot(g.angle),_):f).subtract(y)}(r,new D(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 Gv=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!xs(i,"lockMovementX")&&i.left!==o,d=!xs(i,"lockMovementY")&&i.top!==h;return l&&i.set(lt,o),d&&i.set(Le,h),(l||d)&&Dp(np,Rp(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(" "):xe,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=th(jt,this.fill);return[th(Ce,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(Za(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(dn()),_='<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 y=[r,l,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[m]=y,rs(g)&&p.push(g.toSVG(this)),rs(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!==jt?' paint-order="'.concat(this.paintFirst,'" '):""}}function gc(a){return new RegExp("^("+a.join("|")+")\\b","i")}var Np;const Ss=String.raw(Np||(Np=hn(["(?:[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?)"],["(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)"]))),Ru="http://www.w3.org/2000/svg",Uv=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Ss+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Ss+"))?\\s+(.*)"),qv={cx:lt,x:lt,r:"radius",cy:Le,y:Le,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"},Lu="font-size",Iu="clip-path",$v=gc(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Kv=gc(["symbol","image","marker","pattern","view","svg"]),Bp=gc(["symbol","g","a","svg","clipPath","defs"]),Hp=new RegExp("^\\s*("+Ss+"+)\\s*,?\\s*("+Ss+"+)\\s*,?\\s*("+Ss+"+)\\s*,?\\s*("+Ss+"+)\\s*$"),Qv=new D(1,0),Wp=new D,ju=(a,t)=>a.rotate(t),fc=(a,t)=>new D(t).subtract(a),pc=a=>a.distanceFrom(Wp),mc=(a,t)=>Math.atan2(Oo(a,t),Xp(a,t)),zp=a=>mc(Qv,a),bc=a=>a.eq(Wp)?a:a.scalarDivide(pc(a)),Nu=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return bc(new D(-a.y,a.x).scalarMultiply(t?1:-1))},Oo=(a,t)=>a.x*t.y-a.y*t.x,Xp=(a,t)=>a.x*t.x+a.y*t.y,Bu=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=Oo(t,e),i=Oo(t,a),n=Oo(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},Vp="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Gp=new RegExp("(?:\\s|^)"+Vp+Vp+"("+Ss+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class vi{constructor(t){const e=typeof t=="string"?vi.parseShadow(t):t;Object.assign(this,vi.ownDefaults,e),this.id=dn()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Gp.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(Gp,"")||"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=ju(new D(this.offsetX,this.offsetY),Ot(-t.angle)),s=new ut(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*xt((Math.abs(e.x)+this.blur)/t.width,at.NUM_FRACTION_DIGITS)+20,n=100*xt((Math.abs(e.y)+this.blur)/t.height,at.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(n,'%" height="').concat(100+2*n,'%" x="-').concat(i,'%" width="').concat(100+2*i,`%" >
27
+ `),s?s(p.join("")):p.join("")}addPaintOrder(){return this.paintFirst!==jt?' paint-order="'.concat(this.paintFirst,'" '):""}}function gc(a){return new RegExp("^("+a.join("|")+")\\b","i")}var jp;const Ss=String.raw(jp||(jp=hn(["(?:[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?)"],["(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)"]))),Ru="http://www.w3.org/2000/svg",Yv=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Ss+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Ss+"))?\\s+(.*)"),Uv={cx:lt,x:lt,r:"radius",cy:Le,y:Le,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"},Lu="font-size",Iu="clip-path",qv=gc(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),$v=gc(["symbol","image","marker","pattern","view","svg"]),Np=gc(["symbol","g","a","svg","clipPath","defs"]),Bp=new RegExp("^\\s*("+Ss+"+)\\s*,?\\s*("+Ss+"+)\\s*,?\\s*("+Ss+"+)\\s*,?\\s*("+Ss+"+)\\s*$"),Kv=new D(1,0),Hp=new D,ju=(a,t)=>a.rotate(t),fc=(a,t)=>new D(t).subtract(a),pc=a=>a.distanceFrom(Hp),mc=(a,t)=>Math.atan2(Oo(a,t),zp(a,t)),Wp=a=>mc(Kv,a),bc=a=>a.eq(Hp)?a:a.scalarDivide(pc(a)),Nu=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return bc(new D(-a.y,a.x).scalarMultiply(t?1:-1))},Oo=(a,t)=>a.x*t.y-a.y*t.x,zp=(a,t)=>a.x*t.x+a.y*t.y,Bu=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=Oo(t,e),i=Oo(t,a),n=Oo(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},Xp="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Vp=new RegExp("(?:\\s|^)"+Xp+Xp+"("+Ss+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class vi{constructor(t){const e=typeof t=="string"?vi.parseShadow(t):t;Object.assign(this,vi.ownDefaults,e),this.id=dn()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Vp.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(Vp,"")||"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=ju(new D(this.offsetX,this.offsetY),Ot(-t.angle)),s=new ut(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*xt((Math.abs(e.x)+this.blur)/t.width,at.NUM_FRACTION_DIGITS)+20,n=100*xt((Math.abs(e.y)+this.blur)/t.height,at.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(n,'%" height="').concat(100+2*n,'%" x="-').concat(i,'%" width="').concat(100+2*i,`%" >
28
28
  <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(xt(this.blur?this.blur/2:0,at.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
29
29
  <feOffset dx="`).concat(xt(e.x,at.NUM_FRACTION_DIGITS),'" dy="').concat(xt(e.y,at.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=vi.ownDefaults;return this.includeDefaultValues?t:Tu(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}A(vi,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),A(vi,"type","shadow"),N.setClass(vi,"shadow");const sr=(a,t,e)=>Math.max(a,Math.min(t,e)),Jv=[Le,lt,Se,Ve,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",So,Co],yi=[jt,Ce,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Zv={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:lt,originY:Le,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:jt,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},Hu=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/bi*Math.asin(1):e/bi*Math.asin(t/a),{a,c:t,p:e,s}),Yp=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*bi/e),Up=(a,t,e,s)=>-e*Math.cos(a/s*ln)+e+t,Wu=(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,qp=(a,t,e,s)=>e-Wu(s-a,0,e,s)+t;var ty=Object.freeze({__proto__:null,defaultEasing:Up,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:qp,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}=Hu(i,e,n,1.70158);return-Yp(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*qp(2*a,0,e,s)+t:.5*Wu(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}=Hu(i,e,n,1.70158);return a<1?-.5*Yp(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*bi/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*ln)+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:Wu,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}=Hu(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*bi/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*ln)+t});const ey=()=>!1;class zu{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Up,onStart:o=Kn,onChange:h=Kn,onComplete:l=Kn,abort:d=ey,target:u}=t;A(this,"_state","pending"),A(this,"durationProgress",0),A(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=o,this._onChange=h,this._onComplete=l,this._abort=d,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>$a(t),this.delay):$a(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),$a(this.tick)))}register(){rc.push(this)}unregister(){rc.remove(this)}abort(){this._state="aborted",this.unregister()}}const sy=["startValue","endValue"];class iy extends zu{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(T(T({},wt(t,sy)),{},{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 ny=["startValue","endValue"];class ry extends zu{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(T(T({},wt(t,ny)),{},{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 oy=["startValue","endValue","easing","onChange","onComplete","abort"],ay=(a,t,e,s)=>t+e*(1-Math.cos(a/s*ln)),Xu=a=>a&&((t,e,s)=>a(new ut(t).toRgba(),e,s));class hy extends zu{constructor(t){let{startValue:e,endValue:s,easing:i=ay,onChange:n,onComplete:r,abort:o}=t,h=wt(t,oy);const l=new ut(e).getSource(),d=new ut(s).getSource();super(T(T({},h),{},{startValue:l,byValue:d.map((u,g)=>u-l[g]),easing:i,onChange:Xu(n),onComplete:Xu(r),abort:Xu(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),sr(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 Vu(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new ry(a):new iy(a);return t.start(),t}function $p(a){const t=new hy(a);return t.start(),t}class At{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter(i=>!this.includes(i))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=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 D(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,y=p/m;return(n||0<=_&&_<=1)&&(r||0<=y&&y<=1)?new At("Intersection").append(new D(t.x+_*o,t.y+_*h)):new At}if(f===0||p===0){const _=n||r||At.isPointContained(t,s,i)||At.isPointContained(e,s,i)||At.isPointContained(s,t,e)||At.isPointContained(i,t,e);return new At(_?"Coincident":void 0)}return new At("Parallel")}static intersectSegmentLine(t,e,s,i){return At.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return At.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new At,r=s.length;for(let o,h,l,d=0;d<r;d++){if(o=s[d],h=s[(d+1)%r],l=At.intersectLineLine(t,e,o,h,i,!1),l.status==="Coincident")return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return At.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new At,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=At.intersectSegmentPolygon(o,h,e);l.status==="Coincident"?(n.push(l),s.append(o,h)):s.append(...l.points)}return n.length>0&&n.length===t.length?new At("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new D(n.x,i.y),o=new D(i.x,n.y);return At.intersectPolygonPolygon(t,[i,r,n,o])}}class ly extends lp{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?ce(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=ce(t,Ie(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new D(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:i}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,s,i];if(this.group){const r=this.group.calcTransformMatrix();return n.map(o=>ce(o,r))}return n}intersectsWithRect(t,e){return At.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=At.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return At.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every(s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Gs(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Se,t),this._set(Ve,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?un(gp(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||we.concat()}calcACoords(){const t=Eo({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=To(e,s),n=Rt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:ce({x:-o,y:-h},n),tr:ce({x:o,y:-h},n),bl:ce({x:-o,y:h},n),br:ce({x:o,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,Nt(this.originX),Nt(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=Rt(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 D(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=T({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,o=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new D(r*e.scaleX,o*e.scaleY):dc(r,o,Ka(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=Nt(i)-Nt(e),l=Nt(n)-Nt(s);if(h||l){const d=this._getTransformedDimensions();r+=h*d.x,o+=l*d.y}return new D(r,o)}translateToCenterPoint(t,e,s){if(e===Q&&s===Q)return t;const i=this.translateToGivenOrigin(t,e,s,Q,Q);return this.angle?i.rotate(Ot(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,Q,Q,e,s);return this.angle?i.rotate(Ot(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?ce(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new D(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(),lt,Le)}}const cy=["type"],dy=["extraParam"];let _i=class Nd extends ly{static getDefaults(){return Nd.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){mi("warn","Setting type has no effect",t)}constructor(t){super(),A(this,"_cacheContext",null),Object.assign(this,Nd.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=ns(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=at.maxCacheSideLimit,n=at.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=at.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=Ua.limitDimsByArea(r),l=sr(n,o,i),d=sr(n,h,i);return e>l&&(t.zoomX/=e/l,t.width=l,t.capped=!0),s>d&&(t.zoomY/=s/d,t.height=d,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,i=e.y*t.y/this.scaleY;return{width:s+2,height:i+2,zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,s=this._limitCacheSize(this._getCacheCanvasDimensions()),i=at.minCacheSideLimit,n=s.width,r=s.height,o=s.zoomX,h=s.zoomY,l=n!==t.width||r!==t.height,d=this.zoomX!==o||this.zoomY!==h;if(!t||!e)return!1;let u,g,f=l||d,p=0,m=0,_=!1;if(l){const y=this._cacheCanvas.width,x=this._cacheCanvas.height,S=n>y||r>x;_=S||(n<.9*y||r<.9*x)&&y>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])}getObjectScaling(){if(!this.group)return new D(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Jn(this.calcTransformMatrix());return new D(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!==Se&&t!==Ve||(e=this._constrainScale(e)),t===Se&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof vi||(e=new vi(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,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n}=this,{width:r,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n,width:r,height:o,parentClipPaths:[]}),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===Ce&&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,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=_s(e),i=s.getContext("2d");if(i.translate(e.cacheTranslationX,e.cacheTranslationY),i.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach(n=>{n.transform(i)}),e.parentClipPaths.push(t),t.absolutePositioned){const n=Ie(this.calcTransformMatrix());i.transform(n[0],n[1],n[2],n[3],n[4],n[5])}return t.transform(i),t.drawObject(i,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const i=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,i)}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,rs(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&&(rs(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)||we,o=n*i,h=r*i,l=e.nonScaling?new D(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*at.browserShadowBlurConstant*(o+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!rs(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===Ce?(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=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,o=i.y/this.scaleY/n,h=_s({width:Math.ceil(r),height:Math.ceil(o)}),l=h.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(r,0),l.lineTo(r,o),l.lineTo(0,o),l.closePath(),l.translate(r/2,o/2),l.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),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(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=l.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new D(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(N.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Du(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 eh(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Op(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Pu(this,this.getViewportTransform()),this.setCoords();const l=ns(),d=this.getBoundingRect(),u=this.shadow,g=new D;if(u){const x=u.blur,S=u.nonScaling?new D(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 D(m.width/2,m.height/2),Q,Q);const _=this.canvas;m._objects=[this],this.set("canvas",m),this.setCoords();const y=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(),y}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Su(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(){rc.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Vs().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s},{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:o,onChange:h,onComplete:l}=s,d=T(T({},s),{},{target:this,startValue:o??i.reduce((u,g)=>u[g],this),endValue:e,abort:r==null?void 0:r.bind(this),onChange:(u,g,f)=>{i.reduce((p,m,_)=>(_===i.length-1&&(p[m]=u),p[m]),this),h&&h(u,g,f)},onComplete:(u,g,f)=>{this.setCoords(),l&&l(u,g,f)}});return n?$p(d):Vu(d)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let i,n=0;n<e.length;n++){if(i=e[n],i===t)return{fork:[this,...e.slice(0,n)],otherFork:[],common:e.slice(n)};for(let r=0;r<s.length;r++){if(this===s[r])return{fork:[],otherFork:[t,...s.slice(0,r)],common:[this,...e]};if(i===s[r])return{fork:[this,...e.slice(0,n)],otherFork:[t,...s.slice(0,r)],common:e.slice(n)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const i=e.fork.pop(),n=e.otherFork.pop(),r=s._objects.indexOf(i),o=s._objects.indexOf(n);return r>-1&&r>o}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Nd.customProperties,this.constructor.customProperties||[]);let e;const s=at.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:l,top:d,originX:u,originY:g,width:f,height:p,strokeWidth:m,strokeLineCap:_,strokeDashOffset:y,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:C,scaleX:E,scaleY:M,angle:k,flipX:O,flipY:P,opacity:F,visible:R,backgroundColor:W,fillRule:B,paintFirst:X,globalCompositeOperation:K,skewX:tt,skewY:V}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const H=Jt=>xt(Jt,s),Qt=T(T({},Zn(this,t)),{},{type:this.constructor.type,version:pu,originX:u,originY:g,left:H(l),top:H(d),width:H(f),height:H(p),fill:_p(n)?n.toObject():n,stroke:_p(r)?r.toObject():r,strokeWidth:H(m),strokeDashArray:h&&h.concat(),strokeLineCap:_,strokeDashOffset:y,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:H(C),scaleX:H(E),scaleY:H(M),angle:H(k),flipX:O,flipY:P,opacity:H(F),shadow:o&&o.toObject(),visible:R,backgroundColor:W,fillRule:B,paintFirst:X,globalCompositeOperation:K,skewX:H(tt),skewY:H(V)},e?{clipPath:e}:null);return this.includeDefaultValues?Qt:this._removeDefaultValues(Qt)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Tu(t,(i,n)=>{if(n===lt||n===Le||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=wt(t,cy),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=wt(s,dy);return Ja(e,n).then(r=>i?(delete r[i],new this(e[i],r)):new this(r))}static fromObject(t,e){return this._fromObject(t,e)}};A(_i,"stateProperties",Jv),A(_i,"cacheProperties",yi),A(_i,"ownDefaults",Zv),A(_i,"type","FabricObject"),A(_i,"colorProperties",[jt,Ce,"backgroundColor"]),A(_i,"customProperties",[]),N.setClass(_i),N.setClass(_i,"object");const Do=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Pp(a,T(T({},Lp(s,i,n,r)),e)),o};function Po(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 Kp=Do(qa,Po((a,t,e,s)=>{const i=Fu(t,t.originX,t.originY,e,s);if(Nt(t.originX)===Nt(Q)||Nt(t.originX)===Nt(Ft)&&i.x<0||Nt(t.originX)===Nt(lt)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=Fp(t)?2:1,h=n.width,l=Math.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(l,1)),h!==n.width}return!1}));function uy(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?Ce:jt,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,bi,!1),a[h](),l&&a.stroke(),a.restore()}function gy(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?Ce:jt,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(Ot(g)),a["".concat(h,"Rect")](-d,-u,n,r),l&&a.strokeRect(-d,-u,n,r),a.restore()}class Cs{constructor(t){A(this,"visible",!0),A(this,"actionName",ic),A(this,"angle",0),A(this,"x",0),A(this,"y",0),A(this,"offsetX",0),A(this,"offsetY",0),A(this,"sizeX",0),A(this,"sizeY",0),A(this,"touchSizeX",0),A(this,"touchSizeY",0),A(this,"cursorStyle","crosshair"),A(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:l}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&At.isPointInPolygon(s,[r,o,h,l])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new D(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=ac([To(s,i),Eo({angle:t}),hc((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new D(-.5,-.5).transform(o),tr:new D(.5,-.5).transform(o),br:new D(.5,.5).transform(o),bl:new D(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?uy.call(this,t,e,s,i,n):gy.call(this,t,e,s,i,n)}}const fy=(a,t,e)=>e.lockRotation?uc:t.cursorStyle,py=Do(op,Po((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(xs(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=un(g-u+o);if(i.snapAngle&&i.snapAngle>0){const m=i.snapAngle,_=i.snapThreshold||m,y=Math.ceil(f/m)*m,x=Math.floor(f/m)*m;Math.abs(f-x)<_?f=x:Math.abs(f-y)<_&&(f=y)}f<0&&(f=360+f),f%=360;const p=i.angle!==f;return i.angle=f,p}));function Qp(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Jp(a,t,e){const s=xs(a,"lockScalingX"),i=xs(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 my=["e","se","s","sw","w","nw","n","ne","e"],ih=(a,t,e)=>{const s=Qp(a,e);if(Jp(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return uc;const i=Ip(e,t);return"".concat(my[i],"-resize")};function Gu(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Qp(a,n);let h,l,d,u,g,f;if(Jp(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,d=t.scaleY*t.gestureScale;else{if(h=Fu(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),xs(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:y}=t,x=_/(Math.abs(u.x*y.scaleX/n.scaleX)+Math.abs(u.y*y.scaleY/n.scaleY));l=y.scaleX*x,d=y.scaleY*x}else l=Math.abs(h.x*n.scaleX/u.x),d=Math.abs(h.y*n.scaleY/u.y);Fp(t)&&(l*=2,d*=2),t.signX!==g&&r!=="y"&&(t.originX=Rp(t.originX),l*=-1,t.signX=g),t.signY!==f&&r!=="x"&&(t.originY=Rp(t.originY),d*=-1,t.signY=f)}const p=n.scaleX,m=n.scaleY;return r?(r==="x"&&n.set(Se,l),r==="y"&&n.set(Ve,d)):(!xs(n,"lockScalingX")&&n.set(Se,l),!xs(n,"lockScalingY")&&n.set(Ve,d)),p!==n.scaleX||m!==n.scaleY}const vc=Do(ec,Po((a,t,e,s)=>Gu(a,t,e,s))),by=Do(ec,Po((a,t,e,s)=>Gu(a,t,e,s,{by:"x"}))),vy=Do(ec,Po((a,t,e,s)=>Gu(a,t,e,s,{by:"y"}))),yy=["target","ex","ey","skewingSide"],Yu={x:{counterAxis:"y",scale:Se,skew:So,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Ve,skew:Co,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},_y=["ns","nesw","ew","nwse"],wy=(a,t,e)=>{if(t.x!==0&&xs(e,"lockSkewingY")||t.y!==0&&xs(e,"lockSkewingX"))return uc;const s=Ip(e,t)%4;return"".concat(_y[s],"-resize")};function Zp(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:d}=Yu[a];if(xs(n,h))return!1;const{origin:u,flip:g}=Yu[r],f=Nt(e[u])*(n[g]?-1:1),p=-Math.sign(f)*(n[d]?-1:1),m=.5*-((n[l]===0&&Fu(e,Q,Q,s,i)[a]>0||n[l]>0?1:-1)*p)+.5;return Do(ap,Po((y,x,S,C)=>function(E,M,k){let{target:O,ex:P,ey:F,skewingSide:R}=M,W=wt(M,yy);const{skew:B}=Yu[E],X=k.subtract(new D(P,F)).divide(new D(O.scaleX,O.scaleY))[E],K=O[B],tt=W[B],V=Math.tan(Ot(tt)),H=E==="y"?O._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:O._getTransformedDimensions({scaleX:1,scaleY:1}).y,Qt=2*X*R/Math.max(H,1)+V,Jt=un(Math.atan(Qt));O.set(B,Jt);const le=K!==O[B];if(le&&E==="y"){const{skewX:zt,scaleX:_t}=O,Pe=O._getTransformedDimensions({skewY:K}),fi=O._getTransformedDimensions(),Pt=zt!==0?Pe.x/fi.x:1;Pt!==1&&O.set(Se,Pt*_t)}return le}(a,x,new D(S,C))))(t,T(T({},e),{},{[o]:m,skewingSide:p}),s,i)}const xy=(a,t,e,s)=>Zp("x",a,t,e,s),Sy=(a,t,e,s)=>Zp("y",a,t,e,s);function yc(a,t){return a[t.canvas.altActionKey]}const _c=(a,t,e)=>{const s=yc(a,e);return t.x===0?s?So:Ve:t.y===0?s?Co:Se:""},Fo=(a,t,e)=>yc(a,e)?wy(0,t,e):ih(a,t,e),tm=(a,t,e,s)=>yc(a,t.target)?Sy(a,t,e,s):by(a,t,e,s),em=(a,t,e,s)=>yc(a,t.target)?xy(a,t,e,s):vy(a,t,e,s),sm=()=>({ml:new Cs({x:-.5,y:0,cursorStyleHandler:Fo,actionHandler:tm,getActionName:_c}),mr:new Cs({x:.5,y:0,cursorStyleHandler:Fo,actionHandler:tm,getActionName:_c}),mb:new Cs({x:0,y:.5,cursorStyleHandler:Fo,actionHandler:em,getActionName:_c}),mt:new Cs({x:0,y:-.5,cursorStyleHandler:Fo,actionHandler:em,getActionName:_c}),tl:new Cs({x:-.5,y:-.5,cursorStyleHandler:ih,actionHandler:vc}),tr:new Cs({x:.5,y:-.5,cursorStyleHandler:ih,actionHandler:vc}),bl:new Cs({x:-.5,y:.5,cursorStyleHandler:ih,actionHandler:vc}),br:new Cs({x:.5,y:.5,cursorStyleHandler:ih,actionHandler:vc}),mtr:new Cs({x:0,y:-.5,actionHandler:py,cursorStyleHandler:fy,offsetY:-40,withConnection:!0,actionName:_u})}),Cy=()=>({mr:new Cs({x:.5,y:0,actionHandler:Kp,cursorStyleHandler:Fo,actionName:qa}),ml:new Cs({x:-.5,y:0,actionHandler:Kp,cursorStyleHandler:Fo,actionName:qa})}),Ay=()=>T(T({},sm()),Cy());class nh extends _i{static getDefaults(){return T(T({},super.getDefaults()),nh.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),nh.ownDefaults),this.setOptions(t)}static createControls(){return{controls:sm()}}_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(ic))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=To(e.x,e.y),i=Eo({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=Rt(s,i),r=Rt(t,n),o=Rt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Jn(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(Ot(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=T({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=i.borderColor,this._setLineDash(t,i.borderDashArray),this.strokeBorders(t,e),i.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:i}=this,n=T({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=Rt(r,this.calcTransformMatrix()),d=Jn(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(Ot(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=dc(this.width,this.height,Ka(e)),r=this.isStrokeAccountedForInDimensions()?xu:(this.strokeUniform?new D().scalarAdd(this.canvas?this.canvas.getZoom():1):new D(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);i=n.add(r).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else i=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,i,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl((i,n)=>{i.withConnection&&i.getVisibility(this,n)&&(s=!0,t.moveTo(i.x*e.x,i.y*e.y),t.lineTo(i.x*e.x+i.offsetX,i.y*e.y+i.offsetY))}),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:i,cornerDashArray:n,cornerColor:r}=this,o=T({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl((h,l)=>{if(h.getVisibility(this,l)){const d=this.oCoords[l];h.render(t,d.x,d.y,o,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,i]=e;return this.setControlVisible(s,i)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const i=this.width+4,n=this.height+4;return e.clearRect(-i/2,-n/2,i,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function im(a,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(a.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),a}A(nh,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class de extends nh{}im(de,[jp]),N.setClass(de),N.setClass(de,"object");const nm=(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 rm{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new D(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new D(1/this.options.scaleX,1/this.options.scaleY):new D(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 D(t);return e.y+=e.x*Math.tan(Ot(this.options.skewY)),e.x+=e.y*Math.tan(Ot(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const Ty=new D;class Ro extends rm{static getOrthogonalRotationFactor(t,e){const s=e?mc(t,e):zp(t);return Math.abs(s)<ln?-1:1}constructor(t,e,s,i){super(i),A(this,"AB",void 0),A(this,"AC",void 0),A(this,"alpha",void 0),A(this,"bisector",void 0),this.A=new D(t),this.B=new D(e),this.C=new D(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=bc(ju(this.AB.eq(Ty)?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=Nu(i),r=Ro.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%bi==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 D(Ro.getOrthogonalRotationFactor(this.bisector),Ro.getOrthogonalRotationFactor(new D(this.bisector.y,this.bisector.x)));return[new D(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new D(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{Bu(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 D(Math.tan(Ot(i)),Math.tan(Ot(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 D(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 D(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=>{Bu(m,t,e)&&s.push(this.applySkew(this.A).add(m))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%bi==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=Oo(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 om extends rm{constructor(t,e,s){super(s),this.A=new D(t),this.T=new D(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(Nu(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 D(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 Ro(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new D(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(bc(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 am=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 D(r)),n),[new D(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 om(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Ro(n,h,l,t).project()):s.push(...new om(n,r===0?l:h,t).project())}),s},Uu=a=>{const t={};return Object.keys(a).forEach(e=>{t[e]={},Object.keys(a[e]).forEach(s=>{t[e][s]=T({},a[e][s])})}),t},hm=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),wc=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=Ey(a,s))!==!1&&t.push(e);return t},Ey=(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 ky=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:hm,graphemeSplit:wc});const xc=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)},lm=(a,t)=>{const e=t.split(`
38
- `),s=[];let i=-1,n={};a=Uu(a);for(let r=0;r<e.length;r++){const o=wc(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&&(xc(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},cm=(a,t)=>{if(!Array.isArray(a))return Uu(a);const e=t.split(yu),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=wc(e[r]);for(let h=0;h<o.length;h++)i++,a[n]&&a[n].start<=i&&i<a[n].end&&(s[r]=s[r]||{},s[r][h]=T({},a[n].style),i===a[n].end-1&&n++)}return s},gn=["display","transform",jt,"fill-opacity","fill-rule","opacity",Ce,"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 dm(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 My(a,t){let e=!0;const s=dm(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=dm(i=i.parentElement,r);return n.length===0}(a,t)),s&&e&&t.length===0}const Oy=a=>{var t;return(t=qv[a])!==null&&t!==void 0?t:a},Dy=new RegExp("(".concat(Ss,")"),"gi"),Py=a=>a.replace(Dy," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var um,gm,fm,pm,mm,bm,vm;const Te="(".concat(Ss,")"),Fy=String.raw(um||(um=hn(["(skewX)(",")"],["(skewX)\\(","\\)"])),Te),Ry=String.raw(gm||(gm=hn(["(skewY)(",")"],["(skewY)\\(","\\)"])),Te),Ly=String.raw(fm||(fm=hn(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Te,Te,Te),Iy=String.raw(pm||(pm=hn(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Te,Te),jy=String.raw(mm||(mm=hn(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Te,Te),Ny=String.raw(bm||(bm=hn(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Te,Te,Te,Te,Te,Te),qu="(?:".concat(Ny,"|").concat(jy,"|").concat(Ly,"|").concat(Iy,"|").concat(Fy,"|").concat(Ry,")"),By="(?:".concat(qu,"*)"),Hy=String.raw(vm||(vm=hn(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),By),Wy=new RegExp(Hy),zy=new RegExp(qu),Xy=new RegExp(qu,"g");function Sc(a){const t=[];if(!(a=Py(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!Wy.test(a))return[...we];for(const e of a.matchAll(Xy)){const s=zy.exec(e[0]);if(!s)continue;let i=we;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=To(h,l);break;case _u:i=Eo({angle:h},{x:l,y:d});break;case ic:i=hc(h,l);break;case So:i=Cu(h);break;case Co:i=Au(h);break;case"matrix":i=[h,l,d,u,g,f]}t.push(i)}return ac(t)}function Vy(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==jt&&a!==Ce||t!==xe){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===xe?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?Rt(e.transformMatrix,Sc(t)):Sc(t);else if(a==="visible")r=t!==xe&&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"?lt:t==="end"?Ft:Q;else if(a==="charSpacing")n=Ae(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(jt),h=t.indexOf(Ce);r=jt,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=Ce)}else{if(a==="href"||a==="xlink:href"||a==="font"||a==="id")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(Ae):Ae(t,s)}}else r="";return!i&&isNaN(n)?r:n}function Gy(a,t){const e=a.match(Uv);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=Ae(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function $u(a,t){a.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function Yy(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?$u(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 Uy={stroke:"strokeOpacity",fill:"fillOpacity"};function wi(a,t,e){if(!a)return{};let s,i={},n=bu;a.parentNode&&Bp.test(a.parentNode.nodeName)&&(i=wi(a.parentElement,t,e),i.fontSize&&(s=n=Ae(i.fontSize)));const r=T(T(T({},t.reduce((l,d)=>{const u=a.getAttribute(d);return u&&(l[d]=u),l},{})),function(l){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const g in d)My(l,g.split(" "))&&(u=T(T({},u),d[g]));return u}(a,e)),Yy(a));r[Iu]&&a.setAttribute(Iu,r[Iu]),r[Lu]&&(s=Ae(r[Lu],n),r[Lu]="".concat(s));const o={};for(const l in r){const d=Oy(l),u=Vy(d,r[l],i,s);o[d]=u}o&&o.font&&Gy(o.font,o);const h=T(T({},i),o);return Bp.test(a.nodeName)?h:function(l){const d=de.getDefaults();return Object.entries(Uy).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(xt(p.getAlpha()*l[f],2)).toRgba()}),l}(h)}const qy=["left","top","width","height","visible"],ym=["rx","ry"];class Ys extends de{static getDefaults(){return T(T({},super.getDefaults()),Ys.ownDefaults)}constructor(t){super(),Object.assign(this,Ys.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-cn*r,n,i+e,n+cn*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-cn*o,i+e-cn*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+cn*r,n+s,i,n+s-cn*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+cn*o,i+cn*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([...ym,...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=wi(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,d=wt(i,qy);return new this(T(T(T({},e),d),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}A(Ys,"type","Rect"),A(Ys,"cacheProperties",[...yi,...ym]),A(Ys,"ownDefaults",{rx:0,ry:0}),A(Ys,"ATTRIBUTE_NAMES",[...gn,"x","y","rx","ry","width","height"]),N.setClass(Ys),N.setSVGClass(Ys);const xi="initialization",Cc="added",Ku="removed",Ac="imperative",_m=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?sh(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),d=e&&l?Dp(new D(s,s),void 0,a.calcTransformMatrix()):xu,u=!e&&l?s:0,g=dc(i+u,n+u,ac([o,t.calcOwnMatrix()],!0)).add(d).scalarDivide(2);return[h.subtract(g),h.add(g)]};class Tc{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===xi||e===Ac||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==xi&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Ac&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Gs(t.map(u=>_m(i,u)).reduce((u,g)=>u.concat(g),[])),l=new D(o,h),d=new D(n,r).add(l.scalarDivide(2));if(s===xi){const u=this.getInitialSize(e,{size:l,center:d});return{center:d,relativeCorrection:new D(0,0),size:u}}return{center:d.transform(i.calcOwnMatrix()),size:l}}}A(Tc,"type","strategy");class Qu extends Tc{shouldPerformLayout(t){return!0}}A(Qu,"type","fit-content"),N.setClass(Qu);const $y=["strategy"],Ky=["target","strategy","bubbles","prevStrategy"],wm="layoutManager";class rh{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Qu;A(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=T(T({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[nc,rp,qa,op,ec,ap,sc,Nv,Bv].map(i=>t.on(i,n=>this.performLayout(i===nc?{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===xi||s===Cc?this.subscribeTargets(t):s===Ku&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Ac&&t.deep){const n=wt(t,$y);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(T(T({},n),{},{bubbles:!1,target:r})))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===xi?new D:e.getRelativeCenterPoint(),{center:o,correction:h=new D,relativeCorrection:l=new D}=n,d=r.subtract(o).add(h).transform(i===xi?we:Ie(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===xi?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*Nt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*Nt(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=wt(t,Ky),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;n&&l!=null&&l.layoutManager&&((o.path||(o.path=[])).push(s),l.layoutManager.performLayout(T(T({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:wm,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}N.setClass(rh,wm);const Qy=["type","objects","layoutManager"];class Jy extends rh{performLayout(){}}class Us extends hp(de){static getDefaults(){return T(T({},super.getDefaults()),Us.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),A(this,"_activeObjects",[]),A(this,"__objectSelectionTracker",void 0),A(this,"__objectSelectionDisposer",void 0),Object.assign(this,Us.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 rh,this.layoutManager.performLayout({type:xi,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(mi("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(mi("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(Cc,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(Cc,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Ku,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,Rt(Ie(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,Rt(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=de.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let n=0;n<this._objects.length;n++){var i;const r=this._objects[n];(i=this.canvas)!==null&&i!==void 0&&i.preserveObjectStacking&&r.group!==this?(t.save(),t.transform(...Ie(this.calcTransformMatrix())),r.render(t),t.restore()):r.group===this&&r.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(T({target:this,type:Ac},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter(function(i){return!i.excludeFromExport}).map(function(i){const n=i.includeDefaultValues;i.includeDefaultValues=s;const r=i[t||"toObject"](e);return i.includeDefaultValues=n,r})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return T(T(T({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Ys.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=vi.ownDefaults;return this.includeDefaultValues?t:Tu(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}A(vi,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),A(vi,"type","shadow"),N.setClass(vi,"shadow");const sr=(a,t,e)=>Math.max(a,Math.min(t,e)),Qv=[Le,lt,Se,Ve,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",So,Co],yi=[jt,Ce,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Jv={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:lt,originY:Le,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:jt,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},Hu=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/bi*Math.asin(1):e/bi*Math.asin(t/a),{a,c:t,p:e,s}),Gp=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*bi/e),Yp=(a,t,e,s)=>-e*Math.cos(a/s*ln)+e+t,Wu=(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,Up=(a,t,e,s)=>e-Wu(s-a,0,e,s)+t;var Zv=Object.freeze({__proto__:null,defaultEasing:Yp,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:Up,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}=Hu(i,e,n,1.70158);return-Gp(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*Up(2*a,0,e,s)+t:.5*Wu(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}=Hu(i,e,n,1.70158);return a<1?-.5*Gp(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*bi/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*ln)+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:Wu,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}=Hu(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*bi/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*ln)+t});const ty=()=>!1;class zu{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Yp,onStart:o=Kn,onChange:h=Kn,onComplete:l=Kn,abort:d=ty,target:u}=t;A(this,"_state","pending"),A(this,"durationProgress",0),A(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=o,this._onChange=h,this._onComplete=l,this._abort=d,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>$a(t),this.delay):$a(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),$a(this.tick)))}register(){rc.push(this)}unregister(){rc.remove(this)}abort(){this._state="aborted",this.unregister()}}const ey=["startValue","endValue"];class sy extends zu{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(T(T({},wt(t,ey)),{},{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 iy=["startValue","endValue"];class ny extends zu{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(T(T({},wt(t,iy)),{},{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 ry=["startValue","endValue","easing","onChange","onComplete","abort"],oy=(a,t,e,s)=>t+e*(1-Math.cos(a/s*ln)),Xu=a=>a&&((t,e,s)=>a(new ut(t).toRgba(),e,s));class ay extends zu{constructor(t){let{startValue:e,endValue:s,easing:i=oy,onChange:n,onComplete:r,abort:o}=t,h=wt(t,ry);const l=new ut(e).getSource(),d=new ut(s).getSource();super(T(T({},h),{},{startValue:l,byValue:d.map((u,g)=>u-l[g]),easing:i,onChange:Xu(n),onComplete:Xu(r),abort:Xu(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),sr(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 Vu(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new ny(a):new sy(a);return t.start(),t}function qp(a){const t=new ay(a);return t.start(),t}class At{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter(i=>!this.includes(i))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=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 D(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,y=p/m;return(n||0<=_&&_<=1)&&(r||0<=y&&y<=1)?new At("Intersection").append(new D(t.x+_*o,t.y+_*h)):new At}if(f===0||p===0){const _=n||r||At.isPointContained(t,s,i)||At.isPointContained(e,s,i)||At.isPointContained(s,t,e)||At.isPointContained(i,t,e);return new At(_?"Coincident":void 0)}return new At("Parallel")}static intersectSegmentLine(t,e,s,i){return At.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return At.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new At,r=s.length;for(let o,h,l,d=0;d<r;d++){if(o=s[d],h=s[(d+1)%r],l=At.intersectLineLine(t,e,o,h,i,!1),l.status==="Coincident")return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return At.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new At,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=At.intersectSegmentPolygon(o,h,e);l.status==="Coincident"?(n.push(l),s.append(o,h)):s.append(...l.points)}return n.length>0&&n.length===t.length?new At("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new D(n.x,i.y),o=new D(i.x,n.y);return At.intersectPolygonPolygon(t,[i,r,n,o])}}class hy extends hp{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?ce(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=ce(t,Ie(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new D(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:i}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,s,i];if(this.group){const r=this.group.calcTransformMatrix();return n.map(o=>ce(o,r))}return n}intersectsWithRect(t,e){return At.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=At.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return At.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every(s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Gs(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Se,t),this._set(Ve,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?un(up(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||we.concat()}calcACoords(){const t=Eo({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=To(e,s),n=Rt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:ce({x:-o,y:-h},n),tr:ce({x:o,y:-h},n),bl:ce({x:-o,y:h},n),br:ce({x:o,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,Nt(this.originX),Nt(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=Rt(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 D(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=T({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,o=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new D(r*e.scaleX,o*e.scaleY):dc(r,o,Ka(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=Nt(i)-Nt(e),l=Nt(n)-Nt(s);if(h||l){const d=this._getTransformedDimensions();r+=h*d.x,o+=l*d.y}return new D(r,o)}translateToCenterPoint(t,e,s){if(e===Q&&s===Q)return t;const i=this.translateToGivenOrigin(t,e,s,Q,Q);return this.angle?i.rotate(Ot(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,Q,Q,e,s);return this.angle?i.rotate(Ot(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?ce(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new D(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(),lt,Le)}}const ly=["type"],cy=["extraParam"];let _i=class Nd extends hy{static getDefaults(){return Nd.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){mi("warn","Setting type has no effect",t)}constructor(t){super(),A(this,"_cacheContext",null),Object.assign(this,Nd.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=ns(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=at.maxCacheSideLimit,n=at.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=at.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=Ua.limitDimsByArea(r),l=sr(n,o,i),d=sr(n,h,i);return e>l&&(t.zoomX/=e/l,t.width=l,t.capped=!0),s>d&&(t.zoomY/=s/d,t.height=d,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,i=e.y*t.y/this.scaleY;return{width:s+2,height:i+2,zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,s=this._limitCacheSize(this._getCacheCanvasDimensions()),i=at.minCacheSideLimit,n=s.width,r=s.height,o=s.zoomX,h=s.zoomY,l=n!==t.width||r!==t.height,d=this.zoomX!==o||this.zoomY!==h;if(!t||!e)return!1;let u,g,f=l||d,p=0,m=0,_=!1;if(l){const y=this._cacheCanvas.width,x=this._cacheCanvas.height,S=n>y||r>x;_=S||(n<.9*y||r<.9*x)&&y>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])}getObjectScaling(){if(!this.group)return new D(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Jn(this.calcTransformMatrix());return new D(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!==Se&&t!==Ve||(e=this._constrainScale(e)),t===Se&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof vi||(e=new vi(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,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n}=this,{width:r,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n,width:r,height:o,parentClipPaths:[]}),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===Ce&&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,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=_s(e),i=s.getContext("2d");if(i.translate(e.cacheTranslationX,e.cacheTranslationY),i.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach(n=>{n.transform(i)}),e.parentClipPaths.push(t),t.absolutePositioned){const n=Ie(this.calcTransformMatrix());i.transform(n[0],n[1],n[2],n[3],n[4],n[5])}return t.transform(i),t.drawObject(i,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const i=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,i)}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,rs(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&&(rs(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)||we,o=n*i,h=r*i,l=e.nonScaling?new D(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*at.browserShadowBlurConstant*(o+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!rs(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===Ce?(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=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,o=i.y/this.scaleY/n,h=_s({width:Math.ceil(r),height:Math.ceil(o)}),l=h.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(r,0),l.lineTo(r,o),l.lineTo(0,o),l.closePath(),l.translate(r/2,o/2),l.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),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(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=l.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new D(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(N.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Du(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 eh(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Mp(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Pu(this,this.getViewportTransform()),this.setCoords();const l=ns(),d=this.getBoundingRect(),u=this.shadow,g=new D;if(u){const x=u.blur,S=u.nonScaling?new D(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 D(m.width/2,m.height/2),Q,Q);const _=this.canvas;m._objects=[this],this.set("canvas",m),this.setCoords();const y=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(),y}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Su(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(){rc.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Vs().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s},{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:o,onChange:h,onComplete:l}=s,d=T(T({},s),{},{target:this,startValue:o??i.reduce((u,g)=>u[g],this),endValue:e,abort:r==null?void 0:r.bind(this),onChange:(u,g,f)=>{i.reduce((p,m,_)=>(_===i.length-1&&(p[m]=u),p[m]),this),h&&h(u,g,f)},onComplete:(u,g,f)=>{this.setCoords(),l&&l(u,g,f)}});return n?qp(d):Vu(d)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let i,n=0;n<e.length;n++){if(i=e[n],i===t)return{fork:[this,...e.slice(0,n)],otherFork:[],common:e.slice(n)};for(let r=0;r<s.length;r++){if(this===s[r])return{fork:[],otherFork:[t,...s.slice(0,r)],common:[this,...e]};if(i===s[r])return{fork:[this,...e.slice(0,n)],otherFork:[t,...s.slice(0,r)],common:e.slice(n)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const i=e.fork.pop(),n=e.otherFork.pop(),r=s._objects.indexOf(i),o=s._objects.indexOf(n);return r>-1&&r>o}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Nd.customProperties,this.constructor.customProperties||[]);let e;const s=at.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:l,top:d,originX:u,originY:g,width:f,height:p,strokeWidth:m,strokeLineCap:_,strokeDashOffset:y,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:C,scaleX:E,scaleY:M,angle:k,flipX:O,flipY:P,opacity:F,visible:R,backgroundColor:W,fillRule:B,paintFirst:X,globalCompositeOperation:K,skewX:tt,skewY:V}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const H=Jt=>xt(Jt,s),Qt=T(T({},Zn(this,t)),{},{type:this.constructor.type,version:pu,originX:u,originY:g,left:H(l),top:H(d),width:H(f),height:H(p),fill:yp(n)?n.toObject():n,stroke:yp(r)?r.toObject():r,strokeWidth:H(m),strokeDashArray:h&&h.concat(),strokeLineCap:_,strokeDashOffset:y,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:H(C),scaleX:H(E),scaleY:H(M),angle:H(k),flipX:O,flipY:P,opacity:H(F),shadow:o&&o.toObject(),visible:R,backgroundColor:W,fillRule:B,paintFirst:X,globalCompositeOperation:K,skewX:H(tt),skewY:H(V)},e?{clipPath:e}:null);return this.includeDefaultValues?Qt:this._removeDefaultValues(Qt)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Tu(t,(i,n)=>{if(n===lt||n===Le||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=wt(t,ly),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=wt(s,cy);return Ja(e,n).then(r=>i?(delete r[i],new this(e[i],r)):new this(r))}static fromObject(t,e){return this._fromObject(t,e)}};A(_i,"stateProperties",Qv),A(_i,"cacheProperties",yi),A(_i,"ownDefaults",Jv),A(_i,"type","FabricObject"),A(_i,"colorProperties",[jt,Ce,"backgroundColor"]),A(_i,"customProperties",[]),N.setClass(_i),N.setClass(_i,"object");const Do=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Dp(a,T(T({},Rp(s,i,n,r)),e)),o};function Po(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 $p=Do(qa,Po((a,t,e,s)=>{const i=Fu(t,t.originX,t.originY,e,s);if(Nt(t.originX)===Nt(Q)||Nt(t.originX)===Nt(Ft)&&i.x<0||Nt(t.originX)===Nt(lt)&&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.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(l,1)),h!==n.width}return!1}));function dy(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?Ce:jt,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,bi,!1),a[h](),l&&a.stroke(),a.restore()}function uy(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?Ce:jt,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(Ot(g)),a["".concat(h,"Rect")](-d,-u,n,r),l&&a.strokeRect(-d,-u,n,r),a.restore()}class Cs{constructor(t){A(this,"visible",!0),A(this,"actionName",ic),A(this,"angle",0),A(this,"x",0),A(this,"y",0),A(this,"offsetX",0),A(this,"offsetY",0),A(this,"sizeX",0),A(this,"sizeY",0),A(this,"touchSizeX",0),A(this,"touchSizeY",0),A(this,"cursorStyle","crosshair"),A(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:l}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&At.isPointInPolygon(s,[r,o,h,l])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new D(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=ac([To(s,i),Eo({angle:t}),hc((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new D(-.5,-.5).transform(o),tr:new D(.5,-.5).transform(o),br:new D(.5,.5).transform(o),bl:new D(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?dy.call(this,t,e,s,i,n):uy.call(this,t,e,s,i,n)}}const gy=(a,t,e)=>e.lockRotation?uc:t.cursorStyle,fy=Do(rp,Po((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(xs(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=un(g-u+o);if(i.snapAngle&&i.snapAngle>0){const m=i.snapAngle,_=i.snapThreshold||m,y=Math.ceil(f/m)*m,x=Math.floor(f/m)*m;Math.abs(f-x)<_?f=x:Math.abs(f-y)<_&&(f=y)}f<0&&(f=360+f),f%=360;const p=i.angle!==f;return i.angle=f,p}));function Kp(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Qp(a,t,e){const s=xs(a,"lockScalingX"),i=xs(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 py=["e","se","s","sw","w","nw","n","ne","e"],ih=(a,t,e)=>{const s=Kp(a,e);if(Qp(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return uc;const i=Lp(e,t);return"".concat(py[i],"-resize")};function Gu(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Kp(a,n);let h,l,d,u,g,f;if(Qp(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,d=t.scaleY*t.gestureScale;else{if(h=Fu(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),xs(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:y}=t,x=_/(Math.abs(u.x*y.scaleX/n.scaleX)+Math.abs(u.y*y.scaleY/n.scaleY));l=y.scaleX*x,d=y.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=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(Se,l),r==="y"&&n.set(Ve,d)):(!xs(n,"lockScalingX")&&n.set(Se,l),!xs(n,"lockScalingY")&&n.set(Ve,d)),p!==n.scaleX||m!==n.scaleY}const vc=Do(ec,Po((a,t,e,s)=>Gu(a,t,e,s))),my=Do(ec,Po((a,t,e,s)=>Gu(a,t,e,s,{by:"x"}))),by=Do(ec,Po((a,t,e,s)=>Gu(a,t,e,s,{by:"y"}))),vy=["target","ex","ey","skewingSide"],Yu={x:{counterAxis:"y",scale:Se,skew:So,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Ve,skew:Co,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},yy=["ns","nesw","ew","nwse"],_y=(a,t,e)=>{if(t.x!==0&&xs(e,"lockSkewingY")||t.y!==0&&xs(e,"lockSkewingX"))return uc;const s=Lp(e,t)%4;return"".concat(yy[s],"-resize")};function Jp(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:d}=Yu[a];if(xs(n,h))return!1;const{origin:u,flip:g}=Yu[r],f=Nt(e[u])*(n[g]?-1:1),p=-Math.sign(f)*(n[d]?-1:1),m=.5*-((n[l]===0&&Fu(e,Q,Q,s,i)[a]>0||n[l]>0?1:-1)*p)+.5;return Do(op,Po((y,x,S,C)=>function(E,M,k){let{target:O,ex:P,ey:F,skewingSide:R}=M,W=wt(M,vy);const{skew:B}=Yu[E],X=k.subtract(new D(P,F)).divide(new D(O.scaleX,O.scaleY))[E],K=O[B],tt=W[B],V=Math.tan(Ot(tt)),H=E==="y"?O._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:O._getTransformedDimensions({scaleX:1,scaleY:1}).y,Qt=2*X*R/Math.max(H,1)+V,Jt=un(Math.atan(Qt));O.set(B,Jt);const le=K!==O[B];if(le&&E==="y"){const{skewX:zt,scaleX:_t}=O,Pe=O._getTransformedDimensions({skewY:K}),fi=O._getTransformedDimensions(),Pt=zt!==0?Pe.x/fi.x:1;Pt!==1&&O.set(Se,Pt*_t)}return le}(a,x,new D(S,C))))(t,T(T({},e),{},{[o]:m,skewingSide:p}),s,i)}const wy=(a,t,e,s)=>Jp("x",a,t,e,s),xy=(a,t,e,s)=>Jp("y",a,t,e,s);function yc(a,t){return a[t.canvas.altActionKey]}const _c=(a,t,e)=>{const s=yc(a,e);return t.x===0?s?So:Ve:t.y===0?s?Co:Se:""},Fo=(a,t,e)=>yc(a,e)?_y(0,t,e):ih(a,t,e),Zp=(a,t,e,s)=>yc(a,t.target)?xy(a,t,e,s):my(a,t,e,s),tm=(a,t,e,s)=>yc(a,t.target)?wy(a,t,e,s):by(a,t,e,s),em=()=>({ml:new Cs({x:-.5,y:0,cursorStyleHandler:Fo,actionHandler:Zp,getActionName:_c}),mr:new Cs({x:.5,y:0,cursorStyleHandler:Fo,actionHandler:Zp,getActionName:_c}),mb:new Cs({x:0,y:.5,cursorStyleHandler:Fo,actionHandler:tm,getActionName:_c}),mt:new Cs({x:0,y:-.5,cursorStyleHandler:Fo,actionHandler:tm,getActionName:_c}),tl:new Cs({x:-.5,y:-.5,cursorStyleHandler:ih,actionHandler:vc}),tr:new Cs({x:.5,y:-.5,cursorStyleHandler:ih,actionHandler:vc}),bl:new Cs({x:-.5,y:.5,cursorStyleHandler:ih,actionHandler:vc}),br:new Cs({x:.5,y:.5,cursorStyleHandler:ih,actionHandler:vc}),mtr:new Cs({x:0,y:-.5,actionHandler:fy,cursorStyleHandler:gy,offsetY:-40,withConnection:!0,actionName:_u})}),Sy=()=>({mr:new Cs({x:.5,y:0,actionHandler:$p,cursorStyleHandler:Fo,actionName:qa}),ml:new Cs({x:-.5,y:0,actionHandler:$p,cursorStyleHandler:Fo,actionName:qa})}),Cy=()=>T(T({},em()),Sy());class nh extends _i{static getDefaults(){return T(T({},super.getDefaults()),nh.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),nh.ownDefaults),this.setOptions(t)}static createControls(){return{controls:em()}}_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(ic))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=To(e.x,e.y),i=Eo({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=Rt(s,i),r=Rt(t,n),o=Rt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Jn(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(Ot(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=T({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=i.borderColor,this._setLineDash(t,i.borderDashArray),this.strokeBorders(t,e),i.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:i}=this,n=T({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=Rt(r,this.calcTransformMatrix()),d=Jn(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(Ot(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=dc(this.width,this.height,Ka(e)),r=this.isStrokeAccountedForInDimensions()?xu:(this.strokeUniform?new D().scalarAdd(this.canvas?this.canvas.getZoom():1):new D(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);i=n.add(r).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else i=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,i,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl((i,n)=>{i.withConnection&&i.getVisibility(this,n)&&(s=!0,t.moveTo(i.x*e.x,i.y*e.y),t.lineTo(i.x*e.x+i.offsetX,i.y*e.y+i.offsetY))}),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:i,cornerDashArray:n,cornerColor:r}=this,o=T({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl((h,l)=>{if(h.getVisibility(this,l)){const d=this.oCoords[l];h.render(t,d.x,d.y,o,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,i]=e;return this.setControlVisible(s,i)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const i=this.width+4,n=this.height+4;return e.clearRect(-i/2,-n/2,i,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function sm(a,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(a.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),a}A(nh,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class de extends nh{}sm(de,[Ip]),N.setClass(de),N.setClass(de,"object");const im=(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 nm{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new D(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new D(1/this.options.scaleX,1/this.options.scaleY):new D(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 D(t);return e.y+=e.x*Math.tan(Ot(this.options.skewY)),e.x+=e.y*Math.tan(Ot(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const Ay=new D;class Ro extends nm{static getOrthogonalRotationFactor(t,e){const s=e?mc(t,e):Wp(t);return Math.abs(s)<ln?-1:1}constructor(t,e,s,i){super(i),A(this,"AB",void 0),A(this,"AC",void 0),A(this,"alpha",void 0),A(this,"bisector",void 0),this.A=new D(t),this.B=new D(e),this.C=new D(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=bc(ju(this.AB.eq(Ay)?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=Nu(i),r=Ro.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%bi==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 D(Ro.getOrthogonalRotationFactor(this.bisector),Ro.getOrthogonalRotationFactor(new D(this.bisector.y,this.bisector.x)));return[new D(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new D(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{Bu(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 D(Math.tan(Ot(i)),Math.tan(Ot(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 D(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 D(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=>{Bu(m,t,e)&&s.push(this.applySkew(this.A).add(m))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%bi==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=Oo(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 rm extends nm{constructor(t,e,s){super(s),this.A=new D(t),this.T=new D(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(Nu(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 D(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 Ro(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new D(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(bc(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 om=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 D(r)),n),[new D(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 rm(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Ro(n,h,l,t).project()):s.push(...new rm(n,r===0?l:h,t).project())}),s},Uu=a=>{const t={};return Object.keys(a).forEach(e=>{t[e]={},Object.keys(a[e]).forEach(s=>{t[e][s]=T({},a[e][s])})}),t},am=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),wc=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=Ty(a,s))!==!1&&t.push(e);return t},Ty=(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 Ey=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:am,graphemeSplit:wc});const xc=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)},hm=(a,t)=>{const e=t.split(`
38
+ `),s=[];let i=-1,n={};a=Uu(a);for(let r=0;r<e.length;r++){const o=wc(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&&(xc(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},lm=(a,t)=>{if(!Array.isArray(a))return Uu(a);const e=t.split(yu),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=wc(e[r]);for(let h=0;h<o.length;h++)i++,a[n]&&a[n].start<=i&&i<a[n].end&&(s[r]=s[r]||{},s[r][h]=T({},a[n].style),i===a[n].end-1&&n++)}return s},gn=["display","transform",jt,"fill-opacity","fill-rule","opacity",Ce,"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 cm(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 ky(a,t){let e=!0;const s=cm(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=cm(i=i.parentElement,r);return n.length===0}(a,t)),s&&e&&t.length===0}const My=a=>{var t;return(t=Uv[a])!==null&&t!==void 0?t:a},Oy=new RegExp("(".concat(Ss,")"),"gi"),Dy=a=>a.replace(Oy," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var dm,um,gm,fm,pm,mm,bm;const Te="(".concat(Ss,")"),Py=String.raw(dm||(dm=hn(["(skewX)(",")"],["(skewX)\\(","\\)"])),Te),Fy=String.raw(um||(um=hn(["(skewY)(",")"],["(skewY)\\(","\\)"])),Te),Ry=String.raw(gm||(gm=hn(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Te,Te,Te),Ly=String.raw(fm||(fm=hn(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Te,Te),Iy=String.raw(pm||(pm=hn(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Te,Te),jy=String.raw(mm||(mm=hn(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Te,Te,Te,Te,Te,Te),qu="(?:".concat(jy,"|").concat(Iy,"|").concat(Ry,"|").concat(Ly,"|").concat(Py,"|").concat(Fy,")"),Ny="(?:".concat(qu,"*)"),By=String.raw(bm||(bm=hn(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),Ny),Hy=new RegExp(By),Wy=new RegExp(qu),zy=new RegExp(qu,"g");function Sc(a){const t=[];if(!(a=Dy(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!Hy.test(a))return[...we];for(const e of a.matchAll(zy)){const s=Wy.exec(e[0]);if(!s)continue;let i=we;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=To(h,l);break;case _u:i=Eo({angle:h},{x:l,y:d});break;case ic:i=hc(h,l);break;case So:i=Cu(h);break;case Co:i=Au(h);break;case"matrix":i=[h,l,d,u,g,f]}t.push(i)}return ac(t)}function Xy(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==jt&&a!==Ce||t!==xe){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===xe?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?Rt(e.transformMatrix,Sc(t)):Sc(t);else if(a==="visible")r=t!==xe&&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"?lt:t==="end"?Ft:Q;else if(a==="charSpacing")n=Ae(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(jt),h=t.indexOf(Ce);r=jt,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=Ce)}else{if(a==="href"||a==="xlink:href"||a==="font"||a==="id")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(Ae):Ae(t,s)}}else r="";return!i&&isNaN(n)?r:n}function Vy(a,t){const e=a.match(Yv);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=Ae(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function $u(a,t){a.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function Gy(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?$u(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 Yy={stroke:"strokeOpacity",fill:"fillOpacity"};function wi(a,t,e){if(!a)return{};let s,i={},n=bu;a.parentNode&&Np.test(a.parentNode.nodeName)&&(i=wi(a.parentElement,t,e),i.fontSize&&(s=n=Ae(i.fontSize)));const r=T(T(T({},t.reduce((l,d)=>{const u=a.getAttribute(d);return u&&(l[d]=u),l},{})),function(l){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const g in d)ky(l,g.split(" "))&&(u=T(T({},u),d[g]));return u}(a,e)),Gy(a));r[Iu]&&a.setAttribute(Iu,r[Iu]),r[Lu]&&(s=Ae(r[Lu],n),r[Lu]="".concat(s));const o={};for(const l in r){const d=My(l),u=Xy(d,r[l],i,s);o[d]=u}o&&o.font&&Vy(o.font,o);const h=T(T({},i),o);return Np.test(a.nodeName)?h:function(l){const d=de.getDefaults();return Object.entries(Yy).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(xt(p.getAlpha()*l[f],2)).toRgba()}),l}(h)}const Uy=["left","top","width","height","visible"],vm=["rx","ry"];class Ys extends de{static getDefaults(){return T(T({},super.getDefaults()),Ys.ownDefaults)}constructor(t){super(),Object.assign(this,Ys.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-cn*r,n,i+e,n+cn*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-cn*o,i+e-cn*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+cn*r,n+s,i,n+s-cn*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+cn*o,i+cn*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([...vm,...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=wi(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,d=wt(i,Uy);return new this(T(T(T({},e),d),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}A(Ys,"type","Rect"),A(Ys,"cacheProperties",[...yi,...vm]),A(Ys,"ownDefaults",{rx:0,ry:0}),A(Ys,"ATTRIBUTE_NAMES",[...gn,"x","y","rx","ry","width","height"]),N.setClass(Ys),N.setSVGClass(Ys);const xi="initialization",Cc="added",Ku="removed",Ac="imperative",ym=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?sh(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),d=e&&l?Op(new D(s,s),void 0,a.calcTransformMatrix()):xu,u=!e&&l?s:0,g=dc(i+u,n+u,ac([o,t.calcOwnMatrix()],!0)).add(d).scalarDivide(2);return[h.subtract(g),h.add(g)]};class Tc{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===xi||e===Ac||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==xi&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Ac&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Gs(t.map(u=>ym(i,u)).reduce((u,g)=>u.concat(g),[])),l=new D(o,h),d=new D(n,r).add(l.scalarDivide(2));if(s===xi){const u=this.getInitialSize(e,{size:l,center:d});return{center:d,relativeCorrection:new D(0,0),size:u}}return{center:d.transform(i.calcOwnMatrix()),size:l}}}A(Tc,"type","strategy");class Qu extends Tc{shouldPerformLayout(t){return!0}}A(Qu,"type","fit-content"),N.setClass(Qu);const qy=["strategy"],$y=["target","strategy","bubbles","prevStrategy"],_m="layoutManager";class rh{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Qu;A(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=T(T({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[nc,np,qa,rp,ec,op,sc,jv,Nv].map(i=>t.on(i,n=>this.performLayout(i===nc?{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===xi||s===Cc?this.subscribeTargets(t):s===Ku&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Ac&&t.deep){const n=wt(t,qy);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(T(T({},n),{},{bubbles:!1,target:r})))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===xi?new D:e.getRelativeCenterPoint(),{center:o,correction:h=new D,relativeCorrection:l=new D}=n,d=r.subtract(o).add(h).transform(i===xi?we:Ie(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===xi?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*Nt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*Nt(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=wt(t,$y),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;n&&l!=null&&l.layoutManager&&((o.path||(o.path=[])).push(s),l.layoutManager.performLayout(T(T({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:_m,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}N.setClass(rh,_m);const Ky=["type","objects","layoutManager"];class Qy extends rh{performLayout(){}}class Us extends ap(de){static getDefaults(){return T(T({},super.getDefaults()),Us.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),A(this,"_activeObjects",[]),A(this,"__objectSelectionTracker",void 0),A(this,"__objectSelectionDisposer",void 0),Object.assign(this,Us.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 rh,this.layoutManager.performLayout({type:xi,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(mi("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(mi("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(Cc,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(Cc,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Ku,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,Rt(Ie(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,Rt(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=de.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let n=0;n<this._objects.length;n++){var i;const r=this._objects[n];(i=this.canvas)!==null&&i!==void 0&&i.preserveObjectStacking&&r.group!==this?(t.save(),t.transform(...Ie(this.calcTransformMatrix())),r.render(t),t.restore()):r.group===this&&r.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(T({target:this,type:Ac},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter(function(i){return!i.excludeFromExport}).map(function(i){const n=i.includeDefaultValues;i.includeDefaultValues=s;const r=i[t||"toObject"](e);return i.includeDefaultValues=n,r})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return T(T(T({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Ys.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=wt(t,Qy);return Promise.all([ko(i,e),Ja(r,e)]).then(o=>{let[h,l]=o;const d=new this(h,T(T(T({},r),l),{},{layoutManager:new Jy}));if(n){const u=N.getClass(n.type),g=N.getClass(n.strategy);d.layoutManager=new u(new g)}else d.layoutManager=new rh;return d.layoutManager.subscribeTargets({type:xi,target:d,targets:d.getObjects()}),d.setCoords(),d})}}A(Us,"type","Group"),A(Us,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),N.setClass(Us);const xm=(a,t)=>Math.min(t.width/a.width,t.height/a.height),Sm=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Ju="\\s*,?\\s*",oh="".concat(Ju,"(").concat(Ss,")"),Zy="".concat(oh).concat(oh).concat(oh).concat(Ju,"([01])").concat(Ju,"([01])").concat(oh).concat(oh),t_={m:"l",M:"L"},e_=(a,t,e,s,i,n,r,o,h,l,d)=>{const u=vs(a),g=ys(a),f=vs(t),p=ys(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,_]},Cm=(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 Zu(a,t,e,s,i,n,r,o){let h;if(at.cachesBoundsOfCurve&&(h=[...arguments].join(),Ua.boundsOfCurveCache[h]))return Ua.boundsOfCurveCache[h];const l=Math.sqrt,d=Math.abs,u=[],g=[[0,0],[0,0]];let f=6*a-12*e+6*i,p=-3*a+9*e-9*i+3*r,m=3*e-3*a;for(let C=0;C<2;++C){if(C>0&&(f=6*t-12*s+6*n,p=-3*t+9*s-9*n+3*o,m=3*s-3*t),d(p)<1e-12){if(d(f)<1e-12)continue;const P=-m/f;0<P&&P<1&&u.push(P);continue}const E=f*f-4*m*p;if(E<0)continue;const M=l(E),k=(-f+M)/(2*p);0<k&&k<1&&u.push(k);const O=(-f-M)/(2*p);0<O&&O<1&&u.push(O)}let _=u.length;const y=_,x=Tm(a,t,e,s,i,n,r,o);for(;_--;){const{x:C,y:E}=x(u[_]);g[0][_]=C,g[1][_]=E}g[0][y]=a,g[1][y]=t,g[0][y+1]=r,g[1][y+1]=o;const S=[new D(Math.min(...g[0]),Math.min(...g[1])),new D(Math.max(...g[0]),Math.max(...g[1]))];return at.cachesBoundsOfCurve&&(Ua.boundsOfCurveCache[h]=S),S}const s_=(a,t,e)=>{let[s,i,n,r,o,h,l,d]=e;const u=((g,f,p,m,_,y,x)=>{if(p===0||m===0)return[];let S=0,C=0,E=0;const M=Math.PI,k=x*mu,O=ys(k),P=vs(k),F=.5*(-P*g-O*f),R=.5*(-P*f+O*g),W=p**2,B=m**2,X=R**2,K=F**2,tt=W*B-W*X-B*K;let V=Math.abs(p),H=Math.abs(m);if(tt<0){const pi=Math.sqrt(1-tt/(W*B));V*=pi,H*=pi}else E=(_===y?-1:1)*Math.sqrt(tt/(W*X+B*K));const Qt=E*V*R/H,Jt=-E*H*F/V,le=P*Qt-O*Jt+.5*g,zt=O*Qt+P*Jt+.5*f;let _t=Cm(1,0,(F-Qt)/V,(R-Jt)/H),Pe=Cm((F-Qt)/V,(R-Jt)/H,(-F-Qt)/V,(-R-Jt)/H);y===0&&Pe>0?Pe-=2*M:y===1&&Pe<0&&(Pe+=2*M);const fi=Math.ceil(Math.abs(Pe/M*2)),Pt=[],dt=Pe/fi,mo=8/3*Math.sin(dt/4)*Math.sin(dt/4)/Math.sin(dt/2);let bo=_t+dt;for(let pi=0;pi<fi;pi++)Pt[pi]=e_(_t,bo,P,O,V,H,le,zt,mo,S,C),S=Pt[pi][5],C=Pt[pi][6],_t=bo,bo+=dt;return Pt})(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},Am=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":s_(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},Ec=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),Tm=(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 D(r*l+i*d+e*u+a*g,o*l+n*d+s*u+t*g)},Em=a=>a**2,km=a=>2*a*(1-a),Mm=a=>(1-a)**2,i_=(a,t,e,s,i,n,r,o)=>h=>{const l=Em(h),d=km(h),u=Mm(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)},n_=(a,t,e,s,i,n)=>r=>{const o=Em(r),h=km(r),l=Mm(r);return new D(i*o+e*h+a*l,n*o+s*h+t*l)},r_=(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)},Om=(a,t,e)=>{let s=new D(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=Ec(s.x,s.y,r.x,r.y),s=r}return i},o_=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=T({},n),o=.01,h=0;const l=a.iterator,d=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=Ec(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return T(T({},r),{},{angle:d(h)})},tg=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=Ec(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=Tm(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=d,e.iterator=t,e.angleFinder=i_(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=Om(t,i,n),i=l[5],n=l[6];break;case"Q":t=n_(i,n,l[1],l[2],l[3],l[4]),e=d,e.iterator=t,e.angleFinder=r_(i,n,l[1],l[2],l[3],l[4]),e.length=Om(t,i,n),i=l[3],n=l[4];break;case"Z":e=d,e.destX=r,e.destY=o,e.length=Ec(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},Dm=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tg(a),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const i=e[s],n=t/i.length,r=a[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return T(T({},new D(i.x,i.y).lerp(new D(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return T(T({},new D(i.x,i.y).lerp(new D(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return o_(i,t)}},a_=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Pm=new RegExp(Zy,"g"),h_=new RegExp(Ss,"gi"),l_={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Fm=a=>{var t;const e=[],s=(t=a.match(a_))!==null&&t!==void 0?t:[];for(const i of s){const n=i[0];if(n==="z"||n==="Z"){e.push([n]);continue}const r=l_[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){Pm.lastIndex=0;for(let h=null;h=Pm.exec(i);)o.push(...h.slice(1))}else o=i.match(h_)||[];for(let h=0;h<o.length;h+=r){const l=new Array(r),d=t_[n];l[0]=h>0&&d?d:n;for(let u=0;u<r;u++)l[u+1]=parseFloat(o[h+u]);e.push(l)}}return e},c_=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new D(a[0]),s=new D(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},Rm=(a,t)=>a.map(e=>e.map((s,i)=>i===0||t===void 0?s:xt(s,t)).join(" ")).join(" ");function kc(a,t){const e=a.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const d_=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function Lm(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||Kn,s=new(tc()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=Kn};if(i&&i.aborted)throw new fu("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=Kn)},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}=Jn(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Se,i),s.set(Ve,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 u_=Object.freeze({__proto__:null,addTransformToObject:Mp,animate:Vu,animateColor:$p,applyTransformToObject:Mo,calcAngleBetweenVectors:mc,calcDimensionsMatrix:Ka,calcPlaneChangeMatrix:sh,calcVectorRotation:zp,cancelAnimFrame:cp,capValue:sr,composeMatrix:pp,copyCanvasElement:a=>{var t;const e=_s(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:vs,createCanvasElement:ns,createImage:dp,createRotateMatrix:Eo,createScaleMatrix:hc,createSkewXMatrix:Cu,createSkewYMatrix:Au,createTranslateMatrix:To,createVector:fc,crossProduct:Oo,degreesToRadians:Ot,dotProduct:Xp,ease:ty,enlivenObjectEnlivables:Ja,enlivenObjects:ko,findScaleToCover:Sm,findScaleToFit:xm,getBoundsOfCurve:Zu,getOrthonormalVector:Nu,getPathSegmentsInfo:tg,getPointOnPath:Dm,getPointer:kp,getRandomInt:d_,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-ln;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 D(vs(r),ys(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:c_,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:bc,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new Us(a,t),hasStyleChanged:xc,invertTransform:Ie,isBetweenVectors:Bu,isIdentityMatrix:up,isTouchEvent:cc,isTransparent:nm,joinPath:Rm,loadImage:Qa,magnitude:pc,makeBoundingBoxFromPoints:Gs,makePathSimpler:Am,matrixToSVG:Za,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),Pu(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 Us([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:Rt,multiplyTransformMatrixArray:ac,parsePath:Fm,parsePreserveAspectRatioAttribute:ku,parseUnit:Ae,pick:Zn,projectStrokeOnPoints:am,qrDecompose:Jn,radiansToDegrees:un,removeFromArray:Qn,removeTransformFromObject:(a,t)=>{const e=Ie(t),s=Rt(e,a.calcOwnMatrix());Mo(a,s)},removeTransformMatrixForSvgParsing:Mc,request:Lm,requestAnimFrame:$a,resetObjectTransform:Op,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:ju,saveObjectTransform:Du,sendObjectToPlane:Pu,sendPointToPlane:er,sendVectorToPlane:Dp,setStyle:kc,sin:ys,sizeAfterTransform:dc,string:ky,stylesFromArray:cm,stylesToArray:lm,toDataURL:Su,toFixed:xt,transformPath:(a,t,e)=>(e&&(t=Rt(t,[1,0,0,1,-e.x,-e.y])),a.map(s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:o}=ce({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i})),transformPoint:ce});class g_ extends Ep{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),A(this,"upper",void 0),A(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(s),i.parentNode&&i.parentNode.replaceChild(r,i),r.append(i,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=ns();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=xo().createElement("div");return t.setAttribute("data-fabric","wrapper"),kc(t,{position:"relative"}),Tp(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;kc(t,T(T({},s),{},{"touch-action":i?"manipulation":xe})),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),Mu(this.upper.el,t),Mu(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(),Vs().dispose(this.upper.el),delete this.upper,delete this.container}}class Oc extends eh{constructor(){super(...arguments),A(this,"targets",[]),A(this,"_hoveredTargets",[]),A(this,"_objectsToRender",void 0),A(this,"_currentTransform",null),A(this,"_groupSelector",null),A(this,"contextTopDirty",!1)}static getDefaults(){return T(T({},super.getDefaults()),Oc.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 g_(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 nm(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===ic||e===Se||e===Ve||e===qa?i=this.centeredScaling||t.centeredScaling:e===_u&&(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=Ft:["mr","tr","br"].includes(e)&&(s.x=lt),["tl","mt","tr"].includes(e)?s.y=vu:["bl","mb","br"].includes(e)&&(s.y=Le)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?er(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):Yv,l=((f,p,m,_)=>{if(!p||!f)return"drag";const y=_.controls[p];return y.getActionName(m,y,_)})(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:Ot(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:d,original:T(T({},Du(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 D(e,s).transform(this.viewportTransform),o=new D(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=Math.min(r.x,o.x),d=Math.min(r.y,o.y),u=Math.max(r.x,o.x),g=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,d,u-l,g-d)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,d+=h,u-=h,g-=h,de.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,d,u-l,g-d))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,cc(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=vs(d)*n,g=ys(d)*n,f=u+g,p=u-g;s=[new D(r.x-p,r.y-f),new D(o.x+f,o.y-p),new D(h.x+p,h.y+f),new D(l.x-f,l.y+p)]}return At.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,er(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(oc(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&&oc(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!oc(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||(Le in i&&vu in i&&(o=Math.abs(i.top-i.bottom)),Ft in i&&lt 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=er(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new D(1,1):new D(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=ns(),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 tr(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,tr(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),tr(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(nc,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;tr(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&&tr(e)&&this._activeObject===e){const s=Zn(t,["angle","flipX","flipY",lt,Se,Ve,So,Co,Le]);return Mp(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}A(Oc,"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 f_{constructor(t){A(this,"targets",[]),A(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),Qn(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 p_=["target","oldTarget","fireCanvas","e"],Ge={passive:!1},Lo=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},fn=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)},os=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)},m_={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 eg extends Oc{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),A(this,"_isClick",void 0),A(this,"textEditingManager",new f_(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(fn,"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,Ge),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,Ge)}removeListeners(){this.addOrRemove(os,"remove");const t=this._getEventPrefix(),e=ws(this.upperCanvasEl);os(e,"".concat(t,"up"),this._onMouseUp),os(e,"touchend",this._onTouchEnd,Ge),os(e,"".concat(t,"move"),this._onMouseMove,Ge),os(e,"touchmove",this._onMouseMove,Ge),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=T({e:t},Lo(this,t));this.fire("mouse:out",T(T({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",T({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",T(T({},s),{},{target:i})),i&&i.fire("mouseout",T({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",T({e:t},Lo(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 fn(this.upperCanvasEl,"drag",this._onDragProgress)}Ou(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!==xe,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};os(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let h=0;h<i.length;h++){const l=i[h];l.canDrop(t)&&(o=l),l.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",T({e:t,target:e,subTargets:s,dragSource:this._dragSource},Lo(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&&Ou(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){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=ws(i);fn(r,"touchend",this._onTouchEnd,Ge),e&&fn(r,"touchmove",this._onMouseMove,Ge),os(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();os(e,"".concat(s,"move"),this._onMouseMove,Ge);const i=ws(e);fn(i,"".concat(s,"up"),this._onMouseUp),fn(i,"".concat(s,"move"),this._onMouseMove,Ge)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=ws(this.upperCanvasEl);os(s,"touchend",this._onTouchEnd,Ge),os(s,"touchmove",this._onMouseMove,Ge),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{fn(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=ws(this.upperCanvasEl);os(i,"".concat(s,"up"),this._onMouseUp),os(i,"".concat(s,"move"),this._onMouseMove,Ge),fn(e,"".concat(s,"move"),this._onMouseMove,Ge)}}_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),cc(t)),{key:u,control:g}=d||{};if(h=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),l=!0;else if(g){const f=g.getMouseUpHandler(t,n,g);f&&(o=this.getScenePoint(t),f.call(g,t,s,o.x,o.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const d=s.target&&s.target.controls[s.corner],u=d&&d.getMouseUpHandler(t,s.target,d);o=o||this.getScenePoint(t),u&&u.call(d,t,s,o.x,o.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),l?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e){const s=this._target,i=this.targets||[],n=T(T({e:t,target:s,subTargets:i},Lo(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),cc(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=er(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=wt(e,p_);const{targetIn:h,targetOut:l,canvasIn:d,canvasOut:u}=m_[t],g=i!==s;if(i&&g){const f=T(T({},o),{},{e:r,target:i,nextTarget:s},Lo(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&g){const f=T(T({},o),{},{e:r,target:s,previousTarget:i},Lo(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?er(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=tr(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=tr(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.isEditing&&s.exitEditing();const n=new(N.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 D(e,s),o=r.add(new D(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=N.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 Im={x1:0,y1:0,x2:0,y2:0},b_=T(T({},Im),{},{r1:0,r2:0}),Io=(a,t)=>isNaN(a)&&typeof t=="number"?t:a,v_=/^(\d+\.\d+)%|(\d+)%$/;function jm(a){return a&&v_.test(a)}function Nm(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(jm(a)?100:1):NaN;return sr(0,Io(e,t),1)}const y_=/\s*;\s*/,__=/\s*:\s*/;function w_(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(y_);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(__).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:Nm(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Io(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function x_(a,t){const e=[],s=a.getElementsByTagName("stop"),i=Nm(t,1);for(let n=s.length;n--;)e.push(w_(s[n],i));return e}function Bm(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Hm(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function As(a,t){return a.getAttribute(t)}function S_(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"&&jm(d)&&(i*=.01,o==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(i*=n),l!=="y1"&&l!=="y2"||(i*=r)))),h[l]=i,h},{})}(Bm(a)==="linear"?function(e){return{x1:As(e,"x1")||0,y1:As(e,"y1")||0,x2:As(e,"x2")||"100%",y2:As(e,"y2")||0}}(a):function(e){return{x1:As(e,"fx")||As(e,"cx")||"50%",y1:As(e,"fy")||As(e,"cy")||"50%",r1:0,x2:As(e,"cx")||"50%",y2:As(e,"cy")||"50%",r2:As(e,"r")||"50%"}}(a),T(T({},t),{},{gradientUnits:Hm(a)}))}class ah{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:T(T({},e==="radial"?b_:Im),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(dn()):dn()})}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 T(T({},Zn(this,t)),{},{type:this.type,coords:T({},this.coords),colorStops:this.colorStops.map(e=>T({},e)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],i=this.gradientTransform?this.gradientTransform.concat():we.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(u=>T({},u)).sort((u,g)=>u.offset-g.offset);let o=-this.offsetX,h=-this.offsetY;var l;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const d=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(Za(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=wt(t,Ky);return Promise.all([ko(i,e),Ja(r,e)]).then(o=>{let[h,l]=o;const d=new this(h,T(T(T({},r),l),{},{layoutManager:new Qy}));if(n){const u=N.getClass(n.type),g=N.getClass(n.strategy);d.layoutManager=new u(new g)}else d.layoutManager=new rh;return d.layoutManager.subscribeTargets({type:xi,target:d,targets:d.getObjects()}),d.setCoords(),d})}}A(Us,"type","Group"),A(Us,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),N.setClass(Us);const wm=(a,t)=>Math.min(t.width/a.width,t.height/a.height),xm=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Ju="\\s*,?\\s*",oh="".concat(Ju,"(").concat(Ss,")"),Jy="".concat(oh).concat(oh).concat(oh).concat(Ju,"([01])").concat(Ju,"([01])").concat(oh).concat(oh),Zy={m:"l",M:"L"},t_=(a,t,e,s,i,n,r,o,h,l,d)=>{const u=vs(a),g=ys(a),f=vs(t),p=ys(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,_]},Sm=(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 Zu(a,t,e,s,i,n,r,o){let h;if(at.cachesBoundsOfCurve&&(h=[...arguments].join(),Ua.boundsOfCurveCache[h]))return Ua.boundsOfCurveCache[h];const l=Math.sqrt,d=Math.abs,u=[],g=[[0,0],[0,0]];let f=6*a-12*e+6*i,p=-3*a+9*e-9*i+3*r,m=3*e-3*a;for(let C=0;C<2;++C){if(C>0&&(f=6*t-12*s+6*n,p=-3*t+9*s-9*n+3*o,m=3*s-3*t),d(p)<1e-12){if(d(f)<1e-12)continue;const P=-m/f;0<P&&P<1&&u.push(P);continue}const E=f*f-4*m*p;if(E<0)continue;const M=l(E),k=(-f+M)/(2*p);0<k&&k<1&&u.push(k);const O=(-f-M)/(2*p);0<O&&O<1&&u.push(O)}let _=u.length;const y=_,x=Am(a,t,e,s,i,n,r,o);for(;_--;){const{x:C,y:E}=x(u[_]);g[0][_]=C,g[1][_]=E}g[0][y]=a,g[1][y]=t,g[0][y+1]=r,g[1][y+1]=o;const S=[new D(Math.min(...g[0]),Math.min(...g[1])),new D(Math.max(...g[0]),Math.max(...g[1]))];return at.cachesBoundsOfCurve&&(Ua.boundsOfCurveCache[h]=S),S}const e_=(a,t,e)=>{let[s,i,n,r,o,h,l,d]=e;const u=((g,f,p,m,_,y,x)=>{if(p===0||m===0)return[];let S=0,C=0,E=0;const M=Math.PI,k=x*mu,O=ys(k),P=vs(k),F=.5*(-P*g-O*f),R=.5*(-P*f+O*g),W=p**2,B=m**2,X=R**2,K=F**2,tt=W*B-W*X-B*K;let V=Math.abs(p),H=Math.abs(m);if(tt<0){const pi=Math.sqrt(1-tt/(W*B));V*=pi,H*=pi}else E=(_===y?-1:1)*Math.sqrt(tt/(W*X+B*K));const Qt=E*V*R/H,Jt=-E*H*F/V,le=P*Qt-O*Jt+.5*g,zt=O*Qt+P*Jt+.5*f;let _t=Sm(1,0,(F-Qt)/V,(R-Jt)/H),Pe=Sm((F-Qt)/V,(R-Jt)/H,(-F-Qt)/V,(-R-Jt)/H);y===0&&Pe>0?Pe-=2*M:y===1&&Pe<0&&(Pe+=2*M);const fi=Math.ceil(Math.abs(Pe/M*2)),Pt=[],dt=Pe/fi,mo=8/3*Math.sin(dt/4)*Math.sin(dt/4)/Math.sin(dt/2);let bo=_t+dt;for(let pi=0;pi<fi;pi++)Pt[pi]=t_(_t,bo,P,O,V,H,le,zt,mo,S,C),S=Pt[pi][5],C=Pt[pi][6],_t=bo,bo+=dt;return Pt})(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},Cm=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":e_(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},Ec=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),Am=(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 D(r*l+i*d+e*u+a*g,o*l+n*d+s*u+t*g)},Tm=a=>a**2,Em=a=>2*a*(1-a),km=a=>(1-a)**2,s_=(a,t,e,s,i,n,r,o)=>h=>{const l=Tm(h),d=Em(h),u=km(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)},i_=(a,t,e,s,i,n)=>r=>{const o=Tm(r),h=Em(r),l=km(r);return new D(i*o+e*h+a*l,n*o+s*h+t*l)},n_=(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)},Mm=(a,t,e)=>{let s=new D(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=Ec(s.x,s.y,r.x,r.y),s=r}return i},r_=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=T({},n),o=.01,h=0;const l=a.iterator,d=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=Ec(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return T(T({},r),{},{angle:d(h)})},tg=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=Ec(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=Am(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=d,e.iterator=t,e.angleFinder=s_(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=Mm(t,i,n),i=l[5],n=l[6];break;case"Q":t=i_(i,n,l[1],l[2],l[3],l[4]),e=d,e.iterator=t,e.angleFinder=n_(i,n,l[1],l[2],l[3],l[4]),e.length=Mm(t,i,n),i=l[3],n=l[4];break;case"Z":e=d,e.destX=r,e.destY=o,e.length=Ec(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},Om=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tg(a),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const i=e[s],n=t/i.length,r=a[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return T(T({},new D(i.x,i.y).lerp(new D(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return T(T({},new D(i.x,i.y).lerp(new D(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return r_(i,t)}},o_=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Dm=new RegExp(Jy,"g"),a_=new RegExp(Ss,"gi"),h_={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Pm=a=>{var t;const e=[],s=(t=a.match(o_))!==null&&t!==void 0?t:[];for(const i of s){const n=i[0];if(n==="z"||n==="Z"){e.push([n]);continue}const r=h_[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){Dm.lastIndex=0;for(let h=null;h=Dm.exec(i);)o.push(...h.slice(1))}else o=i.match(a_)||[];for(let h=0;h<o.length;h+=r){const l=new Array(r),d=Zy[n];l[0]=h>0&&d?d:n;for(let u=0;u<r;u++)l[u+1]=parseFloat(o[h+u]);e.push(l)}}return e},l_=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new D(a[0]),s=new D(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},Fm=(a,t)=>a.map(e=>e.map((s,i)=>i===0||t===void 0?s:xt(s,t)).join(" ")).join(" ");function kc(a,t){const e=a.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const c_=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function Rm(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||Kn,s=new(tc()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=Kn};if(i&&i.aborted)throw new fu("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=Kn)},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}=Jn(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Se,i),s.set(Ve,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 d_=Object.freeze({__proto__:null,addTransformToObject:kp,animate:Vu,animateColor:qp,applyTransformToObject:Mo,calcAngleBetweenVectors:mc,calcDimensionsMatrix:Ka,calcPlaneChangeMatrix:sh,calcVectorRotation:Wp,cancelAnimFrame:lp,capValue:sr,composeMatrix:fp,copyCanvasElement:a=>{var t;const e=_s(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:vs,createCanvasElement:ns,createImage:cp,createRotateMatrix:Eo,createScaleMatrix:hc,createSkewXMatrix:Cu,createSkewYMatrix:Au,createTranslateMatrix:To,createVector:fc,crossProduct:Oo,degreesToRadians:Ot,dotProduct:zp,ease:Zv,enlivenObjectEnlivables:Ja,enlivenObjects:ko,findScaleToCover:xm,findScaleToFit:wm,getBoundsOfCurve:Zu,getOrthonormalVector:Nu,getPathSegmentsInfo:tg,getPointOnPath:Om,getPointer:Ep,getRandomInt:c_,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-ln;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 D(vs(r),ys(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:l_,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:bc,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new Us(a,t),hasStyleChanged:xc,invertTransform:Ie,isBetweenVectors:Bu,isIdentityMatrix:dp,isTouchEvent:cc,isTransparent:im,joinPath:Fm,loadImage:Qa,magnitude:pc,makeBoundingBoxFromPoints:Gs,makePathSimpler:Cm,matrixToSVG:Za,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),Pu(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 Us([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:Rt,multiplyTransformMatrixArray:ac,parsePath:Pm,parsePreserveAspectRatioAttribute:ku,parseUnit:Ae,pick:Zn,projectStrokeOnPoints:om,qrDecompose:Jn,radiansToDegrees:un,removeFromArray:Qn,removeTransformFromObject:(a,t)=>{const e=Ie(t),s=Rt(e,a.calcOwnMatrix());Mo(a,s)},removeTransformMatrixForSvgParsing:Mc,request:Rm,requestAnimFrame:$a,resetObjectTransform:Mp,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:ju,saveObjectTransform:Du,sendObjectToPlane:Pu,sendPointToPlane:er,sendVectorToPlane:Op,setStyle:kc,sin:ys,sizeAfterTransform:dc,string:Ey,stylesFromArray:lm,stylesToArray:hm,toDataURL:Su,toFixed:xt,transformPath:(a,t,e)=>(e&&(t=Rt(t,[1,0,0,1,-e.x,-e.y])),a.map(s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:o}=ce({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i})),transformPoint:ce});class u_ extends Tp{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),A(this,"upper",void 0),A(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(s),i.parentNode&&i.parentNode.replaceChild(r,i),r.append(i,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=ns();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=xo().createElement("div");return t.setAttribute("data-fabric","wrapper"),kc(t,{position:"relative"}),Ap(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;kc(t,T(T({},s),{},{"touch-action":i?"manipulation":xe})),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),Mu(this.upper.el,t),Mu(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(),Vs().dispose(this.upper.el),delete this.upper,delete this.container}}class Oc extends eh{constructor(){super(...arguments),A(this,"targets",[]),A(this,"_hoveredTargets",[]),A(this,"_objectsToRender",void 0),A(this,"_currentTransform",null),A(this,"_groupSelector",null),A(this,"contextTopDirty",!1)}static getDefaults(){return T(T({},super.getDefaults()),Oc.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 u_(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 im(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===ic||e===Se||e===Ve||e===qa?i=this.centeredScaling||t.centeredScaling:e===_u&&(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=Ft:["mr","tr","br"].includes(e)&&(s.x=lt),["tl","mt","tr"].includes(e)?s.y=vu:["bl","mb","br"].includes(e)&&(s.y=Le)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?er(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):Gv,l=((f,p,m,_)=>{if(!p||!f)return"drag";const y=_.controls[p];return y.getActionName(m,y,_)})(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:Ot(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:d,original:T(T({},Du(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 D(e,s).transform(this.viewportTransform),o=new D(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=Math.min(r.x,o.x),d=Math.min(r.y,o.y),u=Math.max(r.x,o.x),g=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,d,u-l,g-d)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,d+=h,u-=h,g-=h,de.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,d,u-l,g-d))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,cc(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=vs(d)*n,g=ys(d)*n,f=u+g,p=u-g;s=[new D(r.x-p,r.y-f),new D(o.x+f,o.y-p),new D(h.x+p,h.y+f),new D(l.x-f,l.y+p)]}return At.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,er(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(oc(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&&oc(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!oc(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||(Le in i&&vu in i&&(o=Math.abs(i.top-i.bottom)),Ft in i&&lt 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=er(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new D(1,1):new D(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=ns(),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 tr(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,tr(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),tr(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(nc,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;tr(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&&tr(e)&&this._activeObject===e){const s=Zn(t,["angle","flipX","flipY",lt,Se,Ve,So,Co,Le]);return kp(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}A(Oc,"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 g_{constructor(t){A(this,"targets",[]),A(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),Qn(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 f_=["target","oldTarget","fireCanvas","e"],Ge={passive:!1},Lo=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},fn=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)},os=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)},p_={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 eg extends Oc{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),A(this,"_isClick",void 0),A(this,"textEditingManager",new g_(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(fn,"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,Ge),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,Ge)}removeListeners(){this.addOrRemove(os,"remove");const t=this._getEventPrefix(),e=ws(this.upperCanvasEl);os(e,"".concat(t,"up"),this._onMouseUp),os(e,"touchend",this._onTouchEnd,Ge),os(e,"".concat(t,"move"),this._onMouseMove,Ge),os(e,"touchmove",this._onMouseMove,Ge),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=T({e:t},Lo(this,t));this.fire("mouse:out",T(T({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",T({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",T(T({},s),{},{target:i})),i&&i.fire("mouseout",T({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",T({e:t},Lo(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 fn(this.upperCanvasEl,"drag",this._onDragProgress)}Ou(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!==xe,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};os(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let h=0;h<i.length;h++){const l=i[h];l.canDrop(t)&&(o=l),l.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",T({e:t,target:e,subTargets:s,dragSource:this._dragSource},Lo(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&&Ou(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){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=ws(i);fn(r,"touchend",this._onTouchEnd,Ge),e&&fn(r,"touchmove",this._onMouseMove,Ge),os(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();os(e,"".concat(s,"move"),this._onMouseMove,Ge);const i=ws(e);fn(i,"".concat(s,"up"),this._onMouseUp),fn(i,"".concat(s,"move"),this._onMouseMove,Ge)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=ws(this.upperCanvasEl);os(s,"touchend",this._onTouchEnd,Ge),os(s,"touchmove",this._onMouseMove,Ge),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{fn(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=ws(this.upperCanvasEl);os(i,"".concat(s,"up"),this._onMouseUp),os(i,"".concat(s,"move"),this._onMouseMove,Ge),fn(e,"".concat(s,"move"),this._onMouseMove,Ge)}}_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),cc(t)),{key:u,control:g}=d||{};if(h=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),l=!0;else if(g){const f=g.getMouseUpHandler(t,n,g);f&&(o=this.getScenePoint(t),f.call(g,t,s,o.x,o.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const d=s.target&&s.target.controls[s.corner],u=d&&d.getMouseUpHandler(t,s.target,d);o=o||this.getScenePoint(t),u&&u.call(d,t,s,o.x,o.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),l?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e){const s=this._target,i=this.targets||[],n=T(T({e:t,target:s,subTargets:i},Lo(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),cc(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=er(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=wt(e,f_);const{targetIn:h,targetOut:l,canvasIn:d,canvasOut:u}=p_[t],g=i!==s;if(i&&g){const f=T(T({},o),{},{e:r,target:i,nextTarget:s},Lo(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&g){const f=T(T({},o),{},{e:r,target:s,previousTarget:i},Lo(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?er(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=tr(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=tr(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.isEditing&&s.exitEditing();const n=new(N.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 D(e,s),o=r.add(new D(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=N.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 Lm={x1:0,y1:0,x2:0,y2:0},m_=T(T({},Lm),{},{r1:0,r2:0}),Io=(a,t)=>isNaN(a)&&typeof t=="number"?t:a,b_=/^(\d+\.\d+)%|(\d+)%$/;function Im(a){return a&&b_.test(a)}function jm(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(Im(a)?100:1):NaN;return sr(0,Io(e,t),1)}const v_=/\s*;\s*/,y_=/\s*:\s*/;function __(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(v_);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(y_).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:jm(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Io(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function w_(a,t){const e=[],s=a.getElementsByTagName("stop"),i=jm(t,1);for(let n=s.length;n--;)e.push(__(s[n],i));return e}function Nm(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Bm(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function As(a,t){return a.getAttribute(t)}function x_(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"&&Im(d)&&(i*=.01,o==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(i*=n),l!=="y1"&&l!=="y2"||(i*=r)))),h[l]=i,h},{})}(Nm(a)==="linear"?function(e){return{x1:As(e,"x1")||0,y1:As(e,"y1")||0,x2:As(e,"x2")||"100%",y2:As(e,"y2")||0}}(a):function(e){return{x1:As(e,"fx")||As(e,"cx")||"50%",y1:As(e,"fy")||As(e,"cy")||"50%",r1:0,x2:As(e,"cx")||"50%",y2:As(e,"cy")||"50%",r2:As(e,"r")||"50%"}}(a),T(T({},t),{},{gradientUnits:Bm(a)}))}class ah{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:T(T({},e==="radial"?m_:Lm),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(dn()):dn()})}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 T(T({},Zn(this,t)),{},{type:this.type,coords:T({},this.coords),colorStops:this.colorStops.map(e=>T({},e)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],i=this.gradientTransform?this.gradientTransform.concat():we.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(u=>T({},u)).sort((u,g)=>u.offset-g.offset);let o=-this.offsetX,h=-this.offsetY;var l;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const d=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(Za(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,y=m>_;s.push("<radialGradient ",d,' cx="',y?u:f,'" cy="',y?g:p,'" r="',y?m:_,'" fx="',y?f:u,'" fy="',y?p:g,`">
43
43
  `),y&&(r.reverse(),r.forEach(S=>{S.offset=1-S.offset}));const x=Math.min(m,_);if(x>0){const S=x/Math.max(m,_);r.forEach(C=>{C.offset+=S*(1-C.offset)})}}return r.forEach(u=>{let{color:g,offset:f,opacity:p}=u;s.push("<stop ",'offset="',100*f+"%",'" style="stop-color:',g,p!==void 0?";stop-opacity: "+p:";",`"/>
44
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(T(T({},t),{},{colorStops:e?e.map(i=>T({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=Hm(t),n=e._findCenterFromElement();return new this(T({id:t.getAttribute("id")||void 0,type:Bm(t),coords:S_(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:x_(t,s.opacity),gradientUnits:i,gradientTransform:Sc(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}A(ah,"type","Gradient"),N.setClass(ah,"gradient"),N.setClass(ah,"linear"),N.setClass(ah,"radial");const C_=["type","source","patternTransform"];class sg{get type(){return"pattern"}set type(t){mi("warn","Setting type has no effect",t)}constructor(t){A(this,"repeat","repeat"),A(this,"offsetX",0),A(this,"offsetY",0),A(this,"crossOrigin",""),this.id=dn(),Object.assign(this,t)}isImageSource(){return!!this.source&&typeof this.source.src=="string"}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const{repeat:e,crossOrigin:s}=this;return T(T({},Zn(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:xt(this.offsetX,at.NUM_FRACTION_DIGITS),offsetY:xt(this.offsetY,at.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:s}=t;const{source:i,repeat:n,id:r}=this,o=Io(this.offsetX/e,0),h=Io(this.offsetY/s,0),l=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):Io(i.width/e,0),d=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):Io(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=wt(t,C_);const o=await Qa(i,T(T({},e),{},{crossOrigin:r.crossOrigin}));return new this(T(T({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}A(sg,"type","Pattern"),N.setClass(sg),N.setClass(sg,"pattern");const A_=["path","left","top"],T_=["d"];class ir extends de{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=wt(e,A_);super(),Object.assign(this,ir.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(lt,i),typeof n=="number"&&this.set(Le,n)}_setPath(t,e){this.path=Am(Array.isArray(t)?t:Fm(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new D(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const i of this.path)switch(i[0]){case"L":t.lineTo(i[1]+e,i[2]+s);break;case"M":t.moveTo(i[1]+e,i[2]+s);break;case"C":t.bezierCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s,i[5]+e,i[6]+s);break;case"Q":t.quadraticCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),{},{path:this.path.map(e=>e.slice())})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=Rm(this.path,at.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
- `)]}_getOffsetTransform(){const t=at.NUM_FRACTION_DIGITS;return" translate(".concat(xt(-this.pathOffset.x,t),", ").concat(xt(-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({x:e,y:s},{x:i,y:n});break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...Zu(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(...Zu(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 Gs(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return T(T({},t),{},{pathOffset:new D(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=wi(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,T(T(T({},wt(i,T_)),e),{},{left:void 0,top:void 0}))}}A(ir,"type","Path"),A(ir,"cacheProperties",[...yi,"path","fillRule"]),A(ir,"ATTRIBUTE_NAMES",[...gn,"d"]),N.setClass(ir),N.setSVGClass(ir);const E_=["left","top","radius"],Wm=["radius","startAngle","endAngle","counterClockwise"];class Si extends de{static getDefaults(){return T(T({},super.getDefaults()),Si.ownDefaults)}constructor(t){super(),Object.assign(this,Si.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,Ot(this.startAngle),Ot(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(Se)}getRadiusY(){return this.get("radius")*this.get(Ve)}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([...Wm,...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(T(T({},t),{},{colorStops:e?e.map(i=>T({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=Bm(t),n=e._findCenterFromElement();return new this(T({id:t.getAttribute("id")||void 0,type:Nm(t),coords:x_(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:w_(t,s.opacity),gradientUnits:i,gradientTransform:Sc(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}A(ah,"type","Gradient"),N.setClass(ah,"gradient"),N.setClass(ah,"linear"),N.setClass(ah,"radial");const S_=["type","source","patternTransform"];class sg{get type(){return"pattern"}set type(t){mi("warn","Setting type has no effect",t)}constructor(t){A(this,"repeat","repeat"),A(this,"offsetX",0),A(this,"offsetY",0),A(this,"crossOrigin",""),this.id=dn(),Object.assign(this,t)}isImageSource(){return!!this.source&&typeof this.source.src=="string"}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const{repeat:e,crossOrigin:s}=this;return T(T({},Zn(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:xt(this.offsetX,at.NUM_FRACTION_DIGITS),offsetY:xt(this.offsetY,at.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:s}=t;const{source:i,repeat:n,id:r}=this,o=Io(this.offsetX/e,0),h=Io(this.offsetY/s,0),l=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):Io(i.width/e,0),d=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):Io(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=wt(t,S_);const o=await Qa(i,T(T({},e),{},{crossOrigin:r.crossOrigin}));return new this(T(T({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}A(sg,"type","Pattern"),N.setClass(sg),N.setClass(sg,"pattern");const C_=["path","left","top"],A_=["d"];class ir extends de{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=wt(e,C_);super(),Object.assign(this,ir.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(lt,i),typeof n=="number"&&this.set(Le,n)}_setPath(t,e){this.path=Cm(Array.isArray(t)?t:Pm(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new D(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const i of this.path)switch(i[0]){case"L":t.lineTo(i[1]+e,i[2]+s);break;case"M":t.moveTo(i[1]+e,i[2]+s);break;case"C":t.bezierCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s,i[5]+e,i[6]+s);break;case"Q":t.quadraticCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),{},{path:this.path.map(e=>e.slice())})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=Fm(this.path,at.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
+ `)]}_getOffsetTransform(){const t=at.NUM_FRACTION_DIGITS;return" translate(".concat(xt(-this.pathOffset.x,t),", ").concat(xt(-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({x:e,y:s},{x:i,y:n});break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...Zu(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(...Zu(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 Gs(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return T(T({},t),{},{pathOffset:new D(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=wi(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,T(T(T({},wt(i,A_)),e),{},{left:void 0,top:void 0}))}}A(ir,"type","Path"),A(ir,"cacheProperties",[...yi,"path","fillRule"]),A(ir,"ATTRIBUTE_NAMES",[...gn,"d"]),N.setClass(ir),N.setSVGClass(ir);const T_=["left","top","radius"],Hm=["radius","startAngle","endAngle","counterClockwise"];class Si extends de{static getDefaults(){return T(T({},super.getDefaults()),Si.ownDefaults)}constructor(t){super(),Object.assign(this,Si.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,Ot(this.startAngle),Ot(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(Se)}getRadiusY(){return this.get("radius")*this.get(Ve)}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([...Hm,...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=Ot(this.startAngle),i=Ot(this.endAngle),n=vs(s)*e,r=ys(s)*e,o=vs(i)*e,h=ys(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=wi(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(T(T({},wt(i,E_)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}A(Si,"type","Circle"),A(Si,"cacheProperties",[...yi,...Wm]),A(Si,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),A(Si,"ATTRIBUTE_NAMES",["cx","cy","r",...gn]),N.setClass(Si),N.setSVGClass(Si);const k_=["x1","y1","x2","y2"],M_=["x1","y1","x2","y2"],ig=["x1","x2","y1","y2"];class nr extends de{constructor(){let[t,e,s,i]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,nr.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(lt,r),typeof o=="number"&&this.set(Le,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}=Gs([{x:t,y:e},{x:s,y:i}]),l=new D(n+o/2,r+h/2);this.setPositionByOrigin(l,Q,Q)}_set(t,e){return super._set(t,e),ig.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;rs(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 D((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:i,width:n,height:r}=this,o=t<=e?-1:1,h=s<=i?-1:1;return{x1:o*n/2,x2:o*-n/2,y1:h*r/2,y2:h*-r/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(i,`" />
50
- `)]}static async fromElement(t,e,s){const i=wi(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],wt(i,k_))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=wt(t,M_);return this._fromObject(T(T({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}A(nr,"type","Line"),A(nr,"cacheProperties",[...yi,...ig]),A(nr,"ATTRIBUTE_NAMES",gn.concat(ig)),N.setClass(nr),N.setSVGClass(nr);class rr extends de{static getDefaults(){return T(T({},super.getDefaults()),rr.ownDefaults)}constructor(t){super(),Object.assign(this,rr.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}A(rr,"type","Triangle"),A(rr,"ownDefaults",{width:100,height:100}),N.setClass(rr),N.setSVGClass(rr);const zm=["rx","ry"];class Ci extends de{static getDefaults(){return T(T({},super.getDefaults()),Ci.ownDefaults)}constructor(t){super(),Object.assign(this,Ci.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(Se)}getRy(){return this.get("ry")*this.get(Ve)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...zm,...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,bi,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=wi(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}A(Ci,"type","Ellipse"),A(Ci,"cacheProperties",[...yi,...zm]),A(Ci,"ownDefaults",{rx:0,ry:0}),A(Ci,"ATTRIBUTE_NAMES",[...gn,"cx","cy","rx","ry"]),N.setClass(Ci),N.setSVGClass(Ci);const D_=["left","top"],Xm={exactBoundingBox:!1};class Ts extends de{static getDefaults(){return T(T({},super.getDefaults()),Ts.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),A(this,"strokeDiff",void 0),Object.assign(this,Ts.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(lt,s),typeof i=="number"&&this.set(Le,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return am(this.points,t,this.isOpen())}_calcDimensions(t){t=T({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(l=>l.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new D,strokeOffset:new D,strokeDiff:new D};const s=Gs(e),i=Ka(T(T({},t),{},{scaleX:1,scaleY:1})),n=Gs(this.points.map(l=>ce(l,i,!0))),r=new D(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(Ot(this.skewX)),h-=o*Math.tan(Ot(this.skewY))),T(T({},s),{},{pathOffset:new D(o,h),strokeOffset:new D(n.left,n.top).subtract(new D(s.left,s.top)).multiply(r),strokeDiff:new D(s.width,s.height).subtract(new D(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Gs(this.points);return new D(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 D(e+i/2,s+n/2),Q,Q)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new D(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 D((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new D((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new D(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===Se||t===Ve)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),i}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),{},{points:this.points.map(e=>{let{x:s,y:i}=e;return{x:s,y:i}})})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,i=at.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(xt(this.points[n].x-e,i),",",xt(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")),T(T({},wt(wi(t,this.ATTRIBUTE_NAMES,s),D_)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}A(Ts,"ownDefaults",Xm),A(Ts,"type","Polyline"),A(Ts,"layoutProperties",[So,Co,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),A(Ts,"cacheProperties",[...yi,"points"]),A(Ts,"ATTRIBUTE_NAMES",[...gn]),N.setClass(Ts),N.setSVGClass(Ts);class Dc extends Ts{isOpen(){return!1}}A(Dc,"ownDefaults",Xm),A(Dc,"type","Polygon"),N.setClass(Dc),N.setSVGClass(Dc);const Vm=["fontSize","fontWeight","fontFamily","fontStyle"],Gm=["underline","overline","linethrough"],Ym=[...Vm,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],Um=[...Ym,...Gm,"textBackgroundColor","direction"],P_=[...Vm,...Gm,Ce,"strokeWidth",jt,"deltaY","textBackgroundColor"],F_={_reNewline:yu,_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:lt,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:lt,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},qs="justify",Pc="justify-left",hh="justify-right",lh="justify-center";class qm extends de{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const i in e[s])for(const n in e[s][i])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const i in s)for(const n in s[i])if(s[i][n][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,r=!0,o=0;for(const h in e){s=0;for(const l in e[h]){const d=e[h][l]||{};n++,d[t]!==void 0?(i?d[t]!==i&&(r=!1):i=d[t],d[t]===this[t]&&delete d[t]):r=!1,Object.keys(d).length!==0?s++:delete e[h][l]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)o+=this._textLines[h].length;r&&n===o&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],Object.keys(s[n]).length===0&&delete s[n];Object.keys(s).length===0&&delete e[i]}}_extendStyles(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const n=Tu(T(T({},this._getStyleDeclaration(s,i)),e),r=>r!==void 0);this._setStyleDeclaration(s,i,n)}getSelectionStyles(t,e,s){const i=[];for(let n=t;n<(e||t);n++)i.push(this.getStyleAtPosition(n,s));return i}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,i):this._getStyleDeclaration(s,i)}setSelectionStyles(t,e,s){for(let i=e;i<(s||e);i++)this._extendStyles(i,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const i=this.styles&&this.styles[t];return i&&(s=i[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return T(T({},Zn(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}A(qm,"_styleProperties",P_);const R_=/ +/g,L_=/"/g;function ng(a,t,e,s,i){return" ".concat(function(n,r){let{left:o,top:h,width:l,height:d}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:at.NUM_FRACTION_DIGITS;const g=th(jt,n,!1),[f,p,m,_]=[o,h,l,d].map(y=>xt(y,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 I_=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let rg;class ue extends qm{static getDefaults(){return T(T({},super.getDefaults()),ue.ownDefaults)}constructor(t,e){super(),A(this,"__charBounds",[]),Object.assign(this,ue.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=tg(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(qs)&&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===qs||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===Ce?(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=Le;break;case"descender":t.textBaseline=vu}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=Ua.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(){return rg||(rg=_s({width:0,height:0}).getContext("2d")),rg}();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===Ft,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 lt:d=n?u-i:0;break;case Q:d=(u-i)/2;break;case Ft: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=Dm(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===Ft?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(jt))&&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(qs),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,_,y,x,S="",C=0;if(e.save(),f!==this.direction&&(e.canvas.setAttribute("dir",u?"ltr":"rtl"),e.direction=u?"ltr":"rtl",e.textAlign=u?lt:Ft),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++)y=E===M||this.charSpacing||l,S+=s[E],_=this.__charBounds[r][E],C===0?(i+=g*(_.kernedWidth-_.width),C+=_.width):C+=_.kernedWidth,h&&!y&&this._reSpaceAndTab.test(s[E])&&(y=!0),y||(p=p||this.getCompleteStyleDeclaration(r,E),m=this.getCompleteStyleDeclaration(r,E+1),y=xc(p,m,!1)),y&&(l?(e.save(),e.translate(_.renderLeft,_.renderTop),e.rotate(_.angle),this._renderChar(t,e,r,E,S,-C/2,0),e.restore()):(x=i,this._renderChar(t,e,r,E,S,x,n)),S="",p=m,i+=g*C,C=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=_s({width:e,height:s}),n=i.getContext("2d");return i.width=e,i.height=s,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,s),n.lineTo(0,s),n.closePath(),n.translate(e/2,s/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(i,"no-repeat")}handleFiller(t,e,s){let i,n;return rs(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===qs||i===lh&&!r||i===hh&&!r||i===Pc&&!r?0:(i===Q&&(o=s/2),i===Ft&&(o=s),i===lh&&(o=s/2),i===hh&&(o=s),n==="rtl"&&(i===Ft||i===qs||i===hh?o=0:i===lt||i===Pc?o=-s:i!==Q&&i!==lh||(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,y=0,x=this.getValueOfPropertyAt(h,0,e),S=this.getValueOfPropertyAt(h,0,jt);const C=s+g*(1-this._fontSizeFraction);let E=this.getHeightOfChar(h,0),M=this.getValueOfPropertyAt(h,0,"deltaY");for(let O=0,P=u.length;O<P;O++){const F=this.__charBounds[h][O];p=this.getValueOfPropertyAt(h,O,e),m=this.getValueOfPropertyAt(h,O,jt);const R=this.getHeightOfChar(h,O),W=this.getValueOfPropertyAt(h,O,"deltaY");if(n&&p&&m)t.save(),t.fillStyle=S,t.translate(F.renderLeft,F.renderTop),t.rotate(F.angle),t.fillRect(-F.kernedWidth/2,o*R+W,F.kernedWidth,this.fontSize/15),t.restore();else if((p!==x||m!==S||R!==E||W!==M)&&y>0){let B=i+f+_;this.direction==="rtl"&&(B=this.width-B-y),x&&S&&(t.fillStyle=S,t.fillRect(B,C+o*E+M,y,this.fontSize/15)),_=F.left,y=F.width,x=p,S=m,E=R,M=W}else y+=F.kernedWidth}let k=i+f+_;this.direction==="rtl"&&(k=this.width-k-y),t.fillStyle=m,p&&m&&t.fillRect(k,C+o*E+M,y-r,this.fontSize/15),s+=d}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||ue.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return wc(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
54
- `];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject([...Um,...t])),{},{styles:lm(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=wi(t,ue.ATTRIBUTE_NAMES,s),n=T(T({},e),i),{textAnchor:r=lt,textDecoration:o="",dx:h=0,dy:l=0,top:d=0,left:u=0,fontSize:g=bu,strokeWidth:f=1}=n,p=wt(n,I_),m=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),T({left:u+h,top:d+l,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:g},p)),_=m.getScaledHeight()/m.height,y=((m.height+m.strokeWidth)*m.lineHeight-m.height)*_,x=m.getScaledHeight()+y;let S=0;return r===Q&&(S=m.getScaledWidth()/2),r===Ft&&(S=m.getScaledWidth()),m.set({left:m.left-S,top:m.top-(x-m.fontSize*(.07+m._fontSizeFraction))/m.lineHeight,strokeWidth:f}),m}static fromObject(t){return this._fromObject(T(T({},t),{},{styles:cm(t.styles||{},t.text)}),{extraParam:"text"})}}A(ue,"textLayoutProperties",Ym),A(ue,"cacheProperties",[...yi,...Um]),A(ue,"ownDefaults",F_),A(ue,"type","Text"),A(ue,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),A(ue,"ATTRIBUTE_NAMES",gn.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),im(ue,[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(L_,"'"),'" '):"",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(...ng(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(xt(r,at.NUM_FRACTION_DIGITS),'" '):"";return'<tspan x="'.concat(xt(e,at.NUM_FRACTION_DIGITS),'" y="').concat(xt(s,at.NUM_FRACTION_DIGITS),'" ').concat(o).concat(n,">").concat(hm(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(qs),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=xc(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(...ng(l,e+h,s,o,n)),h=u,o=g,l=r):o+=f}r&&a.push(...ng(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?th(Ce,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?th(jt,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter(t=>a[t.replace("-","")]).join(" ")}}]),N.setClass(ue),N.setSVGClass(ue);class j_{constructor(t){A(this,"target",void 0),A(this,"__mouseDownInPlace",!1),A(this,"__dragStartFired",!1),A(this,"__isDraggingOver",!1),A(this,"__dragStartSelection",void 0),A(this,"__dragImageDisposer",void 0),A(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(s=>s()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,o=r.canvas,h=new D(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),d=new D(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 D(f.left,f.top)),m=o.viewportTransform,_=p.add(u).transform(m,!0),y=r.backgroundColor,x=Uu(r.styles);r.backgroundColor="";const S={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(S,0,i),r.setSelectionStyles(S,n,r.text.length),r.dirty=!0;const C=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=y,r.styles=x,r.dirty=!0,kc(C,{position:"fixed",left:"".concat(-C.width,"px"),border:xe,width:"".concat(C.width/g,"px"),height:"".concat(C.height/g,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{C.remove()},ws(t.target||this.target.hiddenTextarea).body.appendChild(C),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(C,_.x,_.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=T({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,o=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},d=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const g=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;h>g&&h<=f?h=g:h>f&&(h-=f-g),r.removeChars(g,f),delete this.__dragStartSelection}r._reNewline.test(d)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,l,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+u,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(sc,{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)||xe;h===xe?(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(sc,{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 $m=/[ \n\.,;!\?\-]/;class N_ extends ue{constructor(){super(...arguments),A(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return Vu({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||!yu.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!$m.test(n);)i+=e,n=s[i];return e===-1&&$m.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.enterEditingImpl(),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()))}enterEditingImpl(){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()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;ws(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 D(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new D(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()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(nc),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let o=i;o<this._unwrappedTextLines[s].length;o++)delete this.styles[s][o];if(this.styles[n])for(let o=r;o<this._unwrappedTextLines[n].length;o++){const h=this.styles[n][o];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=h)}for(let o=s+1;o<=n;o++)delete this.styles[o];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const o=this.styles[s],h=r-i;for(let l=i;l<r;l++)delete o[l];for(const l in this.styles[s]){const d=parseInt(l,10);d>=r&&(o[d-h]=o[l],delete o[l])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const g=parseInt(u,10);g>=e&&(h=!0,n[g-e]=this.styles[t][u],o&&e===0||delete this.styles[t][u])}let d=!1;for(h&&!o&&(this.styles[t+s]=n,d=!0),(d||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:T({},i[s-1])}:l?this.styles[t+s]={0:T({},l)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?T({},n):{};s||(s=1);for(const h in r){const l=parseInt(h,10);l>=e&&(n[l+s]=r[l],r[l-s]||delete n[l])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=T({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=T({},o)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let h=0;h<t.length;h++)t[h]===`
56
- `?(o++,n[o]=0):n[o]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),o&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],o),r=1;r<o;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=lt:this._selectionDirection===Ft&&(this._selectionDirection=lt,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Ft?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Ft:this._selectionDirection===lt&&(this._selectionDirection=Ft,this.selectionStart=e),this.selectionEnd=s)}}class B_ extends N_{initHiddenTextarea(){const t=this.canvas&&ws(this.canvas.getElement())||xo(),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(sc),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 y=i.slice(m.selectionEnd-p,m.selectionEnd);if(u&&u.length&&(y.length&&(d=this.getSelectionStyles(o,o+1,!1),d=y.map(()=>d[0])),l?(g=o,f=h):_?(g=h-u.length,f=h):(g=h,f=h+u.length),this.removeStyleFromTo(g,f)),y.length){const{copyPasteData:x}=Vs();e&&y.join("")===x.copiedText&&!at.disableStyleCopyPaste&&(d=x.copiedTextStyle),this.insertNewStyleBlock(y,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}=Vs();t.copiedText=this.getSelectedText(),at.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,r),d=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-l.length+(1-d)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,l=s.length;h<l;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const d=r-i,u=r,g=Math.abs(d-e);o=Math.abs(u-e)<g?h:h-1;break}return n||(o=s.length-1),o}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===Ft);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=sr(0,this.selectionStart,i),this.selectionEnd=sr(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===lt?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=lt,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Ft&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=lt,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===lt&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Ft,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Ft,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const og=a=>!!a.button;class H_ extends B_{constructor(){super(...arguments),A(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler),this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown),this.draggableTextDelegate=new j_(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),Ou(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&&!og(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&&!og(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||og(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(Ie(this.calcTransformMatrix())).add(new D(-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 Fc="moveCursorUp",Rc="moveCursorDown",Lc="moveCursorLeft",Ic="moveCursorRight",jc="exitEditing",W_=T({selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:jc,27:jc,33:Fc,34:Rc,35:Ic,36:Lc,37:Lc,38:Fc,39:Ic,40:Rc},keysMapRtl:{9:jc,27:jc,33:Fc,34:Rc,35:Lc,36:Ic,37:Ic,38:Fc,39:Lc,40:Rc},ctrlKeysMapDown:{65:"selectAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class Ai extends H_{static getDefaults(){return T(T({},super.getDefaults()),Ai.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,T(T({},Ai.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 eg&&this.canvas.textEditingManager.remove(this),e instanceof eg&&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.inCompositionMode?this.renderSelection(t,e):this.renderCursor(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===Ft||this.textAlign===qs||this.textAlign===hh?h.left*=-1:this.textAlign===lt||this.textAlign===Pc?h.left=r-(s>0?s:0):this.textAlign!==Q&&this.textAlign!==lh||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/o,l=this.getValueOfPropertyAt(i,n,"deltaY"),d=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(i,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:d+e.top+l,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:o,width:h,height:l}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,h,l)}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(qs),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,y=0,x=0;if(f===l&&(y=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 k=this._getWidthOfCharSpacing();x=this.__charBounds[d][g-1].left+this.__charBounds[d][g-1].width-k}_=m,(this.lineHeight<1||f===d&&this.lineHeight>1)&&(m/=this.lineHeight);let S=s.left+p+y,C=m,E=0;const M=x-y;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",C=1,E=m):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Ft||this.textAlign===qs||this.textAlign===hh?S=this.width-S-M:this.textAlign===lt||this.textAlign===Pc?S=s.left+p-x:this.textAlign!==Q&&this.textAlign!==lh||(S=s.left+p-x)),t.fillRect(S,s.top+s.topOffset+E,M,C),s.topOffset+=_}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,jt)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}A(Ai,"ownDefaults",W_),A(Ai,"type","IText"),N.setClass(Ai),N.setClass(Ai,"i-text");class or extends Ai{static getDefaults(){return T(T({},super.getDefaults()),or.ownDefaults)}constructor(t,e){super(t,T(T({},or.ownDefaults),e))}static createControls(){return{controls:Ay()}}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(qs)&&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),y=n[t];let x;for(f=0,x=0;x<y.length;x++){const{word:S,width:C}=y[x];f+=S.length,u+=p+C-o,u>_&&!m?(l.push(g),g=[],u=C,m=!0):u+=o,m||h||g.push(d),g=g.concat(S),p=h?0:this._measureWord([d],t,f),f++,m=!1}return x&&l.push(g),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),l}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}A(or,"type","Textbox"),A(or,"textLayoutProperties",[...Ai.textLayoutProperties,"width"]),A(or,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),N.setClass(or);class Km extends Tc{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}=Gs(_m(s,i)),h=new D(r,o);if(i.absolutePositioned)return{center:er(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 D,correction:u=new D}=this.calcBoundingBox(e,t)||{};return{center:d.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}A(Km,"type","clip-path"),N.setClass(Km);class Qm extends Tc{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new D(s.width||i.x,s.height||i.y)}}A(Qm,"type","fixed"),N.setClass(Qm);class z_ extends rh{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 ar extends Us{static getDefaults(){return T(T({},super.getDefaults()),ar.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,ar.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))?(mi("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===Ku?s.forEach(i=>{i._onAfterObjectsChange(Cc,e)}):s.forEach(i=>{i._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=T(T({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}A(ar,"type","ActiveSelection"),A(ar,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),N.setClass(ar),N.setClass(ar,"activeSelection");class X_{constructor(){A(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const o={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach(l=>{l.applyTo(o)});const{imageData:h}=o;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),o}}class Jm{constructor(){let{tileSize:t=at.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};A(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),A(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=_s({width:t,height:e}),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,y=g.destinationHeight;p===_&&m===y||(f.width=_,f.height=y)}(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 ag;function V_(){const{WebGLProbe:a}=Vs();return a.queryWebGL(ns()),at.enableGLFiltering&&a.isSupported(at.textureSize)?new Jm({tileSize:at.textureSize}):new X_}function hg(){return!ag&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(ag=V_()),ag}const G_=["filters","resizeFilter","src","crossOrigin","type"],Zm=["cropX","cropY"];class ge extends de{static getDefaults(){return T(T({},super.getDefaults()),ge.ownDefaults)}constructor(t,e){super(),A(this,"_lastScaleX",1),A(this,"_lastScaleY",1),A(this,"_filterScalingX",1),A(this,"_filterScalingY",1),this.filters=[],Object.assign(this,ge.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(dn()),this.setElement(typeof t=="string"?(this.canvas&&ws(this.canvas.getElement())||xo()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(e),t.classList.add(ge.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=hg(!1);e instanceof Jm&&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&&Vs().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach(s=>{s&&e.push(s.toObject())}),T(T({},super.toObject([...Zm,...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=dn();n.push('<clipPath id="imageCrop_'+l+`">
49
+ `]}}static async fromElement(t,e,s){const i=wi(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(T(T({},wt(i,T_)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}A(Si,"type","Circle"),A(Si,"cacheProperties",[...yi,...Hm]),A(Si,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),A(Si,"ATTRIBUTE_NAMES",["cx","cy","r",...gn]),N.setClass(Si),N.setSVGClass(Si);const E_=["x1","y1","x2","y2"],k_=["x1","y1","x2","y2"],ig=["x1","x2","y1","y2"];class nr extends de{constructor(){let[t,e,s,i]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,nr.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(lt,r),typeof o=="number"&&this.set(Le,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}=Gs([{x:t,y:e},{x:s,y:i}]),l=new D(n+o/2,r+h/2);this.setPositionByOrigin(l,Q,Q)}_set(t,e){return super._set(t,e),ig.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;rs(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 D((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:i,width:n,height:r}=this,o=t<=e?-1:1,h=s<=i?-1:1;return{x1:o*n/2,x2:o*-n/2,y1:h*r/2,y2:h*-r/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(i,`" />
50
+ `)]}static async fromElement(t,e,s){const i=wi(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],wt(i,E_))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=wt(t,k_);return this._fromObject(T(T({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}A(nr,"type","Line"),A(nr,"cacheProperties",[...yi,...ig]),A(nr,"ATTRIBUTE_NAMES",gn.concat(ig)),N.setClass(nr),N.setSVGClass(nr);class rr extends de{static getDefaults(){return T(T({},super.getDefaults()),rr.ownDefaults)}constructor(t){super(),Object.assign(this,rr.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}A(rr,"type","Triangle"),A(rr,"ownDefaults",{width:100,height:100}),N.setClass(rr),N.setSVGClass(rr);const Wm=["rx","ry"];class Ci extends de{static getDefaults(){return T(T({},super.getDefaults()),Ci.ownDefaults)}constructor(t){super(),Object.assign(this,Ci.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(Se)}getRy(){return this.get("ry")*this.get(Ve)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Wm,...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,bi,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=wi(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function M_(a){if(!a)return[];const t=a.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}A(Ci,"type","Ellipse"),A(Ci,"cacheProperties",[...yi,...Wm]),A(Ci,"ownDefaults",{rx:0,ry:0}),A(Ci,"ATTRIBUTE_NAMES",[...gn,"cx","cy","rx","ry"]),N.setClass(Ci),N.setSVGClass(Ci);const O_=["left","top"],zm={exactBoundingBox:!1};class Ts extends de{static getDefaults(){return T(T({},super.getDefaults()),Ts.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),A(this,"strokeDiff",void 0),Object.assign(this,Ts.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(lt,s),typeof i=="number"&&this.set(Le,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return om(this.points,t,this.isOpen())}_calcDimensions(t){t=T({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(l=>l.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new D,strokeOffset:new D,strokeDiff:new D};const s=Gs(e),i=Ka(T(T({},t),{},{scaleX:1,scaleY:1})),n=Gs(this.points.map(l=>ce(l,i,!0))),r=new D(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(Ot(this.skewX)),h-=o*Math.tan(Ot(this.skewY))),T(T({},s),{},{pathOffset:new D(o,h),strokeOffset:new D(n.left,n.top).subtract(new D(s.left,s.top)).multiply(r),strokeDiff:new D(s.width,s.height).subtract(new D(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Gs(this.points);return new D(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 D(e+i/2,s+n/2),Q,Q)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new D(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 D((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new D((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new D(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===Se||t===Ve)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),i}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject(t)),{},{points:this.points.map(e=>{let{x:s,y:i}=e;return{x:s,y:i}})})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,i=at.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(xt(this.points[n].x-e,i),",",xt(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(M_(t.getAttribute("points")),T(T({},wt(wi(t,this.ATTRIBUTE_NAMES,s),O_)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}A(Ts,"ownDefaults",zm),A(Ts,"type","Polyline"),A(Ts,"layoutProperties",[So,Co,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),A(Ts,"cacheProperties",[...yi,"points"]),A(Ts,"ATTRIBUTE_NAMES",[...gn]),N.setClass(Ts),N.setSVGClass(Ts);class Dc extends Ts{isOpen(){return!1}}A(Dc,"ownDefaults",zm),A(Dc,"type","Polygon"),N.setClass(Dc),N.setSVGClass(Dc);const Xm=["fontSize","fontWeight","fontFamily","fontStyle"],Vm=["underline","overline","linethrough"],Gm=[...Xm,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],Ym=[...Gm,...Vm,"textBackgroundColor","direction"],D_=[...Xm,...Vm,Ce,"strokeWidth",jt,"deltaY","textBackgroundColor"],P_={_reNewline:yu,_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:lt,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:lt,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},qs="justify",Pc="justify-left",hh="justify-right",lh="justify-center";class Um extends de{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const i in e[s])for(const n in e[s][i])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const i in s)for(const n in s[i])if(s[i][n][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,r=!0,o=0;for(const h in e){s=0;for(const l in e[h]){const d=e[h][l]||{};n++,d[t]!==void 0?(i?d[t]!==i&&(r=!1):i=d[t],d[t]===this[t]&&delete d[t]):r=!1,Object.keys(d).length!==0?s++:delete e[h][l]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)o+=this._textLines[h].length;r&&n===o&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],Object.keys(s[n]).length===0&&delete s[n];Object.keys(s).length===0&&delete e[i]}}_extendStyles(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const n=Tu(T(T({},this._getStyleDeclaration(s,i)),e),r=>r!==void 0);this._setStyleDeclaration(s,i,n)}getSelectionStyles(t,e,s){const i=[];for(let n=t;n<(e||t);n++)i.push(this.getStyleAtPosition(n,s));return i}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,i):this._getStyleDeclaration(s,i)}setSelectionStyles(t,e,s){for(let i=e;i<(s||e);i++)this._extendStyles(i,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const i=this.styles&&this.styles[t];return i&&(s=i[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return T(T({},Zn(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}A(Um,"_styleProperties",D_);const F_=/ +/g,R_=/"/g;function ng(a,t,e,s,i){return" ".concat(function(n,r){let{left:o,top:h,width:l,height:d}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:at.NUM_FRACTION_DIGITS;const g=th(jt,n,!1),[f,p,m,_]=[o,h,l,d].map(y=>xt(y,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 L_=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let rg;class ue extends Um{static getDefaults(){return T(T({},super.getDefaults()),ue.ownDefaults)}constructor(t,e){super(),A(this,"__charBounds",[]),Object.assign(this,ue.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=tg(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(qs)&&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===qs||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===Ce?(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=Le;break;case"descender":t.textBaseline=vu}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=Ua.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(){return rg||(rg=_s({width:0,height:0}).getContext("2d")),rg}();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===Ft,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 lt:d=n?u-i:0;break;case Q:d=(u-i)/2;break;case Ft: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=Om(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===Ft?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(jt))&&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(qs),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,_,y,x,S="",C=0;if(e.save(),f!==this.direction&&(e.canvas.setAttribute("dir",u?"ltr":"rtl"),e.direction=u?"ltr":"rtl",e.textAlign=u?lt:Ft),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++)y=E===M||this.charSpacing||l,S+=s[E],_=this.__charBounds[r][E],C===0?(i+=g*(_.kernedWidth-_.width),C+=_.width):C+=_.kernedWidth,h&&!y&&this._reSpaceAndTab.test(s[E])&&(y=!0),y||(p=p||this.getCompleteStyleDeclaration(r,E),m=this.getCompleteStyleDeclaration(r,E+1),y=xc(p,m,!1)),y&&(l?(e.save(),e.translate(_.renderLeft,_.renderTop),e.rotate(_.angle),this._renderChar(t,e,r,E,S,-C/2,0),e.restore()):(x=i,this._renderChar(t,e,r,E,S,x,n)),S="",p=m,i+=g*C,C=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=_s({width:e,height:s}),n=i.getContext("2d");return i.width=e,i.height=s,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,s),n.lineTo(0,s),n.closePath(),n.translate(e/2,s/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(i,"no-repeat")}handleFiller(t,e,s){let i,n;return rs(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===qs||i===lh&&!r||i===hh&&!r||i===Pc&&!r?0:(i===Q&&(o=s/2),i===Ft&&(o=s),i===lh&&(o=s/2),i===hh&&(o=s),n==="rtl"&&(i===Ft||i===qs||i===hh?o=0:i===lt||i===Pc?o=-s:i!==Q&&i!==lh||(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,y=0,x=this.getValueOfPropertyAt(h,0,e),S=this.getValueOfPropertyAt(h,0,jt);const C=s+g*(1-this._fontSizeFraction);let E=this.getHeightOfChar(h,0),M=this.getValueOfPropertyAt(h,0,"deltaY");for(let O=0,P=u.length;O<P;O++){const F=this.__charBounds[h][O];p=this.getValueOfPropertyAt(h,O,e),m=this.getValueOfPropertyAt(h,O,jt);const R=this.getHeightOfChar(h,O),W=this.getValueOfPropertyAt(h,O,"deltaY");if(n&&p&&m)t.save(),t.fillStyle=S,t.translate(F.renderLeft,F.renderTop),t.rotate(F.angle),t.fillRect(-F.kernedWidth/2,o*R+W,F.kernedWidth,this.fontSize/15),t.restore();else if((p!==x||m!==S||R!==E||W!==M)&&y>0){let B=i+f+_;this.direction==="rtl"&&(B=this.width-B-y),x&&S&&(t.fillStyle=S,t.fillRect(B,C+o*E+M,y,this.fontSize/15)),_=F.left,y=F.width,x=p,S=m,E=R,M=W}else y+=F.kernedWidth}let k=i+f+_;this.direction==="rtl"&&(k=this.width-k-y),t.fillStyle=m,p&&m&&t.fillRect(k,C+o*E+M,y-r,this.fontSize/15),s+=d}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||ue.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return wc(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
54
+ `];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return T(T({},super.toObject([...Ym,...t])),{},{styles:hm(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=wi(t,ue.ATTRIBUTE_NAMES,s),n=T(T({},e),i),{textAnchor:r=lt,textDecoration:o="",dx:h=0,dy:l=0,top:d=0,left:u=0,fontSize:g=bu,strokeWidth:f=1}=n,p=wt(n,L_),m=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),T({left:u+h,top:d+l,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:g},p)),_=m.getScaledHeight()/m.height,y=((m.height+m.strokeWidth)*m.lineHeight-m.height)*_,x=m.getScaledHeight()+y;let S=0;return r===Q&&(S=m.getScaledWidth()/2),r===Ft&&(S=m.getScaledWidth()),m.set({left:m.left-S,top:m.top-(x-m.fontSize*(.07+m._fontSizeFraction))/m.lineHeight,strokeWidth:f}),m}static fromObject(t){return this._fromObject(T(T({},t),{},{styles:lm(t.styles||{},t.text)}),{extraParam:"text"})}}A(ue,"textLayoutProperties",Gm),A(ue,"cacheProperties",[...yi,...Ym]),A(ue,"ownDefaults",P_),A(ue,"type","Text"),A(ue,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),A(ue,"ATTRIBUTE_NAMES",gn.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),sm(ue,[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(R_,"'"),'" '):"",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(...ng(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(F_)),n=i?'style="'.concat(i,'"'):"",r=t.deltaY,o=r?' dy="'.concat(xt(r,at.NUM_FRACTION_DIGITS),'" '):"";return'<tspan x="'.concat(xt(e,at.NUM_FRACTION_DIGITS),'" y="').concat(xt(s,at.NUM_FRACTION_DIGITS),'" ').concat(o).concat(n,">").concat(am(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(qs),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=xc(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(...ng(l,e+h,s,o,n)),h=u,o=g,l=r):o+=f}r&&a.push(...ng(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?th(Ce,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?th(jt,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter(t=>a[t.replace("-","")]).join(" ")}}]),N.setClass(ue),N.setSVGClass(ue);class I_{constructor(t){A(this,"target",void 0),A(this,"__mouseDownInPlace",!1),A(this,"__dragStartFired",!1),A(this,"__isDraggingOver",!1),A(this,"__dragStartSelection",void 0),A(this,"__dragImageDisposer",void 0),A(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(s=>s()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,o=r.canvas,h=new D(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),d=new D(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 D(f.left,f.top)),m=o.viewportTransform,_=p.add(u).transform(m,!0),y=r.backgroundColor,x=Uu(r.styles);r.backgroundColor="";const S={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(S,0,i),r.setSelectionStyles(S,n,r.text.length),r.dirty=!0;const C=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=y,r.styles=x,r.dirty=!0,kc(C,{position:"fixed",left:"".concat(-C.width,"px"),border:xe,width:"".concat(C.width/g,"px"),height:"".concat(C.height/g,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{C.remove()},ws(t.target||this.target.hiddenTextarea).body.appendChild(C),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(C,_.x,_.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=T({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,o=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},d=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const g=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;h>g&&h<=f?h=g:h>f&&(h-=f-g),r.removeChars(g,f),delete this.__dragStartSelection}r._reNewline.test(d)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,l,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+u,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(sc,{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)||xe;h===xe?(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(sc,{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 qm=/[ \n\.,;!\?\-]/;class j_ extends ue{constructor(){super(...arguments),A(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return Vu({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||!yu.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!qm.test(n);)i+=e,n=s[i];return e===-1&&qm.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.enterEditingImpl(),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()))}enterEditingImpl(){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()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;ws(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 D(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new D(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()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(nc),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let o=i;o<this._unwrappedTextLines[s].length;o++)delete this.styles[s][o];if(this.styles[n])for(let o=r;o<this._unwrappedTextLines[n].length;o++){const h=this.styles[n][o];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=h)}for(let o=s+1;o<=n;o++)delete this.styles[o];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const o=this.styles[s],h=r-i;for(let l=i;l<r;l++)delete o[l];for(const l in this.styles[s]){const d=parseInt(l,10);d>=r&&(o[d-h]=o[l],delete o[l])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const g=parseInt(u,10);g>=e&&(h=!0,n[g-e]=this.styles[t][u],o&&e===0||delete this.styles[t][u])}let d=!1;for(h&&!o&&(this.styles[t+s]=n,d=!0),(d||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:T({},i[s-1])}:l?this.styles[t+s]={0:T({},l)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?T({},n):{};s||(s=1);for(const h in r){const l=parseInt(h,10);l>=e&&(n[l+s]=r[l],r[l-s]||delete n[l])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=T({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=T({},o)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let h=0;h<t.length;h++)t[h]===`
56
+ `?(o++,n[o]=0):n[o]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),o&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],o),r=1;r<o;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=lt:this._selectionDirection===Ft&&(this._selectionDirection=lt,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Ft?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Ft:this._selectionDirection===lt&&(this._selectionDirection=Ft,this.selectionStart=e),this.selectionEnd=s)}}class N_ extends j_{initHiddenTextarea(){const t=this.canvas&&ws(this.canvas.getElement())||xo(),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(sc),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 y=i.slice(m.selectionEnd-p,m.selectionEnd);if(u&&u.length&&(y.length&&(d=this.getSelectionStyles(o,o+1,!1),d=y.map(()=>d[0])),l?(g=o,f=h):_?(g=h-u.length,f=h):(g=h,f=h+u.length),this.removeStyleFromTo(g,f)),y.length){const{copyPasteData:x}=Vs();e&&y.join("")===x.copiedText&&!at.disableStyleCopyPaste&&(d=x.copiedTextStyle),this.insertNewStyleBlock(y,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}=Vs();t.copiedText=this.getSelectedText(),at.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,r),d=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-l.length+(1-d)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,l=s.length;h<l;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const d=r-i,u=r,g=Math.abs(d-e);o=Math.abs(u-e)<g?h:h-1;break}return n||(o=s.length-1),o}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===Ft);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=sr(0,this.selectionStart,i),this.selectionEnd=sr(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===lt?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=lt,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Ft&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=lt,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===lt&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Ft,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Ft,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const og=a=>!!a.button;class B_ extends N_{constructor(){super(...arguments),A(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler),this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown),this.draggableTextDelegate=new I_(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),Ou(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&&!og(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&&!og(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||og(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(Ie(this.calcTransformMatrix())).add(new D(-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 Fc="moveCursorUp",Rc="moveCursorDown",Lc="moveCursorLeft",Ic="moveCursorRight",jc="exitEditing",H_=T({selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:jc,27:jc,33:Fc,34:Rc,35:Ic,36:Lc,37:Lc,38:Fc,39:Ic,40:Rc},keysMapRtl:{9:jc,27:jc,33:Fc,34:Rc,35:Lc,36:Ic,37:Ic,38:Fc,39:Lc,40:Rc},ctrlKeysMapDown:{65:"selectAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class Ai extends B_{static getDefaults(){return T(T({},super.getDefaults()),Ai.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,T(T({},Ai.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 eg&&this.canvas.textEditingManager.remove(this),e instanceof eg&&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.inCompositionMode?this.renderSelection(t,e):this.renderCursor(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===Ft||this.textAlign===qs||this.textAlign===hh?h.left*=-1:this.textAlign===lt||this.textAlign===Pc?h.left=r-(s>0?s:0):this.textAlign!==Q&&this.textAlign!==lh||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/o,l=this.getValueOfPropertyAt(i,n,"deltaY"),d=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(i,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:d+e.top+l,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:o,width:h,height:l}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,h,l)}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(qs),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,y=0,x=0;if(f===l&&(y=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 k=this._getWidthOfCharSpacing();x=this.__charBounds[d][g-1].left+this.__charBounds[d][g-1].width-k}_=m,(this.lineHeight<1||f===d&&this.lineHeight>1)&&(m/=this.lineHeight);let S=s.left+p+y,C=m,E=0;const M=x-y;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",C=1,E=m):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Ft||this.textAlign===qs||this.textAlign===hh?S=this.width-S-M:this.textAlign===lt||this.textAlign===Pc?S=s.left+p-x:this.textAlign!==Q&&this.textAlign!==lh||(S=s.left+p-x)),t.fillRect(S,s.top+s.topOffset+E,M,C),s.topOffset+=_}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,jt)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}A(Ai,"ownDefaults",H_),A(Ai,"type","IText"),N.setClass(Ai),N.setClass(Ai,"i-text");class or extends Ai{static getDefaults(){return T(T({},super.getDefaults()),or.ownDefaults)}constructor(t,e){super(t,T(T({},or.ownDefaults),e))}static createControls(){return{controls:Cy()}}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(qs)&&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),y=n[t];let x;for(f=0,x=0;x<y.length;x++){const{word:S,width:C}=y[x];f+=S.length,u+=p+C-o,u>_&&!m?(l.push(g),g=[],u=C,m=!0):u+=o,m||h||g.push(d),g=g.concat(S),p=h?0:this._measureWord([d],t,f),f++,m=!1}return x&&l.push(g),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),l}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}A(or,"type","Textbox"),A(or,"textLayoutProperties",[...Ai.textLayoutProperties,"width"]),A(or,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),N.setClass(or);class $m extends Tc{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}=Gs(ym(s,i)),h=new D(r,o);if(i.absolutePositioned)return{center:er(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 D,correction:u=new D}=this.calcBoundingBox(e,t)||{};return{center:d.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}A($m,"type","clip-path"),N.setClass($m);class Km extends Tc{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new D(s.width||i.x,s.height||i.y)}}A(Km,"type","fixed"),N.setClass(Km);class W_ extends rh{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 ar extends Us{static getDefaults(){return T(T({},super.getDefaults()),ar.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,ar.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new W_})}_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))?(mi("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===Ku?s.forEach(i=>{i._onAfterObjectsChange(Cc,e)}):s.forEach(i=>{i._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=T(T({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}A(ar,"type","ActiveSelection"),A(ar,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),N.setClass(ar),N.setClass(ar,"activeSelection");class z_{constructor(){A(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const o={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach(l=>{l.applyTo(o)});const{imageData:h}=o;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),o}}class Qm{constructor(){let{tileSize:t=at.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};A(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),A(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=_s({width:t,height:e}),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,y=g.destinationHeight;p===_&&m===y||(f.width=_,f.height=y)}(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 ag;function X_(){const{WebGLProbe:a}=Vs();return a.queryWebGL(ns()),at.enableGLFiltering&&a.isSupported(at.textureSize)?new Qm({tileSize:at.textureSize}):new z_}function hg(){return!ag&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(ag=X_()),ag}const V_=["filters","resizeFilter","src","crossOrigin","type"],Jm=["cropX","cropY"];class ge extends de{static getDefaults(){return T(T({},super.getDefaults()),ge.ownDefaults)}constructor(t,e){super(),A(this,"_lastScaleX",1),A(this,"_lastScaleY",1),A(this,"_filterScalingX",1),A(this,"_filterScalingY",1),this.filters=[],Object.assign(this,ge.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(dn()),this.setElement(typeof t=="string"?(this.canvas&&ws(this.canvas.getElement())||xo()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(e),t.classList.add(ge.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=hg(!1);e instanceof Qm&&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&&Vs().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach(s=>{s&&e.push(s.toObject())}),T(T({},super.toObject([...Jm,...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=dn();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!==jt?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 Qa(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=_s(r),{width:h,height:l}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,hg().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=_s({width:s,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);hg().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,y=Math.min(n,l/s-o),x=Math.min(r,d/i-h);e&&t.drawImage(e,u,g,f,p,m,_,y,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=ku(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===xe&&t.alignY===xe?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=xm(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=Sm(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=wt(t,G_);return Promise.all([Qa(n,T(T({},e),{},{crossOrigin:r})),s&&ko(s,e),i&&ko([i],e),Ja(h,e)]).then(l=>{let[d,u=[],[g]=[],f={}]=l;return new this(d,T(T({},h),{},{src:n,filters:u,resizeFilter:g},f))})}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;return Qa(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=wi(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"],e,i).catch(n=>(mi("log","Unable to parse Image",n),null))}}function lg(a){if(!Kv.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&&Hp.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("+Ae(d||"0")+" "+Ae(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 y={width:0,height:0};if(g)return y.width=Ae(h),y.height=Ae(l),y;const x=t.match(Hp);r=-parseFloat(x[1]),o=-parseFloat(x[2]);const S=parseFloat(x[3]),C=parseFloat(x[4]);y.minX=r,y.minY=o,y.viewBoxWidth=S,y.viewBoxHeight=C,f?(y.width=S,y.height=C):(y.width=Ae(h),y.height=Ae(l),i=y.width/S,n=y.height/C);const E=ku(a.getAttribute("preserveAspectRatio")||"");if(E.alignX!==xe&&(E.meetOrSlice==="meet"&&(n=i=i>n?n:i),E.meetOrSlice==="slice"&&(n=i=i>n?i:n),m=y.width-S*i,_=y.height-C*i,E.alignX==="Mid"&&(m/=2),E.alignY==="Mid"&&(_/=2),E.alignX==="Min"&&(m=0),E.alignY==="Min"&&(_=0)),i===1&&n===1&&r===0&&o===0&&d===0&&u===0)return y;if((d||u)&&a.parentNode.nodeName!=="#document"&&(p=" translate("+Ae(d||"0")+" "+Ae(u||"0")+") "),e=p+" matrix("+i+" 0 0 "+n+" "+(r*i+m)+" "+(o*n+_)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(Ru,"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),y}A(ge,"type","Image"),A(ge,"cacheProperties",[...yi,...Zm]),A(ge,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),A(ge,"CSS_CANVAS","canvas-img"),A(ge,"ATTRIBUTE_NAMES",[...gn,"x","y","width","height","preserveAspectRatio","xlink:href","crossOrigin","image-rendering"]),N.setClass(ge),N.setSVGClass(ge);const Nc=a=>a.tagName.replace("svg:",""),Y_=gc(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function t0(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 U_=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],cg="xlink:href";function e0(a,t){var e;const s=((e=t.getAttribute(cg))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(cg)&&e0(a,i),i&&(U_.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(cg)}const q_=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function $_(a){const t=a.getElementsByTagName("style");let e,s;const i={};for(e=0,s=t.length;e<s;e++){const n=(t[e].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");n.trim()!==""&&n.split("}").filter((r,o,h)=>h.length>1&&r.trim()).forEach(r=>{if((r.match(/{/g)||[]).length>1&&r.trim().startsWith("@"))return;const o=r.split("{"),h={},l=o[1].trim().split(";").filter(function(d){return d.trim()});for(e=0,s=l.length;e<s;e++){const d=l[e].split(":"),u=d[0].trim(),g=d[1].trim();h[u]=g}(r=o[0].trim()).split(",").forEach(d=>{(d=d.replace(/^svg/i,"").trim())!==""&&(i[d]=T(T({},i[d]||{}),h))})})}return i}const s0=a=>N.getSVGClass(Nc(a).toLowerCase());class K_{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=t0(r,q_),h={};let l=o.length;for(;l--;){const d=o[l];d.getAttribute("xlink:href")&&e0(r,d);const u=d.getAttribute("id");u&&(h[u]=d)}return h}(i),this.cssRules=$_(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=s0(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,jt),this.resolveGradient(s,t,Ce),s instanceof ge&&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=ah.fromElement(i,t,T(T({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e,s){const i=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(i){const n=Ie(t.calcTransformMatrix()),r=i[0].parentElement;let o=e;for(;!s&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const h=Sc("".concat(o.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const l=await Promise.all(i.map(x=>s0(x).fromElement(x,this.options,this.cssRules).then(S=>(Mc(S),S.fillRule=S.clipRule,delete S.clipRule,S)))),d=l.length===1?l[0]:new Us(l),u=Rt(n,d.calcTransformMatrix());d.clipPath&&await this.resolveClipPath(d,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:g,scaleY:f,angle:p,skewX:m,translateX:_,translateY:y}=Jn(u);d.set({flipX:!1,flipY:!1}),d.set({scaleX:g,scaleY:f,angle:p,skewX:m,skewY:0}),d.setPositionByOrigin(new D(_,y),Q,Q),t.clipPath=d}else delete t.clipPath}}const i0=a=>$v.test(Nc(a)),dg=()=>({objects:[],elements:[],options:{},allElements:[]});async function Q_(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return mi("log",new fu("parseSVGDocument")),dg();const i=a.documentElement;(function(d){const u=t0(d,["use","svg:use"]),g=["x","y","xlink:href","href","transform"];for(const f of u){const p=f.attributes,m={};for(const P of p)P.value&&(m[P.name]=P.value);const _=(m["xlink:href"]||m.href||"").slice(1);if(_==="")return;const y=d.getElementById(_);if(y===null)return;let x=y.cloneNode(!0);const S=x.attributes,C={};for(const P of S)P.value&&(C[P.name]=P.value);const{x:E=0,y:M=0,transform:k=""}=m,O="".concat(k," ").concat(C.transform||""," translate(").concat(E,", ").concat(M,")");if(lg(x),/^svg$/i.test(x.nodeName)){const P=x.ownerDocument.createElementNS(Ru,"g");Object.entries(C).forEach(F=>{let[R,W]=F;return P.setAttributeNS(Ru,R,W)}),P.append(...x.childNodes),x=P}for(const P of p){if(!P)continue;const{name:F,value:R}=P;if(!g.includes(F))if(F==="style"){const W={};$u(R,W),Object.entries(C).forEach(X=>{let[K,tt]=X;W[K]=tt}),$u(C.style||"",W);const B=Object.entries(W).map(X=>X.join(":")).join(";");x.setAttribute(F,B)}else!C[F]&&x.setAttribute(F,R)}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=T(T({},lg(i)),{},{crossOrigin:e,signal:s}),o=n.filter(d=>(lg(d),i0(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 T(T({},dg()),{},{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=>i0(g))}),{objects:await new K_(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function J_(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{Lm(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>Q_(s,t,e)).catch(()=>dg())}const Bc=a=>a.webgl!==void 0,ug="precision highp float",Z_=`
62
+ `)],this.fill=l}return n=this.paintFirst!==jt?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 Qa(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=_s(r),{width:h,height:l}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,hg().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=_s({width:s,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);hg().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,y=Math.min(n,l/s-o),x=Math.min(r,d/i-h);e&&t.drawImage(e,u,g,f,p,m,_,y,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=ku(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===xe&&t.alignY===xe?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=wm(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=xm(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=wt(t,V_);return Promise.all([Qa(n,T(T({},e),{},{crossOrigin:r})),s&&ko(s,e),i&&ko([i],e),Ja(h,e)]).then(l=>{let[d,u=[],[g]=[],f={}]=l;return new this(d,T(T({},h),{},{src:n,filters:u,resizeFilter:g},f))})}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;return Qa(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=wi(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"],e,i).catch(n=>(mi("log","Unable to parse Image",n),null))}}function lg(a){if(!$v.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&&Bp.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("+Ae(d||"0")+" "+Ae(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 y={width:0,height:0};if(g)return y.width=Ae(h),y.height=Ae(l),y;const x=t.match(Bp);r=-parseFloat(x[1]),o=-parseFloat(x[2]);const S=parseFloat(x[3]),C=parseFloat(x[4]);y.minX=r,y.minY=o,y.viewBoxWidth=S,y.viewBoxHeight=C,f?(y.width=S,y.height=C):(y.width=Ae(h),y.height=Ae(l),i=y.width/S,n=y.height/C);const E=ku(a.getAttribute("preserveAspectRatio")||"");if(E.alignX!==xe&&(E.meetOrSlice==="meet"&&(n=i=i>n?n:i),E.meetOrSlice==="slice"&&(n=i=i>n?i:n),m=y.width-S*i,_=y.height-C*i,E.alignX==="Mid"&&(m/=2),E.alignY==="Mid"&&(_/=2),E.alignX==="Min"&&(m=0),E.alignY==="Min"&&(_=0)),i===1&&n===1&&r===0&&o===0&&d===0&&u===0)return y;if((d||u)&&a.parentNode.nodeName!=="#document"&&(p=" translate("+Ae(d||"0")+" "+Ae(u||"0")+") "),e=p+" matrix("+i+" 0 0 "+n+" "+(r*i+m)+" "+(o*n+_)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(Ru,"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),y}A(ge,"type","Image"),A(ge,"cacheProperties",[...yi,...Jm]),A(ge,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),A(ge,"CSS_CANVAS","canvas-img"),A(ge,"ATTRIBUTE_NAMES",[...gn,"x","y","width","height","preserveAspectRatio","xlink:href","crossOrigin","image-rendering"]),N.setClass(ge),N.setSVGClass(ge);const Nc=a=>a.tagName.replace("svg:",""),G_=gc(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function Zm(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 Y_=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],cg="xlink:href";function t0(a,t){var e;const s=((e=t.getAttribute(cg))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(cg)&&t0(a,i),i&&(Y_.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(cg)}const U_=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function q_(a){const t=a.getElementsByTagName("style");let e,s;const i={};for(e=0,s=t.length;e<s;e++){const n=(t[e].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");n.trim()!==""&&n.split("}").filter((r,o,h)=>h.length>1&&r.trim()).forEach(r=>{if((r.match(/{/g)||[]).length>1&&r.trim().startsWith("@"))return;const o=r.split("{"),h={},l=o[1].trim().split(";").filter(function(d){return d.trim()});for(e=0,s=l.length;e<s;e++){const d=l[e].split(":"),u=d[0].trim(),g=d[1].trim();h[u]=g}(r=o[0].trim()).split(",").forEach(d=>{(d=d.replace(/^svg/i,"").trim())!==""&&(i[d]=T(T({},i[d]||{}),h))})})}return i}const e0=a=>N.getSVGClass(Nc(a).toLowerCase());class $_{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=Zm(r,U_),h={};let l=o.length;for(;l--;){const d=o[l];d.getAttribute("xlink:href")&&t0(r,d);const u=d.getAttribute("id");u&&(h[u]=d)}return h}(i),this.cssRules=q_(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=e0(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,jt),this.resolveGradient(s,t,Ce),s instanceof ge&&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=ah.fromElement(i,t,T(T({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e,s){const i=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(i){const n=Ie(t.calcTransformMatrix()),r=i[0].parentElement;let o=e;for(;!s&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const h=Sc("".concat(o.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const l=await Promise.all(i.map(x=>e0(x).fromElement(x,this.options,this.cssRules).then(S=>(Mc(S),S.fillRule=S.clipRule,delete S.clipRule,S)))),d=l.length===1?l[0]:new Us(l),u=Rt(n,d.calcTransformMatrix());d.clipPath&&await this.resolveClipPath(d,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:g,scaleY:f,angle:p,skewX:m,translateX:_,translateY:y}=Jn(u);d.set({flipX:!1,flipY:!1}),d.set({scaleX:g,scaleY:f,angle:p,skewX:m,skewY:0}),d.setPositionByOrigin(new D(_,y),Q,Q),t.clipPath=d}else delete t.clipPath}}const s0=a=>qv.test(Nc(a)),dg=()=>({objects:[],elements:[],options:{},allElements:[]});async function K_(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return mi("log",new fu("parseSVGDocument")),dg();const i=a.documentElement;(function(d){const u=Zm(d,["use","svg:use"]),g=["x","y","xlink:href","href","transform"];for(const f of u){const p=f.attributes,m={};for(const P of p)P.value&&(m[P.name]=P.value);const _=(m["xlink:href"]||m.href||"").slice(1);if(_==="")return;const y=d.getElementById(_);if(y===null)return;let x=y.cloneNode(!0);const S=x.attributes,C={};for(const P of S)P.value&&(C[P.name]=P.value);const{x:E=0,y:M=0,transform:k=""}=m,O="".concat(k," ").concat(C.transform||""," translate(").concat(E,", ").concat(M,")");if(lg(x),/^svg$/i.test(x.nodeName)){const P=x.ownerDocument.createElementNS(Ru,"g");Object.entries(C).forEach(F=>{let[R,W]=F;return P.setAttributeNS(Ru,R,W)}),P.append(...x.childNodes),x=P}for(const P of p){if(!P)continue;const{name:F,value:R}=P;if(!g.includes(F))if(F==="style"){const W={};$u(R,W),Object.entries(C).forEach(X=>{let[K,tt]=X;W[K]=tt}),$u(C.style||"",W);const B=Object.entries(W).map(X=>X.join(":")).join(";");x.setAttribute(F,B)}else!C[F]&&x.setAttribute(F,R)}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=T(T({},lg(i)),{},{crossOrigin:e,signal:s}),o=n.filter(d=>(lg(d),s0(d)&&!function(u){let g=u;for(;g&&(g=g.parentElement);)if(g&&g.nodeName&&G_.test(Nc(g))&&!g.getAttribute("instantiated_by_use"))return!0;return!1}(d)));if(!o||o&&!o.length)return T(T({},dg()),{},{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=>s0(g))}),{objects:await new $_(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function Q_(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{Rm(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>K_(s,t,e)).catch(()=>dg())}const Bc=a=>a.webgl!==void 0,ug="precision highp float",J_=`
63
63
  `.concat(ug,`;
64
64
  varying vec2 vTexCoord;
65
65
  uniform sampler2D uTexture;
66
66
  void main() {
67
67
  gl_FragColor = texture2D(uTexture, vTexCoord);
68
- }`),tw=["type"],ew=["type"],sw=new RegExp(ug,"g");class Xt{get type(){return this.constructor.type}constructor(){let t=wt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},tw);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Z_}getVertexSource(){return`
68
+ }`),Z_=["type"],tw=["type"],ew=new RegExp(ug,"g");class Xt{get type(){return this.constructor.type}constructor(){let t=wt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Z_);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return J_}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"}}=Vs();i!=="highp"&&(e=e.replace(sw,ug.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 Xs("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Xs("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 Xs("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 Xs('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{sourceWidth:e,sourceHeight:s}=t,i=_s({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return T({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(wt(t,ew))}}A(Xt,"type","BaseFilter"),A(Xt,"uniformLocations",[]);const iw={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"}}=Vs();i!=="highp"&&(e=e.replace(ew,ug.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 Xs("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Xs("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 Xs("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 Xs('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{sourceWidth:e,sourceHeight:s}=t,i=_s({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return T({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(wt(t,tw))}}A(Xt,"type","BaseFilter"),A(Xt,"uniformLocations",[]);const sw={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);
@@ -107,10 +107,10 @@ Resulting to default behavior: removing object from previous canvas and adding t
107
107
  vec4 color = texture2D(uTexture, vTexCoord);
108
108
  gl_FragColor = color;
109
109
  if (color.a > 0.0) {
110
- `.concat(iw[this.mode],`
110
+ `.concat(sw[this.mode],`
111
111
  }
112
112
  }
113
- `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new ut(this.color).getSource(),i=s[0]*this.alpha,n=s[1]*this.alpha,r=s[2]*this.alpha,o=1-this.alpha;for(let h=0;h<e.length;h+=4){const l=e[h],d=e[h+1],u=e[h+2];switch(this.mode){case"multiply":e[h]=l*i/255,e[h+1]=d*n/255,e[h+2]=u*r/255;break;case"screen":e[h]=255-(255-l)*(255-i)/255,e[h+1]=255-(255-d)*(255-n)/255,e[h+2]=255-(255-u)*(255-r)/255;break;case"add":e[h]=l+i,e[h+1]=d+n,e[h+2]=u+r;break;case"difference":e[h]=Math.abs(l-i),e[h+1]=Math.abs(d-n),e[h+2]=Math.abs(u-r);break;case"subtract":e[h]=l-i,e[h+1]=d-n,e[h+2]=u-r;break;case"darken":e[h]=Math.min(l,i),e[h+1]=Math.min(d,n),e[h+2]=Math.min(u,r);break;case"lighten":e[h]=Math.max(l,i),e[h+1]=Math.max(d,n),e[h+2]=Math.max(u,r);break;case"overlay":e[h]=i<128?2*l*i/255:255-2*(255-l)*(255-i)/255,e[h+1]=n<128?2*d*n/255:255-2*(255-d)*(255-n)/255,e[h+2]=r<128?2*u*r/255:255-2*(255-u)*(255-r)/255;break;case"exclusion":e[h]=i+l-2*i*l/255,e[h+1]=n+d-2*n*d/255,e[h+2]=r+u-2*r*u/255;break;case"tint":e[h]=i+l*o,e[h+1]=n+d*o,e[h+2]=r+u*o}}}sendUniformData(t,e){const s=new ut(this.color).getSource();s[0]=this.alpha*s[0]/255,s[1]=this.alpha*s[1]/255,s[2]=this.alpha*s[2]/255,s[3]=this.alpha,t.uniform4fv(e.uColor,s)}}A(Hc,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),A(Hc,"type","BlendColor"),A(Hc,"uniformLocations",["uColor"]),N.setClass(Hc);const nw={multiply:`
113
+ `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new ut(this.color).getSource(),i=s[0]*this.alpha,n=s[1]*this.alpha,r=s[2]*this.alpha,o=1-this.alpha;for(let h=0;h<e.length;h+=4){const l=e[h],d=e[h+1],u=e[h+2];switch(this.mode){case"multiply":e[h]=l*i/255,e[h+1]=d*n/255,e[h+2]=u*r/255;break;case"screen":e[h]=255-(255-l)*(255-i)/255,e[h+1]=255-(255-d)*(255-n)/255,e[h+2]=255-(255-u)*(255-r)/255;break;case"add":e[h]=l+i,e[h+1]=d+n,e[h+2]=u+r;break;case"difference":e[h]=Math.abs(l-i),e[h+1]=Math.abs(d-n),e[h+2]=Math.abs(u-r);break;case"subtract":e[h]=l-i,e[h+1]=d-n,e[h+2]=u-r;break;case"darken":e[h]=Math.min(l,i),e[h+1]=Math.min(d,n),e[h+2]=Math.min(u,r);break;case"lighten":e[h]=Math.max(l,i),e[h+1]=Math.max(d,n),e[h+2]=Math.max(u,r);break;case"overlay":e[h]=i<128?2*l*i/255:255-2*(255-l)*(255-i)/255,e[h+1]=n<128?2*d*n/255:255-2*(255-d)*(255-n)/255,e[h+2]=r<128?2*u*r/255:255-2*(255-u)*(255-r)/255;break;case"exclusion":e[h]=i+l-2*i*l/255,e[h+1]=n+d-2*n*d/255,e[h+2]=r+u-2*r*u/255;break;case"tint":e[h]=i+l*o,e[h+1]=n+d*o,e[h+2]=r+u*o}}}sendUniformData(t,e){const s=new ut(this.color).getSource();s[0]=this.alpha*s[0]/255,s[1]=this.alpha*s[1]/255,s[2]=this.alpha*s[2]/255,s[3]=this.alpha,t.uniform4fv(e.uColor,s)}}A(Hc,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),A(Hc,"type","BlendColor"),A(Hc,"uniformLocations",["uColor"]),N.setClass(Hc);const iw={multiply:`
114
114
  precision highp float;
115
115
  uniform sampler2D uTexture;
116
116
  uniform sampler2D uImage;
@@ -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
- `},rw=["type","image"];class Wc extends Xt{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return nw[this.mode]}getVertexSource(){return`
139
+ `},nw=["type","image"];class Wc extends Xt{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return iw[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=ns());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],y=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*y/255,e[d+3]=p*x/255;break;case"mask":e[d+3]=x}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return T(T({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=wt(t,rw);return ge.fromObject(i,e).then(r=>new this(T(T({},n),{},{image:r})))}}A(Wc,"type","BlendImage"),A(Wc,"defaults",{mode:"multiply",alpha:1}),A(Wc,"uniformLocations",["uTransformMatrix","uImage"]),N.setClass(Wc);class zc extends Xt{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=ns());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],y=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*y/255,e[d+3]=p*x/255;break;case"mask":e[d+3]=x}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return T(T({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=wt(t,nw);return ge.fromObject(i,e).then(r=>new this(T(T({},n),{},{image:r})))}}A(Wc,"type","BlendImage"),A(Wc,"defaults",{mode:"multiply",alpha:1}),A(Wc,"uniformLocations",["uTransformMatrix","uImage"]),N.setClass(Wc);class zc extends Xt{getFragmentSource(){return`
150
150
  precision highp float;
151
151
  uniform sampler2D uTexture;
152
152
  uniform vec2 uDelta;
@@ -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 T(T({},super.toObject()),{},{matrix:[...this.matrix]})}}function hr(a,t){var e;const s=(A(e=class extends jo{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),A(e,"defaults",{colorsOnly:!1,matrix:t}),e);return N.setClass(s,a),s}A(jo,"type","ColorMatrix"),A(jo,"defaults",{matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0}),A(jo,"uniformLocations",["uColorMatrix","uConstants"]),N.setClass(jo),hr("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),hr("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),hr("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),hr("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),hr("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),hr("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),hr("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 n0 extends Xt{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=>N.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}A(n0,"type","Composed"),N.setClass(n0);class Vc extends Xt{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 T(T({},super.toObject()),{},{matrix:[...this.matrix]})}}function hr(a,t){var e;const s=(A(e=class extends jo{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),A(e,"defaults",{colorsOnly:!1,matrix:t}),e);return N.setClass(s,a),s}A(jo,"type","ColorMatrix"),A(jo,"defaults",{matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0}),A(jo,"uniformLocations",["uColorMatrix","uConstants"]),N.setClass(jo),hr("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),hr("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),hr("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),hr("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),hr("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),hr("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),hr("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 i0 extends Xt{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=>N.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}A(i0,"type","Composed"),N.setClass(i0);class Vc extends Xt{getFragmentSource(){return`
194
194
  precision highp float;
195
195
  uniform sampler2D uTexture;
196
196
  uniform float uContrast;
@@ -200,7 +200,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
200
200
  float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
201
201
  color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
202
202
  gl_FragColor = color;
203
- }`}isNeutralState(){return this.contrast===0}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.floor(255*this.contrast),i=259*(s+255)/(255*(259-s));for(let n=0;n<e.length;n+=4)e[n]=i*(e[n]-128)+128,e[n+1]=i*(e[n+1]-128)+128,e[n+2]=i*(e[n+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}A(Vc,"type","Contrast"),A(Vc,"defaults",{contrast:0}),A(Vc,"uniformLocations",["uContrast"]),N.setClass(Vc);const ow={Convolute_3_1:`
203
+ }`}isNeutralState(){return this.contrast===0}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.floor(255*this.contrast),i=259*(s+255)/(255*(259-s));for(let n=0;n<e.length;n+=4)e[n]=i*(e[n]-128)+128,e[n+1]=i*(e[n+1]-128)+128,e[n+2]=i*(e[n+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}A(Vc,"type","Contrast"),A(Vc,"defaults",{contrast:0}),A(Vc,"uniformLocations",["uContrast"]),N.setClass(Vc);const rw={Convolute_3_1:`
204
204
  precision highp float;
205
205
  uniform sampler2D uTexture;
206
206
  uniform float uMatrix[9];
@@ -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 Xt{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return ow[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,_,y,x,S,C,E,M,k,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(k=0;k<n;k++)x=M+O-r,y=E+k-r,x<0||x>=h||y<0||y>=o||(S=4*(x*o+y),C=i[O*n+k],g+=s[S]*C,f+=s[S+1]*C,p+=s[S+2]*C,u||(m+=s[S+3]*C));d[_]=g,d[_+1]=f,d[_+2]=p,d[_+3]=u?s[_+3]:m}t.imageData=l}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return T(T({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}A(Gc,"type","Convolute"),A(Gc,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),A(Gc,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),N.setClass(Gc);const r0="Gamma";class Yc extends Xt{getFragmentSource(){return`
347
+ `};class Gc extends Xt{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return rw[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,_,y,x,S,C,E,M,k,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(k=0;k<n;k++)x=M+O-r,y=E+k-r,x<0||x>=h||y<0||y>=o||(S=4*(x*o+y),C=i[O*n+k],g+=s[S]*C,f+=s[S+1]*C,p+=s[S+2]*C,u||(m+=s[S+3]*C));d[_]=g,d[_+1]=f,d[_+2]=p,d[_+3]=u?s[_+3]:m}t.imageData=l}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return T(T({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}A(Gc,"type","Convolute"),A(Gc,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),A(Gc,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),N.setClass(Gc);const n0="Gamma";class Yc extends Xt{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:r0,gamma:this.gamma.concat()}}}A(Yc,"type",r0),A(Yc,"defaults",{gamma:[1,1,1]}),A(Yc,"uniformLocations",["uGamma"]),N.setClass(Yc);const aw={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:n0,gamma:this.gamma.concat()}}}A(Yc,"type",n0),A(Yc,"defaults",{gamma:[1,1,1]}),A(Yc,"uniformLocations",["uGamma"]),N.setClass(Yc);const ow={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 Uc extends Xt{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 aw[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}A(Uc,"type","Grayscale"),A(Uc,"defaults",{mode:"average"}),A(Uc,"uniformLocations",["uMode"]),N.setClass(Uc);class gg extends jo{calculateMatrix(){const t=this.rotation*Math.PI,e=vs(t),s=ys(t),i=1/3,n=Math.sqrt(i)*s,r=1-e;this.matrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],this.matrix[0]=e+r/3,this.matrix[1]=i*r-n,this.matrix[2]=i*r+n,this.matrix[5]=i*r+n,this.matrix[6]=e+i*r,this.matrix[7]=i*r-n,this.matrix[10]=i*r-n,this.matrix[11]=i*r+n,this.matrix[12]=e+i*r}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}A(gg,"type","HueRotation"),A(gg,"defaults",{rotation:0}),N.setClass(gg);class qc extends Xt{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 Uc extends Xt{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 ow[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}A(Uc,"type","Grayscale"),A(Uc,"defaults",{mode:"average"}),A(Uc,"uniformLocations",["uMode"]),N.setClass(Uc);class gg extends jo{calculateMatrix(){const t=this.rotation*Math.PI,e=vs(t),s=ys(t),i=1/3,n=Math.sqrt(i)*s,r=1-e;this.matrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],this.matrix[0]=e+r/3,this.matrix[1]=i*r-n,this.matrix[2]=i*r+n,this.matrix[5]=i*r+n,this.matrix[6]=e+i*r,this.matrix[7]=i*r-n,this.matrix[10]=i*r-n,this.matrix[11]=i*r+n,this.matrix[12]=e+i*r}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}A(gg,"type","HueRotation"),A(gg,"defaults",{rotation:0}),N.setClass(gg);class qc extends Xt{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;
@@ -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}}A(td,"type","Vibrance"),A(td,"defaults",{vibrance:0}),A(td,"uniformLocations",["uVibrance"]),N.setClass(td);const hw="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 lw(a){return new URL(Object.assign({"../assets/close.svg":hw})[`../assets/${a}`],typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Ct&&Ct.tagName.toUpperCase()==="SCRIPT"&&Ct.src||new URL("pdf-canvas.umd.js",document.baseURI).href).href}function cw(a){return new Promise((t,e)=>{const s=window.URL.createObjectURL(a),i=new Image;i.src=s,i.addEventListener("load",async()=>{window.URL.revokeObjectURL(s),t(await dw(i))}),i.addEventListener("error",n=>{window.URL.revokeObjectURL(s),e(n)})})}function dw(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 o0=null;function uw(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function gw(){const a=o0??uw();return o0=a,a/72}function fw(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 as=new Map;function pw(a){const t=new eg(a);return as.set(a,t),t}function mw(a,t){const e=Date.now();return{PDFId:`${a.name}-${e}`,name:a.name.replace(/.pdf/,""),updateDate:e,PDFBase64:t}}function bw(a,t){const e=a.getViewport({scale:t}),s=document.createElement("canvas"),i=s.getContext("2d"),n=gw()/window.devicePixelRatio;s.width=Math.floor(e.width*n),s.height=Math.floor(e.height*n);const r={canvasContext:i,viewport:e,transform:[n,0,0,n,0,0]},o=a.render(r);return{canvas:s,renderTask:o}}async function vw(a,t,e){const s=a||lw("close.svg"),{objects:i,options:n}=await J_(s),r=i.filter(h=>h!==null),o=u_.groupSVGElements(r,n);return r.forEach(h=>{h.stroke=t}),o.hoverCursor="pointer",o.stroke=`${t}-${e}`,o}function yw(a,t){if(!as.get(a))return;const s=1/3,i=Aw(t,s);h0(a,i,s)}async function _w(a,t){const e=await cw(t),s=Date.now(),n={PDFId:`${t.name}${s}`,name:t.name.replace(/.png|.jpg|.jpeg/,""),updateDate:s,PDFBase64:e};return a0(a,{url:e}),{...n,pages:1}}async function a0(a,{url:t,scale:e=.5}){if(!as.get(a))return;const i=await ge.fromURL(t);i.scale(e),h0(a,i,e)}function h0(a,t,e){const s=as.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function ch(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function ww(a,t,e){!e||!a||(e.scale(1/t),ch(a,e))}function xw(a,t,e){a&&(a.borderScaleFactor=1/t,a.cornerSize=6*(1/t),a.touchCornerSize=24*(1/t),a.cornerStrokeColor=e.stroke,a.setCoords())}function Sw(a){const t=as.get(a);t&&(t.discardActiveObject(),t.renderAll())}function Cw(a){const t=as.get(a);t&&(t.clear(),as.delete(a))}function Aw(a,t){return new ge(a,{scaleX:t,scaleY:t})}var dh={};dh.d=(a,t)=>{for(var e in t)dh.o(t,e)&&!dh.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},dh.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var $=globalThis.pdfjsLib={};dh.d($,{AbortException:()=>cr,AnnotationEditorLayer:()=>Qg,AnnotationEditorParamsType:()=>U,AnnotationEditorType:()=>Z,AnnotationEditorUIManager:()=>ur,AnnotationLayer:()=>SS,AnnotationMode:()=>pn,ColorPicker:()=>vd,DOMSVGFactory:()=>Vg,DrawLayer:()=>Jg,FeatureTest:()=>Ee,GlobalWorkerOptions:()=>Mi,ImageKind:()=>ed,InvalidPDFException:()=>c0,MissingPDFException:()=>lr,OPS:()=>Es,OutputScale:()=>Tg,PDFDataRangeTransport:()=>X0,PDFDateString:()=>Cg,PDFWorker:()=>Ho,PasswordResponses:()=>Mw,PermissionFlag:()=>kw,PixelsPerInch:()=>bn,RenderingCancelledException:()=>xg,TextLayer:()=>yh,UnexpectedResponseException:()=>rd,Util:()=>z,VerbosityLevel:()=>sd,XfaLayer:()=>U0,build:()=>iS,createValidAbsoluteUrl:()=>Fw,fetchData:()=>ad,getDocument:()=>qx,getFilenameFromUrl:()=>zw,getPdfFilenameFromUrl:()=>Xw,getXfaPageViewport:()=>Vw,isDataScheme:()=>hd,isPdfFile:()=>Sg,noContextMenu:()=>hs,normalizeUnicode:()=>Bw,setLayerDimensions:()=>dr,shadow:()=>ot,version:()=>sS});const fe=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),l0=[1,0,0,1,0,0],fg=[.001,0,0,.001,0,0],Tw=1e7,pg=1.35,Ye={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},pn={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Ew="pdfjs_internal_editor_",Z={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},U={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},kw={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},pe={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},ed={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Vt={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},uh={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},sd={ERRORS:0,WARNINGS:1,INFOS:5},Es={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},Mw={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let id=sd.WARNINGS;function Ow(a){Number.isInteger(a)&&(id=a)}function Dw(){return id}function nd(a){id>=sd.INFOS&&console.log(`Info: ${a}`)}function st(a){id>=sd.WARNINGS&&console.log(`Warning: ${a}`)}function yt(a){throw new Error(a)}function Gt(a,t){a||yt(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 Fw(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=Nw(a)}catch{}}const s=t?new URL(a,t):new URL(a);if(Pw(s))return s}catch{}return null}function ot(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const mn=function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class mg extends mn{constructor(t,e){super(t,"PasswordException"),this.code=e}}class bg extends mn{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class c0 extends mn{constructor(t){super(t,"InvalidPDFException")}}class lr extends mn{constructor(t){super(t,"MissingPDFException")}}class rd extends mn{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Rw extends mn{constructor(t){super(t,"FormatError")}}class cr extends mn{constructor(t){super(t,"AbortException")}}function d0(a){(typeof a!="object"||(a==null?void 0:a.length)===void 0)&&yt("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"&&yt("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 Lw(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function vg(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function Iw(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function jw(){try{return new Function(""),!0}catch{return!1}}class Ee{static get isLittleEndian(){return ot(this,"isLittleEndian",Iw())}static get isEvalSupported(){return ot(this,"isEvalSupported",jw())}static get isOffscreenCanvasSupported(){return ot(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?ot(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):ot(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,e;return ot(this,"isCSSRoundSupported",(e=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:e.call(t,"width: round(1.5px, 1px)"))}}const yg=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class z{static makeHexColor(t,e,s){return`#${yg[t]}${yg[e]}${yg[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)],v(this,Di,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),v(this,Di,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}}Di=new WeakSet,Bd=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&&v(this,Di,Bd).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;v(this,Di,Bd).call(this,t,e,s,i,n,r,o,h,(-d+p)/m,g),v(this,Di,Bd).call(this,t,e,s,i,n,r,o,h,(-d-p)/m,g)},w(z,Di);function Nw(a){return decodeURIComponent(escape(a))}let _g=null,u0=null;function Bw(a){return _g||(_g=/([\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(_g,(t,e,s)=>e?e.normalize("NFKC"):u0.get(s))}function Hw(){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 wg="pdfjs_internal_id_",Ti={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};function Ww(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(d0(a))}const Ei="http://www.w3.org/2000/svg",pr=class pr{};q(pr,"CSS",96),q(pr,"PDF",72),q(pr,"PDF_TO_CSS_UNITS",pr.CSS/pr.PDF);let bn=pr;async function ad(a,t="text"){if(fh(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 gh{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 ot(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 gh({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 xg extends mn{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function hd(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function Sg(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function zw(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function Xw(a,t="document.pdf"){if(typeof a!="string")return t;if(hd(a))return st('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(a);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class g0{constructor(){q(this,"started",Object.create(null));q(this,"times",[])}time(t){t in this.started&&st(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||st(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
499
- `);return t.join("")}}function fh(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function hs(a){a.preventDefault()}function f0(a){console.log("Deprecated API usage: "+a)}class Cg{static toDateObject(t){if(!t||typeof t!="string")return null;c(this,Sh)||b(this,Sh,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const e=c(this,Sh).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))}}Sh=new WeakMap,w(Cg,Sh);function Vw(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new gh({viewBox:n,scale:t,rotation:e})}function Ag(a){if(a.startsWith("#")){const t=parseInt(a.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return a.startsWith("rgb(")?a.slice(4,-1).split(",").map(t=>parseInt(t)):a.startsWith("rgba(")?a.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(st(`Not a valid color format: "${a}"`),[0,0,0])}function Gw(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,Ag(s))}t.remove()}function Tt(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function ki(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 dr(a,t,e=!1,s=!0){if(t instanceof gh){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Ee.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,d=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=d,r.height=u):(r.width=u,r.height=d)}s&&a.setAttribute("data-main-rotation",t.rotation)}class Tg{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}const Pi=class Pi{constructor(t){w(this,Me);w(this,yn,null);w(this,mr,null);w(this,ks);w(this,br,null);w(this,Ch,null);b(this,ks,t),c(Pi,Ah)||b(Pi,Ah,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=b(this,yn,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=c(this,ks)._uiManager._signal;t.addEventListener("contextmenu",hs,{signal:e}),t.addEventListener("pointerdown",v(Pi,wd,ob),{signal:e});const s=b(this,br,document.createElement("div"));s.className="buttons",t.append(s);const i=c(this,ks).toolbarPosition;if(i){const{style:n}=t,r=c(this,ks)._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return v(this,Me,lb).call(this),t}get div(){return c(this,yn)}hide(){var t;c(this,yn).classList.add("hidden"),(t=c(this,mr))==null||t.hideDropdown()}show(){var t;c(this,yn).classList.remove("hidden"),(t=c(this,Ch))==null||t.shown()}async addAltText(t){const e=await t.render();v(this,Me,Hd).call(this,e),c(this,br).prepend(e,c(this,Me,of)),b(this,Ch,t)}addColorPicker(t){b(this,mr,t);const e=t.renderButton();v(this,Me,Hd).call(this,e),c(this,br).prepend(e,c(this,Me,of))}remove(){var t;c(this,yn).remove(),(t=c(this,mr))==null||t.destroy(),b(this,mr,null)}};yn=new WeakMap,mr=new WeakMap,ks=new WeakMap,br=new WeakMap,Ch=new WeakMap,Ah=new WeakMap,wd=new WeakSet,ob=function(t){t.stopPropagation()},Me=new WeakSet,ab=function(t){c(this,ks)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},hb=function(t){c(this,ks)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},Hd=function(t){const e=c(this,ks)._uiManager._signal;t.addEventListener("focusin",v(this,Me,ab).bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",v(this,Me,hb).bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",hs,{signal:e})},lb=function(){const{editorType:t,_uiManager:e}=c(this,ks),s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",c(Pi,Ah)[t]),v(this,Me,Hd).call(this,s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),c(this,br).append(s)},of=function(){const t=document.createElement("div");return t.className="divider",t},w(Pi,wd),w(Pi,Ah,null);let Eg=Pi;class Yw{constructor(t){w(this,_n);w(this,Th,null);w(this,vr,null);w(this,yr);b(this,yr,t)}show(t,e,s){const[i,n]=v(this,_n,db).call(this,e,s),{style:r}=c(this,vr)||b(this,vr,v(this,_n,cb).call(this));t.append(c(this,vr)),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){c(this,vr).remove()}}Th=new WeakMap,vr=new WeakMap,yr=new WeakMap,_n=new WeakSet,cb=function(){const t=b(this,vr,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",hs,{signal:c(this,yr)._signal});const e=b(this,Th,document.createElement("div"));return e.className="buttons",t.append(e),v(this,_n,ub).call(this),t},db=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]},ub=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,yr)._signal;t.addEventListener("contextmenu",hs,{signal:s}),t.addEventListener("click",()=>{c(this,yr).highlightSelection("floating_button")},{signal:s}),c(this,Th).append(t)};function ld(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}function Uw(a){return Math.round(Math.min(255,Math.max(1,255*a))).toString(16).padStart(2,"0")}class qw{constructor(){w(this,xd,0)}get id(){return`${Ew}${Fe(this,xd)._++}`}}xd=new WeakMap;const tf=class tf{constructor(){w(this,zo);w(this,Wo,Hw());w(this,Eh,0);w(this,me,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 ot(this,"_isSVGFittingCanvas",n)}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return v(this,zo,Wd).call(this,`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return v(this,zo,Wd).call(this,t,t)}async getFromBlob(t,e){const s=await e;return v(this,zo,Wd).call(this,t,s)}async getFromId(t){c(this,me)||b(this,me,new Map);const e=c(this,me).get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){c(this,me)||b(this,me,new Map);let s=c(this,me).get(t);if(s!=null&&s.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${c(this,Wo)}_${Fe(this,Eh)._++}`,refCounter:1,isSvg:!1},c(this,me).set(t,s),c(this,me).set(s.id,s),s}getSvgUrl(t){const e=c(this,me).get(t);return e!=null&&e.isSvg?e.svgUrl:null}deleteId(t){var i;c(this,me)||b(this,me,new Map);const e=c(this,me).get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const n=new OffscreenCanvas(s.width,s.height);n.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=n.convertToBlob()}(i=s.close)==null||i.call(s),e.bitmap=null}isValidId(t){return t.startsWith(`image_${c(this,Wo)}_`)}};Wo=new WeakMap,Eh=new WeakMap,me=new WeakMap,zo=new WeakSet,Wd=async function(t,e){c(this,me)||b(this,me,new Map);let s=c(this,me).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,Wo)}_${Fe(this,Eh)._++}`,refCounter:0,isSvg:!1});let i;if(typeof e=="string"?(s.url=e,i=await ad(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=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,me).set(t,s),s&&c(this,me).set(s.id,s),s};let kg=tf;class $w{constructor(t=128){w(this,Zt,[]);w(this,wn,!1);w(this,kh);w(this,te,-1);b(this,kh,t)}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),c(this,wn))return;const h={cmd:t,undo:e,post:s,type:n};if(c(this,te)===-1){c(this,Zt).length>0&&(c(this,Zt).length=0),b(this,te,0),c(this,Zt).push(h);return}if(r&&c(this,Zt)[c(this,te)].type===n){o&&(h.undo=c(this,Zt)[c(this,te)].undo),c(this,Zt)[c(this,te)]=h;return}const l=c(this,te)+1;l===c(this,kh)?c(this,Zt).splice(0,1):(b(this,te,l),l<c(this,Zt).length&&c(this,Zt).splice(l)),c(this,Zt).push(h)}undo(){if(c(this,te)===-1)return;b(this,wn,!0);const{undo:t,post:e}=c(this,Zt)[c(this,te)];t(),e==null||e(),b(this,wn,!1),b(this,te,c(this,te)-1)}redo(){if(c(this,te)<c(this,Zt).length-1){b(this,te,c(this,te)+1),b(this,wn,!0);const{cmd:t,post:e}=c(this,Zt)[c(this,te)];t(),e==null||e(),b(this,wn,!1)}}hasSomethingToUndo(){return c(this,te)!==-1}hasSomethingToRedo(){return c(this,te)<c(this,Zt).length-1}destroy(){b(this,Zt,null)}}Zt=new WeakMap,wn=new WeakMap,kh=new WeakMap,te=new WeakMap;class ph{constructor(t){w(this,Sd);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Ee.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(v(this,Sd,gb).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()))}}Sd=new WeakSet,gb=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 Cd=class Cd{get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Gw(t),ot(this,"_colors",t)}convert(t){const e=Ag(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 Cd._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}};q(Cd,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Mg=Cd;const $o=class $o{constructor(t,e,s,i,n,r,o,h,l,d,u){w(this,I);w(this,Xo,new AbortController);w(this,qe,null);w(this,Yt,new Map);w(this,ne,new Map);w(this,Vo,null);w(this,Fi,null);w(this,Go,null);w(this,Ms,new $w);w(this,xn,null);w(this,Yo,0);w(this,_r,new Set);w(this,Ks,null);w(this,Os,null);w(this,wr,new Set);w(this,Mh,!1);w(this,Oh,!1);w(this,Uo,!1);w(this,Dh,null);w(this,Qs,null);w(this,Sn,null);w(this,qo,null);w(this,Cn,!1);w(this,Js,null);w(this,Ad,new qw);w(this,An,!1);w(this,Ph,!1);w(this,Tn,null);w(this,xr,null);w(this,Fh,null);w(this,Rh,null);w(this,ee,Z.NONE);w(this,ft,new Set);w(this,Ri,null);w(this,Sr,null);w(this,Lh,null);w(this,Ih,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});w(this,En,[0,0]);w(this,Zs,null);w(this,Li,null);w(this,jh,null);w(this,cs,null);const g=this._signal=c(this,Xo).signal;b(this,Li,t),b(this,jh,e),b(this,Vo,s),this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",f=>this.updateParams(f.type,f.value),{signal:g}),v(this,I,mb).call(this),v(this,I,_b).call(this),v(this,I,hf).call(this),b(this,Fi,n.annotationStorage),b(this,Dh,n.filterFactory),b(this,Sr,r),b(this,qo,o||null),b(this,Mh,h),b(this,Oh,l),b(this,Uo,d),b(this,Rh,u||null),this.viewParameters={realScale:bn.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=$o.prototype,e=r=>c(r,Li).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 ot(this,"_keyboardManager",new ph([[["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,Li).contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&c(r,Li).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}destroy(){var t,e,s,i;(t=c(this,cs))==null||t.resolve(),b(this,cs,null),(e=c(this,Xo))==null||e.abort(),b(this,Xo,null),this._signal=null;for(const n of c(this,ne).values())n.destroy();c(this,ne).clear(),c(this,Yt).clear(),c(this,wr).clear(),b(this,qe,null),c(this,ft).clear(),c(this,Ms).destroy(),(s=c(this,Vo))==null||s.destroy(),(i=c(this,Js))==null||i.hide(),b(this,Js,null),c(this,Qs)&&(clearTimeout(c(this,Qs)),b(this,Qs,null)),c(this,Zs)&&(clearTimeout(c(this,Zs)),b(this,Zs,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return c(this,Rh)}get useNewAltTextFlow(){return c(this,Oh)}get useNewAltTextWhenAddingImage(){return c(this,Uo)}get hcmFilter(){return ot(this,"hcmFilter",c(this,Sr)?c(this,Dh).addHCMFilter(c(this,Sr).foreground,c(this,Sr).background):"none")}get direction(){return ot(this,"direction",getComputedStyle(c(this,Li)).direction)}get highlightColors(){return ot(this,"highlightColors",c(this,qo)?new Map(c(this,qo).split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return ot(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){b(this,Fh,t)}editAltText(t,e=!1){var s;(s=c(this,Vo))==null||s.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":b(this,Uo,e);break}}onPageChanging({pageNumber:t}){b(this,Yo,t-1)}focusMainContainer(){c(this,Li).focus()}findParent(t,e){for(const s of c(this,ne).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,jh).classList.toggle("noUserSelect",t)}addShouldRescale(t){c(this,wr).add(t)}removeShouldRescale(t){c(this,wr).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*bn.PDF_TO_CSS_UNITS;for(const e of c(this,wr))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=v(this,I,zd).call(this,e).closest(".textLayer"),d=this.getSelectionBoxes(l);if(!d)return;e.empty();const u=v(this,I,af).call(this,l),g=c(this,ee)===Z.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(Z.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&c(this,Fi)&&!c(this,Fi).has(t.id)&&c(this,Fi).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,c(this,Cn)&&(b(this,Cn,!1),v(this,I,Xd).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of c(this,ft))if(e.div.contains(t)){b(this,xr,[e,t]),e._focusEventsAllowed=!1;break}}focus(){if(!c(this,xr))return;const[t,e]=c(this,xr);b(this,xr,null),e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}addEditListeners(){v(this,I,hf).call(this),v(this,I,lf).call(this)}removeEditListeners(){v(this,I,yb).call(this),v(this,I,cf).call(this)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of c(this,Os))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,Os))if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){var s;if(t.preventDefault(),(s=c(this,qe))==null||s.commitOrRemove(),!this.hasSelection)return;const e=[];for(const i of c(this,ft)){const n=i.serialize(!0);n&&e.push(n)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of c(this,Os))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){st(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)v(this,I,df).call(this,h);v(this,I,uf).call(this,n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){st(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),c(this,ee)!==Z.NONE&&!this.isEditorHandlingKeyboard&&$o._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,c(this,Cn)&&(b(this,Cn,!1),v(this,I,Xd).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?(v(this,I,bb).call(this),v(this,I,lf).call(this),v(this,I,Re).call(this,{isEditing:c(this,ee)!==Z.NONE,isEmpty:v(this,I,Bl).call(this),hasSomethingToUndo:c(this,Ms).hasSomethingToUndo(),hasSomethingToRedo:c(this,Ms).hasSomethingToRedo(),hasSelectedEditor:!1})):(v(this,I,vb).call(this),v(this,I,cf).call(this),v(this,I,Re).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!c(this,Os)){b(this,Os,t);for(const e of c(this,Os))v(this,I,qn).call(this,e.defaultPropertiesToUpdate)}}getId(){return c(this,Ad).id}get currentLayer(){return c(this,ne).get(c(this,Yo))}getLayer(t){return c(this,ne).get(t)}get currentPageIndex(){return c(this,Yo)}addLayer(t){c(this,ne).set(t.pageIndex,t),c(this,An)?t.enable():t.disable()}removeLayer(t){c(this,ne).delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(c(this,ee)!==t&&!(c(this,cs)&&(await c(this,cs).promise,!c(this,cs)))){if(b(this,cs,Promise.withResolvers()),b(this,ee,t),t===Z.NONE){this.setEditingState(!1),v(this,I,xb).call(this),c(this,cs).resolve();return}this.setEditingState(!0),await v(this,I,wb).call(this),this.unselectAll();for(const i of c(this,ne).values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),c(this,cs).resolve();return}for(const i of c(this,Yt).values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();c(this,cs).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==c(this,ee)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){var s;if(c(this,Os)){switch(t){case U.CREATE:this.currentLayer.addNewEditor();return;case U.HIGHLIGHT_DEFAULT_COLOR:(s=c(this,Fh))==null||s.updateColor(e);break;case U.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(c(this,Lh)||b(this,Lh,new Map)).set(t,e),this.showAllEditors("highlight",e);break}for(const i of c(this,ft))i.updateParams(t,e);for(const i of c(this,Os))i.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){var n;for(const r of c(this,Yt).values())r.editorType===t&&r.show(e);(((n=c(this,Lh))==null?void 0:n.get(U.HIGHLIGHT_SHOW_ALL))??!0)!==e&&v(this,I,qn).call(this,[[U.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(c(this,Ph)!==t){b(this,Ph,t);for(const e of c(this,ne).values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}getEditors(t){const e=[];for(const s of c(this,Yt).values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return c(this,Yt).get(t)}addEditor(t){c(this,Yt).set(t.id,t)}removeEditor(t){var e;t.div.contains(document.activeElement)&&(c(this,Qs)&&clearTimeout(c(this,Qs)),b(this,Qs,setTimeout(()=>{this.focusMainContainer(),b(this,Qs,null)},0))),c(this,Yt).delete(t.id),this.unselect(t),(!t.annotationElementId||!c(this,_r).has(t.annotationElementId))&&((e=c(this,Fi))==null||e.remove(t.id))}addDeletedAnnotationElement(t){c(this,_r).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return c(this,_r).has(t)}removeDeletedAnnotationElement(t){c(this,_r).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){c(this,qe)!==t&&(b(this,qe,t),t&&v(this,I,qn).call(this,t.propertiesToUpdate))}updateUI(t){c(this,I,Sb)===t&&v(this,I,qn).call(this,t.propertiesToUpdate)}toggleSelected(t){if(c(this,ft).has(t)){c(this,ft).delete(t),t.unselect(),v(this,I,Re).call(this,{hasSelectedEditor:this.hasSelection});return}c(this,ft).add(t),t.select(),v(this,I,qn).call(this,t.propertiesToUpdate),v(this,I,Re).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const e of c(this,ft))e!==t&&e.unselect();c(this,ft).clear(),c(this,ft).add(t),t.select(),v(this,I,qn).call(this,t.propertiesToUpdate),v(this,I,Re).call(this,{hasSelectedEditor:!0})}isSelected(t){return c(this,ft).has(t)}get firstSelectedEditor(){return c(this,ft).values().next().value}unselect(t){t.unselect(),c(this,ft).delete(t),v(this,I,Re).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return c(this,ft).size!==0}get isEnterHandled(){return c(this,ft).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){c(this,Ms).undo(),v(this,I,Re).call(this,{hasSomethingToUndo:c(this,Ms).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:v(this,I,Bl).call(this)})}redo(){c(this,Ms).redo(),v(this,I,Re).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:c(this,Ms).hasSomethingToRedo(),isEmpty:v(this,I,Bl).call(this)})}addCommands(t){c(this,Ms).add(t),v(this,I,Re).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:v(this,I,Bl).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...c(this,ft)],e=()=>{for(const i of t)i.remove()},s=()=>{for(const i of t)v(this,I,df).call(this,i)};this.addCommands({cmd:e,undo:s,mustExec:!0})}commitOrRemove(){var t;(t=c(this,qe))==null||t.commitOrRemove()}hasSomethingToControl(){return c(this,qe)||this.hasSelection}selectAll(){for(const t of c(this,ft))t.commit();v(this,I,uf).call(this,c(this,Yt).values())}unselectAll(){if(!(c(this,qe)&&(c(this,qe).commitOrRemove(),c(this,ee)!==Z.NONE))&&this.hasSelection){for(const t of c(this,ft))t.unselect();c(this,ft).clear(),v(this,I,Re).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;c(this,En)[0]+=t,c(this,En)[1]+=e;const[i,n]=c(this,En),r=[...c(this,ft)],o=1e3;c(this,Zs)&&clearTimeout(c(this,Zs)),b(this,Zs,setTimeout(()=>{b(this,Zs,null),c(this,En)[0]=c(this,En)[1]=0,this.addCommands({cmd:()=>{for(const h of r)c(this,Yt).has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)c(this,Yt).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,Ks,new Map);for(const t of c(this,ft))c(this,Ks).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!c(this,Ks))return!1;this.disableUserSelect(!1);const t=c(this,Ks);b(this,Ks,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,Yt).has(i.id)){const h=c(this,ne).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,Ks))for(const s of c(this,Ks).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,ft).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return c(this,qe)===t}getActive(){return c(this,qe)}getMode(){return c(this,ee)}get imageManager(){return ot(this,"imageManager",new kg)}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,Go)||b(this,Go,new Map)).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){var e;(e=c(this,Go))==null||e.delete(t)}renderAnnotationElement(t){var i;const e=(i=c(this,Go))==null?void 0:i.get(t.data.id);if(!e)return;const s=c(this,Fi).getRawValue(e);s&&(c(this,ee)===Z.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}};Xo=new WeakMap,qe=new WeakMap,Yt=new WeakMap,ne=new WeakMap,Vo=new WeakMap,Fi=new WeakMap,Go=new WeakMap,Ms=new WeakMap,xn=new WeakMap,Yo=new WeakMap,_r=new WeakMap,Ks=new WeakMap,Os=new WeakMap,wr=new WeakMap,Mh=new WeakMap,Oh=new WeakMap,Uo=new WeakMap,Dh=new WeakMap,Qs=new WeakMap,Sn=new WeakMap,qo=new WeakMap,Cn=new WeakMap,Js=new WeakMap,Ad=new WeakMap,An=new WeakMap,Ph=new WeakMap,Tn=new WeakMap,xr=new WeakMap,Fh=new WeakMap,Rh=new WeakMap,ee=new WeakMap,ft=new WeakMap,Ri=new WeakMap,Sr=new WeakMap,Lh=new WeakMap,Ih=new WeakMap,En=new WeakMap,Zs=new WeakMap,Li=new WeakMap,jh=new WeakMap,cs=new WeakMap,I=new WeakSet,zd=function({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t},af=function(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of c(this,ne).values())if(s.hasTextLayer(t))return s;return null},fb=function(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=v(this,I,zd).call(this,t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(c(this,Js)||b(this,Js,new Yw(this)),c(this,Js).show(s,i,this.direction==="ltr"))},pb=function(){var n,r,o;const t=document.getSelection();if(!t||t.isCollapsed){c(this,Ri)&&((n=c(this,Js))==null||n.hide(),b(this,Ri,null),v(this,I,Re).call(this,{hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===c(this,Ri))return;const i=v(this,I,zd).call(this,t).closest(".textLayer");if(!i){c(this,Ri)&&((r=c(this,Js))==null||r.hide(),b(this,Ri,null),v(this,I,Re).call(this,{hasSelectedText:!1}));return}if((o=c(this,Js))==null||o.hide(),b(this,Ri,e),v(this,I,Re).call(this,{hasSelectedText:!0}),!(c(this,ee)!==Z.HIGHLIGHT&&c(this,ee)!==Z.NONE)&&(c(this,ee)===Z.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),b(this,Cn,this.isShiftKeyDown),!this.isShiftKeyDown)){const h=c(this,ee)===Z.HIGHLIGHT?v(this,I,af).call(this,i):null;h==null||h.toggleDrawing();const l=new AbortController,d=this.combinedSignal(l),u=g=>{g.type==="pointerup"&&g.button!==0||(l.abort(),h==null||h.toggleDrawing(!0),g.type==="pointerup"&&v(this,I,Xd).call(this,"main_toolbar"))};window.addEventListener("pointerup",u,{signal:d}),window.addEventListener("blur",u,{signal:d})}},Xd=function(t=""){c(this,ee)===Z.HIGHLIGHT?this.highlightSelection(t):c(this,Mh)&&v(this,I,fb).call(this)},mb=function(){document.addEventListener("selectionchange",v(this,I,pb).bind(this),{signal:this._signal})},bb=function(){if(c(this,Sn))return;b(this,Sn,new AbortController);const t=this.combinedSignal(c(this,Sn));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},vb=function(){var t;(t=c(this,Sn))==null||t.abort(),b(this,Sn,null)},hf=function(){if(c(this,Tn))return;b(this,Tn,new AbortController);const t=this.combinedSignal(c(this,Tn));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},yb=function(){var t;(t=c(this,Tn))==null||t.abort(),b(this,Tn,null)},lf=function(){if(c(this,xn))return;b(this,xn,new AbortController);const t=this.combinedSignal(c(this,xn));document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})},cf=function(){var t;(t=c(this,xn))==null||t.abort(),b(this,xn,null)},_b=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Re=function(t){Object.entries(t).some(([s,i])=>c(this,Ih)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(c(this,Ih),t)}),c(this,ee)===Z.HIGHLIGHT&&t.hasSelectedEditor===!1&&v(this,I,qn).call(this,[[U.HIGHLIGHT_FREE,!0]]))},qn=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},wb=async function(){if(!c(this,An)){b(this,An,!0);const t=[];for(const e of c(this,ne).values())t.push(e.enable());await Promise.all(t);for(const e of c(this,Yt).values())e.enable()}},xb=function(){if(this.unselectAll(),c(this,An)){b(this,An,!1);for(const t of c(this,ne).values())t.disable();for(const t of c(this,Yt).values())t.disable()}},df=function(t){const e=c(this,ne).get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},Sb=function(){let t=null;for(t of c(this,ft));return t},Bl=function(){if(c(this,Yt).size===0)return!0;if(c(this,Yt).size===1)for(const t of c(this,Yt).values())return t.isEmpty();return!1},uf=function(t){for(const e of c(this,ft))e.unselect();c(this,ft).clear();for(const e of t)e.isEmpty()||(c(this,ft).add(e),e.select());v(this,I,Re).call(this,{hasSelectedEditor:this.hasSelection})},q($o,"TRANSLATE_SMALL",1),q($o,"TRANSLATE_BIG",10);let ur=$o;const Oe=class Oe{constructor(t){w(this,Ps);w(this,se,null);w(this,ti,!1);w(this,Ds,null);w(this,Ko,null);w(this,ei,null);w(this,$e,null);w(this,Qo,!1);w(this,si,null);w(this,Be,null);w(this,Ii,null);w(this,Cr,null);w(this,ii,!1);b(this,Be,t),b(this,ii,t._uiManager.useNewAltTextFlow),c(Oe,kn)||b(Oe,kn,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(t){Oe._l10n??(Oe._l10n=t)}async render(){const t=b(this,Ds,document.createElement("button"));t.className="altText",t.tabIndex="0";const e=b(this,Ko,document.createElement("span"));t.append(e),c(this,ii)?(t.classList.add("new"),t.setAttribute("data-l10n-id",c(Oe,kn).missing),e.setAttribute("data-l10n-id",c(Oe,kn)["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=c(this,Be)._uiManager._signal;t.addEventListener("contextmenu",hs,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),c(this,Be)._uiManager.editAltText(c(this,Be)),c(this,ii)&&c(this,Be)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:c(this,Ps,Hl)}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(b(this,Qo,!0),i(n))},{signal:s}),await v(this,Ps,Vd).call(this),t}finish(){c(this,Ds)&&(c(this,Ds).focus({focusVisible:c(this,Qo)}),b(this,Qo,!1))}isEmpty(){return c(this,ii)?c(this,se)===null:!c(this,se)&&!c(this,ti)}hasData(){return c(this,ii)?c(this,se)!==null||!!c(this,Ii):this.isEmpty()}get guessedText(){return c(this,Ii)}async setGuessedText(t){c(this,se)===null&&(b(this,Ii,t),b(this,Cr,await Oe._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),v(this,Ps,Vd).call(this))}toggleAltTextBadge(t=!1){var e;if(!c(this,ii)||c(this,se)){(e=c(this,si))==null||e.remove(),b(this,si,null);return}if(!c(this,si)){const s=b(this,si,document.createElement("div"));s.className="noAltTextBadge",c(this,Be).div.append(s)}c(this,si).classList.toggle("hidden",!t)}serialize(t){let e=c(this,se);return!t&&c(this,Ii)===e&&(e=c(this,Cr)),{altText:e,decorative:c(this,ti),guessedText:c(this,Ii),textWithDisclaimer:c(this,Cr)}}get data(){return{altText:c(this,se),decorative:c(this,ti)}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(b(this,Ii,s),b(this,Cr,i)),!(c(this,se)===t&&c(this,ti)===e)&&(n||(b(this,se,t),b(this,ti,e)),v(this,Ps,Vd).call(this))}toggle(t=!1){c(this,Ds)&&(!t&&c(this,$e)&&(clearTimeout(c(this,$e)),b(this,$e,null)),c(this,Ds).disabled=!t)}shown(){c(this,Be)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:c(this,Ps,Hl)}})}destroy(){var t,e;(t=c(this,Ds))==null||t.remove(),b(this,Ds,null),b(this,Ko,null),b(this,ei,null),(e=c(this,si))==null||e.remove(),b(this,si,null)}};se=new WeakMap,ti=new WeakMap,Ds=new WeakMap,Ko=new WeakMap,ei=new WeakMap,$e=new WeakMap,Qo=new WeakMap,si=new WeakMap,Be=new WeakMap,Ii=new WeakMap,Cr=new WeakMap,ii=new WeakMap,kn=new WeakMap,Ps=new WeakSet,Hl=function(){return c(this,se)&&"added"||c(this,se)===null&&this.guessedText&&"review"||"missing"},Vd=async function(){var i,n,r;const t=c(this,Ds);if(!t)return;if(c(this,ii)){if(t.classList.toggle("done",!!c(this,se)),t.setAttribute("data-l10n-id",c(Oe,kn)[c(this,Ps,Hl)]),(i=c(this,Ko))==null||i.setAttribute("data-l10n-id",c(Oe,kn)[`${c(this,Ps,Hl)}-label`]),!c(this,se)){(n=c(this,ei))==null||n.remove();return}}else{if(!c(this,se)&&!c(this,ti)){t.classList.remove("done"),(r=c(this,ei))==null||r.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=c(this,ei);if(!e){b(this,ei,e=document.createElement("span")),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${c(this,Be).id}`;const o=100,h=c(this,Be)._uiManager._signal;h.addEventListener("abort",()=>{clearTimeout(c(this,$e)),b(this,$e,null)},{once:!0}),t.addEventListener("mouseenter",()=>{b(this,$e,setTimeout(()=>{b(this,$e,null),c(this,ei).classList.add("show"),c(this,Be)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:h}),t.addEventListener("mouseleave",()=>{var l;c(this,$e)&&(clearTimeout(c(this,$e)),b(this,$e,null)),(l=c(this,ei))==null||l.classList.remove("show")},{signal:h})}c(this,ti)?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=c(this,se)),e.parentNode||t.append(e);const s=c(this,Be).getImageForAltText();s==null||s.setAttribute("aria-describedby",e.id)},w(Oe,kn,null),q(Oe,"_l10n",null);let cd=Oe;const ct=class ct{constructor(t){w(this,et);w(this,Ar,null);w(this,Fs,null);w(this,Et,null);w(this,Jo,!1);w(this,Tr,!1);w(this,re,null);w(this,Er,null);w(this,Mn,null);w(this,Nh,"");w(this,kr,!1);w(this,On,null);w(this,Bh,!1);w(this,Mr,!1);w(this,ji,!1);w(this,ni,null);w(this,Zo,0);w(this,ta,0);w(this,ds,null);q(this,"_editToolbar",null);q(this,"_initialOptions",Object.create(null));q(this,"_initialData",null);q(this,"_isVisible",!0);q(this,"_uiManager",null);q(this,"_focusEventsAllowed",!0);w(this,Hh,!1);w(this,Td,ct._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=ct.prototype._resizeWithKeyboard,e=ur.TRANSLATE_SMALL,s=ur.TRANSLATE_BIG;return ot(this,"_resizerKeyboardManager",new ph([[["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"],ct.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return ot(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Kw({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){if(ct._l10n??(ct._l10n=t),ct._l10nResizer||(ct._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),ct._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);ct._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){yt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return c(this,Hh)}set _isDraggable(t){var e;b(this,Hh,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,Td)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):v(this,et,Wl).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(c(this,kr)?b(this,kr,!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){v(this,et,gf).call(this,this.parentDimensions,t,e)}translateInPage(t,e){c(this,On)||b(this,On,[this.x,this.y]),v(this,et,gf).call(this,this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){c(this,On)||b(this,On,[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,On)&&(c(this,On)[0]!==this.x||c(this,On)[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=ct,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 v(s=ct,Wh,ff).call(s,t,e,this.parentRotation)}pageTranslationToScreen(t,e){var s;return v(s=ct,Wh,ff).call(s,t,e,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,c(this,Tr)||(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,Tr)&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!c(this,Tr)&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=c(this,Et))==null||t.finish()}async addEditToolbar(){return this._editToolbar||c(this,Mr)?this._editToolbar:(this._editToolbar=new Eg(this),this.div.append(this._editToolbar.render()),c(this,Et)&&await this._editToolbar.addAltText(c(this,Et)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=c(this,Et))==null||t.destroy())}addContainer(t){var s;const e=(s=this._editToolbar)==null?void 0:s.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){c(this,Et)||(cd.initialize(ct._l10n),b(this,Et,new cd(this)),c(this,Ar)&&(c(this,Et).data=c(this,Ar),b(this,Ar,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=c(this,Et))==null?void 0:t.data}set altTextData(t){c(this,Et)&&(c(this,Et).data=t)}get guessedAltText(){var t;return(t=c(this,Et))==null?void 0:t.guessedText}async setGuessedAltText(t){var e;await((e=c(this,Et))==null?void 0:e.setGuessedText(t))}serializeAltText(t){var e;return(e=c(this,Et))==null?void 0:e.serialize(t)}hasAltText(){return!!c(this,Et)&&!c(this,Et).isEmpty()}hasAltTextData(){var t;return((t=c(this,Et))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=c(this,Jo)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),v(this,et,yf).call(this);const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),ld(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=Ee.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(b(this,kr,!0),this._isDraggable){v(this,et,Tb).call(this,t);return}v(this,et,vf).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){c(this,ni)&&clearTimeout(c(this,ni)),b(this,ni,setTimeout(()=>{var t;b(this,ni,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,Mr,!0)}disableEditMode(){b(this,Mr,!1)}isInEditMode(){return c(this,Mr)}shouldGetKeyboardEvents(){return c(this,ji)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){v(this,et,yf).call(this)}rotate(t){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,e=null){yt("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,b(i,Ar,t.accessibilityData);const[n,r]=i.pageDimensions,[o,h,l,d]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=d/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t;if((t=c(this,Mn))==null||t.abort(),b(this,Mn,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),c(this,ni)&&(clearTimeout(c(this,ni)),b(this,ni,null)),v(this,et,Wl).call(this),this.removeEditToolbar(),c(this,ds)){for(const e of c(this,ds).values())clearTimeout(e);b(this,ds,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(v(this,et,Cb).call(this),c(this,re).classList.remove("hidden"),ld(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,Er,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const e=c(this,re).children;if(!c(this,Fs)){b(this,Fs,Array.from(e));const r=v(this,et,Eb).bind(this),o=v(this,et,kb).bind(this),h=this._uiManager._signal;for(const l of c(this,Fs)){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",v(this,et,Mb).bind(this,d),{signal:h}),l.setAttribute("data-l10n-id",ct._l10nResizer[d])}}const s=c(this,Fs)[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,Fs).length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)c(this,re).append(c(this,re).firstChild);else if(n>i)for(let o=0;o<n-i;o++)c(this,re).firstChild.before(c(this,re).lastChild);let r=0;for(const o of e){const l=c(this,Fs)[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",ct._l10nResizer[l])}}v(this,et,_f).call(this,0),b(this,ji,!0),c(this,re).firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}_resizeWithKeyboard(t,e){c(this,ji)&&v(this,et,bf).call(this,c(this,Nh),{movementX:t,movementY:e})}_stopResizingWithKeyboard(){v(this,et,Wl).call(this),this.div.focus()}select(){var t,e,s;if(this.makeResizable(),(t=this.div)==null||t.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{var i,n;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((n=this._editToolbar)==null||n.show())});return}(e=this._editToolbar)==null||e.show(),(s=c(this,Et))==null||s.toggleAltTextBadge(!1)}unselect(){var t,e,s,i,n;(t=c(this,re))==null||t.classList.add("hidden"),(e=this.div)==null||e.classList.remove("selectedEditor"),(s=this.div)!=null&&s.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(n=c(this,Et))==null||n.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return c(this,Bh)}set isEditing(t){b(this,Bh,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){b(this,Tr,!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,ds)||b(this,ds,new Map);const{action:s}=t;let i=c(this,ds).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),c(this,ds).delete(s),c(this,ds).size===0&&b(this,ds,null)},ct._telemetryTimeout),c(this,ds).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,Jo,!1)}disable(){this.div&&(this.div.tabIndex=-1),b(this,Jo,!0)}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;(e==null?void 0:e.nodeName)==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}};Ar=new WeakMap,Fs=new WeakMap,Et=new WeakMap,Jo=new WeakMap,Tr=new WeakMap,re=new WeakMap,Er=new WeakMap,Mn=new WeakMap,Nh=new WeakMap,kr=new WeakMap,On=new WeakMap,Bh=new WeakMap,Mr=new WeakMap,ji=new WeakMap,ni=new WeakMap,Zo=new WeakMap,ta=new WeakMap,ds=new WeakMap,Hh=new WeakMap,Td=new WeakMap,et=new WeakSet,gf=function([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()},Wh=new WeakSet,ff=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]}},pf=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]}},Cb=function(){if(c(this,re))return;b(this,re,document.createElement("div")),c(this,re).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,re).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",v(this,et,Ab).bind(this,s),{signal:e}),i.addEventListener("contextmenu",hs,{signal:e}),i.tabIndex=-1}this.div.prepend(c(this,re))},Ab=function(t,e){var p;e.preventDefault();const{isMac:s}=Ee.platform;if(e.button!==0||e.ctrlKey&&s)return;(p=c(this,Et))==null||p.toggle(!1);const i=this._isDraggable;this._isDraggable=!1;const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",v(this,et,bf).bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("contextmenu",hs,{signal:r});const o=this.x,h=this.y,l=this.width,d=this.height,u=this.parent.div.style.cursor,g=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const f=()=>{var m;n.abort(),this.parent.togglePointerEvents(!0),(m=c(this,Et))==null||m.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=u,this.div.style.cursor=g,v(this,et,mf).call(this,o,h,l,d)};window.addEventListener("pointerup",f,{signal:r}),window.addEventListener("blur",f,{signal:r})},mf=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})},bf=function(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=ct.MIN_SIZE/s,d=ct.MIN_SIZE/i,u=V=>Math.round(V*1e4)/1e4,g=v(this,et,pf).call(this,this.rotation),f=(V,H)=>[g[0]*V+g[2]*H,g[1]*V+g[3]*H],p=v(this,et,pf).call(this,360-this.rotation),m=(V,H)=>[p[0]*V+p[2]*H,p[1]*V+p[3]*H];let _,y,x=!1,S=!1;switch(t){case"topLeft":x=!0,_=(V,H)=>[0,0],y=(V,H)=>[V,H];break;case"topMiddle":_=(V,H)=>[V/2,0],y=(V,H)=>[V/2,H];break;case"topRight":x=!0,_=(V,H)=>[V,0],y=(V,H)=>[0,H];break;case"middleRight":S=!0,_=(V,H)=>[V,H/2],y=(V,H)=>[0,H/2];break;case"bottomRight":x=!0,_=(V,H)=>[V,H],y=(V,H)=>[0,0];break;case"bottomMiddle":_=(V,H)=>[V/2,H],y=(V,H)=>[V/2,0];break;case"bottomLeft":x=!0,_=(V,H)=>[0,H],y=(V,H)=>[V,0];break;case"middleLeft":S=!0,_=(V,H)=>[0,H/2],y=(V,H)=>[V,H/2];break}const C=_(o,h),E=y(o,h);let M=f(...E);const k=u(n+M[0]),O=u(r+M[1]);let P=1,F=1,[R,W]=this.screenToPageTranslation(e.movementX,e.movementY);if([R,W]=m(R/s,W/i),x){const V=Math.hypot(o,h);P=F=Math.max(Math.min(Math.hypot(E[0]-C[0]-R,E[1]-C[1]-W)/V,1/o,1/h),l/o,d/h)}else S?P=Math.max(l,Math.min(1,Math.abs(E[0]-C[0]-R)))/o:F=Math.max(d,Math.min(1,Math.abs(E[1]-C[1]-W)))/h;const B=u(o*P),X=u(h*F);M=f(...y(B,X));const K=k-M[0],tt=O-M[1];this.width=B,this.height=X,this.x=K,this.y=tt,this.setDims(s*B,i*X),this.fixAndSetPosition()},vf=function(t){const{isMac:e}=Ee.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)},Tb=function(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();const s=new AbortController,i=this._uiManager.combinedSignal(s);if(e){this.div.classList.add("moving"),b(this,Zo,t.clientX),b(this,ta,t.clientY);const r=o=>{const{clientX:h,clientY:l}=o,[d,u]=this.screenToPageTranslation(h-c(this,Zo),l-c(this,ta));b(this,Zo,h),b(this,ta,l),this._uiManager.dragSelectedEditors(d,u)};window.addEventListener("pointermove",r,{passive:!0,capture:!0,signal:i})}const n=()=>{s.abort(),e&&this.div.classList.remove("moving"),b(this,kr,!1),this._uiManager.endDragSession()||v(this,et,vf).call(this,t)};window.addEventListener("pointerup",n,{signal:i}),window.addEventListener("blur",n,{signal:i})},yf=function(){if(c(this,Mn)||!this.div)return;b(this,Mn,new AbortController);const t=this._uiManager.combinedSignal(c(this,Mn));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},Eb=function(t){ct._resizerKeyboardManager.exec(this,t)},kb=function(t){var e;c(this,ji)&&((e=t.relatedTarget)==null?void 0:e.parentNode)!==c(this,re)&&v(this,et,Wl).call(this)},Mb=function(t){b(this,Nh,c(this,ji)?t:"")},_f=function(t){if(c(this,Fs))for(const e of c(this,Fs))e.tabIndex=t},Wl=function(){if(b(this,ji,!1),v(this,et,_f).call(this,-1),c(this,Er)){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=c(this,Er);v(this,et,mf).call(this,t,e,s,i),b(this,Er,null)}},w(ct,Wh),q(ct,"_l10n",null),q(ct,"_l10nResizer",null),q(ct,"_borderLineWidth",-1),q(ct,"_colorManager",new Mg),q(ct,"_zIndex",1),q(ct,"_telemetryTimeout",1e3);let gt=ct;class Kw extends gt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const p0=3285377520,ls=4294901760,$s=65535;class m0{constructor(t){this.h1=t?t&4294967295:p0,this.h2=t?t&4294967295:p0}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let m=0,_=t.length;m<_;m++){const y=t.charCodeAt(m);y<=255?e[s++]=y:(e[s++]=y>>>8,e[s++]=y&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&$s,p=g&$s;for(let m=0;m<i;m++)m&1?(o=r[m],o=o*u&ls|o*f&$s,o=o<<15|o>>>17,o=o*g&ls|o*p&$s,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[m],h=h*u&ls|h*f&$s,h=h<<15|h>>>17,h=h*g&ls|h*p&$s,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&ls|o*f&$s,o=o<<15|o>>>17,o=o*g&ls|o*p&$s,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&ls|t*36045&$s,e=e*4283543511&ls|((e<<16|t>>>16)*2950163797&ls)>>>16,t^=e>>>1,t=t*444984403&ls|t*60499&$s,e=e*3301882366&ls|((e<<16|t>>>16)*3120437893&ls)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Og=Object.freeze({map:null,hash:"",transfer:void 0});class Dg{constructor(){w(this,Ed);w(this,Or,!1);w(this,Dr,null);w(this,ie,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=c(this,ie).get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return c(this,ie).get(t)}remove(t){if(c(this,ie).delete(t),c(this,ie).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of c(this,ie).values())if(e instanceof gt)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=c(this,ie).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,ie).set(t,e);i&&v(this,Ed,Ob).call(this),e instanceof gt&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return c(this,ie).has(t)}getAll(){return c(this,ie).size>0?vg(c(this,ie)):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return c(this,ie).size}resetModified(){c(this,Or)&&(b(this,Or,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new b0(this)}get serializable(){if(c(this,ie).size===0)return Og;const t=new Map,e=new m0,s=[],i=Object.create(null);let n=!1;for(const[r,o]of c(this,ie)){const h=o instanceof gt?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||(n=!!h.bitmap))}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Og}get editorStats(){let t=null;const e=new Map;for(const s of c(this,ie).values()){if(!(s instanceof gt))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||(t=Object.create(null));const r=t[n]||(t[n]=new Map);for(const[o,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const d=l.get(h)??0;l.set(h,d+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){b(this,Dr,null)}get modifiedIds(){if(c(this,Dr))return c(this,Dr);const t=[];for(const e of c(this,ie).values())!(e instanceof gt)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return b(this,Dr,{ids:new Set(t),hash:t.join(",")})}}Or=new WeakMap,Dr=new WeakMap,ie=new WeakMap,Ed=new WeakSet,Ob=function(){c(this,Or)||(b(this,Or,!0),typeof this.onSetModified=="function"&&this.onSetModified())};class b0 extends Dg{constructor(e){super();w(this,zh);const{map:s,hash:i,transfer:n}=e.serializable,r=structuredClone(s,n?{transfer:n}:null);b(this,zh,{map:r,hash:i,transfer:n})}get print(){yt("Should not call PrintAnnotationStorage.print")}get serializable(){return c(this,zh)}get modifiedIds(){return ot(this,"modifiedIds",{ids:new Set,hash:""})}}zh=new WeakMap;class Qw{constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){w(this,ea,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,ea).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||c(this,ea).has(t.loadedName))){if(Gt(!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,ea).add(s),e==null||e(t)}catch{st(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}yt("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw st(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){var e;const t=!!((e=this._document)!=null&&e.fonts);return ot(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(fe||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),ot(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(Gt(!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 ot(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(C,E){return C.charCodeAt(E)<<24|C.charCodeAt(E+1)<<16|C.charCodeAt(E+2)<<8|C.charCodeAt(E+3)&255}function i(C,E,M,k){const O=C.substring(0,E),P=C.substring(E+M);return O+k+P}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function d(C,E){if(++l>30){st("Load test font never loaded."),E();return}if(h.font="30px "+C,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){E();return}setTimeout(d.bind(null,C,E))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let g=this._loadTestFont;g=i(g,976,u.length,u);const p=16,m=1482184792;let _=s(g,p);for(n=0,r=u.length-3;n<r;n+=4)_=_-m+s(u,n)|0;n<u.length&&(_=_-m+s(u+"XXX",n)|0),g=i(g,p,4,Lw(_));const y=`url(data:font/opentype;base64,${btoa(g)});`,x=`@font-face {font-family:"${u}";src:${y}}`;this.insertRule(x);const S=this._document.createElement("div");S.style.visibility="hidden",S.style.width=S.style.height="10px",S.style.position="absolute",S.style.top=S.style.left="0px";for(const C of[t.loadedName,u]){const E=this._document.createElement("span");E.textContent="Hi",E.style.fontFamily=C,S.append(E)}this._document.body.append(S),d(u,()=>{S.remove(),e.complete()})}}ea=new WeakMap;class Jw{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 s;if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Ww(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}return(s=this._inspectFont)==null||s.call(this,this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];let s;try{s=t.get(this.loadedName+"_path_"+e)}catch(n){st(`getPathGenerator - ignoring character: "${n}".`)}if(!Array.isArray(s)||s.length===0)return this.compiledGlyphs[e]=function(n,r){};const i=[];for(let n=0,r=s.length;n<r;)switch(s[n++]){case Ti.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 Ti.MOVE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.moveTo(o,h)),n+=2}break;case Ti.LINE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.lineTo(o,h)),n+=2}break;case Ti.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 Ti.RESTORE:i.push(o=>o.restore());break;case Ti.SAVE:i.push(o=>o.save());break;case Ti.SCALE:Gt(i.length===2,"Scale command is only valid at the third position.");break;case Ti.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 Ti.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)}}}class v0{constructor({enableHWA:t=!1}){w(this,Xh,!1);b(this,Xh,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,Xh)})}}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){yt("Abstract method `_createCanvas` called.")}}Xh=new WeakMap;class Zw extends v0{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}}class y0{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){yt("Abstract method `_fetch` called.")}}class _0 extends y0{async _fetch(t){const e=await ad(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):od(e)}}class w0{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class tx extends w0{constructor({docId:e,ownerDocument:s=globalThis.document}){super();w(this,j);w(this,Pr);w(this,Fr);w(this,ri);w(this,Ni);w(this,be);w(this,kd);w(this,Rr,0);b(this,Ni,e),b(this,be,s)}addFilter(e){if(!e)return"none";let s=c(this,j,_e).get(e);if(s)return s;const[i,n,r]=v(this,j,Gd).call(this,e),o=e.length===1?i:`${i}${n}${r}`;if(s=c(this,j,_e).get(o),s)return c(this,j,_e).set(e,s),s;const h=`g_${c(this,Ni)}_transfer_map_${Fe(this,Rr)._++}`,l=v(this,j,za).call(this,h);c(this,j,_e).set(e,l),c(this,j,_e).set(o,l);const d=v(this,j,Xa).call(this,h);return v(this,j,Xl).call(this,i,n,r,d),l}addHCMFilter(e,s){var p;const i=`${e}-${s}`,n="base";let r=c(this,j,Ha).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,j,Ha).set(n,r)),!e||!s))return r.url;const o=v(this,j,Vl).call(this,e);e=z.makeHexColor(...o);const h=v(this,j,Vl).call(this,s);if(s=z.makeHexColor(...h),c(this,j,Wa).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,Ni)}_hcm_filter`,g=r.filter=v(this,j,Xa).call(this,u);v(this,j,Xl).call(this,d,d,d,g),v(this,j,wf).call(this,g);const f=(m,_)=>{const y=o[m]/255,x=h[m]/255,S=new Array(_+1);for(let C=0;C<=_;C++)S[C]=y+C/_*(x-y);return S.join(",")};return v(this,j,Xl).call(this,f(0,5),f(1,5),f(2,5),g),r.url=v(this,j,za).call(this,u),r.url}addAlphaFilter(e){let s=c(this,j,_e).get(e);if(s)return s;const[i]=v(this,j,Gd).call(this,[e]),n=`alpha_${i}`;if(s=c(this,j,_e).get(n),s)return c(this,j,_e).set(e,s),s;const r=`g_${c(this,Ni)}_alpha_map_${Fe(this,Rr)._++}`,o=v(this,j,za).call(this,r);c(this,j,_e).set(e,o),c(this,j,_e).set(n,o);const h=v(this,j,Xa).call(this,r);return v(this,j,xf).call(this,i,h),o}addLuminosityFilter(e){let s=c(this,j,_e).get(e||"luminosity");if(s)return s;let i,n;if(e?([i]=v(this,j,Gd).call(this,[e]),n=`luminosity_${i}`):n="luminosity",s=c(this,j,_e).get(n),s)return c(this,j,_e).set(e,s),s;const r=`g_${c(this,Ni)}_luminosity_map_${Fe(this,Rr)._++}`,o=v(this,j,za).call(this,r);c(this,j,_e).set(e,o),c(this,j,_e).set(n,o);const h=v(this,j,Xa).call(this,r);return v(this,j,Db).call(this,h),e&&v(this,j,xf).call(this,i,h),o}addHighlightHCMFilter(e,s,i,n,r){var x;const o=`${s}-${i}-${n}-${r}`;let h=c(this,j,Ha).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,j,Ha).set(e,h)),!s||!i))return h.url;const[l,d]=[s,i].map(v(this,j,Vl).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(v(this,j,Vl).bind(this));g<u&&([u,g,f,p]=[g,u,p,f]),c(this,j,Wa).style.color="";const m=(S,C,E)=>{const M=new Array(256),k=(g-u)/E,O=S/255,P=(C-S)/(255*E);let F=0;for(let R=0;R<=E;R++){const W=Math.round(u+R*k),B=O+R*P;for(let X=F;X<=W;X++)M[X]=B;F=W+1}for(let R=F;R<256;R++)M[R]=M[F-1];return M.join(",")},_=`g_${c(this,Ni)}_hcm_${e}_filter`,y=h.filter=v(this,j,Xa).call(this,_);return v(this,j,wf).call(this,y),v(this,j,Xl).call(this,m(f[0],p[0],5),m(f[1],p[1],5),m(f[2],p[2],5),y),h.url=v(this,j,za).call(this,_),h.url}destroy(e=!1){e&&c(this,j,Ha).size!==0||(c(this,ri)&&(c(this,ri).parentNode.parentNode.remove(),b(this,ri,null)),c(this,Fr)&&(c(this,Fr).clear(),b(this,Fr,null)),b(this,Rr,0))}}Pr=new WeakMap,Fr=new WeakMap,ri=new WeakMap,Ni=new WeakMap,be=new WeakMap,kd=new WeakMap,Rr=new WeakMap,j=new WeakSet,_e=function(){return c(this,Fr)||b(this,Fr,new Map)},Ha=function(){return c(this,kd)||b(this,kd,new Map)},Wa=function(){if(!c(this,ri)){const e=c(this,be).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,be).createElementNS(Ei,"svg");i.setAttribute("width",0),i.setAttribute("height",0),b(this,ri,c(this,be).createElementNS(Ei,"defs")),e.append(i),i.append(c(this,ri)),c(this,be).body.append(e)}return c(this,ri)},Gd=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(",")]},za=function(e){if(c(this,Pr)===void 0){b(this,Pr,"");const s=c(this,be).URL;s!==c(this,be).baseURI&&(hd(s)?st('#createUrl: ignore "data:"-URL for performance reasons.'):b(this,Pr,s.split("#",1)[0]))}return`url(${c(this,Pr)}#${e})`},Db=function(e){const s=c(this,be).createElementNS(Ei,"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)},wf=function(e){const s=c(this,be).createElementNS(Ei,"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)},Xa=function(e){const s=c(this,be).createElementNS(Ei,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",e),c(this,j,Wa).append(s),s},zl=function(e,s,i){const n=c(this,be).createElementNS(Ei,s);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),e.append(n)},Xl=function(e,s,i,n){const r=c(this,be).createElementNS(Ei,"feComponentTransfer");n.append(r),v(this,j,zl).call(this,r,"feFuncR",e),v(this,j,zl).call(this,r,"feFuncG",s),v(this,j,zl).call(this,r,"feFuncB",i)},xf=function(e,s){const i=c(this,be).createElementNS(Ei,"feComponentTransfer");s.append(i),v(this,j,zl).call(this,i,"feFuncA",e)},Vl=function(e){return c(this,j,Wa).style.color=e,Ag(getComputedStyle(c(this,j,Wa)).getPropertyValue("color"))};class x0{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){yt("Abstract method `_fetch` called.")}}class S0 extends x0{async _fetch(t){const e=await ad(t,"arraybuffer");return new Uint8Array(e)}}if(fe){var Pg=Promise.withResolvers(),mh=null;(async()=>{const t=await Promise.resolve().then(()=>_d),e=await Promise.resolve().then(()=>_d),s=await Promise.resolve().then(()=>_d),i=await Promise.resolve().then(()=>_d);let n,r;return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:n,path2d:r}))})().then(t=>{mh=t,Pg.resolve()},t=>{st(`loadPackages: ${t}`),mh=new Map,Pg.resolve()})}class vn{static get promise(){return Pg.promise}static get(t){return mh==null?void 0:mh.get(t)}}async function C0(a){const e=await vn.get("fs").promises.readFile(a);return new Uint8Array(e)}class ex extends w0{}class sx extends v0{_createCanvas(t,e){return vn.get("canvas").createCanvas(t,e)}}class ix extends y0{async _fetch(t){return C0(t)}}class nx extends x0{async _fetch(t){return C0(t)}}const ke={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Fg(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 Rg{getPattern(){yt("Abstract method `getPattern` called.")}}class rx extends Rg{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===ke.STROKE||i===ke.FILL){const r=e.current.getClippedPathBoundingBox(i,Tt(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),d=l.context;d.clearRect(0,0,d.canvas.width,d.canvas.height),d.beginPath(),d.rect(0,0,d.canvas.width,d.canvas.height),d.translate(-r[0],-r[1]),s=z.transform(s,[1,0,0,1,r[0],r[1]]),d.transform(...e.baseTransform),this.matrix&&d.transform(...this.matrix),Fg(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 Fg(t,this._bbox),n=this._createGradient(t);return n}}function Lg(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,y=(h[i]+t.offsetX)*t.scaleX,x=(h[i+1]+t.offsetY)*t.scaleY;if(p>=x)return;const S=l[n],C=l[n+1],E=l[n+2],M=l[r],k=l[r+1],O=l[r+2],P=l[o],F=l[o+1],R=l[o+2],W=Math.round(p),B=Math.round(x);let X,K,tt,V,H,Qt,Jt,le;for(let zt=W;zt<=B;zt++){if(zt<_){const dt=zt<p?0:(p-zt)/(p-_);X=f-(f-m)*dt,K=S-(S-M)*dt,tt=C-(C-k)*dt,V=E-(E-O)*dt}else{let dt;zt>x?dt=1:_===x?dt=0:dt=(_-zt)/(_-x),X=m-(m-y)*dt,K=M-(M-P)*dt,tt=k-(k-F)*dt,V=O-(O-R)*dt}let _t;zt<p?_t=0:zt>x?_t=1:_t=(p-zt)/(p-x),H=f-(f-y)*_t,Qt=S-(S-P)*_t,Jt=C-(C-F)*_t,le=E-(E-R)*_t;const Pe=Math.round(Math.min(X,H)),fi=Math.round(Math.max(X,H));let Pt=u*zt+Pe*4;for(let dt=Pe;dt<=fi;dt++)_t=(X-dt)/(X-H),_t<0?_t=0:_t>1&&(_t=1),d[Pt++]=K-(K-Qt)*_t|0,d[Pt++]=tt-(tt-Jt)*_t|0,d[Pt++]=V-(V-le)*_t|0,d[Pt++]=255}}function ox(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++)Lg(a,e,s[d],s[d+1],s[d+o],i[d],i[d+1],i[d+o]),Lg(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)Lg(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 ax extends Rg{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,y=g+2*2,x=s.getCanvas("mesh",_,y),S=x.context,C=S.createImageData(u,g);if(e){const M=C.data;for(let k=0,O=M.length;k<O;k+=4)M[k]=e[0],M[k+1]=e[1],M[k+2]=e[2],M[k+3]=255}for(const M of this._figures)ox(C,M,m);return S.putImageData(C,2,2),{canvas:x.canvas,offsetX:o-2*f,offsetY:h-2*p,scaleX:f,scaleY:p}}getPattern(t,e,s,i){Fg(t,this._bbox);let n;if(i===ke.SHADING)n=z.singularValueDecompose2dScale(Tt(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===ke.SHADING?null:this._background,e.cachedCanvases);return i!==ke.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class hx extends Rg{getPattern(){return"hotpink"}}function lx(a){switch(a[0]){case"RadialAxial":return new rx(a);case"Mesh":return new ax(a);case"Dummy":return new hx}throw new Error(`Unknown IR type: ${a[0]}`)}const A0={COLORED:1,UNCOLORED:2},Md=class Md{constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),nd("TilingType: "+n);const d=e[0],u=e[1],g=e[2],f=e[3],p=g-d,m=f-u,_=z.singularValueDecompose2dScale(this.matrix),y=z.singularValueDecompose2dScale(this.baseTransform),x=_[0]*y[0],S=_[1]*y[1];let C=p,E=m,M=!1,k=!1;const O=Math.ceil(h*x),P=Math.ceil(l*S),F=Math.ceil(p*x),R=Math.ceil(m*S);O>=F?C=h:M=!0,P>=R?E=l:k=!0;const W=this.getSizeAndScale(C,this.ctx.canvas.width,x),B=this.getSizeAndScale(E,this.ctx.canvas.height,S),X=t.cachedCanvases.getCanvas("pattern",W.size,B.size),K=X.context,tt=o.createCanvasGraphics(K);if(tt.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(tt,i,r),K.translate(-W.scale*d,-B.scale*u),tt.transform(W.scale,0,0,B.scale,0,0),K.save(),this.clipBbox(tt,d,u,g,f),tt.baseTransform=Tt(tt.ctx),tt.executeOperatorList(s),tt.endDrawing(),K.restore(),M||k){const V=X.canvas;M&&(C=h),k&&(E=l);const H=this.getSizeAndScale(C,this.ctx.canvas.width,x),Qt=this.getSizeAndScale(E,this.ctx.canvas.height,S),Jt=H.size,le=Qt.size,zt=t.cachedCanvases.getCanvas("pattern-workaround",Jt,le),_t=zt.context,Pe=M?Math.floor(p/h):0,fi=k?Math.floor(m/l):0;for(let Pt=0;Pt<=Pe;Pt++)for(let dt=0;dt<=fi;dt++)_t.drawImage(V,Jt*Pt,le*dt,Jt,le,0,0,Jt,le);return{canvas:zt.canvas,scaleX:H.scale,scaleY:Qt.scale,offsetX:d,offsetY:u}}return{canvas:X.canvas,scaleX:W.scale,scaleY:B.scale,offsetX:d,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(Md.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,o=n-s;t.ctx.rect(e,s,r,o),t.current.updateRectMinMax(Tt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case A0.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case A0.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 Rw(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==ke.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}};q(Md,"MAX_PATTERN_SIZE",3e3);let Ig=Md;function cx({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Ee.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 y=t<g?a[t]:255;e[f++]=y&128?l:h,e[f++]=y&64?l:h,e[f++]=y&32?l:h,e[f++]=y&16?l:h,e[f++]=y&8?l:h,e[f++]=y&4?l:h,e[f++]=y&2?l:h,e[f++]=y&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 T0=16,E0=100,dx=15,k0=10,M0=1e3,je=16;function ux(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 gx{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 dd(a,t,e,s,i,n,r,o,h,l){const[d,u,g,f,p,m]=Tt(a);if(u===0&&g===0){const x=r*d+p,S=Math.round(x),C=o*f+m,E=Math.round(C),M=(r+h)*d+p,k=Math.abs(Math.round(M)-S)||1,O=(o+l)*f+m,P=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,k,P),a.setTransform(d,u,g,f,p,m),[k,P]}if(d===0&&f===0){const x=o*g+p,S=Math.round(x),C=r*u+m,E=Math.round(C),M=(o+l)*g+p,k=Math.abs(Math.round(M)-S)||1,O=(r+h)*u+m,P=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,P,k),a.setTransform(d,u,g,f,p,m),[P,k]}a.drawImage(t,e,s,i,n,r,o,h,l);const _=Math.hypot(d,u),y=Math.hypot(g,f);return[_*h,y*l]}function fx(a){const{width:t,height:e}=a;if(t>M0||e>M0)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 y of a.data){let x=128;for(;x>0;)u[g++]=y&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 y=(u[g]?4:0)+(u[g-d]?8:0);for(h=1;h<t;h++)y=(y>>2)+(u[g+1]?4:0)+(u[g-d+1]?8:0),i[y]&&(r[l+h]=i[y],++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 y=o*n;const x=y+t;for(;y<x&&!r[y];)y++;if(y===x)continue;m.moveTo(y%n,o);const S=y;let C=r[y];do{const E=p[C];do y+=E;while(!r[y]);const M=r[y];M!==5&&M!==10?(C=M,r[y]=0):(C=M&51*C>>4,r[y]&=C>>2|C<<2),m.lineTo(y%n,y/n|0),r[y]||--f}while(S!==y);--o}return u=null,r=null,function(y){y.save(),y.scale(1/t,-1/e),y.translate(0,-e),y.fill(m),y.beginPath(),y.restore()}}class O0{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=l0,this.textMatrixScale=1,this.fontMatrix=fg,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=pe.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=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=ke.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===ke.STROKE){e||yt("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=ke.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%je,n=(e-i)/je,r=i===0?n:n+1,o=a.createImageData(s,je);let h=0,l;const d=t.data,u=o.data;let g,f,p,m;if(t.kind===ed.GRAYSCALE_1BPP){const _=d.byteLength,y=new Uint32Array(u.buffer,0,u.byteLength>>2),x=y.length,S=s+7>>3,C=4294967295,E=Ee.isLittleEndian?4278190080:255;for(g=0;g<r;g++){for(p=g<n?je:i,l=0,f=0;f<p;f++){const M=_-h;let k=0;const O=M>S?s:M*8-7,P=O&-8;let F=0,R=0;for(;k<P;k+=8)R=d[h++],y[l++]=R&128?C:E,y[l++]=R&64?C:E,y[l++]=R&32?C:E,y[l++]=R&16?C:E,y[l++]=R&8?C:E,y[l++]=R&4?C:E,y[l++]=R&2?C:E,y[l++]=R&1?C:E;for(;k<O;k++)F===0&&(R=d[h++],F=128),y[l++]=R&F?C:E,F>>=1}for(;l<x;)y[l++]=0;a.putImageData(o,0,g*je)}}else if(t.kind===ed.RGBA_32BPP){for(f=0,m=s*je*4,g=0;g<n;g++)u.set(d.subarray(h,h+m)),h+=m,a.putImageData(o,0,f),f+=je;g<r&&(m=s*i*4,u.set(d.subarray(h,h+m)),a.putImageData(o,0,f))}else if(t.kind===ed.RGB_24BPP)for(p=je,m=s*p,g=0;g<r;g++){for(g>=n&&(p=i,m=s*p),l=0,f=m;f--;)u[l++]=d[h++],u[l++]=d[h++],u[l++]=d[h++],u[l++]=255;a.putImageData(o,0,g*je)}else throw new Error(`bad image kind: ${t.kind}`)}function P0(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%je,n=(e-i)/je,r=i===0?n:n+1,o=a.createImageData(s,je);let h=0;const l=t.data,d=o.data;for(let u=0;u<r;u++){const g=u<n?je:i;({srcPos:h}=cx({src:l,srcPos:h,dest:d,width:s,height:g,nonBlackColor:0})),a.putImageData(o,0,u*je)}}function bh(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 ud(a){if(a.strokeStyle=a.fillStyle="#000000",a.fillRule="nonzero",a.globalAlpha=1,a.lineWidth=1,a.lineCap="butt",a.lineJoin="miter",a.miterLimit=10,a.globalCompositeOperation="source-over",a.font="10px sans-serif",a.setLineDash!==void 0&&(a.setLineDash([]),a.lineDashOffset=0),!fe){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function F0(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)*bn.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const px=["butt","round","square"],mx=["miter","round","bevel"],bx={},R0={},ef=class ef{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){w(this,Dn);this.ctx=t,this.current=new O0(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 gx(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...Tt(this.compositeCtx))}this.ctx.save(),ud(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=Tt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>k0&&typeof s=="function",d=l?Date.now()+dx: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!==Es.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>k0){if(Date.now()>d)return s(),o;u=0}}}endDrawing(){v(this,Dn,Sf).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(),v(this,Dn,Cf).call(this)}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i,l="prescale1",d,u;for(;n>2&&o>1||r>2&&h>1;){let g=o,f=h;n>2&&o>1&&(g=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/g),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),d=this.cachedCanvases.getCanvas(l,g,f),u=d.context,u.clearRect(0,0,g,f),u.drawImage(t,0,0,o,h,0,0,g,f),t=d.canvas,o=g,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=Tt(e);let h,l,d,u;if((t.bitmap||t.data)&&t.count>1){const 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 P=h.get(l);if(P&&!r){const F=Math.round(Math.min(o[0],o[2])+o[4]),R=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:P,offsetX:F,offsetY:R}}d=P}d||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),P0(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),y=Math.round(m-f)||1,x=Math.round(_-p)||1,S=this.cachedCanvases.getCanvas("fillCanvas",y,x),C=S.context,E=f,M=p;C.translate(-E,-M),C.transform(...g),d||(d=this._scaleImage(u.canvas,ki(C)),d=d.img,h&&r&&h.set(l,d)),C.imageSmoothingEnabled=F0(Tt(C),t.interpolate),dd(C,d,0,0,d.width,d.height,0,0,s,i),C.globalCompositeOperation="source-in";const k=z.transform(ki(C),[1,0,0,1,-E,-M]);return C.fillStyle=r?n.getPattern(e,this,k,ke.FILL):n,C.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,S.canvas)),{canvas:S.canvas,offsetX:Math.round(E),offsetY:Math.round(M)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=px[t]}setLineJoin(t){this.ctx.lineJoin=mx[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...Tt(this.suspendedCtx)),bh(this.suspendedCtx,n),ux(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(),bh(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){const _=z.makeHexColor(...r);if(f<0||p<0||f+s>g.width||p+i>g.height){const y=this.cachedCanvases.getCanvas("maskExtension",s,i),x=y.context;x.drawImage(g,-f,-p),x.globalCompositeOperation="destination-atop",x.fillStyle=_,x.fillRect(0,0,s,i),x.globalCompositeOperation="source-over",g=y.canvas,f=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const y=new Path2D;y.rect(f,p,s,i),t.clip(y),t.globalCompositeOperation="destination-atop",t.fillStyle=_,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?(bh(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(),bh(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const d=Tt(i),u=d[0]===0&&d[3]===0||d[1]===0&&d[2]===0,g=u?s.slice(0):null;for(let f=0,p=0,m=t.length;f<m;f++)switch(t[f]|0){case Es.rectangle:r=e[p++],o=e[p++];const _=e[p++],y=e[p++],x=r+_,S=o+y;i.moveTo(r,o),_===0||y===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 Es.moveTo:r=e[p++],o=e[p++],i.moveTo(r,o),u||n.updatePathMinMax(d,r,o);break;case Es.lineTo:r=e[p++],o=e[p++],i.lineTo(r,o),u||n.updatePathMinMax(d,r,o);break;case Es.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 Es.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 Es.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 Es.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,ki(e),ke.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,ki(e),ke.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=bx}eoClip(){this.pendingClip=R0}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||fg,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&st("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=((d=s.systemFontInfo)==null?void 0:d.css)||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<T0?l=T0:e>E0&&(l=E0),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,s,i){const n=this.ctx,r=this.current,o=r.font,h=r.textRenderingMode,l=r.fontSize/r.fontSizeScale,d=h&pe.FILL_STROKE_MASK,u=!!(h&pe.ADD_TO_PATH_FLAG),g=r.patternFill&&!o.missingFile;let f;(o.disableFontFace||u||g)&&(f=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||g?(n.save(),n.translate(e,s),n.beginPath(),f(n,l),i&&n.setTransform(...i),(d===pe.FILL||d===pe.FILL_STROKE)&&n.fill(),(d===pe.STROKE||d===pe.FILL_STROKE)&&n.stroke(),n.restore()):((d===pe.FILL||d===pe.FILL_STROKE)&&n.fillText(t,e,s),(d===pe.STROKE||d===pe.FILL_STROKE)&&n.strokeText(t,e,s)),u&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Tt(n),x:e,y:s,fontSize:l,addToPath:f})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return ot(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,d=e.textHScale*l,u=t.length,g=s.vertical,f=g?1:-1,p=s.defaultVMetrics,m=i*e.fontMatrix[0],_=e.textRenderingMode===pe.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(d,-1):n.scale(d,1);let y;if(e.patternFill){n.save();const M=e.fillColor.getPattern(n,this,ki(n),ke.FILL);y=Tt(n),n.restore(),n.fillStyle=M}let x=e.lineWidth;const S=e.textMatrixScale;if(S===0||x===0){const M=e.textRenderingMode&pe.FILL_STROKE_MASK;(M===pe.STROKE||M===pe.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 k=0;for(const O of t)M.push(O.unicode),k+=O.width;n.fillText(M.join(""),0,0),e.x+=k*m*d,n.restore(),this.compose();return}let C=0,E;for(E=0;E<u;++E){const M=t[E];if(typeof M=="number"){C+=f*M*i/1e3;continue}let k=!1;const O=(M.isSpace?h:0)+o,P=M.fontChar,F=M.accent;let R,W,B=M.width;if(g){const K=M.vmetric||p,tt=-(M.vmetric?K[1]:B*.5)*m,V=K[2]*m;B=K?-K[0]:B,R=tt/r,W=(C+V)/r}else R=C/r,W=0;if(s.remeasure&&B>0){const K=n.measureText(P).width*1e3/i*r;if(B<K&&this.isFontSubpixelAAEnabled){const tt=B/K;k=!0,n.save(),n.scale(tt,1),R/=tt}else B!==K&&(R+=(B-K)/2e3*i/r)}if(this.contentVisible&&(M.isInFont||s.missingFile)){if(_&&!F)n.fillText(P,R,W);else if(this.paintChar(P,R,W,y),F){const K=R+i*F.offset.x/r,tt=W-i*F.offset.y/r;this.paintChar(F.fontChar,K,tt,y)}}const X=g?B*m-O*l:B*m+O*l;C+=X,k&&n.restore()}g?e.y-=C:e.x+=C*d,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,d=s.textHScale*r,u=s.fontMatrix||fg,g=t.length,f=s.textRenderingMode===pe.INVISIBLE;let p,m,_,y;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"){y=o*m*n/1e3,this.ctx.translate(y,0),s.x+=y*d;continue}const x=(m.isSpace?l:0)+h,S=i.charProcOperatorList[m.operatorListId];if(!S){st(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(S),this.restore()),_=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||Tt(this.ctx),n={createCanvasGraphics:r=>new ef(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new Ig(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=lx(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,ki(e),ke.SHADING);const i=ki(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(){yt("Should not call beginInlineImage")}beginImageData(){yt("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Tt(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(Tt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||nd("TODO: Support non-isolated groups."),t.knockout&&st("Knockout groups not supported.");const s=Tt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=z.getAxialAlignedBoundingBox(t.bbox,Tt(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()),bh(e,g),this.ctx=g,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=Tt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=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(v(this,Dn,Sf).call(this),ud(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(Tt(this.ctx)),{viewportScale:d}=this,u=Math.ceil(r*this.outputScaleX*d),g=Math.ceil(o*this.outputScaleY*d);this.annotationCanvas=this.canvasFactory.create(u,g);const{canvas:f,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(h,0,0,-l,0,o*l),ud(this.ctx)}else ud(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new O0(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),v(this,Dn,Cf).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=fx(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=Tt(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let d=0,u=r.length;d<u;d+=2){const g=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);P0(u,g),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,ki(e),ke.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),dd(e,d.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){st("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){st("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,d=i.length;l<d;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!fe){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;D0(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,ki(i));i.imageSmoothingEnabled=F0(Tt(i),t.interpolate),dd(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),dd(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===R0?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Tt(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const d=h*t;r=o=d<1?1/d:1}else if(t===0)r=1/h,o=1/l;else{const d=h*t,u=l*t;r=d<1?1/d:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),d=Math.hypot(i,n);if(t===0)r=d/h,o=l/h;else{const u=t*h;r=d>u?d/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};Dn=new WeakSet,Sf=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)},Cf=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 No=ef;for(const a in Es)No.prototype[a]!==void 0&&(No.prototype[Es[a]]=No.prototype[a]);class Mi{static get workerPort(){return c(this,Vh)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");b(this,Vh,t)}static get workerSrc(){return c(this,Gh)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");b(this,Gh,t)}}Vh=new WeakMap,Gh=new WeakMap,w(Mi,Vh,null),w(Mi,Gh,"");const gd={UNKNOWN:0,DATA:1,ERROR:2},Bt={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Ue(a){switch(a instanceof Error||typeof a=="object"&&a!==null||yt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new cr(a.message);case"MissingPDFException":return new lr(a.message);case"PasswordException":return new mg(a.message,a.code);case"UnexpectedResponseException":return new rd(a.message,a.status);case"UnknownErrorException":return new bg(a.message,a.details);default:return new bg(a.message,a.toString())}}class vh{constructor(t,e,s){w(this,us);w(this,sa,new AbortController);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),s.addEventListener("message",v(this,us,Pb).bind(this),{signal:c(this,sa).signal})}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:Bt.PULL,streamId:n,desiredSize:l.desiredSize}),d.promise},cancel:l=>{Gt(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:Bt.CANCEL,streamId:n,reason:Ue(l)}),d.promise}},s)}destroy(){var t;(t=c(this,sa))==null||t.abort(),b(this,sa,null)}}sa=new WeakMap,us=new WeakSet,Pb=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){v(this,us,Rb).call(this,t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===gd.DATA)i.resolve(t.data);else if(t.callback===gd.ERROR)i.reject(Ue(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;new Promise(function(r){r(e(t.data))}).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:gd.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:gd.ERROR,callbackId:t.callbackId,reason:Ue(r)})});return}if(t.streamId){v(this,us,Fb).call(this,t);return}e(t.data)},Fb=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:Bt.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Bt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){Gt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Bt.ERROR,streamId:e,reason:Ue(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:Bt.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Bt.START_COMPLETE,streamId:e,reason:Ue(l)})})},Rb=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 Bt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Ue(t.reason));break;case Bt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Ue(t.reason));break;case Bt.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:Bt.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:Bt.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Bt.PULL_COMPLETE,streamId:e,reason:Ue(h)})});break;case Bt.ENQUEUE:if(Gt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Bt.CLOSE:if(Gt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),v(this,us,Yd).call(this,r,e);break;case Bt.ERROR:Gt(r,"error should have stream controller"),r.controller.error(Ue(t.reason)),v(this,us,Yd).call(this,r,e);break;case Bt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Ue(t.reason)),v(this,us,Yd).call(this,r,e);break;case Bt.CANCEL:if(!o)break;new Promise(function(h){var l;h((l=o.onCancel)==null?void 0:l.call(o,Ue(t.reason)))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Bt.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Bt.CANCEL_COMPLETE,streamId:e,reason:Ue(h)})}),o.sinkCapability.reject(Ue(t.reason)),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}},Yd=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 vx{constructor({parsedData:t,rawData:e}){w(this,Lr);w(this,Yh);b(this,Lr,t),b(this,Yh,e)}getRaw(){return c(this,Yh)}get(t){return c(this,Lr).get(t)??null}getAll(){return vg(c(this,Lr))}has(t){return c(this,Lr).has(t)}}Lr=new WeakMap,Yh=new WeakMap;const Bo=Symbol("INTERNAL");class yx{constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){w(this,Uh,!1);w(this,qh,!1);w(this,$h,!1);w(this,ia,!0);b(this,Uh,!!(t&Ye.DISPLAY)),b(this,qh,!!(t&Ye.PRINT)),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(c(this,$h))return c(this,ia);if(!c(this,ia))return!1;const{print:t,view:e}=this.usage;return c(this,Uh)?(e==null?void 0:e.viewState)!=="OFF":c(this,qh)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,e,s=!1){t!==Bo&&yt("Internal method `_setVisible` called."),b(this,$h,s),b(this,ia,e)}}Uh=new WeakMap,qh=new WeakMap,$h=new WeakMap,ia=new WeakMap;class _x{constructor(t,e=Ye.DISPLAY){w(this,Kh);w(this,Pn,null);w(this,pt,new Map);w(this,na,null);w(this,ra,null);if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,b(this,ra,t.order);for(const s of t.groups)c(this,pt).set(s.id,new yx(e,s));if(t.baseState==="OFF")for(const s of c(this,pt).values())s._setVisible(Bo,!1);for(const s of t.on)c(this,pt).get(s)._setVisible(Bo,!0);for(const s of t.off)c(this,pt).get(s)._setVisible(Bo,!1);b(this,na,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:(st(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return v(this,Kh,Af).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!c(this,pt).has(e))return st(`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 st(`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 st(`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 st(`Optional content group not found: ${e}`),!0;if(c(this,pt).get(e).visible)return!1}return!0}return st(`Unknown optional content policy ${t.policy}.`),!0}return st(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){var n;const i=c(this,pt).get(t);if(!i){st(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const r of i.rbGroups)for(const o of r)o!==t&&((n=c(this,pt).get(o))==null||n._setVisible(Bo,!1,!0));i._setVisible(Bo,!!e,!0),b(this,Pn,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":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}b(this,Pn,null)}get hasInitialVisibility(){return c(this,na)===null||this.getHash()===c(this,na)}getOrder(){return c(this,pt).size?c(this,ra)?c(this,ra).slice():[...c(this,pt).keys()]:null}getGroups(){return c(this,pt).size>0?vg(c(this,pt)):null}getGroup(t){return c(this,pt).get(t)||null}getHash(){if(c(this,Pn)!==null)return c(this,Pn);const t=new m0;for(const[e,s]of c(this,pt))t.update(`${e}:${s.visible}`);return b(this,Pn,t.hexdigest())}}Pn=new WeakMap,pt=new WeakMap,na=new WeakMap,ra=new WeakMap,Kh=new WeakSet,Af=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=v(this,Kh,Af).call(this,n);else if(c(this,pt).has(n))r=c(this,pt).get(n).visible;else return st(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"};class wx{constructor(t,{disableRange:e=!1,disableStream:s=!1}){Gt(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)});Gt(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(){Gt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new xx(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Sx(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 xx{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Sg(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 Sx{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 Cx(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,_,y]=g;if(m=parseInt(m,10),m in u){if(m===0)break;continue}u[m]=[_,y]}const p=[];for(let m=0;m<u.length&&m in u;++m){let[_,y]=u[m];y=o(y),_&&(y=unescape(y),m===0&&(y=h(y))),p.push(y)}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 jg(a,t){const e=new Headers;if(!a||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function Ng({responseHeaders:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a.get("Accept-Ranges")!=="bytes"||(a.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function Bg(a){const t=a.get("Content-Disposition");if(t){let e=Cx(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Sg(e))return e}return null}function fd(a,t){return a===404||a===0&&t.startsWith("file:")?new lr('Missing PDF "'+t+'".'):new rd(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function L0(a){return a===200||a===206}function I0(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function j0(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(st(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class N0{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=jg(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 Gt(!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 Tx(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;const s=new Headers(t.headers),i=e.url;fetch(i,I0(s,this._withCredentials,this._abortController)).then(n=>{if(!L0(n.status))throw fd(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=Ng({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=Bg(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new cr("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 Tx{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,I0(n,this._withCredentials,this._abortController)).then(o=>{if(!L0(o.status))throw fd(o.status,r);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:j0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}const Hg=200,Wg=206;function Ex(a){const t=a.response;return typeof t!="string"?t:od(t).buffer}class kx{constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=jg(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,s){const i={begin:t,end:e};for(const n in s)i[n]=s[n];return this.request(i)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=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=Ex(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 Mx{constructor(t){this._source=t,this._manager=new kx(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return Gt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Ox(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Dx(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 Ox{constructor(t,e){this._manager=t;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(s),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),s=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map(r=>{const[o,...h]=r.split(": ");return[o,h.join(": ")]})),{allowRangeRequests:i,suggestedLength:n}=Ng({responseHeaders: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._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=fd(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){var e;(e=this.onProgress)==null||e.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Dx{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=fd(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 Px=/^[a-z][a-z0-9\-+.]+:/i;function Fx(a){if(Px.test(a))return new URL(a);const t=vn.get("url");return new URL(t.pathToFileURL(a))}function B0(a,t,e){return a.protocol==="http:"?vn.get("http").request(a,{headers:t},e):vn.get("https").request(a,{headers:t},e)}class Rx{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.headers=jg(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 Gt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new jx(this):new Lx(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new Nx(this,t,e):new Ix(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 cr("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)}}class Lx extends H0{constructor(t){super(t);const e=Object.fromEntries(t.headers),s=i=>{if(i.statusCode===404){const h=new lr(`Missing PDF "${this._url}".`);this._storedError=h,this._headersCapability.reject(h);return}this._headersCapability.resolve(),this._setReadableStream(i);const n=new Headers(this._readableStream.headers),{allowRangeRequests:r,suggestedLength:o}=Ng({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=o||this._contentLength,this._filename=Bg(n)};this._request=B0(this._url,e,s),this._request.on("error",i=>{this._storedError=i,this._headersCapability.reject(i)}),this._request.end()}}class Ix extends W0{constructor(t,e,s){super(t);const i=Object.fromEntries(t.headers);i.Range=`bytes=${e}-${s-1}`;const n=r=>{if(r.statusCode===404){const o=new lr(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(r)};this._request=B0(this._url,i,n),this._request.on("error",r=>{this._storedError=r}),this._request.end()}}class jx extends H0{constructor(t){super(t);const e=vn.get("fs");e.promises.lstat(this._url).then(s=>{this._contentLength=s.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()},s=>{s.code==="ENOENT"&&(s=new lr(`Missing PDF "${this._url}".`)),this._storedError=s,this._headersCapability.reject(s)})}}class Nx extends W0{constructor(t,e,s){super(t);const i=vn.get("fs");this._setReadableStream(i.createReadStream(this._url,{start:e,end:s-1}))}}const Bx=1e5,Ne=30,Hx=.8,Ut=class Ut{constructor({textContentSource:t,container:e,viewport:s}){w(this,Hi);w(this,Fn,Promise.withResolvers());w(this,He,null);w(this,Qh,!1);w(this,Jh,!!((nb=globalThis.FontInspector)!=null&&nb.enabled));w(this,Ir,null);w(this,Bi,null);w(this,Zh,0);w(this,tl,0);w(this,jr,null);w(this,oa,null);w(this,aa,0);w(this,Rn,0);w(this,ha,Object.create(null));w(this,el,[]);w(this,la,null);w(this,Nr,[]);w(this,sl,new WeakMap);w(this,il,null);var h;if(t instanceof ReadableStream)b(this,la,t);else if(typeof t=="object")b(this,la,new ReadableStream({start(l){l.enqueue(t),l.close()}}));else throw new Error('No "textContentSource" parameter specified.');b(this,He,b(this,oa,e)),b(this,Rn,s.scale*(globalThis.devicePixelRatio||1)),b(this,aa,s.rotation),b(this,Bi,{div:null,properties:null,ctx:null});const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;b(this,il,[1,0,0,-1,-r,o+n]),b(this,tl,i),b(this,Zh,n),v(h=Ut,Ke,jb).call(h),dr(e,s),c(this,Fn).promise.finally(()=>{c(Ut,ca).delete(this),b(this,Bi,null),b(this,ha,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Ee.platform;return ot(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{c(this,jr).read().then(({value:e,done:s})=>{if(s){c(this,Fn).resolve();return}c(this,Ir)??b(this,Ir,e.lang),Object.assign(c(this,ha),e.styles),v(this,Hi,Lb).call(this,e.items),t()},c(this,Fn).reject)};return b(this,jr,c(this,la).getReader()),c(Ut,ca).add(this),t(),c(this,Fn).promise}update({viewport:t,onBefore:e=null}){var n;const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==c(this,aa)&&(e==null||e(),b(this,aa,i),dr(c(this,oa),{rotation:i})),s!==c(this,Rn)){e==null||e(),b(this,Rn,s);const r={div:null,properties:null,ctx:v(n=Ut,Ke,Ud).call(n,c(this,Ir))};for(const o of c(this,Nr))r.properties=c(this,sl).get(o),r.div=o,v(this,Hi,Tf).call(this,r)}}cancel(){var e;const t=new cr("TextLayer task cancelled.");(e=c(this,jr))==null||e.cancel(t).catch(()=>{}),b(this,jr,null),c(this,Fn).reject(t)}get textDivs(){return c(this,Nr)}get textContentItemsStr(){return c(this,el)}static cleanup(){if(!(c(this,ca).size>0)){c(this,Br).clear();for(const{canvas:t}of c(this,Hr).values())t.remove();c(this,Hr).clear()}}};Fn=new WeakMap,He=new WeakMap,Qh=new WeakMap,Jh=new WeakMap,Ir=new WeakMap,Bi=new WeakMap,Zh=new WeakMap,tl=new WeakMap,jr=new WeakMap,oa=new WeakMap,aa=new WeakMap,Rn=new WeakMap,ha=new WeakMap,el=new WeakMap,la=new WeakMap,Nr=new WeakMap,sl=new WeakMap,il=new WeakMap,Br=new WeakMap,Hr=new WeakMap,nl=new WeakMap,Ln=new WeakMap,ca=new WeakMap,Hi=new WeakSet,Lb=function(t){var i,n;if(c(this,Qh))return;(n=c(this,Bi)).ctx??(n.ctx=v(i=Ut,Ke,Ud).call(i,c(this,Ir)));const e=c(this,Nr),s=c(this,el);for(const r of t){if(e.length>Bx){st("Ignoring additional textDivs for performance reasons."),b(this,Qh,!0);return}if(r.str===void 0){if(r.type==="beginMarkedContentProps"||r.type==="beginMarkedContent"){const o=c(this,He);b(this,He,document.createElement("span")),c(this,He).classList.add("markedContent"),r.id!==null&&c(this,He).setAttribute("id",`${r.id}`),o.append(c(this,He))}else r.type==="endMarkedContent"&&b(this,He,c(this,He).parentNode);continue}s.push(r.str),v(this,Hi,Ib).call(this,r)}},Ib=function(t){var m;const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};c(this,Nr).push(e);const i=z.transform(c(this,il),t.transform);let n=Math.atan2(i[1],i[0]);const r=c(this,ha)[t.fontName];r.vertical&&(n+=Math.PI/2);let o=c(this,Jh)&&r.fontSubstitution||r.fontFamily;o=Ut.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*v(m=Ut,Ke,Nb).call(m,o,c(this,Ir));let d,u;n===0?(d=i[4],u=i[5]-l):(d=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const g="calc(var(--scale-factor)*",f=e.style;c(this,He)===c(this,oa)?(f.left=`${(100*d/c(this,tl)).toFixed(2)}%`,f.top=`${(100*u/c(this,Zh)).toFixed(2)}%`):(f.left=`${g}${d.toFixed(2)}px)`,f.top=`${g}${u.toFixed(2)}px)`),f.fontSize=`${g}${(c(Ut,Ln)*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,c(this,Jh)&&(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]),y=Math.abs(t.transform[3]);_!==y&&Math.max(_,y)/Math.min(_,y)>1.5&&(p=!0)}if(p&&(s.canvasWidth=r.vertical?t.height:t.width),c(this,sl).set(e,s),c(this,Bi).div=e,c(this,Bi).properties=s,v(this,Hi,Tf).call(this,c(this,Bi)),s.hasText&&c(this,He).append(e),s.hasEOL){const _=document.createElement("br");_.setAttribute("role","presentation"),c(this,He).append(_)}},Tf=function(t){var o;const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(c(Ut,Ln)>1&&(r=`scale(${1/c(Ut,Ln)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:h}=n,{canvasWidth:l,fontSize:d}=s;v(o=Ut,Ke,Ef).call(o,i,d*c(this,Rn),h);const{width:u}=i.measureText(e.textContent);u>0&&(r=`scaleX(${l*c(this,Rn)/u}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)},Ke=new WeakSet,Ud=function(t=null){let e=c(this,Hr).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,Hr).set(t,e),c(this,nl).set(e,{size:0,family:""})}return e},Ef=function(t,e,s){const i=c(this,nl).get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)},jb=function(){if(c(this,Ln)!==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,Ln,t.getBoundingClientRect().height),t.remove()},Nb=function(t,e){const s=c(this,Br).get(t);if(s)return s;const i=v(this,Ke,Ud).call(this,e);i.canvas.width=i.canvas.height=Ne,v(this,Ke,Ef).call(this,i,Ne,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const d=r/(r+o);return c(this,Br).set(t,d),i.canvas.width=i.canvas.height=0,d}i.strokeStyle="red",i.clearRect(0,0,Ne,Ne),i.strokeText("g",0,0);let h=i.getImageData(0,0,Ne,Ne).data;o=0;for(let d=h.length-1-3;d>=0;d-=4)if(h[d]>0){o=Math.ceil(d/4/Ne);break}i.clearRect(0,0,Ne,Ne),i.strokeText("A",0,Ne),h=i.getImageData(0,0,Ne,Ne).data,r=0;for(let d=0,u=h.length;d<u;d+=4)if(h[d]>0){r=Ne-Math.floor(d/4/Ne);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):Hx;return c(this,Br).set(t,l),l},w(Ut,Ke),w(Ut,Br,new Map),w(Ut,Hr,new Map),w(Ut,nl,new WeakMap),w(Ut,Ln,null),w(Ut,ca,new Set);let yh=Ut;class _h{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(_h.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 Wx=65536,zx=100,Xx=5e3,Vx=fe?sx:Zw,Gx=fe?ix:_0,Yx=fe?ex:tx,Ux=fe?nx:S0;function qx(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?$x(a.url):null,i=a.data?Kx(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:Wx;let d=a.worker instanceof Ho?a.worker:null;const u=a.verbosity,g=typeof a.docBaseUrl=="string"&&!hd(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,p=a.cMapPacked!==!1,m=a.CMapReaderFactory||Gx,_=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,y=a.StandardFontDataFactory||Ux,x=a.stopAtErrors!==!0,S=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,C=a.isEvalSupported!==!1,E=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!fe,M=typeof a.isChrome=="boolean"?a.isChrome:!Ee.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),k=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,O=typeof a.disableFontFace=="boolean"?a.disableFontFace:fe,P=a.fontExtraProperties===!0,F=a.enableXfa===!0,R=a.ownerDocument||globalThis.document,W=a.disableRange===!0,B=a.disableStream===!0,X=a.disableAutoFetch===!0,K=a.pdfBug===!0,tt=a.CanvasFactory||Vx,V=a.FilterFactory||Yx,H=a.enableHWA===!0,Qt=h?h.length:a.length??NaN,Jt=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!fe&&!O,le=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:m===_0&&y===S0&&f&&_&&fh(f,document.baseURI)&&fh(_,document.baseURI);a.canvasFactory&&f0("`canvasFactory`-instance option, please use `CanvasFactory` instead."),a.filterFactory&&f0("`filterFactory`-instance option, please use `FilterFactory` instead.");const zt=null;Ow(u);const _t={canvasFactory:new tt({ownerDocument:R,enableHWA:H}),filterFactory:new V({docId:e,ownerDocument:R}),cMapReaderFactory:le?null:new m({baseUrl:f,isCompressed:p}),standardFontDataFactory:le?null:new y({baseUrl:_})};if(!d){const Pt={verbosity:u,port:Mi.workerPort};d=Pt.port?Ho.fromPort(Pt):new Ho(Pt),t._worker=d}const Pe={docId:e,apiVersion:"4.8.69",data:i,password:o,disableAutoFetch:X,rangeChunkSize:l,length:Qt,docBaseUrl:g,enableXfa:F,evaluatorOptions:{maxImageSize:S,disableFontFace:O,ignoreErrors:x,isEvalSupported:C,isOffscreenCanvasSupported:E,isChrome:M,canvasMaxAreaInBytes:k,fontExtraProperties:P,useSystemFonts:Jt,cMapUrl:le?f:null,standardFontDataUrl:le?_:null}},fi={disableFontFace:O,fontExtraProperties:P,ownerDocument:R,pdfBug:K,styleElement:zt,loadingParams:{disableAutoFetch:X,enableXfa:F}};return d.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const Pt=d.messageHandler.sendWithPromise("GetDocRequest",Pe,i?[i.buffer]:null);let dt;if(h)dt=new wx(h,{disableRange:W,disableStream:B});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let mo;fe?mo=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&fh(s)?N0:Rx:mo=fh(s)?N0:Mx,dt=new mo({url:s,length:Qt,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:W,disableStream:B})}return Pt.then(mo=>{if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const bo=new vh(e,mo,d.port),pi=new tS(bo,t,dt,fi,_t);t._transport=pi,bo.send("Ready",null)})}).catch(t._capability.reject),t}function $x(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(fe&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Kx(a){if(fe&&typeof Buffer<"u"&&a instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength)return a;if(typeof a=="string")return 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 z0(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 Dd=class Dd{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Fe(Dd,Od)._++}`,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)}};Od=new WeakMap,w(Dd,Od,0);let zg=Dd;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){yt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Qx{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return ot(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 Jx{constructor(t,e,s,i=!1){w(this,gs);w(this,In,null);w(this,Wi,!1);this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new g0: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 gh({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 ot(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=pn.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:d=null,isEditing:u=!1}){var C,E;(C=this._stats)==null||C.time("Overall");const g=this._transport.getRenderingIntent(s,i,d,u),{renderingIntent:f,cacheKey:p}=g;b(this,Wi,!1),v(this,gs,qd).call(this),o||(o=this._transport.getOptionalContentConfig(f));let m=this._intentStates.get(p);m||(m=Object.create(null),this._intentStates.set(p,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const _=!!(f&Ye.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(E=this._stats)==null||E.time("Page Request"),this._pumpOperatorList(g));const y=M=>{var k;m.renderTasks.delete(x),(this._maybeCleanupAfterRender||_)&&b(this,Wi,!0),v(this,gs,Va).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"),(k=globalThis.Stats)!=null&&k.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},x=new Xg({callback:y,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,k])=>{var O;if(this.destroyed){y();return}if((O=this._stats)==null||O.time("Rendering"),!(k.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:k}),x.operatorListChanged()}).catch(y),S}getOperatorList({intent:t="display",annotationMode:e=pn.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=>_h.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,Wi,!1),v(this,gs,qd).call(this),Promise.all(t)}cleanup(t=!1){b(this,Wi,!0);const e=v(this,gs,Va).call(this,!1);return t&&e&&this._stats&&(this._stats=new g0),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&&v(this,gs,Va).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();v(this,gs,Va).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 xg){let i=zx;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 cr(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}}In=new WeakMap,Wi=new WeakMap,gs=new WeakSet,Va=function(t=!1){if(v(this,gs,qd).call(this),!c(this,Wi)||this.destroyed)return!1;if(t)return b(this,In,setTimeout(()=>{b(this,In,null),v(this,gs,Va).call(this,!1)},Xx)),!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,Wi,!1),!0},qd=function(){c(this,In)&&(clearTimeout(c(this,In)),b(this,In,null))};class Zx{constructor(){w(this,zi,new Map);w(this,Pd,Promise.resolve())}postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};c(this,Pd).then(()=>{for(const[i]of c(this,zi))i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if((s==null?void 0:s.signal)instanceof AbortSignal){const{signal:n}=s;if(n.aborted){st("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}c(this,zi).set(e,i)}removeEventListener(t,e){const s=c(this,zi).get(e);s==null||s(),c(this,zi).delete(e)}terminate(){for(const[,t]of c(this,zi))t==null||t();c(this,zi).clear()}}zi=new WeakMap,Pd=new WeakMap;const St=class St{constructor({name:t=null,port:e=null,verbosity:s=Dw()}={}){w(this,da);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(St,zr))!=null&&i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(c(St,zr)||b(St,zr,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return fe?Promise.all([vn.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 vh("main","worker",t),this._messageHandler.on("ready",function(){}),v(this,da,$d).call(this)}_initialize(){if(c(St,Wr)||c(St,ua,Kd)){this._setupFakeWorker();return}let{workerSrc:t}=St;try{St._isSameOrigin(window.location.href,t)||(t=St._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new vh("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,v(this,da,$d).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(){c(St,Wr)||(st("Setting up fake worker."),b(St,Wr,!0)),St._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Zx;this._port=e;const s=`fake${Fe(St,Fd)._++}`,i=new vh(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new vh(s,s+"_worker",e),v(this,da,$d).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(St,zr))==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,zr))==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 St(t)}static get workerSrc(){if(Mi.workerSrc)return Mi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return ot(this,"_setupFakeWorkerGlobal",(async()=>c(this,ua,Kd)?c(this,ua,Kd):(await import(this.workerSrc)).WorkerMessageHandler)())}};Fd=new WeakMap,Wr=new WeakMap,zr=new WeakMap,da=new WeakSet,$d=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},ua=new WeakSet,Kd=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},w(St,ua),w(St,Fd,0),w(St,Wr,!1),w(St,zr),fe&&(b(St,Wr,!0),Mi.workerSrc||(Mi.workerSrc="./pdf.worker.mjs")),St._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},St._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let Ho=St;class tS{constructor(t,e,s,i,n){w(this,Xr);w(this,Xi,new Map);w(this,oi,new Map);w(this,ga,new Map);w(this,fa,new Map);w(this,ai,null);this.messageHandler=t,this.loadingTask=e,this.commonObjs=new V0,this.fontLoader=new Qw({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 ot(this,"annotationStorage",new Dg)}getRenderingIntent(t,e=pn.ENABLE,s=null,i=!1,n=!1){let r=Ye.DISPLAY,o=Og;switch(t){case"any":r=Ye.ANY;break;case"display":break;case"print":r=Ye.PRINT;break;default:st(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Ye.PRINT&&s instanceof b0?s:this.annotationStorage;switch(e){case pn.DISABLE:r+=Ye.ANNOTATIONS_DISABLE;break;case pn.ENABLE:break;case pn.ENABLE_FORMS:r+=Ye.ANNOTATIONS_FORMS;break;case pn.ENABLE_STORAGE:r+=Ye.ANNOTATIONS_STORAGE,o=h.serializable;break;default:st(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Ye.IS_EDITING),n&&(r+=Ye.OPLIST);const{ids:l,hash:d}=h.modifiedIds,u=[r,o.hash,d];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}destroy(){var s;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(s=c(this,ai))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const i of c(this,oi).values())t.push(i._destroy());c(this,oi).clear(),c(this,ga).clear(),c(this,fa).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,Xi).clear(),this.filterFactory.destroy(),yh.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new cr("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)=>{Gt(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}Gt(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",async s=>{var o;await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&((o=e.onProgress)==null||o.call(e,this._lastProgress)),this._fullReader.onProgress=h=>{var l;(l=e.onProgress)==null||l.call(e,{loaded:h.loaded,total:h.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{Gt(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}Gt(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 Qx(s,this))}),t.on("DocException",function(s){let i;switch(s.name){case"PasswordException":i=new mg(s.message,s.code);break;case"InvalidPDFException":i=new c0(s.message);break;case"MissingPDFException":i=new lr(s.message);break;case"UnexpectedResponseException":i=new rd(s.message,s.status);break;case"UnknownErrorException":i=new bg(s.message,s.details);break;default:yt("DocException - expected a valid Error.")}e._capability.reject(i)}),t.on("PasswordRequest",s=>{if(b(this,ai,Promise.withResolvers()),e.onPassword){const i=n=>{n instanceof Error?c(this,ai).reject(n):c(this,ai).resolve({password:n})};try{e.onPassword(i,s.code)}catch(n){c(this,ai).reject(n)}}else c(this,ai).reject(new mg(s.message,s.code));return c(this,ai).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,oi).get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{var r;if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:o,fontExtraProperties:h,pdfBug:l}=this._params;if("error"in n){const f=n.error;st(`Error during font loading: ${f}`),this.commonObjs.resolve(s,f);break}const d=l&&((r=globalThis.FontInspector)!=null&&r.enabled)?(f,p)=>globalThis.FontInspector.fontAdded(f,p):null,u=new Jw(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;Gt(g,"The imageRef must be defined.");for(const f of c(this,oi).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,oi).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)>Tw&&(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",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var s;this.annotationStorage.size<=0&&st("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((s=this._fullReader)==null?void 0:s.filename)??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=c(this,ga).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,fa).set(n.refStr,t);const r=new Jx(e,n,this,this._params.pdfBug);return c(this,oi).set(e,r),r});return c(this,ga).set(e,i),i}getPageIndex(t){return z0(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 v(this,Xr,Gl).call(this,"GetFieldObjects")}hasJSActions(){return v(this,Xr,Gl).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 v(this,Xr,Gl).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 v(this,Xr,Gl).call(this,"GetOptionalContentConfig").then(e=>new _x(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=c(this,Xi).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 vx(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,Xi).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,oi).values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),c(this,Xi).clear(),this.filterFactory.destroy(!0),yh.cleanup()}}cachedPageNumber(t){if(!z0(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return c(this,fa).get(e)??null}}Xi=new WeakMap,oi=new WeakMap,ga=new WeakMap,fa=new WeakMap,ai=new WeakMap,Xr=new WeakSet,Gl=function(t,e=null){const s=c(this,Xi).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return c(this,Xi).set(t,i),i};const pd=Symbol("INITIAL_DATA");class V0{constructor(){w(this,rl);w(this,Rs,Object.create(null))}get(t,e=null){if(e){const i=v(this,rl,kf).call(this,t);return i.promise.then(()=>e(i.data)),null}const s=c(this,Rs)[t];if(!s||s.data===pd)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=c(this,Rs)[t];return!!e&&e.data!==pd}resolve(t,e=null){const s=v(this,rl,kf).call(this,t);s.data=e,s.resolve()}clear(){var t;for(const e in c(this,Rs)){const{data:s}=c(this,Rs)[e];(t=s==null?void 0:s.bitmap)==null||t.close()}b(this,Rs,Object.create(null))}*[Symbol.iterator](){for(const t in c(this,Rs)){const{data:e}=c(this,Rs)[t];e!==pd&&(yield[t,e])}}}Rs=new WeakMap,rl=new WeakSet,kf=function(t){var e;return(e=c(this,Rs))[t]||(e[t]={...Promise.withResolvers(),data:pd})};class eS{constructor(t){w(this,jn,null);b(this,jn,t),this.onContinue=null}get promise(){return c(this,jn).capability.promise}cancel(t=0){c(this,jn).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=c(this,jn).operatorList;if(!t)return!1;const{annotationCanvasMap:e}=c(this,jn);return t.form||t.canvas&&(e==null?void 0:e.size)>0}}jn=new WeakMap;const Gr=class Gr{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,Nn,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 eS(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(Gr,Vr).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(Gr,Vr).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 No(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,Nn)&&(window.cancelAnimationFrame(c(this,Nn)),b(this,Nn,null)),c(Gr,Vr).delete(this._canvas),this.callback(t||new xg(`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,Nn,window.requestAnimationFrame(()=>{b(this,Nn,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(Gr,Vr).delete(this._canvas),this.callback())))}};Nn=new WeakMap,Vr=new WeakMap,w(Gr,Vr,new WeakSet);let Xg=Gr;const sS="4.8.69",iS="3634dab10";function G0(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function wh(a){return Math.max(0,Math.min(255,255*a))}class Y0{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=wh(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(wh)}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[wh(1-Math.min(1,t+i)),wh(1-Math.min(1,s+i)),wh(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 nS{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){yt("Abstract method `_createSVG` called.")}}class Vg extends nS{_createSVG(t){return document.createElementNS(Ei,t)}}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&&_h.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:y}=_;if(y==="#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,y):document.createElement(y);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&&_h.shouldBuildText(y)&&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 xh=1e3,rS=9,gr=new WeakSet;function Oi(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class oS{static create(t){switch(t.data.annotationType){case Vt.LINK:return new q0(t);case Vt.TEXT:return new aS(t);case Vt.WIDGET:switch(t.data.fieldType){case"Tx":return new hS(t);case"Btn":return t.data.radioButton?new $0(t):t.data.checkBox?new cS(t):new dS(t);case"Ch":return new uS(t);case"Sig":return new lS(t)}return new fr(t);case Vt.POPUP:return new Gg(t);case Vt.FREETEXT:return new K0(t);case Vt.LINE:return new fS(t);case Vt.SQUARE:return new pS(t);case Vt.CIRCLE:return new mS(t);case Vt.POLYLINE:return new Q0(t);case Vt.CARET:return new vS(t);case Vt.INK:return new Yg(t);case Vt.POLYGON:return new bS(t);case Vt.HIGHLIGHT:return new J0(t);case Vt.UNDERLINE:return new yS(t);case Vt.SQUIGGLY:return new _S(t);case Vt.STRIKEOUT:return new wS(t);case Vt.STAMP:return new Z0(t);case Vt.FILEATTACHMENT:return new xS(t);default:return new Lt(t)}}}const sf=class sf{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){w(this,ol);w(this,Yr,null);w(this,pa,!1);w(this,ma,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,Yr)||b(this,Yr,{rect:this.data.rect.slice(0)});const{rect:e}=t;e&&v(this,ol,Mf).call(this,e),(s=c(this,ma))==null||s.popup.updateEdited(t)}resetEdited(){var t;c(this,Yr)&&(v(this,ol,Mf).call(this,c(this,Yr).rect),(t=c(this,ma))==null||t.popup.resetEdited(),b(this,Yr,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 fr||(n.tabIndex=xh);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,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}=Oi(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 uh.SOLID:r.borderStyle="solid";break;case uh.DASHED:r.borderStyle="dashed";break;case uh.BEVELED:st("Unimplemented border style: beveled");break;case uh.INSET:st("Unimplemented border style: inset");break;case uh.UNDERLINE:r.borderBottomStyle="solid";break}const y=e.borderColor||null;y?(b(this,pa,!0),r.borderColor=z.makeHexColor(y[0]|0,y[1]|0,y[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}=Oi(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]=Y0[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:Y0[`${r}_rgb`](o)})};return ot(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,_,y,x]=t.subarray(2,6);if(i===m&&n===_&&e===y&&s===x)return}const{style:r}=this.container;let o;if(c(this,pa)){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 y=t[m],x=t[m+1],S=t[m+2],C=t[m+3],E=d.createElement("rect"),M=(S-e)/h,k=(n-x)/l,O=(y-S)/h,P=(x-C)/l;E.setAttribute("x",M),E.setAttribute("y",k),E.setAttribute("width",O),E.setAttribute("height",P),f.append(E),o==null||o.push(`<rect vector-effect="non-scaling-stroke" x="${M}" y="${k}" width="${O}" height="${P}"/>`)}c(this,pa)&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=b(this,ma,new Gg({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(e.render())}render(){yt("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&&!gr.has(l)){st(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&gr.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})})}};Yr=new WeakMap,pa=new WeakMap,ma=new WeakMap,ol=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}=Oi(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 Lt=sf;class q0 extends Lt{constructor(e,s=null){super(e,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});w(this,Qe);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?(v(this,Qe,Bb).call(this,i,e.attachment,e.attachmentDest),n=!0):e.setOCGState?(v(this,Qe,Hb).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==="")&&v(this,Qe,vo).call(this)}_bindNamedAction(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(s),!1),v(this,Qe,vo).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),v(this,Qe,vo).call(this)}_bindResetFormAction(e,s){const i=e.onclick;if(i||(e.href=this.linkService.getAnchorUrl("")),v(this,Qe,vo).call(this),!this._fieldObjects){st('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(e.onclick=()=>!1);return}e.onclick=()=>{var u;i==null||i();const{fields:n,refs:r,include:o}=s,h=[];if(n.length!==0||r.length!==0){const g=new Set(r);for(const f of n){const p=this._fieldObjects[f]||[];for(const{id:m}of p)g.add(m)}for(const f of Object.values(this._fieldObjects))for(const p of f)g.has(p.id)===o&&h.push(p)}else for(const g of Object.values(this._fieldObjects))h.push(...g);const l=this.annotationStorage,d=[];for(const g of h){const{id:f}=g;switch(d.push(f),g.type){case"text":{const m=g.defaultValue||"";l.setValue(f,{value:m});break}case"checkbox":case"radiobutton":{const m=g.defaultValue===g.exportValues;l.setValue(f,{value:m});break}case"combobox":case"listbox":{const m=g.defaultValue||"";l.setValue(f,{value:m});break}default:continue}const p=document.querySelector(`[data-element-id="${f}"]`);if(p){if(!gr.has(p)){st(`_bindResetFormAction - element not allowed: ${f}`);continue}}else continue;p.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((u=this.linkService.eventBus)==null||u.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:d,name:"ResetForm"}})),!1}}}Qe=new WeakSet,vo=function(){this.container.setAttribute("data-internal-link","")},Bb=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},v(this,Qe,vo).call(this)},Hb=function(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(s),!1),v(this,Qe,vo).call(this)};class aS extends Lt{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 fr extends Lt{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 Ee.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||rS,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/(pg*i))||1,u=l/d;r=Math.min(i,h(u/pg))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/pg))}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 hS extends fr{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),gr.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=xh,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:y}=m;if(_===0){y.removeAttribute("maxLength");return}y.setAttribute("maxLength",_);let x=d.userValue;!x||x.length<=_||(x=x.slice(0,_),y.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:y.selectionStart,selEnd:y.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:y,selectionEnd:x}=m;let S=y,C=x;switch(f.inputType){case"deleteWordBackward":{const M=_.substring(0,y).match(/\w*[^\w]*$/);M&&(S-=M[0].length);break}case"deleteWordForward":{const M=_.substring(y).match(/^[^\w]*\w*/);M&&(C+=M[0].length);break}case"deleteContentBackward":y===x&&(S-=1);break;case"deleteContentForward":y===x&&(C+=1);break}f.preventDefault(),(E=this.linkService.eventBus)==null||E.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:_,change:p||"",willCommit:!1,selStart:S,selEnd:C}})}),this._setEventListeners(s,d,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],f=>f.target.value)}if(u&&s.addEventListener("blur",u),this.data.comb){const f=(this.data.rect[2]-this.data.rect[0])/h;s.classList.add("comb"),s.style.letterSpacing=`calc(${f}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class lS extends fr{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class cS extends fr{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 gr.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=xh,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 fr{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(gr.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=xh,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 dS 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 uS extends fr{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");gr.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=xh;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],y=document.createElement("option");y.textContent=p,y.value=m,_?_.before(y):i.append(y),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,y=document.createElement("option");y.textContent=m,y.value=_,i.append(y)}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 Lt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Lt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new gS({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,s.container.ariaHasPopup="dialog",e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${wg}${s}`).join(",")),this.container}}class gS{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,ba,v(this,mt,Xb).bind(this));w(this,Rd,v(this,mt,Df).bind(this));w(this,Ld,v(this,mt,Zd).bind(this));w(this,va,v(this,mt,Jd).bind(this));w(this,Ur,null);w(this,Dt,null);w(this,Vi,null);w(this,ya,null);w(this,al,null);w(this,hl,null);w(this,_a,null);w(this,Gi,!1);w(this,Ls,null);w(this,Yi,null);w(this,ll,null);w(this,Ui,null);w(this,cl,null);w(this,qr,null);w(this,$r,!1);var g;b(this,Dt,t),b(this,cl,i),b(this,Vi,r),b(this,Ui,o),b(this,hl,h),b(this,Ur,e),b(this,ll,l),b(this,_a,d),b(this,al,s),b(this,ya,Cg.toDateObject(n)),this.trigger=s.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",c(this,va)),f.addEventListener("mouseenter",c(this,Ld)),f.addEventListener("mouseleave",c(this,Rd)),f.classList.add("popupTriggerArea");for(const f of s)(g=f.container)==null||g.addEventListener("keydown",c(this,ba));c(this,Dt).hidden=!0,u&&v(this,mt,Jd).call(this)}render(){if(c(this,Ls))return;const t=b(this,Ls,document.createElement("div"));if(t.className="popup",c(this,Ur)){const n=t.style.outlineColor=z.makeHexColor(...c(this,Ur));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,Ur).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,cl),t.append(e),c(this,ya)){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:c(this,ya).valueOf()})),e.append(n)}const i=c(this,mt,Qd);if(i)U0.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(c(this,Vi));t.append(n)}c(this,Dt).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,qr)||b(this,qr,{contentsObj:c(this,Vi),richText:c(this,Ui)}),t&&b(this,Yi,null),e&&(b(this,Ui,v(this,mt,zb).call(this,e)),b(this,Vi,null)),(s=c(this,Ls))==null||s.remove(),b(this,Ls,null)}resetEdited(){var t;c(this,qr)&&({contentsObj:Fe(this,Vi)._,richText:Fe(this,Ui)._}=c(this,qr),b(this,qr,null),(t=c(this,Ls))==null||t.remove(),b(this,Ls,null),b(this,Yi,null))}forceHide(){b(this,$r,this.isVisible),c(this,$r)&&(c(this,Dt).hidden=!0)}maybeShow(){c(this,$r)&&(c(this,Ls)||v(this,mt,Zd).call(this),b(this,$r,!1),c(this,Dt).hidden=!1)}get isVisible(){return c(this,Dt).hidden===!1}}ba=new WeakMap,Rd=new WeakMap,Ld=new WeakMap,va=new WeakMap,Ur=new WeakMap,Dt=new WeakMap,Vi=new WeakMap,ya=new WeakMap,al=new WeakMap,hl=new WeakMap,_a=new WeakMap,Gi=new WeakMap,Ls=new WeakMap,Yi=new WeakMap,ll=new WeakMap,Ui=new WeakMap,cl=new WeakMap,qr=new WeakMap,$r=new WeakMap,mt=new WeakSet,Qd=function(){const t=c(this,Ui),e=c(this,Vi);return t!=null&&t.str&&(!(e!=null&&e.str)||e.str===t.str)&&c(this,Ui).html||null},Of=function(){var t,e,s;return((s=(e=(t=c(this,mt,Qd))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.fontSize)||0},Wb=function(){var t,e,s;return((s=(e=(t=c(this,mt,Qd))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.color)||null},zb=function(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:c(this,mt,Wb),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},Xb=function(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&c(this,Gi))&&v(this,mt,Jd).call(this)},Vb=function(){if(c(this,Yi)!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=c(this,hl);let r=!!c(this,_a),o=r?c(this,_a):c(this,ll);for(const p of c(this,al))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,Yi,[100*(u-i)/e,100*(g-n)/s]);const{style:f}=c(this,Dt);f.left=`${c(this,Yi)[0]}%`,f.top=`${c(this,Yi)[1]}%`},Jd=function(){b(this,Gi,!c(this,Gi)),c(this,Gi)?(v(this,mt,Zd).call(this),c(this,Dt).addEventListener("click",c(this,va)),c(this,Dt).addEventListener("keydown",c(this,ba))):(v(this,mt,Df).call(this),c(this,Dt).removeEventListener("click",c(this,va)),c(this,Dt).removeEventListener("keydown",c(this,ba)))},Zd=function(){c(this,Ls)||this.render(),this.isVisible?c(this,Gi)&&c(this,Dt).classList.add("focused"):(v(this,mt,Vb).call(this),c(this,Dt).hidden=!1,c(this,Dt).style.zIndex=parseInt(c(this,Dt).style.zIndex)+1e3)},Df=function(){c(this,Dt).classList.remove("focused"),!(c(this,Gi)||!this.isVisible)&&(c(this,Dt).hidden=!0,c(this,Dt).style.zIndex=parseInt(c(this,Dt).style.zIndex)-1e3)};class K0 extends Lt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=Z.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 fS extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,dl,null)}render(){this.container.classList.add("lineAnnotation");const e=this.data,{width:s,height:i}=Oi(e.rect),n=this.svgFactory.create(s,i,!0),r=b(this,dl,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,dl)}addHighlightArea(){this.container.classList.add("highlightArea")}}dl=new WeakMap;class pS extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,ul,null)}render(){this.container.classList.add("squareAnnotation");const e=this.data,{width:s,height:i}=Oi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,ul,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,ul)}addHighlightArea(){this.container.classList.add("highlightArea")}}ul=new WeakMap;class mS extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,gl,null)}render(){this.container.classList.add("circleAnnotation");const e=this.data,{width:s,height:i}=Oi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,gl,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,gl)}addHighlightArea(){this.container.classList.add("highlightArea")}}gl=new WeakMap;class Q0 extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,fl,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}=Oi(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,fl,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,fl)}addHighlightArea(){this.container.classList.add("highlightArea")}}fl=new WeakMap;class bS extends Q0{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class vS extends Lt{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 Yg extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,pl,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?Z.HIGHLIGHT:Z.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{width:r,height:o}=Oi(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,pl).push(u),u.setAttribute("points",d),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),h.append(u)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(h),this._editOnDoubleClick(),this.container}getElementsToTriggerPopup(){return c(this,pl)}addHighlightArea(){this.container.classList.add("highlightArea")}}pl=new WeakMap;class J0 extends Lt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=Z.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class yS extends Lt{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 _S extends Lt{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 wS extends Lt{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 Lt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=Z.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class xS extends Lt{constructor(e){var i;super(e,{isRenderable:!0});w(this,bl);w(this,ml,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",v(this,bl,Pf).bind(this)),b(this,ml,i);const{isMac:n}=Ee.platform;return e.addEventListener("keydown",r=>{r.key==="Enter"&&(n?r.metaKey:r.ctrlKey)&&v(this,bl,Pf).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),e.append(i),e}getElementsToTriggerPopup(){return c(this,ml)}addHighlightArea(){this.container.classList.add("highlightArea")}}ml=new WeakMap,bl=new WeakSet,Pf=function(){var e;(e=this.downloadManager)==null||e.openOrDownloadData(this.content,this.filename)};class SS{constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){w(this,Jr);w(this,vl,null);w(this,Kr,null);w(this,Qr,new Map);w(this,yl,null);this.div=t,b(this,vl,e),b(this,Kr,s),b(this,yl,o||null),this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return c(this,Qr).size>0}async render(t){var r;const{annotations:e}=t,s=this.div;dr(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new Vg,annotationStorage:t.annotationStorage||new Dg,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===Vt.POPUP;if(h){const u=i.get(o.id);if(!u)continue;n.elements=u}else{const{width:u,height:g}=Oi(o.rect);if(u<=0||g<=0)continue}n.data=o;const l=oS.create(n);if(!l.isRenderable)continue;if(!h&&o.popupRef){const u=i.get(o.popupRef);u?u.push(l):i.set(o.popupRef,[l])}const d=l.render();o.hidden&&(d.style.visibility="hidden"),await v(this,Jr,Gb).call(this,d,o.id),l._isEditable&&(c(this,Qr).set(l.data.id,l),(r=this._annotationEditorUIManager)==null||r.renderAnnotationElement(l))}v(this,Jr,Ff).call(this)}update({viewport:t}){const e=this.div;this.viewport=t,dr(e,{rotation:t.rotation}),v(this,Jr,Ff).call(this),e.hidden=!1}getEditableAnnotations(){return Array.from(c(this,Qr).values())}getEditableAnnotation(t){return c(this,Qr).get(t)}}vl=new WeakMap,Kr=new WeakMap,Qr=new WeakMap,yl=new WeakMap,Jr=new WeakSet,Gb=async function(t,e){var r,o;const s=t.firstChild||t,i=s.id=`${wg}${e}`,n=await((r=c(this,yl))==null?void 0:r.getAriaAttributes(i));if(n)for(const[h,l]of n)s.setAttribute(h,l);this.div.append(t),(o=c(this,vl))==null||o.moveElementInDOM(this.div,t,s,!1)},Ff=function(){if(!c(this,Kr))return;const t=this.div;for(const[e,s]of c(this,Kr)){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,Kr).clear()};const md=/\r\n?|\n/g,vt=class vt extends gt{constructor(e){super({...e,name:"freeTextEditor"});w(this,Ht);w(this,Is);w(this,Je,"");w(this,_l,`${this.id}-editor`);w(this,Zr,null);w(this,Ze);b(this,Is,e.color||vt._defaultColor||gt._defaultLineColor),b(this,Ze,e.fontSize||vt._defaultFontSize)}static get _keyboardManager(){const e=vt.prototype,s=r=>r.isEmpty(),i=ur.TRANSLATE_SMALL,n=ur.TRANSLATE_BIG;return ot(this,"_keyboardManager",new ph([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],e.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],e.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],e._translateEmpty,{args:[-i,0],checker:s}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e._translateEmpty,{args:[-n,0],checker:s}],[["ArrowRight","mac+ArrowRight"],e._translateEmpty,{args:[i,0],checker:s}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e._translateEmpty,{args:[n,0],checker:s}],[["ArrowUp","mac+ArrowUp"],e._translateEmpty,{args:[0,-i],checker:s}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e._translateEmpty,{args:[0,-n],checker:s}],[["ArrowDown","mac+ArrowDown"],e._translateEmpty,{args:[0,i],checker:s}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e._translateEmpty,{args:[0,n],checker:s}]]))}static initialize(e,s){gt.initialize(e,s);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,s){switch(e){case U.FREETEXT_SIZE:vt._defaultFontSize=s;break;case U.FREETEXT_COLOR:vt._defaultColor=s;break}}updateParams(e,s){switch(e){case U.FREETEXT_SIZE:v(this,Ht,Yb).call(this,s);break;case U.FREETEXT_COLOR:v(this,Ht,Ub).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[U.FREETEXT_SIZE,vt._defaultFontSize],[U.FREETEXT_COLOR,vt._defaultColor||gt._defaultLineColor]]}get propertiesToUpdate(){return[[U.FREETEXT_SIZE,c(this,Ze)],[U.FREETEXT_COLOR,c(this,Is)]]}_translateEmpty(e,s){this._uiManager.translateSelectedEditors(e,s,!0)}getInitialTranslation(){const e=this.parentScale;return[-vt._internalPadding*e,-(vt._internalPadding+c(this,Ze))*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(Z.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),b(this,Zr,new AbortController);const e=this._uiManager.combinedSignal(c(this,Zr));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:e})}disableEditMode(){var e;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",c(this,_l)),this._isDraggable=!0,(e=c(this,Zr))==null||e.abort(),b(this,Zr,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var e;this.width||(this.enableEditMode(),this.editorDiv.focus(),(e=this._initialOptions)!=null&&e.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const e=c(this,Je),s=b(this,Je,v(this,Ht,qb).call(this).trimEnd());if(e===s)return;const i=n=>{if(b(this,Je,n),!n){this.remove();return}v(this,Ht,su).call(this),this._uiManager.rebuild(this),v(this,Ht,tu).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(e)},mustExec:!1}),v(this,Ht,tu).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){vt._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,_l)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${c(this,Ze)}px * var(--scale-factor))`,i.color=c(this,Is),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),ld(this,this.div,["dblclick","keydown"]),this.width){const[n,r]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[h,l]=this.getInitialTranslation();[h,l]=this.pageTranslationToScreen(h,l);const[d,u]=this.pageDimensions,[g,f]=this.pageTranslation;let p,m;switch(this.rotation){case 0:p=e+(o[0]-g)/d,m=s+this.height-(o[1]-f)/u;break;case 90:p=e+(o[0]-g)/d,m=s-(o[1]-f)/u,[h,l]=[l,-h];break;case 180:p=e-this.width+(o[0]-g)/d,m=s-(o[1]-f)/u,[h,l]=[-h,-l];break;case 270:p=e+(o[0]-g-this.height*u)/d,m=s+(o[1]-f-this.width*d)/u,[h,l]=[-l,h];break}this.setAt(p*n,m*r,h,l)}else this.setAt(e*n,s*r,this.width*n,this.height*r);v(this,Ht,su).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=v(p=vt,qi,Rf).call(p,s.getData("text")||"").replaceAll(md,`
498
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=Math.max(e[i],e[i+1],e[i+2]),r=(e[i]+e[i+1]+e[i+2])/3,o=2*Math.abs(n-r)/255*s;e[i]+=n!==e[i]?(n-e[i])*o:0,e[i+1]+=n!==e[i+1]?(n-e[i+1])*o:0,e[i+2]+=n!==e[i+2]?(n-e[i+2])*o:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}A(td,"type","Vibrance"),A(td,"defaults",{vibrance:0}),A(td,"uniformLocations",["uVibrance"]),N.setClass(td);const aw="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 hw(a){return new URL(Object.assign({"../assets/close.svg":aw})[`../assets/${a}`],typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Ct&&Ct.tagName.toUpperCase()==="SCRIPT"&&Ct.src||new URL("pdf-canvas.umd.js",document.baseURI).href).href}function lw(a){return new Promise((t,e)=>{const s=window.URL.createObjectURL(a),i=new Image;i.src=s,i.addEventListener("load",async()=>{window.URL.revokeObjectURL(s),t(await cw(i))}),i.addEventListener("error",n=>{window.URL.revokeObjectURL(s),e(n)})})}function cw(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 r0=null;function dw(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function uw(){const a=r0??dw();return r0=a,a/72}function gw(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 as=new Map;function fw(a){const t=new eg(a);return as.set(a,t),t}function pw(a,t){const e=Date.now();return{PDFId:`${a.name}-${e}`,name:a.name.replace(/.pdf/,""),updateDate:e,PDFBase64:t}}function mw(a,t){const e=a.getViewport({scale:t}),s=document.createElement("canvas"),i=s.getContext("2d"),n=uw()/window.devicePixelRatio;s.width=Math.floor(e.width*n),s.height=Math.floor(e.height*n);const r={canvasContext:i,viewport:e,transform:[n,0,0,n,0,0]},o=a.render(r);return{canvas:s,renderTask:o}}async function bw(a,t,e){const s=a||hw("close.svg"),{objects:i,options:n}=await Q_(s),r=i.filter(h=>h!==null),o=d_.groupSVGElements(r,n);return r.forEach(h=>{h.stroke=t}),o.hoverCursor="pointer",o.stroke=`${t}-${e}`,o}function vw(a,t){if(!as.get(a))return;const s=1/3,i=Cw(t,s);a0(a,i,s)}async function yw(a,t){const e=await lw(t),s=Date.now(),n={PDFId:`${t.name}${s}`,name:t.name.replace(/.png|.jpg|.jpeg/,""),updateDate:s,PDFBase64:e};return o0(a,{url:e}),{...n,pages:1}}async function o0(a,{url:t,scale:e=.5}){if(!as.get(a))return;const i=await ge.fromURL(t);i.scale(e),a0(a,i,e)}function a0(a,t,e){const s=as.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function ch(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function _w(a,t,e){!e||!a||(e.scale(1/t),ch(a,e))}function ww(a,t,e){a&&(a.borderScaleFactor=1/t,a.cornerSize=6*(1/t),a.touchCornerSize=24*(1/t),a.cornerStrokeColor=e.stroke,a.setCoords())}function xw(a){const t=as.get(a);t&&(t.discardActiveObject(),t.renderAll())}function Sw(a){const t=as.get(a);t&&(t.clear(),as.delete(a))}function Cw(a,t){return new ge(a,{scaleX:t,scaleY:t})}var dh={};dh.d=(a,t)=>{for(var e in t)dh.o(t,e)&&!dh.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},dh.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var $=globalThis.pdfjsLib={};dh.d($,{AbortException:()=>cr,AnnotationEditorLayer:()=>Qg,AnnotationEditorParamsType:()=>U,AnnotationEditorType:()=>Z,AnnotationEditorUIManager:()=>ur,AnnotationLayer:()=>xS,AnnotationMode:()=>pn,ColorPicker:()=>vd,DOMSVGFactory:()=>Vg,DrawLayer:()=>Jg,FeatureTest:()=>Ee,GlobalWorkerOptions:()=>Mi,ImageKind:()=>ed,InvalidPDFException:()=>l0,MissingPDFException:()=>lr,OPS:()=>Es,OutputScale:()=>Tg,PDFDataRangeTransport:()=>z0,PDFDateString:()=>Cg,PDFWorker:()=>Ho,PasswordResponses:()=>kw,PermissionFlag:()=>Ew,PixelsPerInch:()=>bn,RenderingCancelledException:()=>xg,TextLayer:()=>yh,UnexpectedResponseException:()=>rd,Util:()=>z,VerbosityLevel:()=>sd,XfaLayer:()=>Y0,build:()=>sS,createValidAbsoluteUrl:()=>Pw,fetchData:()=>ad,getDocument:()=>Ux,getFilenameFromUrl:()=>Ww,getPdfFilenameFromUrl:()=>zw,getXfaPageViewport:()=>Xw,isDataScheme:()=>hd,isPdfFile:()=>Sg,noContextMenu:()=>hs,normalizeUnicode:()=>Nw,setLayerDimensions:()=>dr,shadow:()=>ot,version:()=>eS});const fe=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),h0=[1,0,0,1,0,0],fg=[.001,0,0,.001,0,0],Aw=1e7,pg=1.35,Ye={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},pn={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Tw="pdfjs_internal_editor_",Z={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},U={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},Ew={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},pe={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},ed={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Vt={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},uh={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},sd={ERRORS:0,WARNINGS:1,INFOS:5},Es={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},kw={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let id=sd.WARNINGS;function Mw(a){Number.isInteger(a)&&(id=a)}function Ow(){return id}function nd(a){id>=sd.INFOS&&console.log(`Info: ${a}`)}function st(a){id>=sd.WARNINGS&&console.log(`Warning: ${a}`)}function yt(a){throw new Error(a)}function Gt(a,t){a||yt(t)}function Dw(a){switch(a==null?void 0:a.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Pw(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=jw(a)}catch{}}const s=t?new URL(a,t):new URL(a);if(Dw(s))return s}catch{}return null}function ot(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const mn=function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class mg extends mn{constructor(t,e){super(t,"PasswordException"),this.code=e}}class bg extends mn{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class l0 extends mn{constructor(t){super(t,"InvalidPDFException")}}class lr extends mn{constructor(t){super(t,"MissingPDFException")}}class rd extends mn{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Fw extends mn{constructor(t){super(t,"FormatError")}}class cr extends mn{constructor(t){super(t,"AbortException")}}function c0(a){(typeof a!="object"||(a==null?void 0:a.length)===void 0)&&yt("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"&&yt("Invalid argument for stringToBytes");const t=a.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=a.charCodeAt(s)&255;return e}function Rw(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function vg(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function Lw(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function Iw(){try{return new Function(""),!0}catch{return!1}}class Ee{static get isLittleEndian(){return ot(this,"isLittleEndian",Lw())}static get isEvalSupported(){return ot(this,"isEvalSupported",Iw())}static get isOffscreenCanvasSupported(){return ot(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?ot(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):ot(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,e;return ot(this,"isCSSRoundSupported",(e=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:e.call(t,"width: round(1.5px, 1px)"))}}const yg=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class z{static makeHexColor(t,e,s){return`#${yg[t]}${yg[e]}${yg[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)],v(this,Di,nf).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),v(this,Di,nf).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}}Di=new WeakSet,Bd=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)},nf=function(t,e,s,i,n,r,o,h,l,d,u,g){if(Math.abs(l)<1e-12){Math.abs(d)>=1e-12&&v(this,Di,Bd).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;v(this,Di,Bd).call(this,t,e,s,i,n,r,o,h,(-d+p)/m,g),v(this,Di,Bd).call(this,t,e,s,i,n,r,o,h,(-d-p)/m,g)},w(z,Di);function jw(a){return decodeURIComponent(escape(a))}let _g=null,d0=null;function Nw(a){return _g||(_g=/([\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,d0=new Map([["ſt","ſt"]])),a.replaceAll(_g,(t,e,s)=>e?e.normalize("NFKC"):d0.get(s))}function Bw(){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 c0(a)}const wg="pdfjs_internal_id_",Ti={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};function Hw(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(c0(a))}const Ei="http://www.w3.org/2000/svg",pr=class pr{};q(pr,"CSS",96),q(pr,"PDF",72),q(pr,"PDF_TO_CSS_UNITS",pr.CSS/pr.PDF);let bn=pr;async function ad(a,t="text"){if(fh(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 gh{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 ot(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 gh({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 xg extends mn{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function hd(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function Sg(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function Ww(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function zw(a,t="document.pdf"){if(typeof a!="string")return t;if(hd(a))return st('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(a);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class u0{constructor(){q(this,"started",Object.create(null));q(this,"times",[])}time(t){t in this.started&&st(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||st(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
499
+ `);return t.join("")}}function fh(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function hs(a){a.preventDefault()}function g0(a){console.log("Deprecated API usage: "+a)}class Cg{static toDateObject(t){if(!t||typeof t!="string")return null;c(this,Sh)||b(this,Sh,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const e=c(this,Sh).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))}}Sh=new WeakMap,w(Cg,Sh);function Xw(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new gh({viewBox:n,scale:t,rotation:e})}function Ag(a){if(a.startsWith("#")){const t=parseInt(a.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return a.startsWith("rgb(")?a.slice(4,-1).split(",").map(t=>parseInt(t)):a.startsWith("rgba(")?a.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(st(`Not a valid color format: "${a}"`),[0,0,0])}function Vw(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,Ag(s))}t.remove()}function Tt(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function ki(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 dr(a,t,e=!1,s=!0){if(t instanceof gh){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Ee.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,d=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=d,r.height=u):(r.width=u,r.height=d)}s&&a.setAttribute("data-main-rotation",t.rotation)}class Tg{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}const Pi=class Pi{constructor(t){w(this,Me);w(this,yn,null);w(this,mr,null);w(this,ks);w(this,br,null);w(this,Ch,null);b(this,ks,t),c(Pi,Ah)||b(Pi,Ah,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=b(this,yn,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=c(this,ks)._uiManager._signal;t.addEventListener("contextmenu",hs,{signal:e}),t.addEventListener("pointerdown",v(Pi,wd,rb),{signal:e});const s=b(this,br,document.createElement("div"));s.className="buttons",t.append(s);const i=c(this,ks).toolbarPosition;if(i){const{style:n}=t,r=c(this,ks)._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return v(this,Me,hb).call(this),t}get div(){return c(this,yn)}hide(){var t;c(this,yn).classList.add("hidden"),(t=c(this,mr))==null||t.hideDropdown()}show(){var t;c(this,yn).classList.remove("hidden"),(t=c(this,Ch))==null||t.shown()}async addAltText(t){const e=await t.render();v(this,Me,Hd).call(this,e),c(this,br).prepend(e,c(this,Me,rf)),b(this,Ch,t)}addColorPicker(t){b(this,mr,t);const e=t.renderButton();v(this,Me,Hd).call(this,e),c(this,br).prepend(e,c(this,Me,rf))}remove(){var t;c(this,yn).remove(),(t=c(this,mr))==null||t.destroy(),b(this,mr,null)}};yn=new WeakMap,mr=new WeakMap,ks=new WeakMap,br=new WeakMap,Ch=new WeakMap,Ah=new WeakMap,wd=new WeakSet,rb=function(t){t.stopPropagation()},Me=new WeakSet,ob=function(t){c(this,ks)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},ab=function(t){c(this,ks)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},Hd=function(t){const e=c(this,ks)._uiManager._signal;t.addEventListener("focusin",v(this,Me,ob).bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",v(this,Me,ab).bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",hs,{signal:e})},hb=function(){const{editorType:t,_uiManager:e}=c(this,ks),s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",c(Pi,Ah)[t]),v(this,Me,Hd).call(this,s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),c(this,br).append(s)},rf=function(){const t=document.createElement("div");return t.className="divider",t},w(Pi,wd),w(Pi,Ah,null);let Eg=Pi;class Gw{constructor(t){w(this,_n);w(this,Th,null);w(this,vr,null);w(this,yr);b(this,yr,t)}show(t,e,s){const[i,n]=v(this,_n,cb).call(this,e,s),{style:r}=c(this,vr)||b(this,vr,v(this,_n,lb).call(this));t.append(c(this,vr)),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){c(this,vr).remove()}}Th=new WeakMap,vr=new WeakMap,yr=new WeakMap,_n=new WeakSet,lb=function(){const t=b(this,vr,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",hs,{signal:c(this,yr)._signal});const e=b(this,Th,document.createElement("div"));return e.className="buttons",t.append(e),v(this,_n,db).call(this),t},cb=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]},db=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,yr)._signal;t.addEventListener("contextmenu",hs,{signal:s}),t.addEventListener("click",()=>{c(this,yr).highlightSelection("floating_button")},{signal:s}),c(this,Th).append(t)};function ld(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}function Yw(a){return Math.round(Math.min(255,Math.max(1,255*a))).toString(16).padStart(2,"0")}class Uw{constructor(){w(this,xd,0)}get id(){return`${Tw}${Fe(this,xd)._++}`}}xd=new WeakMap;const Zg=class Zg{constructor(){w(this,zo);w(this,Wo,Bw());w(this,Eh,0);w(this,me,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 ot(this,"_isSVGFittingCanvas",n)}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return v(this,zo,Wd).call(this,`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return v(this,zo,Wd).call(this,t,t)}async getFromBlob(t,e){const s=await e;return v(this,zo,Wd).call(this,t,s)}async getFromId(t){c(this,me)||b(this,me,new Map);const e=c(this,me).get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){c(this,me)||b(this,me,new Map);let s=c(this,me).get(t);if(s!=null&&s.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${c(this,Wo)}_${Fe(this,Eh)._++}`,refCounter:1,isSvg:!1},c(this,me).set(t,s),c(this,me).set(s.id,s),s}getSvgUrl(t){const e=c(this,me).get(t);return e!=null&&e.isSvg?e.svgUrl:null}deleteId(t){var i;c(this,me)||b(this,me,new Map);const e=c(this,me).get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const n=new OffscreenCanvas(s.width,s.height);n.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=n.convertToBlob()}(i=s.close)==null||i.call(s),e.bitmap=null}isValidId(t){return t.startsWith(`image_${c(this,Wo)}_`)}};Wo=new WeakMap,Eh=new WeakMap,me=new WeakMap,zo=new WeakSet,Wd=async function(t,e){c(this,me)||b(this,me,new Map);let s=c(this,me).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,Wo)}_${Fe(this,Eh)._++}`,refCounter:0,isSvg:!1});let i;if(typeof e=="string"?(s.url=e,i=await ad(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=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,me).set(t,s),s&&c(this,me).set(s.id,s),s};let kg=Zg;class qw{constructor(t=128){w(this,Zt,[]);w(this,wn,!1);w(this,kh);w(this,te,-1);b(this,kh,t)}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),c(this,wn))return;const h={cmd:t,undo:e,post:s,type:n};if(c(this,te)===-1){c(this,Zt).length>0&&(c(this,Zt).length=0),b(this,te,0),c(this,Zt).push(h);return}if(r&&c(this,Zt)[c(this,te)].type===n){o&&(h.undo=c(this,Zt)[c(this,te)].undo),c(this,Zt)[c(this,te)]=h;return}const l=c(this,te)+1;l===c(this,kh)?c(this,Zt).splice(0,1):(b(this,te,l),l<c(this,Zt).length&&c(this,Zt).splice(l)),c(this,Zt).push(h)}undo(){if(c(this,te)===-1)return;b(this,wn,!0);const{undo:t,post:e}=c(this,Zt)[c(this,te)];t(),e==null||e(),b(this,wn,!1),b(this,te,c(this,te)-1)}redo(){if(c(this,te)<c(this,Zt).length-1){b(this,te,c(this,te)+1),b(this,wn,!0);const{cmd:t,post:e}=c(this,Zt)[c(this,te)];t(),e==null||e(),b(this,wn,!1)}}hasSomethingToUndo(){return c(this,te)!==-1}hasSomethingToRedo(){return c(this,te)<c(this,Zt).length-1}destroy(){b(this,Zt,null)}}Zt=new WeakMap,wn=new WeakMap,kh=new WeakMap,te=new WeakMap;class ph{constructor(t){w(this,Sd);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Ee.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(v(this,Sd,ub).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()))}}Sd=new WeakSet,ub=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 Cd=class Cd{get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Vw(t),ot(this,"_colors",t)}convert(t){const e=Ag(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 Cd._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}};q(Cd,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Mg=Cd;const $o=class $o{constructor(t,e,s,i,n,r,o,h,l,d,u){w(this,I);w(this,Xo,new AbortController);w(this,qe,null);w(this,Yt,new Map);w(this,ne,new Map);w(this,Vo,null);w(this,Fi,null);w(this,Go,null);w(this,Ms,new qw);w(this,xn,null);w(this,Yo,0);w(this,_r,new Set);w(this,Ks,null);w(this,Os,null);w(this,wr,new Set);w(this,Mh,!1);w(this,Oh,!1);w(this,Uo,!1);w(this,Dh,null);w(this,Qs,null);w(this,Sn,null);w(this,qo,null);w(this,Cn,!1);w(this,Js,null);w(this,Ad,new Uw);w(this,An,!1);w(this,Ph,!1);w(this,Tn,null);w(this,xr,null);w(this,Fh,null);w(this,Rh,null);w(this,ee,Z.NONE);w(this,ft,new Set);w(this,Ri,null);w(this,Sr,null);w(this,Lh,null);w(this,Ih,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});w(this,En,[0,0]);w(this,Zs,null);w(this,Li,null);w(this,jh,null);w(this,cs,null);const g=this._signal=c(this,Xo).signal;b(this,Li,t),b(this,jh,e),b(this,Vo,s),this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",f=>this.updateParams(f.type,f.value),{signal:g}),v(this,I,pb).call(this),v(this,I,yb).call(this),v(this,I,af).call(this),b(this,Fi,n.annotationStorage),b(this,Dh,n.filterFactory),b(this,Sr,r),b(this,qo,o||null),b(this,Mh,h),b(this,Oh,l),b(this,Uo,d),b(this,Rh,u||null),this.viewParameters={realScale:bn.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=$o.prototype,e=r=>c(r,Li).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 ot(this,"_keyboardManager",new ph([[["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,Li).contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&c(r,Li).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}destroy(){var t,e,s,i;(t=c(this,cs))==null||t.resolve(),b(this,cs,null),(e=c(this,Xo))==null||e.abort(),b(this,Xo,null),this._signal=null;for(const n of c(this,ne).values())n.destroy();c(this,ne).clear(),c(this,Yt).clear(),c(this,wr).clear(),b(this,qe,null),c(this,ft).clear(),c(this,Ms).destroy(),(s=c(this,Vo))==null||s.destroy(),(i=c(this,Js))==null||i.hide(),b(this,Js,null),c(this,Qs)&&(clearTimeout(c(this,Qs)),b(this,Qs,null)),c(this,Zs)&&(clearTimeout(c(this,Zs)),b(this,Zs,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return c(this,Rh)}get useNewAltTextFlow(){return c(this,Oh)}get useNewAltTextWhenAddingImage(){return c(this,Uo)}get hcmFilter(){return ot(this,"hcmFilter",c(this,Sr)?c(this,Dh).addHCMFilter(c(this,Sr).foreground,c(this,Sr).background):"none")}get direction(){return ot(this,"direction",getComputedStyle(c(this,Li)).direction)}get highlightColors(){return ot(this,"highlightColors",c(this,qo)?new Map(c(this,qo).split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return ot(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){b(this,Fh,t)}editAltText(t,e=!1){var s;(s=c(this,Vo))==null||s.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":b(this,Uo,e);break}}onPageChanging({pageNumber:t}){b(this,Yo,t-1)}focusMainContainer(){c(this,Li).focus()}findParent(t,e){for(const s of c(this,ne).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,jh).classList.toggle("noUserSelect",t)}addShouldRescale(t){c(this,wr).add(t)}removeShouldRescale(t){c(this,wr).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*bn.PDF_TO_CSS_UNITS;for(const e of c(this,wr))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=v(this,I,zd).call(this,e).closest(".textLayer"),d=this.getSelectionBoxes(l);if(!d)return;e.empty();const u=v(this,I,of).call(this,l),g=c(this,ee)===Z.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(Z.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&c(this,Fi)&&!c(this,Fi).has(t.id)&&c(this,Fi).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,c(this,Cn)&&(b(this,Cn,!1),v(this,I,Xd).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of c(this,ft))if(e.div.contains(t)){b(this,xr,[e,t]),e._focusEventsAllowed=!1;break}}focus(){if(!c(this,xr))return;const[t,e]=c(this,xr);b(this,xr,null),e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}addEditListeners(){v(this,I,af).call(this),v(this,I,hf).call(this)}removeEditListeners(){v(this,I,vb).call(this),v(this,I,lf).call(this)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of c(this,Os))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,Os))if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){var s;if(t.preventDefault(),(s=c(this,qe))==null||s.commitOrRemove(),!this.hasSelection)return;const e=[];for(const i of c(this,ft)){const n=i.serialize(!0);n&&e.push(n)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of c(this,Os))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){st(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)v(this,I,cf).call(this,h);v(this,I,df).call(this,n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){st(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),c(this,ee)!==Z.NONE&&!this.isEditorHandlingKeyboard&&$o._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,c(this,Cn)&&(b(this,Cn,!1),v(this,I,Xd).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?(v(this,I,mb).call(this),v(this,I,hf).call(this),v(this,I,Re).call(this,{isEditing:c(this,ee)!==Z.NONE,isEmpty:v(this,I,Bl).call(this),hasSomethingToUndo:c(this,Ms).hasSomethingToUndo(),hasSomethingToRedo:c(this,Ms).hasSomethingToRedo(),hasSelectedEditor:!1})):(v(this,I,bb).call(this),v(this,I,lf).call(this),v(this,I,Re).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!c(this,Os)){b(this,Os,t);for(const e of c(this,Os))v(this,I,qn).call(this,e.defaultPropertiesToUpdate)}}getId(){return c(this,Ad).id}get currentLayer(){return c(this,ne).get(c(this,Yo))}getLayer(t){return c(this,ne).get(t)}get currentPageIndex(){return c(this,Yo)}addLayer(t){c(this,ne).set(t.pageIndex,t),c(this,An)?t.enable():t.disable()}removeLayer(t){c(this,ne).delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(c(this,ee)!==t&&!(c(this,cs)&&(await c(this,cs).promise,!c(this,cs)))){if(b(this,cs,Promise.withResolvers()),b(this,ee,t),t===Z.NONE){this.setEditingState(!1),v(this,I,wb).call(this),c(this,cs).resolve();return}this.setEditingState(!0),await v(this,I,_b).call(this),this.unselectAll();for(const i of c(this,ne).values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),c(this,cs).resolve();return}for(const i of c(this,Yt).values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();c(this,cs).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==c(this,ee)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){var s;if(c(this,Os)){switch(t){case U.CREATE:this.currentLayer.addNewEditor();return;case U.HIGHLIGHT_DEFAULT_COLOR:(s=c(this,Fh))==null||s.updateColor(e);break;case U.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(c(this,Lh)||b(this,Lh,new Map)).set(t,e),this.showAllEditors("highlight",e);break}for(const i of c(this,ft))i.updateParams(t,e);for(const i of c(this,Os))i.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){var n;for(const r of c(this,Yt).values())r.editorType===t&&r.show(e);(((n=c(this,Lh))==null?void 0:n.get(U.HIGHLIGHT_SHOW_ALL))??!0)!==e&&v(this,I,qn).call(this,[[U.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(c(this,Ph)!==t){b(this,Ph,t);for(const e of c(this,ne).values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}getEditors(t){const e=[];for(const s of c(this,Yt).values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return c(this,Yt).get(t)}addEditor(t){c(this,Yt).set(t.id,t)}removeEditor(t){var e;t.div.contains(document.activeElement)&&(c(this,Qs)&&clearTimeout(c(this,Qs)),b(this,Qs,setTimeout(()=>{this.focusMainContainer(),b(this,Qs,null)},0))),c(this,Yt).delete(t.id),this.unselect(t),(!t.annotationElementId||!c(this,_r).has(t.annotationElementId))&&((e=c(this,Fi))==null||e.remove(t.id))}addDeletedAnnotationElement(t){c(this,_r).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return c(this,_r).has(t)}removeDeletedAnnotationElement(t){c(this,_r).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){c(this,qe)!==t&&(b(this,qe,t),t&&v(this,I,qn).call(this,t.propertiesToUpdate))}updateUI(t){c(this,I,xb)===t&&v(this,I,qn).call(this,t.propertiesToUpdate)}toggleSelected(t){if(c(this,ft).has(t)){c(this,ft).delete(t),t.unselect(),v(this,I,Re).call(this,{hasSelectedEditor:this.hasSelection});return}c(this,ft).add(t),t.select(),v(this,I,qn).call(this,t.propertiesToUpdate),v(this,I,Re).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const e of c(this,ft))e!==t&&e.unselect();c(this,ft).clear(),c(this,ft).add(t),t.select(),v(this,I,qn).call(this,t.propertiesToUpdate),v(this,I,Re).call(this,{hasSelectedEditor:!0})}isSelected(t){return c(this,ft).has(t)}get firstSelectedEditor(){return c(this,ft).values().next().value}unselect(t){t.unselect(),c(this,ft).delete(t),v(this,I,Re).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return c(this,ft).size!==0}get isEnterHandled(){return c(this,ft).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){c(this,Ms).undo(),v(this,I,Re).call(this,{hasSomethingToUndo:c(this,Ms).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:v(this,I,Bl).call(this)})}redo(){c(this,Ms).redo(),v(this,I,Re).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:c(this,Ms).hasSomethingToRedo(),isEmpty:v(this,I,Bl).call(this)})}addCommands(t){c(this,Ms).add(t),v(this,I,Re).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:v(this,I,Bl).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...c(this,ft)],e=()=>{for(const i of t)i.remove()},s=()=>{for(const i of t)v(this,I,cf).call(this,i)};this.addCommands({cmd:e,undo:s,mustExec:!0})}commitOrRemove(){var t;(t=c(this,qe))==null||t.commitOrRemove()}hasSomethingToControl(){return c(this,qe)||this.hasSelection}selectAll(){for(const t of c(this,ft))t.commit();v(this,I,df).call(this,c(this,Yt).values())}unselectAll(){if(!(c(this,qe)&&(c(this,qe).commitOrRemove(),c(this,ee)!==Z.NONE))&&this.hasSelection){for(const t of c(this,ft))t.unselect();c(this,ft).clear(),v(this,I,Re).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;c(this,En)[0]+=t,c(this,En)[1]+=e;const[i,n]=c(this,En),r=[...c(this,ft)],o=1e3;c(this,Zs)&&clearTimeout(c(this,Zs)),b(this,Zs,setTimeout(()=>{b(this,Zs,null),c(this,En)[0]=c(this,En)[1]=0,this.addCommands({cmd:()=>{for(const h of r)c(this,Yt).has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)c(this,Yt).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,Ks,new Map);for(const t of c(this,ft))c(this,Ks).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!c(this,Ks))return!1;this.disableUserSelect(!1);const t=c(this,Ks);b(this,Ks,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,Yt).has(i.id)){const h=c(this,ne).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,Ks))for(const s of c(this,Ks).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,ft).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return c(this,qe)===t}getActive(){return c(this,qe)}getMode(){return c(this,ee)}get imageManager(){return ot(this,"imageManager",new kg)}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,Go)||b(this,Go,new Map)).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){var e;(e=c(this,Go))==null||e.delete(t)}renderAnnotationElement(t){var i;const e=(i=c(this,Go))==null?void 0:i.get(t.data.id);if(!e)return;const s=c(this,Fi).getRawValue(e);s&&(c(this,ee)===Z.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}};Xo=new WeakMap,qe=new WeakMap,Yt=new WeakMap,ne=new WeakMap,Vo=new WeakMap,Fi=new WeakMap,Go=new WeakMap,Ms=new WeakMap,xn=new WeakMap,Yo=new WeakMap,_r=new WeakMap,Ks=new WeakMap,Os=new WeakMap,wr=new WeakMap,Mh=new WeakMap,Oh=new WeakMap,Uo=new WeakMap,Dh=new WeakMap,Qs=new WeakMap,Sn=new WeakMap,qo=new WeakMap,Cn=new WeakMap,Js=new WeakMap,Ad=new WeakMap,An=new WeakMap,Ph=new WeakMap,Tn=new WeakMap,xr=new WeakMap,Fh=new WeakMap,Rh=new WeakMap,ee=new WeakMap,ft=new WeakMap,Ri=new WeakMap,Sr=new WeakMap,Lh=new WeakMap,Ih=new WeakMap,En=new WeakMap,Zs=new WeakMap,Li=new WeakMap,jh=new WeakMap,cs=new WeakMap,I=new WeakSet,zd=function({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t},of=function(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of c(this,ne).values())if(s.hasTextLayer(t))return s;return null},gb=function(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=v(this,I,zd).call(this,t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(c(this,Js)||b(this,Js,new Gw(this)),c(this,Js).show(s,i,this.direction==="ltr"))},fb=function(){var n,r,o;const t=document.getSelection();if(!t||t.isCollapsed){c(this,Ri)&&((n=c(this,Js))==null||n.hide(),b(this,Ri,null),v(this,I,Re).call(this,{hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===c(this,Ri))return;const i=v(this,I,zd).call(this,t).closest(".textLayer");if(!i){c(this,Ri)&&((r=c(this,Js))==null||r.hide(),b(this,Ri,null),v(this,I,Re).call(this,{hasSelectedText:!1}));return}if((o=c(this,Js))==null||o.hide(),b(this,Ri,e),v(this,I,Re).call(this,{hasSelectedText:!0}),!(c(this,ee)!==Z.HIGHLIGHT&&c(this,ee)!==Z.NONE)&&(c(this,ee)===Z.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),b(this,Cn,this.isShiftKeyDown),!this.isShiftKeyDown)){const h=c(this,ee)===Z.HIGHLIGHT?v(this,I,of).call(this,i):null;h==null||h.toggleDrawing();const l=new AbortController,d=this.combinedSignal(l),u=g=>{g.type==="pointerup"&&g.button!==0||(l.abort(),h==null||h.toggleDrawing(!0),g.type==="pointerup"&&v(this,I,Xd).call(this,"main_toolbar"))};window.addEventListener("pointerup",u,{signal:d}),window.addEventListener("blur",u,{signal:d})}},Xd=function(t=""){c(this,ee)===Z.HIGHLIGHT?this.highlightSelection(t):c(this,Mh)&&v(this,I,gb).call(this)},pb=function(){document.addEventListener("selectionchange",v(this,I,fb).bind(this),{signal:this._signal})},mb=function(){if(c(this,Sn))return;b(this,Sn,new AbortController);const t=this.combinedSignal(c(this,Sn));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},bb=function(){var t;(t=c(this,Sn))==null||t.abort(),b(this,Sn,null)},af=function(){if(c(this,Tn))return;b(this,Tn,new AbortController);const t=this.combinedSignal(c(this,Tn));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},vb=function(){var t;(t=c(this,Tn))==null||t.abort(),b(this,Tn,null)},hf=function(){if(c(this,xn))return;b(this,xn,new AbortController);const t=this.combinedSignal(c(this,xn));document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})},lf=function(){var t;(t=c(this,xn))==null||t.abort(),b(this,xn,null)},yb=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Re=function(t){Object.entries(t).some(([s,i])=>c(this,Ih)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(c(this,Ih),t)}),c(this,ee)===Z.HIGHLIGHT&&t.hasSelectedEditor===!1&&v(this,I,qn).call(this,[[U.HIGHLIGHT_FREE,!0]]))},qn=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},_b=async function(){if(!c(this,An)){b(this,An,!0);const t=[];for(const e of c(this,ne).values())t.push(e.enable());await Promise.all(t);for(const e of c(this,Yt).values())e.enable()}},wb=function(){if(this.unselectAll(),c(this,An)){b(this,An,!1);for(const t of c(this,ne).values())t.disable();for(const t of c(this,Yt).values())t.disable()}},cf=function(t){const e=c(this,ne).get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},xb=function(){let t=null;for(t of c(this,ft));return t},Bl=function(){if(c(this,Yt).size===0)return!0;if(c(this,Yt).size===1)for(const t of c(this,Yt).values())return t.isEmpty();return!1},df=function(t){for(const e of c(this,ft))e.unselect();c(this,ft).clear();for(const e of t)e.isEmpty()||(c(this,ft).add(e),e.select());v(this,I,Re).call(this,{hasSelectedEditor:this.hasSelection})},q($o,"TRANSLATE_SMALL",1),q($o,"TRANSLATE_BIG",10);let ur=$o;const Oe=class Oe{constructor(t){w(this,Ps);w(this,se,null);w(this,ti,!1);w(this,Ds,null);w(this,Ko,null);w(this,ei,null);w(this,$e,null);w(this,Qo,!1);w(this,si,null);w(this,Be,null);w(this,Ii,null);w(this,Cr,null);w(this,ii,!1);b(this,Be,t),b(this,ii,t._uiManager.useNewAltTextFlow),c(Oe,kn)||b(Oe,kn,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(t){Oe._l10n??(Oe._l10n=t)}async render(){const t=b(this,Ds,document.createElement("button"));t.className="altText",t.tabIndex="0";const e=b(this,Ko,document.createElement("span"));t.append(e),c(this,ii)?(t.classList.add("new"),t.setAttribute("data-l10n-id",c(Oe,kn).missing),e.setAttribute("data-l10n-id",c(Oe,kn)["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=c(this,Be)._uiManager._signal;t.addEventListener("contextmenu",hs,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),c(this,Be)._uiManager.editAltText(c(this,Be)),c(this,ii)&&c(this,Be)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:c(this,Ps,Hl)}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(b(this,Qo,!0),i(n))},{signal:s}),await v(this,Ps,Vd).call(this),t}finish(){c(this,Ds)&&(c(this,Ds).focus({focusVisible:c(this,Qo)}),b(this,Qo,!1))}isEmpty(){return c(this,ii)?c(this,se)===null:!c(this,se)&&!c(this,ti)}hasData(){return c(this,ii)?c(this,se)!==null||!!c(this,Ii):this.isEmpty()}get guessedText(){return c(this,Ii)}async setGuessedText(t){c(this,se)===null&&(b(this,Ii,t),b(this,Cr,await Oe._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),v(this,Ps,Vd).call(this))}toggleAltTextBadge(t=!1){var e;if(!c(this,ii)||c(this,se)){(e=c(this,si))==null||e.remove(),b(this,si,null);return}if(!c(this,si)){const s=b(this,si,document.createElement("div"));s.className="noAltTextBadge",c(this,Be).div.append(s)}c(this,si).classList.toggle("hidden",!t)}serialize(t){let e=c(this,se);return!t&&c(this,Ii)===e&&(e=c(this,Cr)),{altText:e,decorative:c(this,ti),guessedText:c(this,Ii),textWithDisclaimer:c(this,Cr)}}get data(){return{altText:c(this,se),decorative:c(this,ti)}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(b(this,Ii,s),b(this,Cr,i)),!(c(this,se)===t&&c(this,ti)===e)&&(n||(b(this,se,t),b(this,ti,e)),v(this,Ps,Vd).call(this))}toggle(t=!1){c(this,Ds)&&(!t&&c(this,$e)&&(clearTimeout(c(this,$e)),b(this,$e,null)),c(this,Ds).disabled=!t)}shown(){c(this,Be)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:c(this,Ps,Hl)}})}destroy(){var t,e;(t=c(this,Ds))==null||t.remove(),b(this,Ds,null),b(this,Ko,null),b(this,ei,null),(e=c(this,si))==null||e.remove(),b(this,si,null)}};se=new WeakMap,ti=new WeakMap,Ds=new WeakMap,Ko=new WeakMap,ei=new WeakMap,$e=new WeakMap,Qo=new WeakMap,si=new WeakMap,Be=new WeakMap,Ii=new WeakMap,Cr=new WeakMap,ii=new WeakMap,kn=new WeakMap,Ps=new WeakSet,Hl=function(){return c(this,se)&&"added"||c(this,se)===null&&this.guessedText&&"review"||"missing"},Vd=async function(){var i,n,r;const t=c(this,Ds);if(!t)return;if(c(this,ii)){if(t.classList.toggle("done",!!c(this,se)),t.setAttribute("data-l10n-id",c(Oe,kn)[c(this,Ps,Hl)]),(i=c(this,Ko))==null||i.setAttribute("data-l10n-id",c(Oe,kn)[`${c(this,Ps,Hl)}-label`]),!c(this,se)){(n=c(this,ei))==null||n.remove();return}}else{if(!c(this,se)&&!c(this,ti)){t.classList.remove("done"),(r=c(this,ei))==null||r.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=c(this,ei);if(!e){b(this,ei,e=document.createElement("span")),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${c(this,Be).id}`;const o=100,h=c(this,Be)._uiManager._signal;h.addEventListener("abort",()=>{clearTimeout(c(this,$e)),b(this,$e,null)},{once:!0}),t.addEventListener("mouseenter",()=>{b(this,$e,setTimeout(()=>{b(this,$e,null),c(this,ei).classList.add("show"),c(this,Be)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:h}),t.addEventListener("mouseleave",()=>{var l;c(this,$e)&&(clearTimeout(c(this,$e)),b(this,$e,null)),(l=c(this,ei))==null||l.classList.remove("show")},{signal:h})}c(this,ti)?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=c(this,se)),e.parentNode||t.append(e);const s=c(this,Be).getImageForAltText();s==null||s.setAttribute("aria-describedby",e.id)},w(Oe,kn,null),q(Oe,"_l10n",null);let cd=Oe;const ct=class ct{constructor(t){w(this,et);w(this,Ar,null);w(this,Fs,null);w(this,Et,null);w(this,Jo,!1);w(this,Tr,!1);w(this,re,null);w(this,Er,null);w(this,Mn,null);w(this,Nh,"");w(this,kr,!1);w(this,On,null);w(this,Bh,!1);w(this,Mr,!1);w(this,ji,!1);w(this,ni,null);w(this,Zo,0);w(this,ta,0);w(this,ds,null);q(this,"_editToolbar",null);q(this,"_initialOptions",Object.create(null));q(this,"_initialData",null);q(this,"_isVisible",!0);q(this,"_uiManager",null);q(this,"_focusEventsAllowed",!0);w(this,Hh,!1);w(this,Td,ct._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=ct.prototype._resizeWithKeyboard,e=ur.TRANSLATE_SMALL,s=ur.TRANSLATE_BIG;return ot(this,"_resizerKeyboardManager",new ph([[["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"],ct.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return ot(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new $w({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){if(ct._l10n??(ct._l10n=t),ct._l10nResizer||(ct._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),ct._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);ct._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){yt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return c(this,Hh)}set _isDraggable(t){var e;b(this,Hh,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,Td)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):v(this,et,Wl).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(c(this,kr)?b(this,kr,!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){v(this,et,uf).call(this,this.parentDimensions,t,e)}translateInPage(t,e){c(this,On)||b(this,On,[this.x,this.y]),v(this,et,uf).call(this,this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){c(this,On)||b(this,On,[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,On)&&(c(this,On)[0]!==this.x||c(this,On)[1]!==this.y)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=ct,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 v(s=ct,Wh,gf).call(s,t,e,this.parentRotation)}pageTranslationToScreen(t,e){var s;return v(s=ct,Wh,gf).call(s,t,e,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*t/s).toFixed(2)}%`,c(this,Tr)||(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,Tr)&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!c(this,Tr)&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=c(this,Et))==null||t.finish()}async addEditToolbar(){return this._editToolbar||c(this,Mr)?this._editToolbar:(this._editToolbar=new Eg(this),this.div.append(this._editToolbar.render()),c(this,Et)&&await this._editToolbar.addAltText(c(this,Et)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=c(this,Et))==null||t.destroy())}addContainer(t){var s;const e=(s=this._editToolbar)==null?void 0:s.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){c(this,Et)||(cd.initialize(ct._l10n),b(this,Et,new cd(this)),c(this,Ar)&&(c(this,Et).data=c(this,Ar),b(this,Ar,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=c(this,Et))==null?void 0:t.data}set altTextData(t){c(this,Et)&&(c(this,Et).data=t)}get guessedAltText(){var t;return(t=c(this,Et))==null?void 0:t.guessedText}async setGuessedAltText(t){var e;await((e=c(this,Et))==null?void 0:e.setGuessedText(t))}serializeAltText(t){var e;return(e=c(this,Et))==null?void 0:e.serialize(t)}hasAltText(){return!!c(this,Et)&&!c(this,Et).isEmpty()}hasAltTextData(){var t;return((t=c(this,Et))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=c(this,Jo)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),v(this,et,vf).call(this);const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),ld(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:e}=Ee.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(b(this,kr,!0),this._isDraggable){v(this,et,Ab).call(this,t);return}v(this,et,bf).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){c(this,ni)&&clearTimeout(c(this,ni)),b(this,ni,setTimeout(()=>{var t;b(this,ni,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,Mr,!0)}disableEditMode(){b(this,Mr,!1)}isInEditMode(){return c(this,Mr)}shouldGetKeyboardEvents(){return c(this,ji)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){v(this,et,vf).call(this)}rotate(t){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,e=null){yt("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,b(i,Ar,t.accessibilityData);const[n,r]=i.pageDimensions,[o,h,l,d]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=d/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t;if((t=c(this,Mn))==null||t.abort(),b(this,Mn,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),c(this,ni)&&(clearTimeout(c(this,ni)),b(this,ni,null)),v(this,et,Wl).call(this),this.removeEditToolbar(),c(this,ds)){for(const e of c(this,ds).values())clearTimeout(e);b(this,ds,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(v(this,et,Sb).call(this),c(this,re).classList.remove("hidden"),ld(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,Er,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const e=c(this,re).children;if(!c(this,Fs)){b(this,Fs,Array.from(e));const r=v(this,et,Tb).bind(this),o=v(this,et,Eb).bind(this),h=this._uiManager._signal;for(const l of c(this,Fs)){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",v(this,et,kb).bind(this,d),{signal:h}),l.setAttribute("data-l10n-id",ct._l10nResizer[d])}}const s=c(this,Fs)[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,Fs).length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)c(this,re).append(c(this,re).firstChild);else if(n>i)for(let o=0;o<n-i;o++)c(this,re).firstChild.before(c(this,re).lastChild);let r=0;for(const o of e){const l=c(this,Fs)[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",ct._l10nResizer[l])}}v(this,et,yf).call(this,0),b(this,ji,!0),c(this,re).firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}_resizeWithKeyboard(t,e){c(this,ji)&&v(this,et,mf).call(this,c(this,Nh),{movementX:t,movementY:e})}_stopResizingWithKeyboard(){v(this,et,Wl).call(this),this.div.focus()}select(){var t,e,s;if(this.makeResizable(),(t=this.div)==null||t.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{var i,n;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((n=this._editToolbar)==null||n.show())});return}(e=this._editToolbar)==null||e.show(),(s=c(this,Et))==null||s.toggleAltTextBadge(!1)}unselect(){var t,e,s,i,n;(t=c(this,re))==null||t.classList.add("hidden"),(e=this.div)==null||e.classList.remove("selectedEditor"),(s=this.div)!=null&&s.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(n=c(this,Et))==null||n.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return c(this,Bh)}set isEditing(t){b(this,Bh,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){b(this,Tr,!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,ds)||b(this,ds,new Map);const{action:s}=t;let i=c(this,ds).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),c(this,ds).delete(s),c(this,ds).size===0&&b(this,ds,null)},ct._telemetryTimeout),c(this,ds).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,Jo,!1)}disable(){this.div&&(this.div.tabIndex=-1),b(this,Jo,!0)}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;(e==null?void 0:e.nodeName)==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}};Ar=new WeakMap,Fs=new WeakMap,Et=new WeakMap,Jo=new WeakMap,Tr=new WeakMap,re=new WeakMap,Er=new WeakMap,Mn=new WeakMap,Nh=new WeakMap,kr=new WeakMap,On=new WeakMap,Bh=new WeakMap,Mr=new WeakMap,ji=new WeakMap,ni=new WeakMap,Zo=new WeakMap,ta=new WeakMap,ds=new WeakMap,Hh=new WeakMap,Td=new WeakMap,et=new WeakSet,uf=function([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this.fixAndSetPosition()},Wh=new WeakSet,gf=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]}},ff=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]}},Sb=function(){if(c(this,re))return;b(this,re,document.createElement("div")),c(this,re).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,re).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",v(this,et,Cb).bind(this,s),{signal:e}),i.addEventListener("contextmenu",hs,{signal:e}),i.tabIndex=-1}this.div.prepend(c(this,re))},Cb=function(t,e){var p;e.preventDefault();const{isMac:s}=Ee.platform;if(e.button!==0||e.ctrlKey&&s)return;(p=c(this,Et))==null||p.toggle(!1);const i=this._isDraggable;this._isDraggable=!1;const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",v(this,et,mf).bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("contextmenu",hs,{signal:r});const o=this.x,h=this.y,l=this.width,d=this.height,u=this.parent.div.style.cursor,g=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const f=()=>{var m;n.abort(),this.parent.togglePointerEvents(!0),(m=c(this,Et))==null||m.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=u,this.div.style.cursor=g,v(this,et,pf).call(this,o,h,l,d)};window.addEventListener("pointerup",f,{signal:r}),window.addEventListener("blur",f,{signal:r})},pf=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})},mf=function(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=ct.MIN_SIZE/s,d=ct.MIN_SIZE/i,u=V=>Math.round(V*1e4)/1e4,g=v(this,et,ff).call(this,this.rotation),f=(V,H)=>[g[0]*V+g[2]*H,g[1]*V+g[3]*H],p=v(this,et,ff).call(this,360-this.rotation),m=(V,H)=>[p[0]*V+p[2]*H,p[1]*V+p[3]*H];let _,y,x=!1,S=!1;switch(t){case"topLeft":x=!0,_=(V,H)=>[0,0],y=(V,H)=>[V,H];break;case"topMiddle":_=(V,H)=>[V/2,0],y=(V,H)=>[V/2,H];break;case"topRight":x=!0,_=(V,H)=>[V,0],y=(V,H)=>[0,H];break;case"middleRight":S=!0,_=(V,H)=>[V,H/2],y=(V,H)=>[0,H/2];break;case"bottomRight":x=!0,_=(V,H)=>[V,H],y=(V,H)=>[0,0];break;case"bottomMiddle":_=(V,H)=>[V/2,H],y=(V,H)=>[V/2,0];break;case"bottomLeft":x=!0,_=(V,H)=>[0,H],y=(V,H)=>[V,0];break;case"middleLeft":S=!0,_=(V,H)=>[0,H/2],y=(V,H)=>[V,H/2];break}const C=_(o,h),E=y(o,h);let M=f(...E);const k=u(n+M[0]),O=u(r+M[1]);let P=1,F=1,[R,W]=this.screenToPageTranslation(e.movementX,e.movementY);if([R,W]=m(R/s,W/i),x){const V=Math.hypot(o,h);P=F=Math.max(Math.min(Math.hypot(E[0]-C[0]-R,E[1]-C[1]-W)/V,1/o,1/h),l/o,d/h)}else S?P=Math.max(l,Math.min(1,Math.abs(E[0]-C[0]-R)))/o:F=Math.max(d,Math.min(1,Math.abs(E[1]-C[1]-W)))/h;const B=u(o*P),X=u(h*F);M=f(...y(B,X));const K=k-M[0],tt=O-M[1];this.width=B,this.height=X,this.x=K,this.y=tt,this.setDims(s*B,i*X),this.fixAndSetPosition()},bf=function(t){const{isMac:e}=Ee.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)},Ab=function(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();const s=new AbortController,i=this._uiManager.combinedSignal(s);if(e){this.div.classList.add("moving"),b(this,Zo,t.clientX),b(this,ta,t.clientY);const r=o=>{const{clientX:h,clientY:l}=o,[d,u]=this.screenToPageTranslation(h-c(this,Zo),l-c(this,ta));b(this,Zo,h),b(this,ta,l),this._uiManager.dragSelectedEditors(d,u)};window.addEventListener("pointermove",r,{passive:!0,capture:!0,signal:i})}const n=()=>{s.abort(),e&&this.div.classList.remove("moving"),b(this,kr,!1),this._uiManager.endDragSession()||v(this,et,bf).call(this,t)};window.addEventListener("pointerup",n,{signal:i}),window.addEventListener("blur",n,{signal:i})},vf=function(){if(c(this,Mn)||!this.div)return;b(this,Mn,new AbortController);const t=this._uiManager.combinedSignal(c(this,Mn));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},Tb=function(t){ct._resizerKeyboardManager.exec(this,t)},Eb=function(t){var e;c(this,ji)&&((e=t.relatedTarget)==null?void 0:e.parentNode)!==c(this,re)&&v(this,et,Wl).call(this)},kb=function(t){b(this,Nh,c(this,ji)?t:"")},yf=function(t){if(c(this,Fs))for(const e of c(this,Fs))e.tabIndex=t},Wl=function(){if(b(this,ji,!1),v(this,et,yf).call(this,-1),c(this,Er)){const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=c(this,Er);v(this,et,pf).call(this,t,e,s,i),b(this,Er,null)}},w(ct,Wh),q(ct,"_l10n",null),q(ct,"_l10nResizer",null),q(ct,"_borderLineWidth",-1),q(ct,"_colorManager",new Mg),q(ct,"_zIndex",1),q(ct,"_telemetryTimeout",1e3);let gt=ct;class $w extends gt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const f0=3285377520,ls=4294901760,$s=65535;class p0{constructor(t){this.h1=t?t&4294967295:f0,this.h2=t?t&4294967295:f0}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 y=t.charCodeAt(m);y<=255?e[s++]=y:(e[s++]=y>>>8,e[s++]=y&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&$s,p=g&$s;for(let m=0;m<i;m++)m&1?(o=r[m],o=o*u&ls|o*f&$s,o=o<<15|o>>>17,o=o*g&ls|o*p&$s,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[m],h=h*u&ls|h*f&$s,h=h<<15|h>>>17,h=h*g&ls|h*p&$s,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&ls|o*f&$s,o=o<<15|o>>>17,o=o*g&ls|o*p&$s,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&ls|t*36045&$s,e=e*4283543511&ls|((e<<16|t>>>16)*2950163797&ls)>>>16,t^=e>>>1,t=t*444984403&ls|t*60499&$s,e=e*3301882366&ls|((e<<16|t>>>16)*3120437893&ls)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Og=Object.freeze({map:null,hash:"",transfer:void 0});class Dg{constructor(){w(this,Ed);w(this,Or,!1);w(this,Dr,null);w(this,ie,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=c(this,ie).get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return c(this,ie).get(t)}remove(t){if(c(this,ie).delete(t),c(this,ie).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of c(this,ie).values())if(e instanceof gt)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=c(this,ie).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,ie).set(t,e);i&&v(this,Ed,Mb).call(this),e instanceof gt&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return c(this,ie).has(t)}getAll(){return c(this,ie).size>0?vg(c(this,ie)):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return c(this,ie).size}resetModified(){c(this,Or)&&(b(this,Or,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new m0(this)}get serializable(){if(c(this,ie).size===0)return Og;const t=new Map,e=new p0,s=[],i=Object.create(null);let n=!1;for(const[r,o]of c(this,ie)){const h=o instanceof gt?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||(n=!!h.bitmap))}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Og}get editorStats(){let t=null;const e=new Map;for(const s of c(this,ie).values()){if(!(s instanceof gt))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||(t=Object.create(null));const r=t[n]||(t[n]=new Map);for(const[o,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const d=l.get(h)??0;l.set(h,d+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){b(this,Dr,null)}get modifiedIds(){if(c(this,Dr))return c(this,Dr);const t=[];for(const e of c(this,ie).values())!(e instanceof gt)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return b(this,Dr,{ids:new Set(t),hash:t.join(",")})}}Or=new WeakMap,Dr=new WeakMap,ie=new WeakMap,Ed=new WeakSet,Mb=function(){c(this,Or)||(b(this,Or,!0),typeof this.onSetModified=="function"&&this.onSetModified())};class m0 extends Dg{constructor(e){super();w(this,zh);const{map:s,hash:i,transfer:n}=e.serializable,r=structuredClone(s,n?{transfer:n}:null);b(this,zh,{map:r,hash:i,transfer:n})}get print(){yt("Should not call PrintAnnotationStorage.print")}get serializable(){return c(this,zh)}get modifiedIds(){return ot(this,"modifiedIds",{ids:new Set,hash:""})}}zh=new WeakMap;class Kw{constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){w(this,ea,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,ea).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||c(this,ea).has(t.loadedName))){if(Gt(!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,ea).add(s),e==null||e(t)}catch{st(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}yt("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw st(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){var e;const t=!!((e=this._document)!=null&&e.fonts);return ot(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(fe||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),ot(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(Gt(!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 ot(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(C,E){return C.charCodeAt(E)<<24|C.charCodeAt(E+1)<<16|C.charCodeAt(E+2)<<8|C.charCodeAt(E+3)&255}function i(C,E,M,k){const O=C.substring(0,E),P=C.substring(E+M);return O+k+P}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function d(C,E){if(++l>30){st("Load test font never loaded."),E();return}if(h.font="30px "+C,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){E();return}setTimeout(d.bind(null,C,E))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let g=this._loadTestFont;g=i(g,976,u.length,u);const p=16,m=1482184792;let _=s(g,p);for(n=0,r=u.length-3;n<r;n+=4)_=_-m+s(u,n)|0;n<u.length&&(_=_-m+s(u+"XXX",n)|0),g=i(g,p,4,Rw(_));const y=`url(data:font/opentype;base64,${btoa(g)});`,x=`@font-face {font-family:"${u}";src:${y}}`;this.insertRule(x);const S=this._document.createElement("div");S.style.visibility="hidden",S.style.width=S.style.height="10px",S.style.position="absolute",S.style.top=S.style.left="0px";for(const C of[t.loadedName,u]){const E=this._document.createElement("span");E.textContent="Hi",E.style.fontFamily=C,S.append(E)}this._document.body.append(S),d(u,()=>{S.remove(),e.complete()})}}ea=new WeakMap;class Qw{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 s;if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Hw(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}return(s=this._inspectFont)==null||s.call(this,this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];let s;try{s=t.get(this.loadedName+"_path_"+e)}catch(n){st(`getPathGenerator - ignoring character: "${n}".`)}if(!Array.isArray(s)||s.length===0)return this.compiledGlyphs[e]=function(n,r){};const i=[];for(let n=0,r=s.length;n<r;)switch(s[n++]){case Ti.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 Ti.MOVE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.moveTo(o,h)),n+=2}break;case Ti.LINE_TO:{const[o,h]=s.slice(n,n+2);i.push(l=>l.lineTo(o,h)),n+=2}break;case Ti.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 Ti.RESTORE:i.push(o=>o.restore());break;case Ti.SAVE:i.push(o=>o.save());break;case Ti.SCALE:Gt(i.length===2,"Scale command is only valid at the third position.");break;case Ti.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 Ti.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)}}}class b0{constructor({enableHWA:t=!1}){w(this,Xh,!1);b(this,Xh,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,Xh)})}}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){yt("Abstract method `_createCanvas` called.")}}Xh=new WeakMap;class Jw extends b0{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}}class v0{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){yt("Abstract method `_fetch` called.")}}class y0 extends v0{async _fetch(t){const e=await ad(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):od(e)}}class _0{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class Zw extends _0{constructor({docId:e,ownerDocument:s=globalThis.document}){super();w(this,j);w(this,Pr);w(this,Fr);w(this,ri);w(this,Ni);w(this,be);w(this,kd);w(this,Rr,0);b(this,Ni,e),b(this,be,s)}addFilter(e){if(!e)return"none";let s=c(this,j,_e).get(e);if(s)return s;const[i,n,r]=v(this,j,Gd).call(this,e),o=e.length===1?i:`${i}${n}${r}`;if(s=c(this,j,_e).get(o),s)return c(this,j,_e).set(e,s),s;const h=`g_${c(this,Ni)}_transfer_map_${Fe(this,Rr)._++}`,l=v(this,j,za).call(this,h);c(this,j,_e).set(e,l),c(this,j,_e).set(o,l);const d=v(this,j,Xa).call(this,h);return v(this,j,Xl).call(this,i,n,r,d),l}addHCMFilter(e,s){var p;const i=`${e}-${s}`,n="base";let r=c(this,j,Ha).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,j,Ha).set(n,r)),!e||!s))return r.url;const o=v(this,j,Vl).call(this,e);e=z.makeHexColor(...o);const h=v(this,j,Vl).call(this,s);if(s=z.makeHexColor(...h),c(this,j,Wa).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,Ni)}_hcm_filter`,g=r.filter=v(this,j,Xa).call(this,u);v(this,j,Xl).call(this,d,d,d,g),v(this,j,_f).call(this,g);const f=(m,_)=>{const y=o[m]/255,x=h[m]/255,S=new Array(_+1);for(let C=0;C<=_;C++)S[C]=y+C/_*(x-y);return S.join(",")};return v(this,j,Xl).call(this,f(0,5),f(1,5),f(2,5),g),r.url=v(this,j,za).call(this,u),r.url}addAlphaFilter(e){let s=c(this,j,_e).get(e);if(s)return s;const[i]=v(this,j,Gd).call(this,[e]),n=`alpha_${i}`;if(s=c(this,j,_e).get(n),s)return c(this,j,_e).set(e,s),s;const r=`g_${c(this,Ni)}_alpha_map_${Fe(this,Rr)._++}`,o=v(this,j,za).call(this,r);c(this,j,_e).set(e,o),c(this,j,_e).set(n,o);const h=v(this,j,Xa).call(this,r);return v(this,j,wf).call(this,i,h),o}addLuminosityFilter(e){let s=c(this,j,_e).get(e||"luminosity");if(s)return s;let i,n;if(e?([i]=v(this,j,Gd).call(this,[e]),n=`luminosity_${i}`):n="luminosity",s=c(this,j,_e).get(n),s)return c(this,j,_e).set(e,s),s;const r=`g_${c(this,Ni)}_luminosity_map_${Fe(this,Rr)._++}`,o=v(this,j,za).call(this,r);c(this,j,_e).set(e,o),c(this,j,_e).set(n,o);const h=v(this,j,Xa).call(this,r);return v(this,j,Ob).call(this,h),e&&v(this,j,wf).call(this,i,h),o}addHighlightHCMFilter(e,s,i,n,r){var x;const o=`${s}-${i}-${n}-${r}`;let h=c(this,j,Ha).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,j,Ha).set(e,h)),!s||!i))return h.url;const[l,d]=[s,i].map(v(this,j,Vl).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(v(this,j,Vl).bind(this));g<u&&([u,g,f,p]=[g,u,p,f]),c(this,j,Wa).style.color="";const m=(S,C,E)=>{const M=new Array(256),k=(g-u)/E,O=S/255,P=(C-S)/(255*E);let F=0;for(let R=0;R<=E;R++){const W=Math.round(u+R*k),B=O+R*P;for(let X=F;X<=W;X++)M[X]=B;F=W+1}for(let R=F;R<256;R++)M[R]=M[F-1];return M.join(",")},_=`g_${c(this,Ni)}_hcm_${e}_filter`,y=h.filter=v(this,j,Xa).call(this,_);return v(this,j,_f).call(this,y),v(this,j,Xl).call(this,m(f[0],p[0],5),m(f[1],p[1],5),m(f[2],p[2],5),y),h.url=v(this,j,za).call(this,_),h.url}destroy(e=!1){e&&c(this,j,Ha).size!==0||(c(this,ri)&&(c(this,ri).parentNode.parentNode.remove(),b(this,ri,null)),c(this,Fr)&&(c(this,Fr).clear(),b(this,Fr,null)),b(this,Rr,0))}}Pr=new WeakMap,Fr=new WeakMap,ri=new WeakMap,Ni=new WeakMap,be=new WeakMap,kd=new WeakMap,Rr=new WeakMap,j=new WeakSet,_e=function(){return c(this,Fr)||b(this,Fr,new Map)},Ha=function(){return c(this,kd)||b(this,kd,new Map)},Wa=function(){if(!c(this,ri)){const e=c(this,be).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,be).createElementNS(Ei,"svg");i.setAttribute("width",0),i.setAttribute("height",0),b(this,ri,c(this,be).createElementNS(Ei,"defs")),e.append(i),i.append(c(this,ri)),c(this,be).body.append(e)}return c(this,ri)},Gd=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(",")]},za=function(e){if(c(this,Pr)===void 0){b(this,Pr,"");const s=c(this,be).URL;s!==c(this,be).baseURI&&(hd(s)?st('#createUrl: ignore "data:"-URL for performance reasons.'):b(this,Pr,s.split("#",1)[0]))}return`url(${c(this,Pr)}#${e})`},Ob=function(e){const s=c(this,be).createElementNS(Ei,"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)},_f=function(e){const s=c(this,be).createElementNS(Ei,"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)},Xa=function(e){const s=c(this,be).createElementNS(Ei,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",e),c(this,j,Wa).append(s),s},zl=function(e,s,i){const n=c(this,be).createElementNS(Ei,s);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),e.append(n)},Xl=function(e,s,i,n){const r=c(this,be).createElementNS(Ei,"feComponentTransfer");n.append(r),v(this,j,zl).call(this,r,"feFuncR",e),v(this,j,zl).call(this,r,"feFuncG",s),v(this,j,zl).call(this,r,"feFuncB",i)},wf=function(e,s){const i=c(this,be).createElementNS(Ei,"feComponentTransfer");s.append(i),v(this,j,zl).call(this,i,"feFuncA",e)},Vl=function(e){return c(this,j,Wa).style.color=e,Ag(getComputedStyle(c(this,j,Wa)).getPropertyValue("color"))};class w0{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){yt("Abstract method `_fetch` called.")}}class x0 extends w0{async _fetch(t){const e=await ad(t,"arraybuffer");return new Uint8Array(e)}}if(fe){var Pg=Promise.withResolvers(),mh=null;(async()=>{const t=await Promise.resolve().then(()=>_d),e=await Promise.resolve().then(()=>_d),s=await Promise.resolve().then(()=>_d),i=await Promise.resolve().then(()=>_d);let n,r;return new Map(Object.entries({fs:t,http:e,https:s,url:i,canvas:n,path2d:r}))})().then(t=>{mh=t,Pg.resolve()},t=>{st(`loadPackages: ${t}`),mh=new Map,Pg.resolve()})}class vn{static get promise(){return Pg.promise}static get(t){return mh==null?void 0:mh.get(t)}}async function S0(a){const e=await vn.get("fs").promises.readFile(a);return new Uint8Array(e)}class tx extends _0{}class ex extends b0{_createCanvas(t,e){return vn.get("canvas").createCanvas(t,e)}}class sx extends v0{async _fetch(t){return S0(t)}}class ix extends w0{async _fetch(t){return S0(t)}}const ke={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Fg(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 Rg{getPattern(){yt("Abstract method `getPattern` called.")}}class nx extends Rg{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===ke.STROKE||i===ke.FILL){const r=e.current.getClippedPathBoundingBox(i,Tt(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),d=l.context;d.clearRect(0,0,d.canvas.width,d.canvas.height),d.beginPath(),d.rect(0,0,d.canvas.width,d.canvas.height),d.translate(-r[0],-r[1]),s=z.transform(s,[1,0,0,1,r[0],r[1]]),d.transform(...e.baseTransform),this.matrix&&d.transform(...this.matrix),Fg(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 Fg(t,this._bbox),n=this._createGradient(t);return n}}function Lg(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,y=(h[i]+t.offsetX)*t.scaleX,x=(h[i+1]+t.offsetY)*t.scaleY;if(p>=x)return;const S=l[n],C=l[n+1],E=l[n+2],M=l[r],k=l[r+1],O=l[r+2],P=l[o],F=l[o+1],R=l[o+2],W=Math.round(p),B=Math.round(x);let X,K,tt,V,H,Qt,Jt,le;for(let zt=W;zt<=B;zt++){if(zt<_){const dt=zt<p?0:(p-zt)/(p-_);X=f-(f-m)*dt,K=S-(S-M)*dt,tt=C-(C-k)*dt,V=E-(E-O)*dt}else{let dt;zt>x?dt=1:_===x?dt=0:dt=(_-zt)/(_-x),X=m-(m-y)*dt,K=M-(M-P)*dt,tt=k-(k-F)*dt,V=O-(O-R)*dt}let _t;zt<p?_t=0:zt>x?_t=1:_t=(p-zt)/(p-x),H=f-(f-y)*_t,Qt=S-(S-P)*_t,Jt=C-(C-F)*_t,le=E-(E-R)*_t;const Pe=Math.round(Math.min(X,H)),fi=Math.round(Math.max(X,H));let Pt=u*zt+Pe*4;for(let dt=Pe;dt<=fi;dt++)_t=(X-dt)/(X-H),_t<0?_t=0:_t>1&&(_t=1),d[Pt++]=K-(K-Qt)*_t|0,d[Pt++]=tt-(tt-Jt)*_t|0,d[Pt++]=V-(V-le)*_t|0,d[Pt++]=255}}function rx(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++)Lg(a,e,s[d],s[d+1],s[d+o],i[d],i[d+1],i[d+o]),Lg(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)Lg(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 ox extends Rg{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,y=g+2*2,x=s.getCanvas("mesh",_,y),S=x.context,C=S.createImageData(u,g);if(e){const M=C.data;for(let k=0,O=M.length;k<O;k+=4)M[k]=e[0],M[k+1]=e[1],M[k+2]=e[2],M[k+3]=255}for(const M of this._figures)rx(C,M,m);return S.putImageData(C,2,2),{canvas:x.canvas,offsetX:o-2*f,offsetY:h-2*p,scaleX:f,scaleY:p}}getPattern(t,e,s,i){Fg(t,this._bbox);let n;if(i===ke.SHADING)n=z.singularValueDecompose2dScale(Tt(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===ke.SHADING?null:this._background,e.cachedCanvases);return i!==ke.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class ax extends Rg{getPattern(){return"hotpink"}}function hx(a){switch(a[0]){case"RadialAxial":return new nx(a);case"Mesh":return new ox(a);case"Dummy":return new ax}throw new Error(`Unknown IR type: ${a[0]}`)}const C0={COLORED:1,UNCOLORED:2},Md=class Md{constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),nd("TilingType: "+n);const d=e[0],u=e[1],g=e[2],f=e[3],p=g-d,m=f-u,_=z.singularValueDecompose2dScale(this.matrix),y=z.singularValueDecompose2dScale(this.baseTransform),x=_[0]*y[0],S=_[1]*y[1];let C=p,E=m,M=!1,k=!1;const O=Math.ceil(h*x),P=Math.ceil(l*S),F=Math.ceil(p*x),R=Math.ceil(m*S);O>=F?C=h:M=!0,P>=R?E=l:k=!0;const W=this.getSizeAndScale(C,this.ctx.canvas.width,x),B=this.getSizeAndScale(E,this.ctx.canvas.height,S),X=t.cachedCanvases.getCanvas("pattern",W.size,B.size),K=X.context,tt=o.createCanvasGraphics(K);if(tt.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(tt,i,r),K.translate(-W.scale*d,-B.scale*u),tt.transform(W.scale,0,0,B.scale,0,0),K.save(),this.clipBbox(tt,d,u,g,f),tt.baseTransform=Tt(tt.ctx),tt.executeOperatorList(s),tt.endDrawing(),K.restore(),M||k){const V=X.canvas;M&&(C=h),k&&(E=l);const H=this.getSizeAndScale(C,this.ctx.canvas.width,x),Qt=this.getSizeAndScale(E,this.ctx.canvas.height,S),Jt=H.size,le=Qt.size,zt=t.cachedCanvases.getCanvas("pattern-workaround",Jt,le),_t=zt.context,Pe=M?Math.floor(p/h):0,fi=k?Math.floor(m/l):0;for(let Pt=0;Pt<=Pe;Pt++)for(let dt=0;dt<=fi;dt++)_t.drawImage(V,Jt*Pt,le*dt,Jt,le,0,0,Jt,le);return{canvas:zt.canvas,scaleX:H.scale,scaleY:Qt.scale,offsetX:d,offsetY:u}}return{canvas:X.canvas,scaleX:W.scale,scaleY:B.scale,offsetX:d,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(Md.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,o=n-s;t.ctx.rect(e,s,r,o),t.current.updateRectMinMax(Tt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case 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 Fw(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==ke.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}};q(Md,"MAX_PATTERN_SIZE",3e3);let Ig=Md;function lx({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Ee.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 y=t<g?a[t]:255;e[f++]=y&128?l:h,e[f++]=y&64?l:h,e[f++]=y&32?l:h,e[f++]=y&16?l:h,e[f++]=y&8?l:h,e[f++]=y&4?l:h,e[f++]=y&2?l:h,e[f++]=y&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,cx=15,E0=10,k0=1e3,je=16;function dx(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 ux{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 dd(a,t,e,s,i,n,r,o,h,l){const[d,u,g,f,p,m]=Tt(a);if(u===0&&g===0){const x=r*d+p,S=Math.round(x),C=o*f+m,E=Math.round(C),M=(r+h)*d+p,k=Math.abs(Math.round(M)-S)||1,O=(o+l)*f+m,P=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,k,P),a.setTransform(d,u,g,f,p,m),[k,P]}if(d===0&&f===0){const x=o*g+p,S=Math.round(x),C=r*u+m,E=Math.round(C),M=(o+l)*g+p,k=Math.abs(Math.round(M)-S)||1,O=(r+h)*u+m,P=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,P,k),a.setTransform(d,u,g,f,p,m),[P,k]}a.drawImage(t,e,s,i,n,r,o,h,l);const _=Math.hypot(d,u),y=Math.hypot(g,f);return[_*h,y*l]}function gx(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 y of a.data){let x=128;for(;x>0;)u[g++]=y&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 y=(u[g]?4:0)+(u[g-d]?8:0);for(h=1;h<t;h++)y=(y>>2)+(u[g+1]?4:0)+(u[g-d+1]?8:0),i[y]&&(r[l+h]=i[y],++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 y=o*n;const x=y+t;for(;y<x&&!r[y];)y++;if(y===x)continue;m.moveTo(y%n,o);const S=y;let C=r[y];do{const E=p[C];do y+=E;while(!r[y]);const M=r[y];M!==5&&M!==10?(C=M,r[y]=0):(C=M&51*C>>4,r[y]&=C>>2|C<<2),m.lineTo(y%n,y/n|0),r[y]||--f}while(S!==y);--o}return u=null,r=null,function(y){y.save(),y.scale(1/t,-1/e),y.translate(0,-e),y.fill(m),y.beginPath(),y.restore()}}class M0{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=h0,this.textMatrixScale=1,this.fontMatrix=fg,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=pe.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=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=ke.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===ke.STROKE){e||yt("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=ke.FILL,e=null){return z.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function O0(a,t){if(typeof ImageData<"u"&&t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%je,n=(e-i)/je,r=i===0?n:n+1,o=a.createImageData(s,je);let h=0,l;const d=t.data,u=o.data;let g,f,p,m;if(t.kind===ed.GRAYSCALE_1BPP){const _=d.byteLength,y=new Uint32Array(u.buffer,0,u.byteLength>>2),x=y.length,S=s+7>>3,C=4294967295,E=Ee.isLittleEndian?4278190080:255;for(g=0;g<r;g++){for(p=g<n?je:i,l=0,f=0;f<p;f++){const M=_-h;let k=0;const O=M>S?s:M*8-7,P=O&-8;let F=0,R=0;for(;k<P;k+=8)R=d[h++],y[l++]=R&128?C:E,y[l++]=R&64?C:E,y[l++]=R&32?C:E,y[l++]=R&16?C:E,y[l++]=R&8?C:E,y[l++]=R&4?C:E,y[l++]=R&2?C:E,y[l++]=R&1?C:E;for(;k<O;k++)F===0&&(R=d[h++],F=128),y[l++]=R&F?C:E,F>>=1}for(;l<x;)y[l++]=0;a.putImageData(o,0,g*je)}}else if(t.kind===ed.RGBA_32BPP){for(f=0,m=s*je*4,g=0;g<n;g++)u.set(d.subarray(h,h+m)),h+=m,a.putImageData(o,0,f),f+=je;g<r&&(m=s*i*4,u.set(d.subarray(h,h+m)),a.putImageData(o,0,f))}else if(t.kind===ed.RGB_24BPP)for(p=je,m=s*p,g=0;g<r;g++){for(g>=n&&(p=i,m=s*p),l=0,f=m;f--;)u[l++]=d[h++],u[l++]=d[h++],u[l++]=d[h++],u[l++]=255;a.putImageData(o,0,g*je)}else throw new Error(`bad image kind: ${t.kind}`)}function D0(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%je,n=(e-i)/je,r=i===0?n:n+1,o=a.createImageData(s,je);let h=0;const l=t.data,d=o.data;for(let u=0;u<r;u++){const g=u<n?je:i;({srcPos:h}=lx({src:l,srcPos:h,dest:d,width:s,height:g,nonBlackColor:0})),a.putImageData(o,0,u*je)}}function bh(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 ud(a){if(a.strokeStyle=a.fillStyle="#000000",a.fillRule="nonzero",a.globalAlpha=1,a.lineWidth=1,a.lineCap="butt",a.lineJoin="miter",a.miterLimit=10,a.globalCompositeOperation="source-over",a.font="10px sans-serif",a.setLineDash!==void 0&&(a.setLineDash([]),a.lineDashOffset=0),!fe){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function 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)*bn.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const fx=["butt","round","square"],px=["miter","round","bevel"],mx={},F0={},tf=class tf{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){w(this,Dn);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 ux(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...Tt(this.compositeCtx))}this.ctx.save(),ud(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=Tt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>E0&&typeof s=="function",d=l?Date.now()+cx: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!==Es.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(){v(this,Dn,xf).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(),v(this,Dn,Sf).call(this)}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i,l="prescale1",d,u;for(;n>2&&o>1||r>2&&h>1;){let g=o,f=h;n>2&&o>1&&(g=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/g),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),d=this.cachedCanvases.getCanvas(l,g,f),u=d.context,u.clearRect(0,0,g,f),u.drawImage(t,0,0,o,h,0,0,g,f),t=d.canvas,o=g,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=Tt(e);let h,l,d,u;if((t.bitmap||t.data)&&t.count>1){const 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 P=h.get(l);if(P&&!r){const F=Math.round(Math.min(o[0],o[2])+o[4]),R=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:P,offsetX:F,offsetY:R}}d=P}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),y=Math.round(m-f)||1,x=Math.round(_-p)||1,S=this.cachedCanvases.getCanvas("fillCanvas",y,x),C=S.context,E=f,M=p;C.translate(-E,-M),C.transform(...g),d||(d=this._scaleImage(u.canvas,ki(C)),d=d.img,h&&r&&h.set(l,d)),C.imageSmoothingEnabled=P0(Tt(C),t.interpolate),dd(C,d,0,0,d.width,d.height,0,0,s,i),C.globalCompositeOperation="source-in";const k=z.transform(ki(C),[1,0,0,1,-E,-M]);return C.fillStyle=r?n.getPattern(e,this,k,ke.FILL):n,C.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,S.canvas)),{canvas:S.canvas,offsetX:Math.round(E),offsetY:Math.round(M)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=fx[t]}setLineJoin(t){this.ctx.lineJoin=px[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...Tt(this.suspendedCtx)),bh(this.suspendedCtx,n),dx(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(),bh(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){const _=z.makeHexColor(...r);if(f<0||p<0||f+s>g.width||p+i>g.height){const y=this.cachedCanvases.getCanvas("maskExtension",s,i),x=y.context;x.drawImage(g,-f,-p),x.globalCompositeOperation="destination-atop",x.fillStyle=_,x.fillRect(0,0,s,i),x.globalCompositeOperation="source-over",g=y.canvas,f=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const y=new Path2D;y.rect(f,p,s,i),t.clip(y),t.globalCompositeOperation="destination-atop",t.fillStyle=_,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?(bh(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(),bh(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const d=Tt(i),u=d[0]===0&&d[3]===0||d[1]===0&&d[2]===0,g=u?s.slice(0):null;for(let f=0,p=0,m=t.length;f<m;f++)switch(t[f]|0){case Es.rectangle:r=e[p++],o=e[p++];const _=e[p++],y=e[p++],x=r+_,S=o+y;i.moveTo(r,o),_===0||y===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 Es.moveTo:r=e[p++],o=e[p++],i.moveTo(r,o),u||n.updatePathMinMax(d,r,o);break;case Es.lineTo:r=e[p++],o=e[p++],i.lineTo(r,o),u||n.updatePathMinMax(d,r,o);break;case Es.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 Es.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 Es.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 Es.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,ki(e),ke.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,ki(e),ke.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=mx}eoClip(){this.pendingClip=F0}beginText(){this.current.textMatrix=h0,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||fg,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&st("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=((d=s.systemFontInfo)==null?void 0:d.css)||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<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&pe.FILL_STROKE_MASK,u=!!(h&pe.ADD_TO_PATH_FLAG),g=r.patternFill&&!o.missingFile;let f;(o.disableFontFace||u||g)&&(f=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||g?(n.save(),n.translate(e,s),n.beginPath(),f(n,l),i&&n.setTransform(...i),(d===pe.FILL||d===pe.FILL_STROKE)&&n.fill(),(d===pe.STROKE||d===pe.FILL_STROKE)&&n.stroke(),n.restore()):((d===pe.FILL||d===pe.FILL_STROKE)&&n.fillText(t,e,s),(d===pe.STROKE||d===pe.FILL_STROKE)&&n.strokeText(t,e,s)),u&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Tt(n),x:e,y:s,fontSize:l,addToPath:f})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return ot(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,d=e.textHScale*l,u=t.length,g=s.vertical,f=g?1:-1,p=s.defaultVMetrics,m=i*e.fontMatrix[0],_=e.textRenderingMode===pe.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(d,-1):n.scale(d,1);let y;if(e.patternFill){n.save();const M=e.fillColor.getPattern(n,this,ki(n),ke.FILL);y=Tt(n),n.restore(),n.fillStyle=M}let x=e.lineWidth;const S=e.textMatrixScale;if(S===0||x===0){const M=e.textRenderingMode&pe.FILL_STROKE_MASK;(M===pe.STROKE||M===pe.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 k=0;for(const O of t)M.push(O.unicode),k+=O.width;n.fillText(M.join(""),0,0),e.x+=k*m*d,n.restore(),this.compose();return}let C=0,E;for(E=0;E<u;++E){const M=t[E];if(typeof M=="number"){C+=f*M*i/1e3;continue}let k=!1;const O=(M.isSpace?h:0)+o,P=M.fontChar,F=M.accent;let R,W,B=M.width;if(g){const K=M.vmetric||p,tt=-(M.vmetric?K[1]:B*.5)*m,V=K[2]*m;B=K?-K[0]:B,R=tt/r,W=(C+V)/r}else R=C/r,W=0;if(s.remeasure&&B>0){const K=n.measureText(P).width*1e3/i*r;if(B<K&&this.isFontSubpixelAAEnabled){const tt=B/K;k=!0,n.save(),n.scale(tt,1),R/=tt}else B!==K&&(R+=(B-K)/2e3*i/r)}if(this.contentVisible&&(M.isInFont||s.missingFile)){if(_&&!F)n.fillText(P,R,W);else if(this.paintChar(P,R,W,y),F){const K=R+i*F.offset.x/r,tt=W-i*F.offset.y/r;this.paintChar(F.fontChar,K,tt,y)}}const X=g?B*m-O*l:B*m+O*l;C+=X,k&&n.restore()}g?e.y-=C:e.x+=C*d,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,d=s.textHScale*r,u=s.fontMatrix||fg,g=t.length,f=s.textRenderingMode===pe.INVISIBLE;let p,m,_,y;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"){y=o*m*n/1e3,this.ctx.translate(y,0),s.x+=y*d;continue}const x=(m.isSpace?l:0)+h,S=i.charProcOperatorList[m.operatorListId];if(!S){st(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(S),this.restore()),_=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||Tt(this.ctx),n={createCanvasGraphics:r=>new tf(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new Ig(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=hx(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,ki(e),ke.SHADING);const i=ki(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(){yt("Should not call beginInlineImage")}beginImageData(){yt("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Tt(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(Tt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||nd("TODO: Support non-isolated groups."),t.knockout&&st("Knockout groups not supported.");const s=Tt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=z.getAxialAlignedBoundingBox(t.bbox,Tt(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()),bh(e,g),this.ctx=g,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=Tt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=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(v(this,Dn,xf).call(this),ud(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(Tt(this.ctx)),{viewportScale:d}=this,u=Math.ceil(r*this.outputScaleX*d),g=Math.ceil(o*this.outputScaleY*d);this.annotationCanvas=this.canvasFactory.create(u,g);const{canvas:f,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(h,0,0,-l,0,o*l),ud(this.ctx)}else ud(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new M0(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),v(this,Dn,Sf).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=gx(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=Tt(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let d=0,u=r.length;d<u;d+=2){const g=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,ki(e),ke.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),dd(e,d.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){st("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){st("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,d=i.length;l<d;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!fe){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;O0(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,ki(i));i.imageSmoothingEnabled=P0(Tt(i),t.interpolate),dd(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;O0(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),dd(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===F0?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Tt(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const d=h*t;r=o=d<1?1/d:1}else if(t===0)r=1/h,o=1/l;else{const d=h*t,u=l*t;r=d<1?1/d:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),d=Math.hypot(i,n);if(t===0)r=d/h,o=l/h;else{const u=t*h;r=d>u?d/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};Dn=new WeakSet,xf=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)},Sf=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 No=tf;for(const a in Es)No.prototype[a]!==void 0&&(No.prototype[Es[a]]=No.prototype[a]);class Mi{static get workerPort(){return c(this,Vh)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");b(this,Vh,t)}static get workerSrc(){return c(this,Gh)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");b(this,Gh,t)}}Vh=new WeakMap,Gh=new WeakMap,w(Mi,Vh,null),w(Mi,Gh,"");const gd={UNKNOWN:0,DATA:1,ERROR:2},Bt={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Ue(a){switch(a instanceof Error||typeof a=="object"&&a!==null||yt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new cr(a.message);case"MissingPDFException":return new lr(a.message);case"PasswordException":return new mg(a.message,a.code);case"UnexpectedResponseException":return new rd(a.message,a.status);case"UnknownErrorException":return new bg(a.message,a.details);default:return new bg(a.message,a.toString())}}class vh{constructor(t,e,s){w(this,us);w(this,sa,new AbortController);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),s.addEventListener("message",v(this,us,Db).bind(this),{signal:c(this,sa).signal})}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:Bt.PULL,streamId:n,desiredSize:l.desiredSize}),d.promise},cancel:l=>{Gt(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:Bt.CANCEL,streamId:n,reason:Ue(l)}),d.promise}},s)}destroy(){var t;(t=c(this,sa))==null||t.abort(),b(this,sa,null)}}sa=new WeakMap,us=new WeakSet,Db=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){v(this,us,Fb).call(this,t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===gd.DATA)i.resolve(t.data);else if(t.callback===gd.ERROR)i.reject(Ue(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;new Promise(function(r){r(e(t.data))}).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:gd.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:gd.ERROR,callbackId:t.callbackId,reason:Ue(r)})});return}if(t.streamId){v(this,us,Pb).call(this,t);return}e(t.data)},Pb=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:Bt.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Bt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){Gt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Bt.ERROR,streamId:e,reason:Ue(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:Bt.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Bt.START_COMPLETE,streamId:e,reason:Ue(l)})})},Fb=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 Bt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Ue(t.reason));break;case Bt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Ue(t.reason));break;case Bt.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:Bt.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:Bt.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Bt.PULL_COMPLETE,streamId:e,reason:Ue(h)})});break;case Bt.ENQUEUE:if(Gt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Bt.CLOSE:if(Gt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),v(this,us,Yd).call(this,r,e);break;case Bt.ERROR:Gt(r,"error should have stream controller"),r.controller.error(Ue(t.reason)),v(this,us,Yd).call(this,r,e);break;case Bt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Ue(t.reason)),v(this,us,Yd).call(this,r,e);break;case Bt.CANCEL:if(!o)break;new Promise(function(h){var l;h((l=o.onCancel)==null?void 0:l.call(o,Ue(t.reason)))}).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Bt.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Bt.CANCEL_COMPLETE,streamId:e,reason:Ue(h)})}),o.sinkCapability.reject(Ue(t.reason)),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}},Yd=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 bx{constructor({parsedData:t,rawData:e}){w(this,Lr);w(this,Yh);b(this,Lr,t),b(this,Yh,e)}getRaw(){return c(this,Yh)}get(t){return c(this,Lr).get(t)??null}getAll(){return vg(c(this,Lr))}has(t){return c(this,Lr).has(t)}}Lr=new WeakMap,Yh=new WeakMap;const Bo=Symbol("INTERNAL");class vx{constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){w(this,Uh,!1);w(this,qh,!1);w(this,$h,!1);w(this,ia,!0);b(this,Uh,!!(t&Ye.DISPLAY)),b(this,qh,!!(t&Ye.PRINT)),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(c(this,$h))return c(this,ia);if(!c(this,ia))return!1;const{print:t,view:e}=this.usage;return c(this,Uh)?(e==null?void 0:e.viewState)!=="OFF":c(this,qh)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,e,s=!1){t!==Bo&&yt("Internal method `_setVisible` called."),b(this,$h,s),b(this,ia,e)}}Uh=new WeakMap,qh=new WeakMap,$h=new WeakMap,ia=new WeakMap;class yx{constructor(t,e=Ye.DISPLAY){w(this,Kh);w(this,Pn,null);w(this,pt,new Map);w(this,na,null);w(this,ra,null);if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,b(this,ra,t.order);for(const s of t.groups)c(this,pt).set(s.id,new vx(e,s));if(t.baseState==="OFF")for(const s of c(this,pt).values())s._setVisible(Bo,!1);for(const s of t.on)c(this,pt).get(s)._setVisible(Bo,!0);for(const s of t.off)c(this,pt).get(s)._setVisible(Bo,!1);b(this,na,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:(st(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return v(this,Kh,Cf).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!c(this,pt).has(e))return st(`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 st(`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 st(`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 st(`Optional content group not found: ${e}`),!0;if(c(this,pt).get(e).visible)return!1}return!0}return st(`Unknown optional content policy ${t.policy}.`),!0}return st(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){var n;const i=c(this,pt).get(t);if(!i){st(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const r of i.rbGroups)for(const o of r)o!==t&&((n=c(this,pt).get(o))==null||n._setVisible(Bo,!1,!0));i._setVisible(Bo,!!e,!0),b(this,Pn,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":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}b(this,Pn,null)}get hasInitialVisibility(){return c(this,na)===null||this.getHash()===c(this,na)}getOrder(){return c(this,pt).size?c(this,ra)?c(this,ra).slice():[...c(this,pt).keys()]:null}getGroups(){return c(this,pt).size>0?vg(c(this,pt)):null}getGroup(t){return c(this,pt).get(t)||null}getHash(){if(c(this,Pn)!==null)return c(this,Pn);const t=new p0;for(const[e,s]of c(this,pt))t.update(`${e}:${s.visible}`);return b(this,Pn,t.hexdigest())}}Pn=new WeakMap,pt=new WeakMap,na=new WeakMap,ra=new WeakMap,Kh=new WeakSet,Cf=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=v(this,Kh,Cf).call(this,n);else if(c(this,pt).has(n))r=c(this,pt).get(n).visible;else return st(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"};class _x{constructor(t,{disableRange:e=!1,disableStream:s=!1}){Gt(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)});Gt(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(){Gt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new wx(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new xx(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 wx{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Sg(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 xx{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 Sx(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,_,y]=g;if(m=parseInt(m,10),m in u){if(m===0)break;continue}u[m]=[_,y]}const p=[];for(let m=0;m<u.length&&m in u;++m){let[_,y]=u[m];y=o(y),_&&(y=unescape(y),m===0&&(y=h(y))),p.push(y)}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 jg(a,t){const e=new Headers;if(!a||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function Ng({responseHeaders:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a.get("Accept-Ranges")!=="bytes"||(a.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function Bg(a){const t=a.get("Content-Disposition");if(t){let e=Sx(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Sg(e))return e}return null}function fd(a,t){return a===404||a===0&&t.startsWith("file:")?new lr('Missing PDF "'+t+'".'):new rd(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function R0(a){return a===200||a===206}function L0(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function I0(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(st(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class j0{constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=jg(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 Gt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new Cx(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Ax(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 Cx{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers),i=e.url;fetch(i,L0(s,this._withCredentials,this._abortController)).then(n=>{if(!R0(n.status))throw fd(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=Ng({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=Bg(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new cr("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 Ax{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,L0(n,this._withCredentials,this._abortController)).then(o=>{if(!R0(o.status))throw fd(o.status,r);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:I0(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}const Hg=200,Wg=206;function Tx(a){const t=a.response;return typeof t!="string"?t:od(t).buffer}class Ex{constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=jg(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,s){const i={begin:t,end:e};for(const n in s)i[n]=s[n];return this.request(i)}requestFull(t){return this.request(t)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=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=Tx(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 kx{constructor(t){this._source=t,this._manager=new Ex(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return Gt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Mx(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Ox(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 Mx{constructor(t,e){this._manager=t;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(s),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),s=new Headers(e.getAllResponseHeaders().trim().split(/[\r\n]+/).map(r=>{const[o,...h]=r.split(": ");return[o,h.join(": ")]})),{allowRangeRequests:i,suggestedLength:n}=Ng({responseHeaders: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._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=fd(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){var e;(e=this.onProgress)==null||e.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Ox{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=fd(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 Dx=/^[a-z][a-z0-9\-+.]+:/i;function Px(a){if(Dx.test(a))return new URL(a);const t=vn.get("url");return new URL(t.pathToFileURL(a))}function N0(a,t,e){return a.protocol==="http:"?vn.get("http").request(a,{headers:t},e):vn.get("https").request(a,{headers:t},e)}class Fx{constructor(t){this.source=t,this.url=Px(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=jg(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 Gt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new Ix(this):new Rx(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new jx(this,t,e):new Lx(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 cr("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)}}class Rx extends B0{constructor(t){super(t);const e=Object.fromEntries(t.headers),s=i=>{if(i.statusCode===404){const h=new lr(`Missing PDF "${this._url}".`);this._storedError=h,this._headersCapability.reject(h);return}this._headersCapability.resolve(),this._setReadableStream(i);const n=new Headers(this._readableStream.headers),{allowRangeRequests:r,suggestedLength:o}=Ng({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=o||this._contentLength,this._filename=Bg(n)};this._request=N0(this._url,e,s),this._request.on("error",i=>{this._storedError=i,this._headersCapability.reject(i)}),this._request.end()}}class Lx extends H0{constructor(t,e,s){super(t);const i=Object.fromEntries(t.headers);i.Range=`bytes=${e}-${s-1}`;const n=r=>{if(r.statusCode===404){const o=new lr(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(r)};this._request=N0(this._url,i,n),this._request.on("error",r=>{this._storedError=r}),this._request.end()}}class Ix extends B0{constructor(t){super(t);const e=vn.get("fs");e.promises.lstat(this._url).then(s=>{this._contentLength=s.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()},s=>{s.code==="ENOENT"&&(s=new lr(`Missing PDF "${this._url}".`)),this._storedError=s,this._headersCapability.reject(s)})}}class jx extends H0{constructor(t,e,s){super(t);const i=vn.get("fs");this._setReadableStream(i.createReadStream(this._url,{start:e,end:s-1}))}}const Nx=1e5,Ne=30,Bx=.8,Ut=class Ut{constructor({textContentSource:t,container:e,viewport:s}){w(this,Hi);w(this,Fn,Promise.withResolvers());w(this,He,null);w(this,Qh,!1);w(this,Jh,!!((ib=globalThis.FontInspector)!=null&&ib.enabled));w(this,Ir,null);w(this,Bi,null);w(this,Zh,0);w(this,tl,0);w(this,jr,null);w(this,oa,null);w(this,aa,0);w(this,Rn,0);w(this,ha,Object.create(null));w(this,el,[]);w(this,la,null);w(this,Nr,[]);w(this,sl,new WeakMap);w(this,il,null);var h;if(t instanceof ReadableStream)b(this,la,t);else if(typeof t=="object")b(this,la,new ReadableStream({start(l){l.enqueue(t),l.close()}}));else throw new Error('No "textContentSource" parameter specified.');b(this,He,b(this,oa,e)),b(this,Rn,s.scale*(globalThis.devicePixelRatio||1)),b(this,aa,s.rotation),b(this,Bi,{div:null,properties:null,ctx:null});const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;b(this,il,[1,0,0,-1,-r,o+n]),b(this,tl,i),b(this,Zh,n),v(h=Ut,Ke,Ib).call(h),dr(e,s),c(this,Fn).promise.finally(()=>{c(Ut,ca).delete(this),b(this,Bi,null),b(this,ha,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Ee.platform;return ot(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{c(this,jr).read().then(({value:e,done:s})=>{if(s){c(this,Fn).resolve();return}c(this,Ir)??b(this,Ir,e.lang),Object.assign(c(this,ha),e.styles),v(this,Hi,Rb).call(this,e.items),t()},c(this,Fn).reject)};return b(this,jr,c(this,la).getReader()),c(Ut,ca).add(this),t(),c(this,Fn).promise}update({viewport:t,onBefore:e=null}){var n;const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==c(this,aa)&&(e==null||e(),b(this,aa,i),dr(c(this,oa),{rotation:i})),s!==c(this,Rn)){e==null||e(),b(this,Rn,s);const r={div:null,properties:null,ctx:v(n=Ut,Ke,Ud).call(n,c(this,Ir))};for(const o of c(this,Nr))r.properties=c(this,sl).get(o),r.div=o,v(this,Hi,Af).call(this,r)}}cancel(){var e;const t=new cr("TextLayer task cancelled.");(e=c(this,jr))==null||e.cancel(t).catch(()=>{}),b(this,jr,null),c(this,Fn).reject(t)}get textDivs(){return c(this,Nr)}get textContentItemsStr(){return c(this,el)}static cleanup(){if(!(c(this,ca).size>0)){c(this,Br).clear();for(const{canvas:t}of c(this,Hr).values())t.remove();c(this,Hr).clear()}}};Fn=new WeakMap,He=new WeakMap,Qh=new WeakMap,Jh=new WeakMap,Ir=new WeakMap,Bi=new WeakMap,Zh=new WeakMap,tl=new WeakMap,jr=new WeakMap,oa=new WeakMap,aa=new WeakMap,Rn=new WeakMap,ha=new WeakMap,el=new WeakMap,la=new WeakMap,Nr=new WeakMap,sl=new WeakMap,il=new WeakMap,Br=new WeakMap,Hr=new WeakMap,nl=new WeakMap,Ln=new WeakMap,ca=new WeakMap,Hi=new WeakSet,Rb=function(t){var i,n;if(c(this,Qh))return;(n=c(this,Bi)).ctx??(n.ctx=v(i=Ut,Ke,Ud).call(i,c(this,Ir)));const e=c(this,Nr),s=c(this,el);for(const r of t){if(e.length>Nx){st("Ignoring additional textDivs for performance reasons."),b(this,Qh,!0);return}if(r.str===void 0){if(r.type==="beginMarkedContentProps"||r.type==="beginMarkedContent"){const o=c(this,He);b(this,He,document.createElement("span")),c(this,He).classList.add("markedContent"),r.id!==null&&c(this,He).setAttribute("id",`${r.id}`),o.append(c(this,He))}else r.type==="endMarkedContent"&&b(this,He,c(this,He).parentNode);continue}s.push(r.str),v(this,Hi,Lb).call(this,r)}},Lb=function(t){var m;const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};c(this,Nr).push(e);const i=z.transform(c(this,il),t.transform);let n=Math.atan2(i[1],i[0]);const r=c(this,ha)[t.fontName];r.vertical&&(n+=Math.PI/2);let o=c(this,Jh)&&r.fontSubstitution||r.fontFamily;o=Ut.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*v(m=Ut,Ke,jb).call(m,o,c(this,Ir));let d,u;n===0?(d=i[4],u=i[5]-l):(d=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const g="calc(var(--scale-factor)*",f=e.style;c(this,He)===c(this,oa)?(f.left=`${(100*d/c(this,tl)).toFixed(2)}%`,f.top=`${(100*u/c(this,Zh)).toFixed(2)}%`):(f.left=`${g}${d.toFixed(2)}px)`,f.top=`${g}${u.toFixed(2)}px)`),f.fontSize=`${g}${(c(Ut,Ln)*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,c(this,Jh)&&(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]),y=Math.abs(t.transform[3]);_!==y&&Math.max(_,y)/Math.min(_,y)>1.5&&(p=!0)}if(p&&(s.canvasWidth=r.vertical?t.height:t.width),c(this,sl).set(e,s),c(this,Bi).div=e,c(this,Bi).properties=s,v(this,Hi,Af).call(this,c(this,Bi)),s.hasText&&c(this,He).append(e),s.hasEOL){const _=document.createElement("br");_.setAttribute("role","presentation"),c(this,He).append(_)}},Af=function(t){var o;const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(c(Ut,Ln)>1&&(r=`scale(${1/c(Ut,Ln)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:h}=n,{canvasWidth:l,fontSize:d}=s;v(o=Ut,Ke,Tf).call(o,i,d*c(this,Rn),h);const{width:u}=i.measureText(e.textContent);u>0&&(r=`scaleX(${l*c(this,Rn)/u}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)},Ke=new WeakSet,Ud=function(t=null){let e=c(this,Hr).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,Hr).set(t,e),c(this,nl).set(e,{size:0,family:""})}return e},Tf=function(t,e,s){const i=c(this,nl).get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)},Ib=function(){if(c(this,Ln)!==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,Ln,t.getBoundingClientRect().height),t.remove()},jb=function(t,e){const s=c(this,Br).get(t);if(s)return s;const i=v(this,Ke,Ud).call(this,e);i.canvas.width=i.canvas.height=Ne,v(this,Ke,Tf).call(this,i,Ne,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const d=r/(r+o);return c(this,Br).set(t,d),i.canvas.width=i.canvas.height=0,d}i.strokeStyle="red",i.clearRect(0,0,Ne,Ne),i.strokeText("g",0,0);let h=i.getImageData(0,0,Ne,Ne).data;o=0;for(let d=h.length-1-3;d>=0;d-=4)if(h[d]>0){o=Math.ceil(d/4/Ne);break}i.clearRect(0,0,Ne,Ne),i.strokeText("A",0,Ne),h=i.getImageData(0,0,Ne,Ne).data,r=0;for(let d=0,u=h.length;d<u;d+=4)if(h[d]>0){r=Ne-Math.floor(d/4/Ne);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):Bx;return c(this,Br).set(t,l),l},w(Ut,Ke),w(Ut,Br,new Map),w(Ut,Hr,new Map),w(Ut,nl,new WeakMap),w(Ut,Ln,null),w(Ut,ca,new Set);let yh=Ut;class _h{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(_h.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 Hx=65536,Wx=100,zx=5e3,Xx=fe?ex:Jw,Vx=fe?sx:y0,Gx=fe?tx:Zw,Yx=fe?ix:x0;function Ux(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?qx(a.url):null,i=a.data?$x(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof z0?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:Hx;let d=a.worker instanceof Ho?a.worker:null;const u=a.verbosity,g=typeof a.docBaseUrl=="string"&&!hd(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,p=a.cMapPacked!==!1,m=a.CMapReaderFactory||Vx,_=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,y=a.StandardFontDataFactory||Yx,x=a.stopAtErrors!==!0,S=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,C=a.isEvalSupported!==!1,E=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!fe,M=typeof a.isChrome=="boolean"?a.isChrome:!Ee.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),k=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,O=typeof a.disableFontFace=="boolean"?a.disableFontFace:fe,P=a.fontExtraProperties===!0,F=a.enableXfa===!0,R=a.ownerDocument||globalThis.document,W=a.disableRange===!0,B=a.disableStream===!0,X=a.disableAutoFetch===!0,K=a.pdfBug===!0,tt=a.CanvasFactory||Xx,V=a.FilterFactory||Gx,H=a.enableHWA===!0,Qt=h?h.length:a.length??NaN,Jt=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!fe&&!O,le=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:m===y0&&y===x0&&f&&_&&fh(f,document.baseURI)&&fh(_,document.baseURI);a.canvasFactory&&g0("`canvasFactory`-instance option, please use `CanvasFactory` instead."),a.filterFactory&&g0("`filterFactory`-instance option, please use `FilterFactory` instead.");const zt=null;Mw(u);const _t={canvasFactory:new tt({ownerDocument:R,enableHWA:H}),filterFactory:new V({docId:e,ownerDocument:R}),cMapReaderFactory:le?null:new m({baseUrl:f,isCompressed:p}),standardFontDataFactory:le?null:new y({baseUrl:_})};if(!d){const Pt={verbosity:u,port:Mi.workerPort};d=Pt.port?Ho.fromPort(Pt):new Ho(Pt),t._worker=d}const Pe={docId:e,apiVersion:"4.8.69",data:i,password:o,disableAutoFetch:X,rangeChunkSize:l,length:Qt,docBaseUrl:g,enableXfa:F,evaluatorOptions:{maxImageSize:S,disableFontFace:O,ignoreErrors:x,isEvalSupported:C,isOffscreenCanvasSupported:E,isChrome:M,canvasMaxAreaInBytes:k,fontExtraProperties:P,useSystemFonts:Jt,cMapUrl:le?f:null,standardFontDataUrl:le?_:null}},fi={disableFontFace:O,fontExtraProperties:P,ownerDocument:R,pdfBug:K,styleElement:zt,loadingParams:{disableAutoFetch:X,enableXfa:F}};return d.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const Pt=d.messageHandler.sendWithPromise("GetDocRequest",Pe,i?[i.buffer]:null);let dt;if(h)dt=new _x(h,{disableRange:W,disableStream:B});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let mo;fe?mo=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&fh(s)?j0:Fx:mo=fh(s)?j0:kx,dt=new mo({url:s,length:Qt,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:W,disableStream:B})}return Pt.then(mo=>{if(t.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const bo=new vh(e,mo,d.port),pi=new Zx(bo,t,dt,fi,_t);t._transport=pi,bo.send("Ready",null)})}).catch(t._capability.reject),t}function qx(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(fe&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function $x(a){if(fe&&typeof Buffer<"u"&&a instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength)return a;if(typeof a=="string")return 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 Dd=class Dd{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Fe(Dd,Od)._++}`,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)}};Od=new WeakMap,w(Dd,Od,0);let zg=Dd;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){yt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Kx{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return ot(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 Qx{constructor(t,e,s,i=!1){w(this,gs);w(this,In,null);w(this,Wi,!1);this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new u0:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new X0,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 gh({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 ot(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=pn.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:d=null,isEditing:u=!1}){var C,E;(C=this._stats)==null||C.time("Overall");const g=this._transport.getRenderingIntent(s,i,d,u),{renderingIntent:f,cacheKey:p}=g;b(this,Wi,!1),v(this,gs,qd).call(this),o||(o=this._transport.getOptionalContentConfig(f));let m=this._intentStates.get(p);m||(m=Object.create(null),this._intentStates.set(p,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const _=!!(f&Ye.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(E=this._stats)==null||E.time("Page Request"),this._pumpOperatorList(g));const y=M=>{var k;m.renderTasks.delete(x),(this._maybeCleanupAfterRender||_)&&b(this,Wi,!0),v(this,gs,Va).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"),(k=globalThis.Stats)!=null&&k.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},x=new Xg({callback:y,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,k])=>{var O;if(this.destroyed){y();return}if((O=this._stats)==null||O.time("Rendering"),!(k.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:k}),x.operatorListChanged()}).catch(y),S}getOperatorList({intent:t="display",annotationMode:e=pn.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=>_h.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,Wi,!1),v(this,gs,qd).call(this),Promise.all(t)}cleanup(t=!1){b(this,Wi,!0);const e=v(this,gs,Va).call(this,!1);return t&&e&&this._stats&&(this._stats=new u0),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&&v(this,gs,Va).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();v(this,gs,Va).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 xg){let i=Wx;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 cr(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}}In=new WeakMap,Wi=new WeakMap,gs=new WeakSet,Va=function(t=!1){if(v(this,gs,qd).call(this),!c(this,Wi)||this.destroyed)return!1;if(t)return b(this,In,setTimeout(()=>{b(this,In,null),v(this,gs,Va).call(this,!1)},zx)),!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,Wi,!1),!0},qd=function(){c(this,In)&&(clearTimeout(c(this,In)),b(this,In,null))};class Jx{constructor(){w(this,zi,new Map);w(this,Pd,Promise.resolve())}postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};c(this,Pd).then(()=>{for(const[i]of c(this,zi))i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if((s==null?void 0:s.signal)instanceof AbortSignal){const{signal:n}=s;if(n.aborted){st("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}c(this,zi).set(e,i)}removeEventListener(t,e){const s=c(this,zi).get(e);s==null||s(),c(this,zi).delete(e)}terminate(){for(const[,t]of c(this,zi))t==null||t();c(this,zi).clear()}}zi=new WeakMap,Pd=new WeakMap;const St=class St{constructor({name:t=null,port:e=null,verbosity:s=Ow()}={}){w(this,da);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(St,zr))!=null&&i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(c(St,zr)||b(St,zr,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return fe?Promise.all([vn.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 vh("main","worker",t),this._messageHandler.on("ready",function(){}),v(this,da,$d).call(this)}_initialize(){if(c(St,Wr)||c(St,ua,Kd)){this._setupFakeWorker();return}let{workerSrc:t}=St;try{St._isSameOrigin(window.location.href,t)||(t=St._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new vh("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,v(this,da,$d).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(){c(St,Wr)||(st("Setting up fake worker."),b(St,Wr,!0)),St._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Jx;this._port=e;const s=`fake${Fe(St,Fd)._++}`,i=new vh(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new vh(s,s+"_worker",e),v(this,da,$d).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(St,zr))==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,zr))==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 St(t)}static get workerSrc(){if(Mi.workerSrc)return Mi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return ot(this,"_setupFakeWorkerGlobal",(async()=>c(this,ua,Kd)?c(this,ua,Kd):(await import(this.workerSrc)).WorkerMessageHandler)())}};Fd=new WeakMap,Wr=new WeakMap,zr=new WeakMap,da=new WeakSet,$d=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},ua=new WeakSet,Kd=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},w(St,ua),w(St,Fd,0),w(St,Wr,!1),w(St,zr),fe&&(b(St,Wr,!0),Mi.workerSrc||(Mi.workerSrc="./pdf.worker.mjs")),St._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},St._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let Ho=St;class Zx{constructor(t,e,s,i,n){w(this,Xr);w(this,Xi,new Map);w(this,oi,new Map);w(this,ga,new Map);w(this,fa,new Map);w(this,ai,null);this.messageHandler=t,this.loadingTask=e,this.commonObjs=new X0,this.fontLoader=new Kw({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 ot(this,"annotationStorage",new Dg)}getRenderingIntent(t,e=pn.ENABLE,s=null,i=!1,n=!1){let r=Ye.DISPLAY,o=Og;switch(t){case"any":r=Ye.ANY;break;case"display":break;case"print":r=Ye.PRINT;break;default:st(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Ye.PRINT&&s instanceof m0?s:this.annotationStorage;switch(e){case pn.DISABLE:r+=Ye.ANNOTATIONS_DISABLE;break;case pn.ENABLE:break;case pn.ENABLE_FORMS:r+=Ye.ANNOTATIONS_FORMS;break;case pn.ENABLE_STORAGE:r+=Ye.ANNOTATIONS_STORAGE,o=h.serializable;break;default:st(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Ye.IS_EDITING),n&&(r+=Ye.OPLIST);const{ids:l,hash:d}=h.modifiedIds,u=[r,o.hash,d];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}destroy(){var s;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(s=c(this,ai))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const i of c(this,oi).values())t.push(i._destroy());c(this,oi).clear(),c(this,ga).clear(),c(this,fa).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,Xi).clear(),this.filterFactory.destroy(),yh.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new cr("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)=>{Gt(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}Gt(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",async s=>{var o;await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&((o=e.onProgress)==null||o.call(e,this._lastProgress)),this._fullReader.onProgress=h=>{var l;(l=e.onProgress)==null||l.call(e,{loaded:h.loaded,total:h.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{Gt(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}Gt(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 Kx(s,this))}),t.on("DocException",function(s){let i;switch(s.name){case"PasswordException":i=new mg(s.message,s.code);break;case"InvalidPDFException":i=new l0(s.message);break;case"MissingPDFException":i=new lr(s.message);break;case"UnexpectedResponseException":i=new rd(s.message,s.status);break;case"UnknownErrorException":i=new bg(s.message,s.details);break;default:yt("DocException - expected a valid Error.")}e._capability.reject(i)}),t.on("PasswordRequest",s=>{if(b(this,ai,Promise.withResolvers()),e.onPassword){const i=n=>{n instanceof Error?c(this,ai).reject(n):c(this,ai).resolve({password:n})};try{e.onPassword(i,s.code)}catch(n){c(this,ai).reject(n)}}else c(this,ai).reject(new mg(s.message,s.code));return c(this,ai).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,oi).get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{var r;if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:o,fontExtraProperties:h,pdfBug:l}=this._params;if("error"in n){const f=n.error;st(`Error during font loading: ${f}`),this.commonObjs.resolve(s,f);break}const d=l&&((r=globalThis.FontInspector)!=null&&r.enabled)?(f,p)=>globalThis.FontInspector.fontAdded(f,p):null,u=new Qw(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;Gt(g,"The imageRef must be defined.");for(const f of c(this,oi).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,oi).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)>Aw&&(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",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var s;this.annotationStorage.size<=0&&st("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((s=this._fullReader)==null?void 0:s.filename)??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=c(this,ga).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,fa).set(n.refStr,t);const r=new Qx(e,n,this,this._params.pdfBug);return c(this,oi).set(e,r),r});return c(this,ga).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 v(this,Xr,Gl).call(this,"GetFieldObjects")}hasJSActions(){return v(this,Xr,Gl).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 v(this,Xr,Gl).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 v(this,Xr,Gl).call(this,"GetOptionalContentConfig").then(e=>new yx(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=c(this,Xi).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 bx(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,Xi).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,oi).values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),c(this,Xi).clear(),this.filterFactory.destroy(!0),yh.cleanup()}}cachedPageNumber(t){if(!W0(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return c(this,fa).get(e)??null}}Xi=new WeakMap,oi=new WeakMap,ga=new WeakMap,fa=new WeakMap,ai=new WeakMap,Xr=new WeakSet,Gl=function(t,e=null){const s=c(this,Xi).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return c(this,Xi).set(t,i),i};const pd=Symbol("INITIAL_DATA");class X0{constructor(){w(this,rl);w(this,Rs,Object.create(null))}get(t,e=null){if(e){const i=v(this,rl,Ef).call(this,t);return i.promise.then(()=>e(i.data)),null}const s=c(this,Rs)[t];if(!s||s.data===pd)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=c(this,Rs)[t];return!!e&&e.data!==pd}resolve(t,e=null){const s=v(this,rl,Ef).call(this,t);s.data=e,s.resolve()}clear(){var t;for(const e in c(this,Rs)){const{data:s}=c(this,Rs)[e];(t=s==null?void 0:s.bitmap)==null||t.close()}b(this,Rs,Object.create(null))}*[Symbol.iterator](){for(const t in c(this,Rs)){const{data:e}=c(this,Rs)[t];e!==pd&&(yield[t,e])}}}Rs=new WeakMap,rl=new WeakSet,Ef=function(t){var e;return(e=c(this,Rs))[t]||(e[t]={...Promise.withResolvers(),data:pd})};class tS{constructor(t){w(this,jn,null);b(this,jn,t),this.onContinue=null}get promise(){return c(this,jn).capability.promise}cancel(t=0){c(this,jn).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=c(this,jn).operatorList;if(!t)return!1;const{annotationCanvasMap:e}=c(this,jn);return t.form||t.canvas&&(e==null?void 0:e.size)>0}}jn=new WeakMap;const Gr=class Gr{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,Nn,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 tS(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(Gr,Vr).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(Gr,Vr).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 No(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,Nn)&&(window.cancelAnimationFrame(c(this,Nn)),b(this,Nn,null)),c(Gr,Vr).delete(this._canvas),this.callback(t||new xg(`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,Nn,window.requestAnimationFrame(()=>{b(this,Nn,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(Gr,Vr).delete(this._canvas),this.callback())))}};Nn=new WeakMap,Vr=new WeakMap,w(Gr,Vr,new WeakSet);let Xg=Gr;const eS="4.8.69",sS="3634dab10";function V0(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function wh(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=wh(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(wh)}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[wh(1-Math.min(1,t+i)),wh(1-Math.min(1,s+i)),wh(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 iS{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){yt("Abstract method `_createSVG` called.")}}class Vg extends iS{_createSVG(t){return document.createElementNS(Ei,t)}}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&&_h.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:y}=_;if(y==="#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,y):document.createElement(y);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&&_h.shouldBuildText(y)&&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 xh=1e3,nS=9,gr=new WeakSet;function Oi(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class rS{static create(t){switch(t.data.annotationType){case Vt.LINK:return new U0(t);case Vt.TEXT:return new oS(t);case Vt.WIDGET:switch(t.data.fieldType){case"Tx":return new aS(t);case"Btn":return t.data.radioButton?new q0(t):t.data.checkBox?new lS(t):new cS(t);case"Ch":return new dS(t);case"Sig":return new hS(t)}return new fr(t);case Vt.POPUP:return new Gg(t);case Vt.FREETEXT:return new $0(t);case Vt.LINE:return new gS(t);case Vt.SQUARE:return new fS(t);case Vt.CIRCLE:return new pS(t);case Vt.POLYLINE:return new K0(t);case Vt.CARET:return new bS(t);case Vt.INK:return new Yg(t);case Vt.POLYGON:return new mS(t);case Vt.HIGHLIGHT:return new Q0(t);case Vt.UNDERLINE:return new vS(t);case Vt.SQUIGGLY:return new yS(t);case Vt.STRIKEOUT:return new _S(t);case Vt.STAMP:return new J0(t);case Vt.FILEATTACHMENT:return new wS(t);default:return new Lt(t)}}}const ef=class ef{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){w(this,ol);w(this,Yr,null);w(this,pa,!1);w(this,ma,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,Yr)||b(this,Yr,{rect:this.data.rect.slice(0)});const{rect:e}=t;e&&v(this,ol,kf).call(this,e),(s=c(this,ma))==null||s.popup.updateEdited(t)}resetEdited(){var t;c(this,Yr)&&(v(this,ol,kf).call(this,c(this,Yr).rect),(t=c(this,ma))==null||t.popup.resetEdited(),b(this,Yr,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 fr||(n.tabIndex=xh);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,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}=Oi(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 uh.SOLID:r.borderStyle="solid";break;case uh.DASHED:r.borderStyle="dashed";break;case uh.BEVELED:st("Unimplemented border style: beveled");break;case uh.INSET:st("Unimplemented border style: inset");break;case uh.UNDERLINE:r.borderBottomStyle="solid";break}const y=e.borderColor||null;y?(b(this,pa,!0),r.borderColor=z.makeHexColor(y[0]|0,y[1]|0,y[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}=Oi(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 ot(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,_,y,x]=t.subarray(2,6);if(i===m&&n===_&&e===y&&s===x)return}const{style:r}=this.container;let o;if(c(this,pa)){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 y=t[m],x=t[m+1],S=t[m+2],C=t[m+3],E=d.createElement("rect"),M=(S-e)/h,k=(n-x)/l,O=(y-S)/h,P=(x-C)/l;E.setAttribute("x",M),E.setAttribute("y",k),E.setAttribute("width",O),E.setAttribute("height",P),f.append(E),o==null||o.push(`<rect vector-effect="non-scaling-stroke" x="${M}" y="${k}" width="${O}" height="${P}"/>`)}c(this,pa)&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=b(this,ma,new Gg({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(e.render())}render(){yt("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&&!gr.has(l)){st(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&gr.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})})}};Yr=new WeakMap,pa=new WeakMap,ma=new WeakMap,ol=new WeakSet,kf=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}=Oi(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 Lt=ef;class U0 extends Lt{constructor(e,s=null){super(e,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});w(this,Qe);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?(v(this,Qe,Nb).call(this,i,e.attachment,e.attachmentDest),n=!0):e.setOCGState?(v(this,Qe,Bb).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==="")&&v(this,Qe,vo).call(this)}_bindNamedAction(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(s),!1),v(this,Qe,vo).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),v(this,Qe,vo).call(this)}_bindResetFormAction(e,s){const i=e.onclick;if(i||(e.href=this.linkService.getAnchorUrl("")),v(this,Qe,vo).call(this),!this._fieldObjects){st('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(e.onclick=()=>!1);return}e.onclick=()=>{var u;i==null||i();const{fields:n,refs:r,include:o}=s,h=[];if(n.length!==0||r.length!==0){const g=new Set(r);for(const f of n){const p=this._fieldObjects[f]||[];for(const{id:m}of p)g.add(m)}for(const f of Object.values(this._fieldObjects))for(const p of f)g.has(p.id)===o&&h.push(p)}else for(const g of Object.values(this._fieldObjects))h.push(...g);const l=this.annotationStorage,d=[];for(const g of h){const{id:f}=g;switch(d.push(f),g.type){case"text":{const m=g.defaultValue||"";l.setValue(f,{value:m});break}case"checkbox":case"radiobutton":{const m=g.defaultValue===g.exportValues;l.setValue(f,{value:m});break}case"combobox":case"listbox":{const m=g.defaultValue||"";l.setValue(f,{value:m});break}default:continue}const p=document.querySelector(`[data-element-id="${f}"]`);if(p){if(!gr.has(p)){st(`_bindResetFormAction - element not allowed: ${f}`);continue}}else continue;p.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((u=this.linkService.eventBus)==null||u.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:d,name:"ResetForm"}})),!1}}}Qe=new WeakSet,vo=function(){this.container.setAttribute("data-internal-link","")},Nb=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},v(this,Qe,vo).call(this)},Bb=function(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(s),!1),v(this,Qe,vo).call(this)};class oS extends Lt{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 fr extends Lt{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 Ee.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||nS,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/(pg*i))||1,u=l/d;r=Math.min(i,h(u/pg))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/pg))}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 aS extends fr{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),gr.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=xh,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:y}=m;if(_===0){y.removeAttribute("maxLength");return}y.setAttribute("maxLength",_);let x=d.userValue;!x||x.length<=_||(x=x.slice(0,_),y.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:y.selectionStart,selEnd:y.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:y,selectionEnd:x}=m;let S=y,C=x;switch(f.inputType){case"deleteWordBackward":{const M=_.substring(0,y).match(/\w*[^\w]*$/);M&&(S-=M[0].length);break}case"deleteWordForward":{const M=_.substring(y).match(/^[^\w]*\w*/);M&&(C+=M[0].length);break}case"deleteContentBackward":y===x&&(S-=1);break;case"deleteContentForward":y===x&&(C+=1);break}f.preventDefault(),(E=this.linkService.eventBus)==null||E.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:_,change:p||"",willCommit:!1,selStart:S,selEnd:C}})}),this._setEventListeners(s,d,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],f=>f.target.value)}if(u&&s.addEventListener("blur",u),this.data.comb){const f=(this.data.rect[2]-this.data.rect[0])/h;s.classList.add("comb"),s.style.letterSpacing=`calc(${f}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class hS extends fr{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class lS extends fr{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 gr.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=xh,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 fr{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(gr.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=xh,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 cS extends U0{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 dS extends fr{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");gr.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=xh;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],y=document.createElement("option");y.textContent=p,y.value=m,_?_.before(y):i.append(y),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,y=document.createElement("option");y.textContent=m,y.value=_,i.append(y)}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 Lt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Lt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new uS({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,s.container.ariaHasPopup="dialog",e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${wg}${s}`).join(",")),this.container}}class uS{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,ba,v(this,mt,zb).bind(this));w(this,Rd,v(this,mt,Of).bind(this));w(this,Ld,v(this,mt,Zd).bind(this));w(this,va,v(this,mt,Jd).bind(this));w(this,Ur,null);w(this,Dt,null);w(this,Vi,null);w(this,ya,null);w(this,al,null);w(this,hl,null);w(this,_a,null);w(this,Gi,!1);w(this,Ls,null);w(this,Yi,null);w(this,ll,null);w(this,Ui,null);w(this,cl,null);w(this,qr,null);w(this,$r,!1);var g;b(this,Dt,t),b(this,cl,i),b(this,Vi,r),b(this,Ui,o),b(this,hl,h),b(this,Ur,e),b(this,ll,l),b(this,_a,d),b(this,al,s),b(this,ya,Cg.toDateObject(n)),this.trigger=s.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",c(this,va)),f.addEventListener("mouseenter",c(this,Ld)),f.addEventListener("mouseleave",c(this,Rd)),f.classList.add("popupTriggerArea");for(const f of s)(g=f.container)==null||g.addEventListener("keydown",c(this,ba));c(this,Dt).hidden=!0,u&&v(this,mt,Jd).call(this)}render(){if(c(this,Ls))return;const t=b(this,Ls,document.createElement("div"));if(t.className="popup",c(this,Ur)){const n=t.style.outlineColor=z.makeHexColor(...c(this,Ur));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,Ur).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,cl),t.append(e),c(this,ya)){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:c(this,ya).valueOf()})),e.append(n)}const i=c(this,mt,Qd);if(i)Y0.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(c(this,Vi));t.append(n)}c(this,Dt).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,qr)||b(this,qr,{contentsObj:c(this,Vi),richText:c(this,Ui)}),t&&b(this,Yi,null),e&&(b(this,Ui,v(this,mt,Wb).call(this,e)),b(this,Vi,null)),(s=c(this,Ls))==null||s.remove(),b(this,Ls,null)}resetEdited(){var t;c(this,qr)&&({contentsObj:Fe(this,Vi)._,richText:Fe(this,Ui)._}=c(this,qr),b(this,qr,null),(t=c(this,Ls))==null||t.remove(),b(this,Ls,null),b(this,Yi,null))}forceHide(){b(this,$r,this.isVisible),c(this,$r)&&(c(this,Dt).hidden=!0)}maybeShow(){c(this,$r)&&(c(this,Ls)||v(this,mt,Zd).call(this),b(this,$r,!1),c(this,Dt).hidden=!1)}get isVisible(){return c(this,Dt).hidden===!1}}ba=new WeakMap,Rd=new WeakMap,Ld=new WeakMap,va=new WeakMap,Ur=new WeakMap,Dt=new WeakMap,Vi=new WeakMap,ya=new WeakMap,al=new WeakMap,hl=new WeakMap,_a=new WeakMap,Gi=new WeakMap,Ls=new WeakMap,Yi=new WeakMap,ll=new WeakMap,Ui=new WeakMap,cl=new WeakMap,qr=new WeakMap,$r=new WeakMap,mt=new WeakSet,Qd=function(){const t=c(this,Ui),e=c(this,Vi);return t!=null&&t.str&&(!(e!=null&&e.str)||e.str===t.str)&&c(this,Ui).html||null},Mf=function(){var t,e,s;return((s=(e=(t=c(this,mt,Qd))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.fontSize)||0},Hb=function(){var t,e,s;return((s=(e=(t=c(this,mt,Qd))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.color)||null},Wb=function(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:c(this,mt,Hb),fontSize:c(this,mt,Mf)?`calc(${c(this,mt,Mf)}px * var(--scale-factor))`:""}};for(const n of t.split(`
501
+ `))e.push({name:"span",value:n,attributes:i});return s},zb=function(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&c(this,Gi))&&v(this,mt,Jd).call(this)},Xb=function(){if(c(this,Yi)!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=c(this,hl);let r=!!c(this,_a),o=r?c(this,_a):c(this,ll);for(const p of c(this,al))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,Yi,[100*(u-i)/e,100*(g-n)/s]);const{style:f}=c(this,Dt);f.left=`${c(this,Yi)[0]}%`,f.top=`${c(this,Yi)[1]}%`},Jd=function(){b(this,Gi,!c(this,Gi)),c(this,Gi)?(v(this,mt,Zd).call(this),c(this,Dt).addEventListener("click",c(this,va)),c(this,Dt).addEventListener("keydown",c(this,ba))):(v(this,mt,Of).call(this),c(this,Dt).removeEventListener("click",c(this,va)),c(this,Dt).removeEventListener("keydown",c(this,ba)))},Zd=function(){c(this,Ls)||this.render(),this.isVisible?c(this,Gi)&&c(this,Dt).classList.add("focused"):(v(this,mt,Xb).call(this),c(this,Dt).hidden=!1,c(this,Dt).style.zIndex=parseInt(c(this,Dt).style.zIndex)+1e3)},Of=function(){c(this,Dt).classList.remove("focused"),!(c(this,Gi)||!this.isVisible)&&(c(this,Dt).hidden=!0,c(this,Dt).style.zIndex=parseInt(c(this,Dt).style.zIndex)-1e3)};class $0 extends Lt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=Z.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 gS extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,dl,null)}render(){this.container.classList.add("lineAnnotation");const e=this.data,{width:s,height:i}=Oi(e.rect),n=this.svgFactory.create(s,i,!0),r=b(this,dl,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,dl)}addHighlightArea(){this.container.classList.add("highlightArea")}}dl=new WeakMap;class fS extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,ul,null)}render(){this.container.classList.add("squareAnnotation");const e=this.data,{width:s,height:i}=Oi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,ul,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,ul)}addHighlightArea(){this.container.classList.add("highlightArea")}}ul=new WeakMap;class pS extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,gl,null)}render(){this.container.classList.add("circleAnnotation");const e=this.data,{width:s,height:i}=Oi(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=b(this,gl,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,gl)}addHighlightArea(){this.container.classList.add("highlightArea")}}gl=new WeakMap;class K0 extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,fl,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}=Oi(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,fl,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,fl)}addHighlightArea(){this.container.classList.add("highlightArea")}}fl=new WeakMap;class mS extends K0{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class bS extends Lt{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 Yg extends Lt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});w(this,pl,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?Z.HIGHLIGHT:Z.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{width:r,height:o}=Oi(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,pl).push(u),u.setAttribute("points",d),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),h.append(u)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(h),this._editOnDoubleClick(),this.container}getElementsToTriggerPopup(){return c(this,pl)}addHighlightArea(){this.container.classList.add("highlightArea")}}pl=new WeakMap;class Q0 extends Lt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=Z.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class vS extends Lt{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 yS extends Lt{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 _S extends Lt{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 Lt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=Z.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class wS extends Lt{constructor(e){var i;super(e,{isRenderable:!0});w(this,bl);w(this,ml,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",v(this,bl,Df).bind(this)),b(this,ml,i);const{isMac:n}=Ee.platform;return e.addEventListener("keydown",r=>{r.key==="Enter"&&(n?r.metaKey:r.ctrlKey)&&v(this,bl,Df).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),e.append(i),e}getElementsToTriggerPopup(){return c(this,ml)}addHighlightArea(){this.container.classList.add("highlightArea")}}ml=new WeakMap,bl=new WeakSet,Df=function(){var e;(e=this.downloadManager)==null||e.openOrDownloadData(this.content,this.filename)};class xS{constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){w(this,Jr);w(this,vl,null);w(this,Kr,null);w(this,Qr,new Map);w(this,yl,null);this.div=t,b(this,vl,e),b(this,Kr,s),b(this,yl,o||null),this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return c(this,Qr).size>0}async render(t){var r;const{annotations:e}=t,s=this.div;dr(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new Vg,annotationStorage:t.annotationStorage||new Dg,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===Vt.POPUP;if(h){const u=i.get(o.id);if(!u)continue;n.elements=u}else{const{width:u,height:g}=Oi(o.rect);if(u<=0||g<=0)continue}n.data=o;const l=rS.create(n);if(!l.isRenderable)continue;if(!h&&o.popupRef){const u=i.get(o.popupRef);u?u.push(l):i.set(o.popupRef,[l])}const d=l.render();o.hidden&&(d.style.visibility="hidden"),await v(this,Jr,Vb).call(this,d,o.id),l._isEditable&&(c(this,Qr).set(l.data.id,l),(r=this._annotationEditorUIManager)==null||r.renderAnnotationElement(l))}v(this,Jr,Pf).call(this)}update({viewport:t}){const e=this.div;this.viewport=t,dr(e,{rotation:t.rotation}),v(this,Jr,Pf).call(this),e.hidden=!1}getEditableAnnotations(){return Array.from(c(this,Qr).values())}getEditableAnnotation(t){return c(this,Qr).get(t)}}vl=new WeakMap,Kr=new WeakMap,Qr=new WeakMap,yl=new WeakMap,Jr=new WeakSet,Vb=async function(t,e){var r,o;const s=t.firstChild||t,i=s.id=`${wg}${e}`,n=await((r=c(this,yl))==null?void 0:r.getAriaAttributes(i));if(n)for(const[h,l]of n)s.setAttribute(h,l);this.div.append(t),(o=c(this,vl))==null||o.moveElementInDOM(this.div,t,s,!1)},Pf=function(){if(!c(this,Kr))return;const t=this.div;for(const[e,s]of c(this,Kr)){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,Kr).clear()};const md=/\r\n?|\n/g,vt=class vt extends gt{constructor(e){super({...e,name:"freeTextEditor"});w(this,Ht);w(this,Is);w(this,Je,"");w(this,_l,`${this.id}-editor`);w(this,Zr,null);w(this,Ze);b(this,Is,e.color||vt._defaultColor||gt._defaultLineColor),b(this,Ze,e.fontSize||vt._defaultFontSize)}static get _keyboardManager(){const e=vt.prototype,s=r=>r.isEmpty(),i=ur.TRANSLATE_SMALL,n=ur.TRANSLATE_BIG;return ot(this,"_keyboardManager",new ph([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],e.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],e.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],e._translateEmpty,{args:[-i,0],checker:s}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e._translateEmpty,{args:[-n,0],checker:s}],[["ArrowRight","mac+ArrowRight"],e._translateEmpty,{args:[i,0],checker:s}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e._translateEmpty,{args:[n,0],checker:s}],[["ArrowUp","mac+ArrowUp"],e._translateEmpty,{args:[0,-i],checker:s}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e._translateEmpty,{args:[0,-n],checker:s}],[["ArrowDown","mac+ArrowDown"],e._translateEmpty,{args:[0,i],checker:s}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e._translateEmpty,{args:[0,n],checker:s}]]))}static initialize(e,s){gt.initialize(e,s);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,s){switch(e){case U.FREETEXT_SIZE:vt._defaultFontSize=s;break;case U.FREETEXT_COLOR:vt._defaultColor=s;break}}updateParams(e,s){switch(e){case U.FREETEXT_SIZE:v(this,Ht,Gb).call(this,s);break;case U.FREETEXT_COLOR:v(this,Ht,Yb).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[U.FREETEXT_SIZE,vt._defaultFontSize],[U.FREETEXT_COLOR,vt._defaultColor||gt._defaultLineColor]]}get propertiesToUpdate(){return[[U.FREETEXT_SIZE,c(this,Ze)],[U.FREETEXT_COLOR,c(this,Is)]]}_translateEmpty(e,s){this._uiManager.translateSelectedEditors(e,s,!0)}getInitialTranslation(){const e=this.parentScale;return[-vt._internalPadding*e,-(vt._internalPadding+c(this,Ze))*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(Z.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),b(this,Zr,new AbortController);const e=this._uiManager.combinedSignal(c(this,Zr));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:e})}disableEditMode(){var e;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",c(this,_l)),this._isDraggable=!0,(e=c(this,Zr))==null||e.abort(),b(this,Zr,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var e;this.width||(this.enableEditMode(),this.editorDiv.focus(),(e=this._initialOptions)!=null&&e.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const e=c(this,Je),s=b(this,Je,v(this,Ht,Ub).call(this).trimEnd());if(e===s)return;const i=n=>{if(b(this,Je,n),!n){this.remove();return}v(this,Ht,su).call(this),this._uiManager.rebuild(this),v(this,Ht,tu).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(e)},mustExec:!1}),v(this,Ht,tu).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){vt._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,_l)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${c(this,Ze)}px * var(--scale-factor))`,i.color=c(this,Is),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),ld(this,this.div,["dblclick","keydown"]),this.width){const[n,r]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[h,l]=this.getInitialTranslation();[h,l]=this.pageTranslationToScreen(h,l);const[d,u]=this.pageDimensions,[g,f]=this.pageTranslation;let p,m;switch(this.rotation){case 0:p=e+(o[0]-g)/d,m=s+this.height-(o[1]-f)/u;break;case 90:p=e+(o[0]-g)/d,m=s-(o[1]-f)/u,[h,l]=[l,-h];break;case 180:p=e-this.width+(o[0]-g)/d,m=s-(o[1]-f)/u,[h,l]=[-h,-l];break;case 270:p=e+(o[0]-g-this.height*u)/d,m=s+(o[1]-f-this.width*d)/u,[h,l]=[-l,h];break}this.setAt(p*n,m*r,h,l)}else this.setAt(e*n,s*r,this.width*n,this.height*r);v(this,Ht,su).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=v(p=vt,qi,Ff).call(p,s.getData("text")||"").replaceAll(md,`
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
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 y=h.parentElement;if(u.push(h.nodeValue.slice(l).replaceAll(md,"")),y!==this.editorDiv){let x=d;for(const S of this.editorDiv.childNodes){if(S===y){x=u;continue}x.push(v(m=vt,qi,eu).call(m,S))}}d.push(h.nodeValue.slice(0,l).replaceAll(md,""))}else if(h===this.editorDiv){let y=d,x=0;for(const S of this.editorDiv.childNodes)x++===l&&(y=u),y.push(v(_=vt,qi,eu).call(_,S))}b(this,Je,`${d.join(`
504
504
  `)}${n}${u.join(`
505
- `)}`),v(this,Ht,su).call(this);const g=new Range;let f=d.reduce((y,x)=>y+x.length,0);for(const{firstChild:y}of this.editorDiv.childNodes)if(y.nodeType===Node.TEXT_NODE){const x=y.nodeValue.length;if(f<=x){g.setStart(y,f),g.setEnd(y,f);break}f-=x}r.removeAllRanges(),r.addRange(g)}get contentDiv(){return this.editorDiv}static async deserialize(e,s,i){var o;let n=null;if(e instanceof K0){const{data:{defaultAppearanceData:{fontSize:h,fontColor:l},rect:d,rotation:u,id:g,popupRef:f},textContent:p,textPosition:m,parent:{page:{pageNumber:_}}}=e;if(!p||p.length===0)return null;n=e={annotationType:Z.FREETEXT,color:Array.from(l),fontSize:h,value:p.join(`
506
- `),position:m,pageIndex:_-1,rect:d.slice(0),rotation:u,id:g,deleted:!1,popupRef:f}}const r=await super.deserialize(e,s,i);return b(r,Ze,e.fontSize),b(r,Is,z.makeHexColor(...e.color)),b(r,Je,v(o=vt,qi,Rf).call(o,e.value)),r.annotationElementId=e.id||null,r._initialData=n,r}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=vt._internalPadding*this.parentScale,i=this.getRect(s,s),n=gt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:c(this,Is)),r={annotationType:Z.FREETEXT,color:n,fontSize:c(this,Ze),value:v(this,Ht,$b).call(this),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?r:this.annotationElementId&&!v(this,Ht,Kb).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,Ze)}px * var(--scale-factor))`,i.color=c(this,Is),s.replaceChildren();for(const r of c(this,Je).split(`
507
- `)){const o=document.createElement("div");o.append(r?document.createTextNode(r):document.createElement("br")),s.append(o)}const n=vt._internalPadding*this.parentScale;return e.updateEdited({rect:this.getRect(n,n),popupContent:c(this,Je)}),s}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}};Is=new WeakMap,Je=new WeakMap,_l=new WeakMap,Zr=new WeakMap,Ze=new WeakMap,Ht=new WeakSet,Yb=function(e){const s=n=>{this.editorDiv.style.fontSize=`calc(${n}px * var(--scale-factor))`,this.translate(0,-(n-c(this,Ze))*this.parentScale),b(this,Ze,n),v(this,Ht,tu).call(this)},i=c(this,Ze);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:U.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Ub=function(e){const s=n=>{b(this,Is,this.editorDiv.style.color=n)},i=c(this,Is);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:U.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},qb=function(){var i;const e=[];this.editorDiv.normalize();let s=null;for(const n of this.editorDiv.childNodes)(s==null?void 0:s.nodeType)===Node.TEXT_NODE&&n.nodeName==="BR"||(e.push(v(i=vt,qi,eu).call(i,n)),s=n);return e.join(`
505
+ `)}`),v(this,Ht,su).call(this);const g=new Range;let f=d.reduce((y,x)=>y+x.length,0);for(const{firstChild:y}of this.editorDiv.childNodes)if(y.nodeType===Node.TEXT_NODE){const x=y.nodeValue.length;if(f<=x){g.setStart(y,f),g.setEnd(y,f);break}f-=x}r.removeAllRanges(),r.addRange(g)}get contentDiv(){return this.editorDiv}static async deserialize(e,s,i){var o;let n=null;if(e instanceof $0){const{data:{defaultAppearanceData:{fontSize:h,fontColor:l},rect:d,rotation:u,id:g,popupRef:f},textContent:p,textPosition:m,parent:{page:{pageNumber:_}}}=e;if(!p||p.length===0)return null;n=e={annotationType:Z.FREETEXT,color:Array.from(l),fontSize:h,value:p.join(`
506
+ `),position:m,pageIndex:_-1,rect:d.slice(0),rotation:u,id:g,deleted:!1,popupRef:f}}const r=await super.deserialize(e,s,i);return b(r,Ze,e.fontSize),b(r,Is,z.makeHexColor(...e.color)),b(r,Je,v(o=vt,qi,Ff).call(o,e.value)),r.annotationElementId=e.id||null,r._initialData=n,r}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=vt._internalPadding*this.parentScale,i=this.getRect(s,s),n=gt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:c(this,Is)),r={annotationType:Z.FREETEXT,color:n,fontSize:c(this,Ze),value:v(this,Ht,qb).call(this),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?r:this.annotationElementId&&!v(this,Ht,$b).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,Ze)}px * var(--scale-factor))`,i.color=c(this,Is),s.replaceChildren();for(const r of c(this,Je).split(`
507
+ `)){const o=document.createElement("div");o.append(r?document.createTextNode(r):document.createElement("br")),s.append(o)}const n=vt._internalPadding*this.parentScale;return e.updateEdited({rect:this.getRect(n,n),popupContent:c(this,Je)}),s}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}};Is=new WeakMap,Je=new WeakMap,_l=new WeakMap,Zr=new WeakMap,Ze=new WeakMap,Ht=new WeakSet,Gb=function(e){const s=n=>{this.editorDiv.style.fontSize=`calc(${n}px * var(--scale-factor))`,this.translate(0,-(n-c(this,Ze))*this.parentScale),b(this,Ze,n),v(this,Ht,tu).call(this)},i=c(this,Ze);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:U.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Yb=function(e){const s=n=>{b(this,Is,this.editorDiv.style.color=n)},i=c(this,Is);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:U.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Ub=function(){var i;const e=[];this.editorDiv.normalize();let s=null;for(const n of this.editorDiv.childNodes)(s==null?void 0:s.nodeType)===Node.TEXT_NODE&&n.nodeName==="BR"||(e.push(v(i=vt,qi,eu).call(i,n)),s=n);return e.join(`
508
508
  `)},tu=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()},qi=new WeakSet,eu=function(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(md,"")},su=function(){if(this.editorDiv.replaceChildren(),!!c(this,Je))for(const e of c(this,Je).split(`
509
- `)){const s=document.createElement("div");s.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(s)}},$b=function(){return c(this,Je).replaceAll(" "," ")},Rf=function(e){return e.replaceAll(" "," ")},Kb=function(e){const{value:s,fontSize:i,color:n,pageIndex:r}=this._initialData;return this._hasBeenMoved||e.value!==s||e.fontSize!==i||e.color.some((o,h)=>o!==n[h])||e.pageIndex!==r},w(vt,qi),q(vt,"_freeTextDefaultContent",""),q(vt,"_internalPadding",0),q(vt,"_defaultColor",null),q(vt,"_defaultFontSize",10),q(vt,"_type","freetext"),q(vt,"_editorType",Z.FREETEXT);let Ug=vt;class tb{toSVGPath(){yt("Abstract method `toSVGPath` must be implemented.")}get box(){yt("Abstract getter `box` must be implemented.")}serialize(t,e){yt("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){yt("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){yt("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}const $i=class $i{constructor({x:t,y:e},s,i,n,r,o=0){w(this,qt);w(this,ts);w(this,js,[]);w(this,wa);w(this,xa);w(this,hi,[]);w(this,it,new Float64Array(18));w(this,to);w(this,eo);w(this,wl);w(this,xl);w(this,Sa);w(this,Ca);w(this,Bn,[]);b(this,ts,s),b(this,Ca,n*i),b(this,xa,r),c(this,it).set([NaN,NaN,NaN,NaN,t,e],6),b(this,wa,o),b(this,xl,c($i,Sl)*i),b(this,wl,c($i,jd)*i),b(this,Sa,i),c(this,Bn).push(t,e)}isEmpty(){return isNaN(c(this,it)[8])}add({x:t,y:e}){var P;b(this,to,t),b(this,eo,e);const[s,i,n,r]=c(this,ts);let[o,h,l,d]=c(this,it).subarray(8,12);const u=t-l,g=e-d,f=Math.hypot(u,g);if(f<c(this,wl))return!1;const p=f-c(this,xl),m=p/f,_=m*u,y=m*g;let x=o,S=h;o=l,h=d,l+=_,d+=y,(P=c(this,Bn))==null||P.push(t,e);const C=-y/p,E=_/p,M=C*c(this,Ca),k=E*c(this,Ca);return c(this,it).set(c(this,it).subarray(2,8),0),c(this,it).set([l+M,d+k],4),c(this,it).set(c(this,it).subarray(14,18),12),c(this,it).set([l-M,d-k],16),isNaN(c(this,it)[6])?(c(this,hi).length===0&&(c(this,it).set([o+M,h+k],2),c(this,hi).push(NaN,NaN,NaN,NaN,(o+M-s)/n,(h+k-i)/r),c(this,it).set([o-M,h-k],14),c(this,js).push(NaN,NaN,NaN,NaN,(o-M-s)/n,(h-k-i)/r)),c(this,it).set([x,S,o,h,l,d],6),!this.isEmpty()):(c(this,it).set([x,S,o,h,l,d],6),Math.abs(Math.atan2(S-h,x-o)-Math.atan2(y,_))<Math.PI/2?([o,h,l,d]=c(this,it).subarray(2,6),c(this,hi).push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+d)/2-i)/r),[o,h,x,S]=c(this,it).subarray(14,18),c(this,js).push(NaN,NaN,NaN,NaN,((x+o)/2-s)/n,((S+h)/2-i)/r),!0):([x,S,o,h,l,d]=c(this,it).subarray(0,6),c(this,hi).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,it).subarray(12,18),c(this,js).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,hi),e=c(this,js);if(isNaN(c(this,it)[6])&&!this.isEmpty())return v(this,qt,Qb).call(this);const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);v(this,qt,Zb).call(this,s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return v(this,qt,Jb).call(this,s),s.join(" ")}newFreeDrawOutline(t,e,s,i,n,r){return new eb(t,e,s,i,n,r)}getOutlines(){var u;const t=c(this,hi),e=c(this,js),s=c(this,it),[i,n,r,o]=c(this,ts),h=new Float64Array((((u=c(this,Bn))==null?void 0:u.length)??0)+2);for(let g=0,f=h.length-2;g<f;g+=2)h[g]=(c(this,Bn)[g]-i)/r,h[g+1]=(c(this,Bn)[g+1]-n)/o;if(h[h.length-2]=(c(this,to)-i)/r,h[h.length-1]=(c(this,eo)-n)/o,isNaN(s[6])&&!this.isEmpty())return v(this,qt,tv).call(this,h);const l=new Float64Array(c(this,hi).length+24+c(this,js).length);let d=t.length;for(let g=0;g<d;g+=2){if(isNaN(t[g])){l[g]=l[g+1]=NaN;continue}l[g]=t[g],l[g+1]=t[g+1]}d=v(this,qt,sv).call(this,l,d);for(let g=e.length-6;g>=6;g-=6)for(let f=0;f<6;f+=2){if(isNaN(e[g+f])){l[d]=l[d+1]=NaN,d+=2;continue}l[d]=e[g+f],l[d+1]=e[g+f+1],d+=2}return v(this,qt,ev).call(this,l,d),this.newFreeDrawOutline(l,h,c(this,ts),c(this,Sa),c(this,wa),c(this,xa))}};ts=new WeakMap,js=new WeakMap,wa=new WeakMap,xa=new WeakMap,hi=new WeakMap,it=new WeakMap,to=new WeakMap,eo=new WeakMap,wl=new WeakMap,xl=new WeakMap,Sa=new WeakMap,Ca=new WeakMap,Bn=new WeakMap,Sl=new WeakMap,Id=new WeakMap,jd=new WeakMap,qt=new WeakSet,Yl=function(){const t=c(this,it).subarray(4,6),e=c(this,it).subarray(16,18),[s,i,n,r]=c(this,ts);return[(c(this,to)+(t[0]-e[0])/2-s)/n,(c(this,eo)+(t[1]-e[1])/2-i)/r,(c(this,to)+(e[0]-t[0])/2-s)/n,(c(this,eo)+(e[1]-t[1])/2-i)/r]},Qb=function(){const[t,e,s,i]=c(this,ts),[n,r,o,h]=v(this,qt,Yl).call(this);return`M${(c(this,it)[2]-t)/s} ${(c(this,it)[3]-e)/i} L${(c(this,it)[4]-t)/s} ${(c(this,it)[5]-e)/i} L${n} ${r} L${o} ${h} L${(c(this,it)[16]-t)/s} ${(c(this,it)[17]-e)/i} L${(c(this,it)[14]-t)/s} ${(c(this,it)[15]-e)/i} Z`},Jb=function(t){const e=c(this,js);t.push(`L${e[4]} ${e[5]} Z`)},Zb=function(t){const[e,s,i,n]=c(this,ts),r=c(this,it).subarray(4,6),o=c(this,it).subarray(16,18),[h,l,d,u]=v(this,qt,Yl).call(this);t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${d} ${u} L${(o[0]-e)/i} ${(o[1]-s)/n}`)},tv=function(t){const e=c(this,it),[s,i,n,r]=c(this,ts),[o,h,l,d]=v(this,qt,Yl).call(this),u=new Float64Array(36);return u.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,l,d,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(u,t,c(this,ts),c(this,Sa),c(this,wa),c(this,xa))},ev=function(t,e){const s=c(this,js);return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6},sv=function(t,e){const s=c(this,it).subarray(4,6),i=c(this,it).subarray(16,18),[n,r,o,h]=c(this,ts),[l,d,u,g]=v(this,qt,Yl).call(this);return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,d,NaN,NaN,NaN,NaN,u,g,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24},w($i,Sl,8),w($i,Id,2),w($i,jd,c($i,Sl)+c($i,Id));let bd=$i;class eb extends tb{constructor(e,s,i,n,r,o){super();w(this,We);w(this,Aa);w(this,so,null);w(this,Ki);w(this,Cl);w(this,es);w(this,Al);w(this,It);b(this,It,e),b(this,es,s),b(this,Aa,i),b(this,Al,n),b(this,Ki,r),b(this,Cl,o),v(this,We,iv).call(this,o);const{x:h,y:l,width:d,height:u}=c(this,so);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,It)[4]} ${c(this,It)[5]}`];for(let s=6,i=c(this,It).length;s<i;s+=6){if(isNaN(c(this,It)[s])){e.push(`L${c(this,It)[s+4]} ${c(this,It)[s+5]}`);continue}e.push(`C${c(this,It)[s]} ${c(this,It)[s+1]} ${c(this,It)[s+2]} ${c(this,It)[s+3]} ${c(this,It)[s+4]} ${c(this,It)[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=v(this,We,Ul).call(this,c(this,It),e,n,o,-h),d=v(this,We,Ul).call(this,c(this,es),e,n,o,-h);break;case 90:l=v(this,We,ql).call(this,c(this,It),e,s,o,h),d=v(this,We,ql).call(this,c(this,es),e,s,o,h);break;case 180:l=v(this,We,Ul).call(this,c(this,It),i,s,-o,h),d=v(this,We,Ul).call(this,c(this,es),i,s,-o,h);break;case 270:l=v(this,We,ql).call(this,c(this,It),i,n,-o,-h),d=v(this,We,ql).call(this,c(this,es),i,n,-o,-h);break}return{outline:Array.from(l),points:[Array.from(d)]}}get box(){return c(this,so)}newOutliner(e,s,i,n,r,o=0){return new bd(e,s,i,n,r,o)}getNewOutline(e,s){const{x:i,y:n,width:r,height:o}=c(this,so),[h,l,d,u]=c(this,Aa),g=r*d,f=o*u,p=i*d+h,m=n*u+l,_=this.newOutliner({x:c(this,es)[0]*g+p,y:c(this,es)[1]*f+m},c(this,Aa),c(this,Al),e,c(this,Cl),s??c(this,Ki));for(let y=2;y<c(this,es).length;y+=2)_.add({x:c(this,es)[y]*g+p,y:c(this,es)[y+1]*f+m});return _.getOutlines()}get mustRemoveSelfIntersections(){return!0}}Aa=new WeakMap,so=new WeakMap,Ki=new WeakMap,Cl=new WeakMap,es=new WeakMap,Al=new WeakMap,It=new WeakMap,We=new WeakSet,Ul=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},iv=function(e){const s=c(this,It);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 y=6,x=s.length;y<x;y+=6){if(isNaN(s[y]))r=Math.min(r,s[y+4]),o=Math.min(o,s[y+5]),h=Math.max(h,s[y+4]),l=Math.max(l,s[y+5]),u<s[y+5]?(d=s[y+4],u=s[y+5]):u===s[y+5]&&(d=g(d,s[y+4]));else{const S=z.bezierBoundingBox(i,n,...s.slice(y,y+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[y+4],n=s[y+5]}const f=r-c(this,Ki),p=o-c(this,Ki),m=h-r+2*c(this,Ki),_=l-o+2*c(this,Ki);b(this,so,{x:f,y:p,width:m,height:_,lastPoint:[d,u]})};class sb{constructor(t,e=0,s=0,i=!0){w(this,De);w(this,Tl);w(this,Hn,[]);w(this,Ns,[]);let n=1/0,r=-1/0,o=1/0,h=-1/0;const d=10**-4;for(const{x:y,y:x,width:S,height:C}of t){const E=Math.floor((y-e)/d)*d,M=Math.ceil((y+S+e)/d)*d,k=Math.floor((x-e)/d)*d,O=Math.ceil((x+C+e)/d)*d,P=[E,k,O,!0],F=[M,k,O,!1];c(this,Hn).push(P,F),n=Math.min(n,E),r=Math.max(r,M),o=Math.min(o,k),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,Hn).at(i?-1:-2),_=[m[0],m[2]];for(const y of c(this,Hn)){const[x,S,C]=y;y[0]=(x-f)/u,y[1]=(S-p)/g,y[2]=(C-p)/g}b(this,Tl,{x:f,y:p,width:u,height:g,lastPoint:_})}getOutlines(){c(this,Hn).sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of c(this,Hn))e[3]?(t.push(...v(this,De,Lf).call(this,e)),v(this,De,rv).call(this,e)):(v(this,De,ov).call(this,e),t.push(...v(this,De,Lf).call(this,e)));return v(this,De,nv).call(this,t)}}Tl=new WeakMap,Hn=new WeakMap,Ns=new WeakMap,De=new WeakSet,nv=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 CS(i,c(this,Tl))},iu=function(t){const e=c(this,Ns);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},rv=function([,t,e]){const s=v(this,De,iu).call(this,t);c(this,Ns).splice(s,0,[t,e])},ov=function([,t,e]){const s=v(this,De,iu).call(this,t);for(let i=s;i<c(this,Ns).length;i++){const[n,r]=c(this,Ns)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ns).splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=c(this,Ns)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ns).splice(i,1);return}}},Lf=function(t){const[e,s,i]=t,n=[[e,s,i]],r=v(this,De,iu).call(this,i);for(let o=0;o<r;o++){const[h,l]=c(this,Ns)[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 CS extends tb{constructor(e,s){super();w(this,El);w(this,Ta);b(this,Ta,e),b(this,El,s)}toSVGPath(){const e=[];for(const s of c(this,Ta)){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,Ta)){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,El)}get classNamesForDrawing(){return["highlight"]}get classNamesForOutlining(){return["highlightOutline"]}}El=new WeakMap,Ta=new WeakMap;class qg extends bd{newFreeDrawOutline(t,e,s,i,n,r){return new AS(t,e,s,i,n,r)}get classNamesForDrawing(){return["highlight","free"]}}class AS extends eb{get classNamesForDrawing(){return["highlight","free"]}get classNamesForOutlining(){return["highlightOutline","free"]}newOutliner(t,e,s,i,n,r=0){return new qg(t,e,s,i,n,r)}}const ze=class ze{constructor({editor:t=null,uiManager:e=null}){w(this,bt);w(this,Bs,null);w(this,io,null);w(this,Ea);w(this,$t,null);w(this,kl,!1);w(this,ka,!1);w(this,Ml,null);w(this,Ol);w(this,Wn,null);w(this,Hs,null);w(this,Ma);var s;t?(b(this,ka,!1),b(this,Ma,U.HIGHLIGHT_COLOR),b(this,Ml,t)):(b(this,ka,!0),b(this,Ma,U.HIGHLIGHT_DEFAULT_COLOR)),b(this,Hs,(t==null?void 0:t._uiManager)||e),b(this,Ol,c(this,Hs)._eventBus),b(this,Ea,(t==null?void 0:t.color)||((s=c(this,Hs))==null?void 0:s.highlightColors.values().next().value)||"#FFFF98"),c(ze,Dl)||b(ze,Dl,Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"}))}static get _keyboardManager(){return ot(this,"_keyboardManager",new ph([[["Escape","mac+Escape"],ze.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ze.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ze.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ze.prototype._moveToPrevious],[["Home","mac+Home"],ze.prototype._moveToBeginning],[["End","mac+End"],ze.prototype._moveToEnd]]))}renderButton(){const t=b(this,Bs,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,Hs)._signal;t.addEventListener("click",v(this,bt,yo).bind(this),{signal:e}),t.addEventListener("keydown",v(this,bt,Nf).bind(this),{signal:e});const s=b(this,io,document.createElement("span"));return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=c(this,Ea),t.append(s),t}renderMainDropdown(){const t=b(this,$t,v(this,bt,If).call(this));return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}_colorSelectFromKeyboard(t){if(t.target===c(this,Bs)){v(this,bt,yo).call(this,t);return}const e=t.target.getAttribute("data-color");e&&v(this,bt,jf).call(this,e,t)}_moveToNext(t){var e,s;if(!c(this,bt,$n)){v(this,bt,yo).call(this,t);return}if(t.target===c(this,Bs)){(e=c(this,$t).firstChild)==null||e.focus();return}(s=t.target.nextSibling)==null||s.focus()}_moveToPrevious(t){var e,s;if(t.target===((e=c(this,$t))==null?void 0:e.firstChild)||t.target===c(this,Bs)){c(this,bt,$n)&&this._hideDropdownFromKeyboard();return}c(this,bt,$n)||v(this,bt,yo).call(this,t),(s=t.target.previousSibling)==null||s.focus()}_moveToBeginning(t){var e;if(!c(this,bt,$n)){v(this,bt,yo).call(this,t);return}(e=c(this,$t).firstChild)==null||e.focus()}_moveToEnd(t){var e;if(!c(this,bt,$n)){v(this,bt,yo).call(this,t);return}(e=c(this,$t).lastChild)==null||e.focus()}hideDropdown(){var t,e;(t=c(this,$t))==null||t.classList.add("hidden"),(e=c(this,Wn))==null||e.abort(),b(this,Wn,null)}_hideDropdownFromKeyboard(){var t;if(!c(this,ka)){if(!c(this,bt,$n)){(t=c(this,Ml))==null||t.unselect();return}this.hideDropdown(),c(this,Bs).focus({preventScroll:!0,focusVisible:c(this,kl)})}}updateColor(t){if(c(this,io)&&(c(this,io).style.backgroundColor=t),!c(this,$t))return;const e=c(this,Hs).highlightColors.values();for(const s of c(this,$t).children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){var t,e;(t=c(this,Bs))==null||t.remove(),b(this,Bs,null),b(this,io,null),(e=c(this,$t))==null||e.remove(),b(this,$t,null)}};Bs=new WeakMap,io=new WeakMap,Ea=new WeakMap,$t=new WeakMap,kl=new WeakMap,ka=new WeakMap,Ml=new WeakMap,Ol=new WeakMap,Wn=new WeakMap,Hs=new WeakMap,Ma=new WeakMap,Dl=new WeakMap,bt=new WeakSet,If=function(){const t=document.createElement("div"),e=c(this,Hs)._signal;t.addEventListener("contextmenu",hs,{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,Hs).highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",c(ze,Dl)[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===c(this,Ea)),n.addEventListener("click",v(this,bt,jf).bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",v(this,bt,Nf).bind(this),{signal:e}),t},jf=function(t,e){e.stopPropagation(),c(this,Ol).dispatch("switchannotationeditorparams",{source:this,type:c(this,Ma),value:t})},Nf=function(t){ze._keyboardManager.exec(this,t)},yo=function(t){if(c(this,bt,$n)){this.hideDropdown();return}if(b(this,kl,t.detail===0),c(this,Wn)||(b(this,Wn,new AbortController),window.addEventListener("pointerdown",v(this,bt,av).bind(this),{signal:c(this,Hs).combinedSignal(c(this,Wn))})),c(this,$t)){c(this,$t).classList.remove("hidden");return}const e=b(this,$t,v(this,bt,If).call(this));c(this,Bs).append(e)},av=function(t){var e;(e=c(this,$t))!=null&&e.contains(t.target)||this.hideDropdown()},$n=function(){return c(this,$t)&&!c(this,$t).classList.contains("hidden")},w(ze,Dl,null);let vd=ze;const ht=class ht extends gt{constructor(e){super({...e,name:"highlightEditor"});w(this,J);w(this,Oa,null);w(this,Pl,0);w(this,Qi);w(this,no,null);w(this,Da,null);w(this,fs,null);w(this,Fl,null);w(this,Rl,0);w(this,ro,null);w(this,Ws,null);w(this,ve,null);w(this,Xe,!1);w(this,Pa,null);w(this,Ji);w(this,Kt,null);w(this,Fa,"");w(this,ps);w(this,Ll,"");this.color=e.color||ht._defaultColor,b(this,ps,e.thickness||ht._defaultThickness),b(this,Ji,e.opacity||ht._defaultOpacity),b(this,Qi,e.boxes||null),b(this,Ll,e.methodOfCreation||""),b(this,Fa,e.text||""),this._isDraggable=!1,e.highlightId>-1?(b(this,Xe,!0),v(this,J,nu).call(this,e),v(this,J,_o).call(this)):c(this,Qi)&&(b(this,Oa,e.anchorNode),b(this,Pl,e.anchorOffset),b(this,Fl,e.focusNode),b(this,Rl,e.focusOffset),v(this,J,Bf).call(this),v(this,J,_o).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const e=ht.prototype;return ot(this,"_keyboardManager",new ph([[["ArrowLeft","mac+ArrowLeft"],e._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],e._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],e._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],e._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:c(this,Xe)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:c(this,ps),methodOfCreation:c(this,Ll)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get("color").size}}static initialize(e,s){var i;gt.initialize(e,s),ht._defaultColor||(ht._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(e,s){switch(e){case U.HIGHLIGHT_DEFAULT_COLOR:ht._defaultColor=s;break;case U.HIGHLIGHT_THICKNESS:ht._defaultThickness=s;break}}translateInPage(e,s){}get toolbarPosition(){return c(this,Pa)}updateParams(e,s){switch(e){case U.HIGHLIGHT_COLOR:v(this,J,hv).call(this,s);break;case U.HIGHLIGHT_THICKNESS:v(this,J,lv).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[U.HIGHLIGHT_DEFAULT_COLOR,ht._defaultColor],[U.HIGHLIGHT_THICKNESS,ht._defaultThickness]]}get propertiesToUpdate(){return[[U.HIGHLIGHT_COLOR,this.color||ht._defaultColor],[U.HIGHLIGHT_THICKNESS,c(this,ps)||ht._defaultThickness],[U.HIGHLIGHT_FREE,c(this,Xe)]]}async addEditToolbar(){const e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(b(this,Da,new vd({editor:this})),e.addColorPicker(c(this,Da))),e):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(v(this,J,$l).call(this))}getBaseTranslation(){return[0,0]}getRect(e,s){return super.getRect(e,s,v(this,J,$l).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){v(this,J,Hf).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(v(this,J,_o).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?v(this,J,Hf).call(this):e&&(v(this,J,_o).call(this,e),s=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(e),this.show(this._isVisible),s&&this.select()}rotate(e){var n,r,o;const{drawLayer:s}=this.parent;let i;c(this,Xe)?(e=(e-this.rotation+360)%360,i=v(n=ht,ms,Ga).call(n,c(this,Ws).box,e)):i=v(r=ht,ms,Ga).call(r,this,e),s.rotate(c(this,ve),e),s.rotate(c(this,Kt),e),s.updateBox(c(this,ve),i),s.updateBox(c(this,Kt),v(o=ht,ms,Ga).call(o,c(this,fs).box,e))}render(){if(this.div)return this.div;const e=super.render();c(this,Fa)&&(e.setAttribute("aria-label",c(this,Fa)),e.setAttribute("role","mark")),c(this,Xe)?e.classList.add("free"):this.div.addEventListener("keydown",v(this,J,dv).bind(this),{signal:this._uiManager._signal});const s=b(this,ro,document.createElement("div"));e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=c(this,no);const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),ld(this,c(this,ro),["pointerover","pointerleave"]),this.enableEditing(),e}pointerover(){this.isSelected||this.parent.drawLayer.addClass(c(this,Kt),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(c(this,Kt),"hovered")}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:v(this,J,ru).call(this,!0);break;case 1:case 3:v(this,J,ru).call(this,!1);break}}select(){var e,s;super.select(),c(this,Kt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Kt),"hovered"),(s=this.parent)==null||s.drawLayer.addClass(c(this,Kt),"selected"))}unselect(){var e;super.unselect(),c(this,Kt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Kt),"selected"),c(this,Xe)||v(this,J,ru).call(this,!1))}get _mustFixPosition(){return!c(this,Xe)}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.show(c(this,ve),e),this.parent.drawLayer.show(c(this,Kt),e))}static startHighlighting(e,s,{target:i,x:n,y:r}){const{x:o,y:h,width:l,height:d}=i.getBoundingClientRect(),u=new AbortController,g=e.combinedSignal(u),f=m=>{m.preventDefault(),m.stopPropagation()},p=m=>{u.abort(),v(this,ms,pv).call(this,e,m)};window.addEventListener("blur",p,{signal:g}),window.addEventListener("pointerup",p,{signal:g}),window.addEventListener("pointerdown",f,{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",hs,{signal:g}),i.addEventListener("pointermove",v(this,ms,fv).bind(this,e),{signal:g}),this._freeHighlight=new qg({x:n,y:r},[o,h,l,d],e.scale,this._defaultThickness/2,s,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(e,s,i){var m,_,y,x;let n=null;if(e instanceof J0){const{data:{quadPoints:S,rect:C,rotation:E,id:M,color:k,opacity:O,popupRef:P},parent:{page:{pageNumber:F}}}=e;n=e={annotationType:Z.HIGHLIGHT,color:Array.from(k),opacity:O,quadPoints:S,boxes:null,pageIndex:F-1,rect:C.slice(0),rotation:E,id:M,deleted:!1,popupRef:P}}else if(e instanceof Yg){const{data:{inkLists:S,rect:C,rotation:E,id:M,color:k,borderStyle:{rawWidth:O},popupRef:P},parent:{page:{pageNumber:F}}}=e;n=e={annotationType:Z.HIGHLIGHT,color:Array.from(k),thickness:O,inkLists:S,boxes:null,pageIndex:F-1,rect:C.slice(0),rotation:E,id:M,deleted:!1,popupRef:P}}const{color:r,quadPoints:o,inkLists:h,opacity:l}=e,d=await super.deserialize(e,s,i);d.color=z.makeHexColor(...r),b(d,Ji,l||1),h&&b(d,ps,e.thickness),d.annotationElementId=e.id||null,d._initialData=n;const[u,g]=d.pageDimensions,[f,p]=d.pageTranslation;if(o){const S=b(d,Qi,[]);for(let C=0;C<o.length;C+=8)S.push({x:(o[C]-f)/u,y:1-(o[C+1]-p)/g,width:(o[C+2]-o[C])/u,height:(o[C+1]-o[C+5])/g});v(m=d,J,Bf).call(m),v(_=d,J,_o).call(_),d.rotate(d.rotation)}else if(h){b(d,Xe,!0);const S=h[0],C={x:S[0]-f,y:g-(S[1]-p)},E=new qg(C,[0,0,u,g],1,c(d,ps)/2,!0,.001);for(let O=0,P=S.length;O<P;O+=2)C.x=S[O]-f,C.y=g-(S[O+1]-p),E.add(C);const{id:M,clipPathId:k}=s.drawLayer.draw(E,d.color,d._defaultOpacity,!0);v(y=d,J,nu).call(y,{highlightOutlines:E.getOutlines(),highlightId:M,clipPathId:k}),v(x=d,J,_o).call(x)}return d}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();const s=this.getRect(0,0),i=gt._colorManager.convert(this.color),n={annotationType:Z.HIGHLIGHT,color:i,opacity:c(this,Ji),thickness:c(this,ps),quadPoints:v(this,J,uv).call(this),outlines:v(this,J,gv).call(this,s),pageIndex:this.pageIndex,rect:s,rotation:v(this,J,$l).call(this),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!v(this,J,mv).call(this,n)?null:(n.id=this.annotationElementId,n)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}};Oa=new WeakMap,Pl=new WeakMap,Qi=new WeakMap,no=new WeakMap,Da=new WeakMap,fs=new WeakMap,Fl=new WeakMap,Rl=new WeakMap,ro=new WeakMap,Ws=new WeakMap,ve=new WeakMap,Xe=new WeakMap,Pa=new WeakMap,Ji=new WeakMap,Kt=new WeakMap,Fa=new WeakMap,ps=new WeakMap,Ll=new WeakMap,J=new WeakSet,Bf=function(){const e=new sb(c(this,Qi),.001);b(this,Ws,e.getOutlines()),{x:this.x,y:this.y,width:this.width,height:this.height}=c(this,Ws).box;const s=new sb(c(this,Qi),.0025,.001,this._uiManager.direction==="ltr");b(this,fs,s.getOutlines());const{lastPoint:i}=c(this,fs).box;b(this,Pa,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height])},nu=function({highlightOutlines:e,highlightId:s,clipPathId:i}){var u,g;if(b(this,Ws,e),b(this,fs,e.getNewOutline(c(this,ps)/2+1.5,.0025)),s>=0)b(this,ve,s),b(this,no,i),this.parent.drawLayer.finalizeLine(s,e),b(this,Kt,this.parent.drawLayer.drawOutline(c(this,fs)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(c(this,ve),e),this.parent.drawLayer.updateBox(c(this,ve),v(u=ht,ms,Ga).call(u,c(this,Ws).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(c(this,Kt),c(this,fs)),this.parent.drawLayer.updateBox(c(this,Kt),v(g=ht,ms,Ga).call(g,c(this,fs).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,fs).box;b(this,Pa,[(d[0]-r)/h,(d[1]-o)/l])},hv=function(e){const s=(r,o)=>{var h,l,d;this.color=r,(h=this.parent)==null||h.drawLayer.changeColor(c(this,ve),r),(l=c(this,Da))==null||l.updateColor(r),b(this,Ji,o),(d=this.parent)==null||d.drawLayer.changeOpacity(c(this,ve),o)},i=this.color,n=c(this,Ji);this.addCommands({cmd:s.bind(this,e,ht._defaultOpacity),undo:s.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:U.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(e)},!0)},lv=function(e){const s=c(this,ps),i=n=>{b(this,ps,n),v(this,J,cv).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:U.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:e},!0)},cv=function(e){if(!c(this,Xe))return;v(this,J,nu).call(this,{highlightOutlines:c(this,Ws).getNewOutline(e/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},Hf=function(){c(this,ve)===null||!this.parent||(this.parent.drawLayer.remove(c(this,ve)),b(this,ve,null),this.parent.drawLayer.remove(c(this,Kt)),b(this,Kt,null))},_o=function(e=this.parent){c(this,ve)===null&&({id:Fe(this,ve)._,clipPathId:Fe(this,no)._}=e.drawLayer.draw(c(this,Ws),this.color,c(this,Ji)),b(this,Kt,e.drawLayer.drawOutline(c(this,fs))),c(this,ro)&&(c(this,ro).style.clipPath=c(this,no)))},ms=new WeakSet,Ga=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}},dv=function(e){ht._keyboardManager.exec(this,e)},ru=function(e){if(!c(this,Oa))return;const s=window.getSelection();e?s.setPosition(c(this,Oa),c(this,Pl)):s.setPosition(c(this,Fl),c(this,Rl))},$l=function(){return c(this,Xe)?this.rotation:0},uv=function(){if(c(this,Xe))return null;const[e,s]=this.pageDimensions,[i,n]=this.pageTranslation,r=c(this,Qi),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},gv=function(e){return c(this,Ws).serialize(e,v(this,J,$l).call(this))},fv=function(e,s){this._freeHighlight.add(s)&&e.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},pv=function(e,s){this._freeHighlight.isEmpty()?e.drawLayer.remove(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=""},mv=function(e){const{color:s}=this._initialData;return e.color.some((i,n)=>i!==s[n])},w(ht,ms),q(ht,"_defaultColor",null),q(ht,"_defaultOpacity",1),q(ht,"_defaultThickness",12),q(ht,"_type","highlight"),q(ht,"_editorType",Z.HIGHLIGHT),q(ht,"_freeHighlightId",-1),q(ht,"_freeHighlight",null),q(ht,"_freeHighlightClipId","");let yd=ht;const kt=class kt extends gt{constructor(e){super({...e,name:"inkEditor"});w(this,L);w(this,oo,0);w(this,ao,0);w(this,li,null);w(this,Zi,new Path2D);w(this,bs,!1);w(this,ho,null);w(this,lo,!1);w(this,co,!1);w(this,tn,null);w(this,Ra,null);w(this,uo,0);w(this,go,0);w(this,zn,null);this.color=e.color||null,this.thickness=e.thickness||null,this.opacity=e.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(e,s){gt.initialize(e,s)}static updateDefaultParams(e,s){switch(e){case U.INK_THICKNESS:kt._defaultThickness=s;break;case U.INK_COLOR:kt._defaultColor=s;break;case U.INK_OPACITY:kt._defaultOpacity=s/100;break}}updateParams(e,s){switch(e){case U.INK_THICKNESS:v(this,L,bv).call(this,s);break;case U.INK_COLOR:v(this,L,vv).call(this,s);break;case U.INK_OPACITY:v(this,L,yv).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[U.INK_THICKNESS,kt._defaultThickness],[U.INK_COLOR,kt._defaultColor||gt._defaultLineColor],[U.INK_OPACITY,Math.round(kt._defaultOpacity*100)]]}get propertiesToUpdate(){return[[U.INK_THICKNESS,this.thickness||kt._defaultThickness],[U.INK_COLOR,this.color||kt._defaultColor||gt._defaultLineColor],[U.INK_OPACITY,Math.round(100*(this.opacity??kt._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(v(this,L,ou).call(this),v(this,L,au).call(this)),this.isAttachedToDOM||(this.parent.add(this),v(this,L,Ya).call(this)),v(this,L,Kl).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,li)&&(clearTimeout(c(this,li)),b(this,li,null)),(e=c(this,tn))==null||e.disconnect(),b(this,tn,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,bs)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,v(this,L,Xf).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),v(this,L,Vf).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){c(this,bs)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),b(this,bs,!0),this.div.classList.add("disabled"),v(this,L,Kl).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,bs)||(this.setInForeground(),e.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),v(this,L,wv).call(this,e.offsetX,e.offsetY))}canvasPointermove(e){e.preventDefault(),v(this,L,zf).call(this,e.offsetX,e.offsetY)}canvasPointerup(e){e.preventDefault(),v(this,L,Gf).call(this,e)}canvasPointerleave(e){v(this,L,Gf).call(this,e)}get isResizable(){return!this.isEmpty()&&c(this,bs)}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]=v(this,L,_v).call(this);if(this.setAt(i,n,0,0),this.setDims(r,o),v(this,L,ou).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,co,!0),v(this,L,Ya).call(this),this.setDims(this.width*h,this.height*l),v(this,L,wo).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return v(this,L,au).call(this),this.div}setDimensions(e,s){const i=Math.round(e),n=Math.round(s);if(c(this,uo)===i&&c(this,go)===n)return;b(this,uo,i),b(this,go,n),this.canvas.style.visibility="hidden";const[r,o]=this.parentDimensions;this.width=e/r,this.height=s/o,this.fixAndSetPosition(),c(this,bs)&&v(this,L,Yf).call(this,e,s),v(this,L,Ya).call(this),v(this,L,wo).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(e,s,i){var _,y,x;if(e instanceof Yg)return null;const n=await 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,bs,!0),b(n,uo,Math.round(h)),b(n,go,Math.round(l));const{paths:g,rect:f,rotation:p}=e;for(let{bezier:S}of g){S=v(_=kt,en,kv).call(_,S,f,p);const C=[];n.paths.push(C);let E=d*(S[0]-u),M=d*(S[1]-u);for(let O=2,P=S.length;O<P;O+=6){const F=d*(S[O]-u),R=d*(S[O+1]-u),W=d*(S[O+2]-u),B=d*(S[O+3]-u),X=d*(S[O+4]-u),K=d*(S[O+5]-u);C.push([[E,M],[F,R],[W,B],[X,K]]),E=X,M=K}const k=v(this,en,Ev).call(this,C);n.bezierPath2D.push(k)}const m=v(y=n,L,qf).call(y);return b(n,ao,Math.max(gt.MIN_SIZE,m[2]-m[0])),b(n,oo,Math.max(gt.MIN_SIZE,m[3]-m[1])),v(x=n,L,Yf).call(x,h,l),n}serialize(){if(this.isEmpty())return null;const e=this.getRect(0,0),s=gt._colorManager.convert(this.ctx.strokeStyle);return{annotationType:Z.INK,color:s,thickness:this.thickness,opacity:this.opacity,paths:v(this,L,Mv).call(this,this.scaleFactor/this.parentScale,this.translationX,this.translationY,e),pageIndex:this.pageIndex,rect:e,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}};oo=new WeakMap,ao=new WeakMap,li=new WeakMap,Zi=new WeakMap,bs=new WeakMap,ho=new WeakMap,lo=new WeakMap,co=new WeakMap,tn=new WeakMap,Ra=new WeakMap,uo=new WeakMap,go=new WeakMap,zn=new WeakMap,L=new WeakSet,bv=function(e){const s=n=>{this.thickness=n,v(this,L,Kl).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:U.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},vv=function(e){const s=n=>{this.color=n,v(this,L,wo).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:U.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},yv=function(e){const s=n=>{this.opacity=n,v(this,L,wo).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:U.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},_v=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]}},Wf=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}${Uw(i)}`},wv=function(e,s){this.canvas.addEventListener("contextmenu",hs,{signal:this._uiManager._signal}),v(this,L,Vf).call(this),b(this,ho,new AbortController);const i=this._uiManager.combinedSignal(c(this,ho));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,c(this,co)||(b(this,co,!0),v(this,L,Ya).call(this),this.thickness||(this.thickness=kt._defaultThickness),this.color||(this.color=kt._defaultColor||gt._defaultLineColor),this.opacity??(this.opacity=kt._defaultOpacity)),this.currentPath.push([e,s]),b(this,lo,!1),v(this,L,Wf).call(this),b(this,zn,()=>{v(this,L,Cv).call(this),c(this,zn)&&window.requestAnimationFrame(c(this,zn))}),window.requestAnimationFrame(c(this,zn))},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,Zi);if(r.push([e,s]),b(this,lo,!0),r.length<=2){o.moveTo(...r[0]),o.lineTo(e,s);return}r.length===3&&(b(this,Zi,o=new Path2D),o.moveTo(...r[0])),v(this,L,Av).call(this,o,...r.at(-3),...r.at(-2),e,s)},xv=function(){if(this.currentPath.length===0)return;const e=this.currentPath.at(-1);c(this,Zi).lineTo(...e)},Sv=function(e,s){b(this,zn,null),e=Math.min(Math.max(e,0),this.canvas.width),s=Math.min(Math.max(s,0),this.canvas.height),v(this,L,zf).call(this,e,s),v(this,L,xv).call(this);let i;if(this.currentPath.length!==1)i=v(this,L,Tv).call(this);else{const l=[e,s];i=[[l,l.slice(),l.slice(),l]]}const n=c(this,Zi),r=this.currentPath;this.currentPath=[],b(this,Zi,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||(v(this,L,ou).call(this),v(this,L,au).call(this)),v(this,L,Kl).call(this))};this.addCommands({cmd:o,undo:h,mustExec:!0})},Cv=function(){if(!c(this,lo))return;b(this,lo,!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,Zi)),r.restore()},Av=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)},Tv=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],y=(f+m)/2,x=(p+_)/2,S=[n+2*(f-n)/3,r+2*(p-r)/3],C=[y+2*(f-y)/3,x+2*(p-x)/3];s.push([[n,r],S,C,[y,x]]),[n,r]=[y,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},wo=function(){if(this.isEmpty()){v(this,L,hu).call(this);return}v(this,L,Wf).call(this);const{canvas:e,ctx:s}=this;s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),v(this,L,hu).call(this);for(const i of this.bezierPath2D)s.stroke(i)},Xf=function(){if(c(this,Ra))return;b(this,Ra,new AbortController);const e=this._uiManager.combinedSignal(c(this,Ra));this.canvas.addEventListener("pointerdown",this.canvasPointerdown.bind(this),{signal:e})},Vf=function(){var e;(e=this.pointerdownAC)==null||e.abort(),this.pointerdownAC=null},Gf=function(e){var s;(s=c(this,ho))==null||s.abort(),b(this,ho,null),v(this,L,Xf).call(this),c(this,li)&&clearTimeout(c(this,li)),b(this,li,setTimeout(()=>{b(this,li,null),this.canvas.removeEventListener("contextmenu",hs)},10)),v(this,L,Sv).call(this,e.offsetX,e.offsetY),this.addToAnnotationStorage(),this.setInBackground()},ou=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")},au=function(){b(this,tn,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&this.setDimensions(s.width,s.height)})),c(this,tn).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,tn))==null||e.disconnect(),b(this,tn,null)},{once:!0})},Ya=function(){if(!c(this,co))return;const[e,s]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*e),this.canvas.height=Math.ceil(this.height*s),v(this,L,hu).call(this)},Yf=function(e,s){const i=v(this,L,lu).call(this),n=(e-i)/c(this,ao),r=(s-i)/c(this,oo);this.scaleFactor=Math.min(n,r)},hu=function(){const e=v(this,L,lu).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+e,this.translationY*this.scaleFactor+e)},en=new WeakSet,Ev=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},kv=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},Mv=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[y,x,S,C]=g[m];if(y[0]===C[0]&&y[1]===C[1]&&_===1){const B=e*y[0]+h,X=e*y[1]+l;f.push(B,X),p.push(B,X);break}const E=e*y[0]+h,M=e*y[1]+l,k=e*x[0]+h,O=e*x[1]+l,P=e*S[0]+h,F=e*S[1]+l,R=e*C[0]+h,W=e*C[1]+l;m===0&&(f.push(E,M),p.push(E,M)),f.push(k,O,P,F,R,W),p.push(k,O),m===_-1&&p.push(R,W)}r.push({bezier:v(d=kt,en,Uf).call(d,f,n,this.rotation),points:v(u=kt,en,Uf).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]},lu=function(){return c(this,bs)?Math.ceil(this.thickness*this.parentScale):0},Kl=function(e=!1){if(this.isEmpty())return;if(!c(this,bs)){v(this,L,wo).call(this);return}const s=v(this,L,qf).call(this),i=v(this,L,lu).call(this);b(this,ao,Math.max(gt.MIN_SIZE,s[2]-s[0])),b(this,oo,Math.max(gt.MIN_SIZE,s[3]-s[1]));const n=Math.ceil(i+c(this,ao)*this.scaleFactor),r=Math.ceil(i+c(this,oo)*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],v(this,L,Ya).call(this),v(this,L,wo).call(this),b(this,uo,n),b(this,go,r),this.setDims(n,r);const u=e?i/this.scaleFactor/2:0;this.translate(l-this.translationX-u,d-this.translationY-u)},w(kt,en),q(kt,"_defaultColor",null),q(kt,"_defaultOpacity",1),q(kt,"_defaultThickness",1),q(kt,"_type","ink"),q(kt,"_editorType",Z.INK);let $g=kt;const Il=class Il extends gt{constructor(e){super({...e,name:"stampEditor"});w(this,nt);w(this,Mt,null);w(this,oe,null);w(this,Xn,null);w(this,sn,null);w(this,Vn,null);w(this,La,"");w(this,ci,null);w(this,nn,null);w(this,di,null);w(this,ss,!1);w(this,Ia,!1);b(this,sn,e.bitmapUrl),b(this,Vn,e.bitmapFile)}static initialize(e,s){gt.initialize(e,s)}static get supportedTypes(){return ot(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(s=>`image/${s}`))}static get supportedTypesStr(){return ot(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,s){s.pasteEditor(Z.STAMP,{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var e;return{type:"stamp",hasAltText:!!((e=this.altTextData)!=null&&e.altText)}}static computeTelemetryFinalData(e){const s=e.get("hasAltText");return{hasAltText:s.get(!0)??0,hasNoAltText:s.get(!1)??0}}async mlGuessAltText(e=null,s=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:r,height:o}=e||this.copyCanvas(null,null,!0).imageData,h=await i.guess({name:"altText",request:{data:n,width:r,height:o,channels:n.length/(r*o)}});if(!h)throw new Error("No response from the AI service.");if(h.error)throw new Error("Error from the AI service.");if(h.cancel)return null;if(!h.output)throw new Error("No valid response from the AI service.");const l=h.output;return await this.setGuessedAltText(l),s&&!this.hasAltTextData()&&(this.altTextData={alt:l,decorative:!1}),l}remove(){var e,s;c(this,oe)&&(b(this,Mt,null),this._uiManager.imageManager.deleteId(c(this,oe)),(e=c(this,ci))==null||e.remove(),b(this,ci,null),(s=c(this,nn))==null||s.disconnect(),b(this,nn,null),c(this,di)&&(clearTimeout(c(this,di)),b(this,di,null))),super.remove()}rebuild(){if(!this.parent){c(this,oe)&&v(this,nt,cu).call(this);return}super.rebuild(),this.div!==null&&(c(this,oe)&&c(this,ci)===null&&v(this,nt,cu).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(c(this,Xn)||c(this,Mt)||c(this,sn)||c(this,Vn)||c(this,oe))}get isResizable(){return!0}render(){if(this.div)return this.div;let e,s;if(this.width&&(e=this.x,s=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),c(this,Mt)?v(this,nt,$f).call(this):v(this,nt,cu).call(this),this.width&&!this.annotationElementId){const[i,n]=this.parentDimensions;this.setAt(e*i,s*n,this.width*i,this.height*n)}return this.div}copyCanvas(e,s,i=!1){var f;e||(e=224);const{width:n,height:r}=c(this,Mt),o=new Tg;let h=c(this,Mt),l=n,d=r,u=null;if(s){if(n>s||r>s){const O=Math.min(s/n,s/r);l=Math.floor(n*O),d=Math.floor(r*O)}u=document.createElement("canvas");const p=u.width=Math.ceil(l*o.sx),m=u.height=Math.ceil(d*o.sy);c(this,ss)||(h=v(this,nt,du).call(this,p,m));const _=u.getContext("2d");_.filter=this._uiManager.hcmFilter;let y="white",x="#cfcfd8";this._uiManager.hcmFilter!=="none"?x="black":(f=window.matchMedia)!=null&&f.call(window,"(prefers-color-scheme: dark)").matches&&(y="#8f8f9d",x="#42414d");const S=15,C=S*o.sx,E=S*o.sy,M=new OffscreenCanvas(C*2,E*2),k=M.getContext("2d");k.fillStyle=y,k.fillRect(0,0,C*2,E*2),k.fillStyle=x,k.fillRect(0,0,C,E),k.fillRect(C,E,C,E),_.fillStyle=_.createPattern(M,"repeat"),_.fillRect(0,0,p,m),_.drawImage(h,0,0,h.width,h.height,0,0,p,m)}let g=null;if(i){let p,m;if(o.symmetric&&h.width<e&&h.height<e)p=h.width,m=h.height;else if(h=c(this,Mt),n>e||r>e){const x=Math.min(e/n,e/r);p=Math.floor(n*x),m=Math.floor(r*x),c(this,ss)||(h=v(this,nt,du).call(this,p,m))}const y=new OffscreenCanvas(p,m).getContext("2d",{willReadFrequently:!0});y.drawImage(h,0,0,h.width,h.height,0,0,p,m),g={width:p,height:m,data:y.getImageData(0,0,p,m).data}}return{canvas:u,width:l,height:d,imageData:g}}getImageForAltText(){return c(this,ci)}static async deserialize(e,s,i){var m;let n=null;if(e instanceof Z0){const{data:{rect:_,rotation:y,id:x,structParent:S,popupRef:C},container:E,parent:{page:{pageNumber:M}}}=e,k=E.querySelector("canvas"),O=i.imageManager.getFromCanvas(E.id,k);k.remove();const P=((m=await s._structTree.getAriaAttributes(`${wg}${x}`))==null?void 0:m.get("aria-label"))||"";n=e={annotationType:Z.STAMP,bitmapId:O.id,bitmap:O.bitmap,pageIndex:M-1,rect:_.slice(0),rotation:y,id:x,deleted:!1,accessibilityData:{decorative:!1,altText:P},isSvg:!1,structParent:S,popupRef:C}}const r=await super.deserialize(e,s,i),{rect:o,bitmap:h,bitmapUrl:l,bitmapId:d,isSvg:u,accessibilityData:g}=e;d&&i.imageManager.isValidId(d)?(b(r,oe,d),h&&b(r,Mt,h)):b(r,sn,l),b(r,ss,u);const[f,p]=r.pageDimensions;return r.width=(o[2]-o[0])/f,r.height=(o[3]-o[1])/p,r.annotationElementId=e.id||null,g&&(r.altTextData=g),r._initialData=n,b(r,Ia,!!n),r}serialize(e=!1,s=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:Z.STAMP,bitmapId:c(this,oe),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:c(this,ss),structTreeParentId:this._structTreeParentId};if(e)return i.bitmapUrl=v(this,nt,uu).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:n,altText:r}=this.serializeAltText(!1);if(!n&&r&&(i.accessibilityData={type:"Figure",alt:r}),this.annotationElementId){const h=v(this,nt,Pv).call(this,i);if(h.isSame)return null;h.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,s===null)return i;s.stamps||(s.stamps=new Map);const o=c(this,ss)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(c(this,oe)))s.stamps.set(c(this,oe),{area:o,serialized:i}),i.bitmap=v(this,nt,uu).call(this,!1);else if(c(this,ss)){const h=s.stamps.get(c(this,oe));o>h.area&&(h.area=o,h.serialized.bitmap.close(),h.serialized.bitmap=v(this,nt,uu).call(this,!1))}return i}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}};Mt=new WeakMap,oe=new WeakMap,Xn=new WeakMap,sn=new WeakMap,Vn=new WeakMap,La=new WeakMap,ci=new WeakMap,nn=new WeakMap,di=new WeakMap,ss=new WeakMap,Ia=new WeakMap,nt=new WeakSet,Ql=function(e,s=!1){if(!e){this.remove();return}b(this,Mt,e.bitmap),s||(b(this,oe,e.id),b(this,ss,e.isSvg)),e.file&&b(this,La,e.file.name),v(this,nt,$f).call(this)},Jl=function(){if(b(this,Xn,null),this._uiManager.enableWaiting(!1),!!c(this,ci)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&c(this,Mt)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&c(this,Mt)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},cu=function(){if(c(this,oe)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(c(this,oe)).then(i=>v(this,nt,Ql).call(this,i,!0)).finally(()=>v(this,nt,Jl).call(this));return}if(c(this,sn)){const i=c(this,sn);b(this,sn,null),this._uiManager.enableWaiting(!0),b(this,Xn,this._uiManager.imageManager.getFromUrl(i).then(n=>v(this,nt,Ql).call(this,n)).finally(()=>v(this,nt,Jl).call(this)));return}if(c(this,Vn)){const i=c(this,Vn);b(this,Vn,null),this._uiManager.enableWaiting(!0),b(this,Xn,this._uiManager.imageManager.getFromFile(i).then(n=>v(this,nt,Ql).call(this,n)).finally(()=>v(this,nt,Jl).call(this)));return}const e=document.createElement("input");e.type="file",e.accept=Il.supportedTypesStr;const s=this._uiManager._signal;b(this,Xn,new Promise(i=>{e.addEventListener("change",async()=>{if(!e.files||e.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const n=await this._uiManager.imageManager.getFromFile(e.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),v(this,nt,Ql).call(this,n)}i()},{signal:s}),e.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>v(this,nt,Jl).call(this))),e.click()},$f=function(){const{div:e}=this;let{width:s,height:i}=c(this,Mt);const[n,r]=this.pageDimensions,o=.75;if(this.width)s=this.width*n,i=this.height*r;else if(s>o*n||i>o*r){const u=Math.min(o*n/s,o*r/i);s*=u,i*=u}const[h,l]=this.parentDimensions;this.setDims(s*h/n,i*l/r),this._uiManager.enableWaiting(!1);const d=b(this,ci,document.createElement("canvas"));d.setAttribute("role","img"),this.addContainer(d),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),v(this,nt,Kf).call(this,s,i),v(this,nt,Dv).call(this),c(this,Ia)||(this.parent.addUndoableEditor(this),b(this,Ia,!0)),this._reportTelemetry({action:"inserted_image"}),c(this,La)&&d.setAttribute("aria-label",c(this,La))},Ov=function(e,s){var o;const[i,n]=this.parentDimensions;this.width=e/i,this.height=s/n,(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,c(this,di)!==null&&clearTimeout(c(this,di)),b(this,di,setTimeout(()=>{b(this,di,null),v(this,nt,Kf).call(this,e,s)},200))},du=function(e,s){const{width:i,height:n}=c(this,Mt);let r=i,o=n,h=c(this,Mt);for(;r>2*e||o>2*s;){const l=r,d=o;r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2)),o>2*s&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2));const u=new OffscreenCanvas(r,o);u.getContext("2d").drawImage(h,0,0,l,d,0,0,r,o),h=u.transferToImageBitmap()}return h},Kf=function(e,s){const i=new Tg,n=Math.ceil(e*i.sx),r=Math.ceil(s*i.sy),o=c(this,ci);if(!o||o.width===n&&o.height===r)return;o.width=n,o.height=r;const h=c(this,ss)?c(this,Mt):v(this,nt,du).call(this,n,r),l=o.getContext("2d");l.filter=this._uiManager.hcmFilter,l.drawImage(h,0,0,h.width,h.height,0,0,n,r)},uu=function(e){if(e){if(c(this,ss)){const n=this._uiManager.imageManager.getSvgUrl(c(this,oe));if(n)return n}const s=document.createElement("canvas");return{width:s.width,height:s.height}=c(this,Mt),s.getContext("2d").drawImage(c(this,Mt),0,0),s.toDataURL()}if(c(this,ss)){const[s,i]=this.pageDimensions,n=Math.round(this.width*s*bn.PDF_TO_CSS_UNITS),r=Math.round(this.height*i*bn.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(n,r);return o.getContext("2d").drawImage(c(this,Mt),0,0,c(this,Mt).width,c(this,Mt).height,0,0,n,r),o.transferToImageBitmap()}return structuredClone(c(this,Mt))},Dv=function(){this._uiManager._signal&&(b(this,nn,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&v(this,nt,Ov).call(this,s.width,s.height)})),c(this,nn).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,nn))==null||e.disconnect(),b(this,nn,null)},{once:!0}))},Pv=function(e){var l;const{rect:s,pageIndex:i,accessibilityData:{altText:n}}=this._initialData,r=e.rect.every((d,u)=>Math.abs(d-s[u])<1),o=e.pageIndex===i,h=(((l=e.accessibilityData)==null?void 0:l.alt)||"")===n;return{isSame:r&&o&&h,isSameAltText:h}},q(Il,"_type","stamp"),q(Il,"_editorType",Z.STAMP);let Kg=Il;const zs=class zs{constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:d}){w(this,ae);w(this,fo);w(this,ja,!1);w(this,ui,null);w(this,Gn,null);w(this,rn,null);w(this,is,new Map);w(this,Yn,!1);w(this,Na,!1);w(this,Ba,!1);w(this,ye,null);w(this,on,null);w(this,G);const u=[...c(zs,Un).values()];if(!zs._initialized){zs._initialized=!0;for(const g of u)g.initialize(d,t)}t.registerEditorTypes(u),b(this,G,t),this.pageIndex=e,this.div=s,b(this,fo,n),b(this,ui,r),this.viewport=l,b(this,ye,h),this.drawLayer=o,this._structTree=i,c(this,G).addLayer(this)}get isEmpty(){return c(this,is).size===0}get isInvisible(){return this.isEmpty&&c(this,G).getMode()===Z.NONE}updateToolbar(t){c(this,G).updateToolbar(t)}updateMode(t=c(this,G).getMode()){switch(v(this,ae,gu).call(this),t){case Z.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Z.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Z.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(zs,Un).values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){var e;return t===((e=c(this,ye))==null?void 0:e.div)}addInkEditorIfNeeded(t){if(c(this,G).getMode()!==Z.INK)return;if(!t){for(const s of c(this,is).values())if(s.isEmpty()){s.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){c(this,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,ui))==null||e.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of c(this,is).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(c(this,G).removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!c(this,ui))return;const e=c(this,ui).getEditableAnnotations();for(const s of e){if(s.hide(),c(this,G).isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){var i;b(this,Ba,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const n of c(this,is).values())if(n.disableEditing(),!!n.annotationElementId){if(n.serialize()!==null){t.set(n.annotationElementId,n);continue}else e.set(n.annotationElementId,n);(i=this.getEditableAnnotation(n.annotationElementId))==null||i.show(),n.remove()}if(c(this,ui)){const n=c(this,ui).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()}}v(this,ae,gu).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const n of c(zs,Un).values())s.remove(`${n._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),b(this,Ba,!1)}getEditableAnnotation(t){var e;return((e=c(this,ui))==null?void 0:e.getEditableAnnotation(t))||null}setActiveEditor(t){c(this,G).getActive()!==t&&c(this,G).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=c(this,ye))!=null&&t.div&&!c(this,on)){b(this,on,new AbortController);const e=c(this,G).combinedSignal(c(this,on));c(this,ye).div.addEventListener("pointerdown",v(this,ae,Fv).bind(this),{signal:e}),c(this,ye).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=c(this,ye))!=null&&t.div&&c(this,on)&&(c(this,on).abort(),b(this,on,null),c(this,ye).div.classList.remove("highlighting"))}enableClick(){if(c(this,Gn))return;b(this,Gn,new AbortController);const t=c(this,G).combinedSignal(c(this,Gn));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=c(this,Gn))==null||t.abort(),b(this,Gn,null)}attach(t){c(this,is).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,is).delete(t.id),(e=c(this,fo))==null||e.removePointerInTextLayer(t.contentDiv),!c(this,Ba)&&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,Na)||this.addInkEditorIfNeeded(!1)}changeParent(t){var e;t.parent!==this&&(t.parent&&t.annotationElementId&&(c(this,G).addDeletedAnnotationElement(t.annotationElementId),gt.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(e=t.parent)==null||e.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),c(this,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,rn)&&(t._focusEventsAllowed=!1,b(this,rn,setTimeout(()=>{b(this,rn,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,fo))==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()}combinedSignal(t){return c(this,G).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=c(this,ae,Qf))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,e){c(this,G).updateToolbar(t),c(this,G).updateMode(t);const{offsetX:s,offsetY:i}=v(this,ae,Zf).call(this),n=this.getNextId(),r=v(this,ae,Jf).call(this,{parent:this,id:n,x:s,y:i,uiManager:c(this,G),isCentered:!0,...e});r&&this.add(r)}async deserialize(t){var e;return await((e=c(zs,Un).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=v(this,ae,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(v(this,ae,Zf).call(this),!0)}setSelected(t){c(this,G).setSelected(t)}toggleSelected(t){c(this,G).toggleSelected(t)}unselect(t){c(this,G).unselect(t)}pointerup(t){const{isMac:e}=Ee.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&c(this,Yn)){if(b(this,Yn,!1),!c(this,ja)){b(this,ja,!0);return}if(c(this,G).getMode()===Z.STAMP){c(this,G).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(c(this,G).getMode()===Z.HIGHLIGHT&&this.enableTextSelection(),c(this,Yn)){b(this,Yn,!1);return}const{isMac:e}=Ee.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;b(this,Yn,!0);const s=c(this,G).getActive();b(this,ja,!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,rn)&&(clearTimeout(c(this,rn)),b(this,rn,null));for(const s of c(this,is).values())(e=c(this,fo))==null||e.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,c(this,is).clear(),c(this,G).removeLayer(this)}render({viewport:t}){this.viewport=t,dr(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(),v(this,ae,gu).call(this);const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,dr(this.div,{rotation:s}),e!==s)for(const i of c(this,is).values())i.rotate(s);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return c(this,G).viewParameters.realScale}};fo=new WeakMap,ja=new WeakMap,ui=new WeakMap,Gn=new WeakMap,rn=new WeakMap,is=new WeakMap,Yn=new WeakMap,Na=new WeakMap,Ba=new WeakMap,ye=new WeakMap,on=new WeakMap,G=new WeakMap,Un=new WeakMap,ae=new WeakSet,Fv=function(t){c(this,G).unselectAll();const{target:e}=t;if(e===c(this,ye).div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&c(this,ye).div.contains(e)){const{isMac:s}=Ee.platform;if(t.button!==0||t.ctrlKey&&s)return;c(this,G).showAllEditors("highlight",!0,!0),c(this,ye).div.classList.add("free"),this.toggleDrawing(),yd.startHighlighting(this,c(this,G).direction==="ltr",{target:c(this,ye).div,x:t.x,y:t.y}),c(this,ye).div.addEventListener("pointerup",()=>{c(this,ye).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:c(this,G)._signal}),t.preventDefault()}},Qf=function(){return c(zs,Un).get(c(this,G).getMode())},Jf=function(t){const e=c(this,ae,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}},gu=function(){b(this,Na,!0);for(const t of c(this,is).values())t.isEmpty()&&t.remove();b(this,Na,!1)},q(zs,"_initialized",!1),w(zs,Un,new Map([Ug,$g,Kg,yd].map(t=>[t._editorType,t])));let Qg=zs;const he=class he{constructor({pageIndex:t}){w(this,po);w(this,gi,null);w(this,jl,0);w(this,Wt,new Map);w(this,an,new Map);this.pageIndex=t}setParent(t){if(!c(this,gi)){b(this,gi,t);return}if(c(this,gi)!==t){if(c(this,Wt).size>0)for(const e of c(this,Wt).values())e.remove(),t.append(e);b(this,gi,t)}}static get _svgFactory(){return ot(this,"_svgFactory",new Vg)}draw(t,e,s,i=!1){const n=Fe(this,jl)._++,r=v(this,po,ep).call(this,t.box);r.classList.add(...t.classNamesForDrawing);const o=he._svgFactory.createElement("defs");r.append(o);const h=he._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,an).set(n,h);const d=v(this,po,Rv).call(this,o,l),u=he._svgFactory.createElement("use");return r.append(u),r.setAttribute("fill",e),r.setAttribute("fill-opacity",s),u.setAttribute("href",`#${l}`),c(this,Wt).set(n,r),{id:n,clipPathId:`url(#${d})`}}drawOutline(t){const e=Fe(this,jl)._++,s=v(this,po,ep).call(this,t.box);s.classList.add(...t.classNamesForOutlining);const i=he._svgFactory.createElement("defs");s.append(i);const n=he._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.mustRemoveSelfIntersections){const d=he._svgFactory.createElement("mask");i.append(d),o=`mask_p${this.pageIndex}_${e}`,d.setAttribute("id",o),d.setAttribute("maskUnits","objectBoundingBox");const u=he._svgFactory.createElement("rect");d.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const g=he._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=he._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,Wt).set(e,s),e}finalizeLine(t,e){const s=c(this,an).get(t);c(this,an).delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){c(this,Wt).get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}updatePath(t,e){c(this,an).get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){var s;v(s=he,Nl,tp).call(s,c(this,Wt).get(t),e)}show(t,e){c(this,Wt).get(t).classList.toggle("hidden",!e)}rotate(t,e){c(this,Wt).get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){c(this,Wt).get(t).setAttribute("fill",e)}changeOpacity(t,e){c(this,Wt).get(t).setAttribute("fill-opacity",e)}addClass(t,e){c(this,Wt).get(t).classList.add(e)}removeClass(t,e){c(this,Wt).get(t).classList.remove(e)}getSVGRoot(t){return c(this,Wt).get(t)}remove(t){c(this,an).delete(t),c(this,gi)!==null&&(c(this,Wt).get(t).remove(),c(this,Wt).delete(t))}destroy(){b(this,gi,null);for(const t of c(this,Wt).values())t.remove();c(this,Wt).clear(),c(this,an).clear()}};gi=new WeakMap,jl=new WeakMap,Wt=new WeakMap,an=new WeakMap,Nl=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}%`},po=new WeakSet,ep=function(t){var s;const e=he._svgFactory.create(1,1,!0);return c(this,gi).append(e),e.setAttribute("aria-hidden",!0),v(s=he,Nl,tp).call(s,e,t),e},Rv=function(t,e){const s=he._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=he._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i},w(he,Nl);let Jg=he;$.AbortException,$.AnnotationEditorLayer,$.AnnotationEditorParamsType,$.AnnotationEditorType,$.AnnotationEditorUIManager,$.AnnotationLayer,$.AnnotationMode,$.ColorPicker,$.DOMSVGFactory,$.DrawLayer,$.FeatureTest;var TS=$.GlobalWorkerOptions;$.ImageKind,$.InvalidPDFException,$.MissingPDFException,$.OPS,$.OutputScale,$.PDFDataRangeTransport,$.PDFDateString,$.PDFWorker,$.PasswordResponses,$.PermissionFlag,$.PixelsPerInch,$.RenderingCancelledException,$.TextLayer,$.UnexpectedResponseException,$.Util,$.VerbosityLevel,$.XfaLayer,$.build,$.createValidAbsoluteUrl,$.fetchData;var ES=$.getDocument;$.getFilenameFromUrl,$.getPdfFilenameFromUrl,$.getXfaPageViewport,$.isDataScheme,$.isPdfFile,$.noContextMenu,$.normalizeUnicode,$.setLayerDimensions,$.shadow,$.version;const kS={fabric:"^6.5.0","pdfjs-dist":"^4.8.69"};function MS(a){return new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>t(s.result)),s.addEventListener("error",e),s.readAsDataURL(a)})}const OS=kS["pdfjs-dist"].replace("^","");TS.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${OS}/pdf.worker.min.mjs`;async function DS(a){const t="data:application/pdf;base64,",e=await MS(a);if(typeof e=="string")return window.atob(e.slice(t.length))}function PS(a,t){return ES({data:a,password:t}).promise}const FS={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},RS={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},LS={stroke:"#000",hoverStroke:"#B7EC5D",src:""};function ib(a=""){let t=0,e=null,s=null,i=1,n={...LS};function r(){if(!a||as.has(a))return;const k=pw(a);return k.on("selection:cleared",()=>C(k)),k}function o(k,O){var R;const P=k.type,F={"application/pdf":h,"image/png":u,"image/jpeg":u};return((R=F[P])==null?void 0:R.call(F,k,O))??Promise.reject(new Error(`Unsupported ${P} file type.`))}async function h(k,O){const P=await DS(k);if(!P)return;const F=mw(k,P);try{return await l({page:1,PDFBase64:P,scale:.8,password:O}),{...F,pages:t}}catch(R){return Promise.reject(R)}}async function l({page:k,PDFBase64:O,scale:P,password:F}){try{const R=await PS(O,F),W=await Y.toRaw(R).getPage(k),{renderTask:B,canvas:X}=bw(W,P);return t=R.numPages,B.promise.then(()=>d(X))}catch(R){return Promise.reject(R)}}function d(k){yw(a,k)}async function u(k){return await _w(a,k)}async function g({url:k,scale:O=.5}){await a0(a,{url:k,scale:O})}async function f(k,O){const P=as.get(a);if(!P)return;const F=await ge.fromURL(k,{},{...FS,...O});P.add(F),m(P,F)}function p(k,O){const P=as.get(a);if(!P)return;const F=new ue(k,{...RS,...O});P.add(F),m(P,F)}function m(k,O){O.on("selected",P=>_({canvas:k,target:P.target})),O.on("modified",P=>ch(P.target,e)),O.on("scaling",P=>ch(P.transform.target,e)),O.on("moving",P=>ch(P.transform.target,e)),O.on("rotating",P=>ch(P.transform.target,e))}async function _({canvas:k,target:O,stroke:P=n.stroke,uuid:F=Date.now()}){if((e==null?void 0:e.stroke)===`${P}-${F}`)return;const R=await vw(n.src,P,F);C(k),e=R,s=O,y(k,O,F),x(i,!0),k.add(R)}function y(k,O,P){e&&(e.on("selected",()=>{k.remove(O),C(k)}),e.on("mouseover",()=>{_({canvas:k,target:O,stroke:n.hoverStroke,uuid:P})}),e.on("mouseout",()=>{_({canvas:k,target:O,stroke:n.stroke,uuid:P})}))}function x(k,O=!1){const P=as.get(a);i=k,P&&(xw(s,k,n),ww(s,k,e),!O&&P.renderAll())}function S(k){if(!k)return;n={...n,...k};const O=as.get(a);!e||!s||!O||_({target:s,canvas:O})}function C(k){e&&(k.remove(e),e=s=null)}function E(){Sw(a)}function M(){Cw(a)}return{createCanvas:r,loadFile:o,specifyPage:l,renderImage:g,addFabric:f,addTextFabric:p,clearActive:E,deleteCanvas:M,scaleFabric:x,setCloseSvgOptions:S}}function IS(a){let t=0;const e=fw(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});Y.onMounted(()=>{window.addEventListener("resize",e)}),Y.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const Zg=Y.defineComponent({__name:"pdf-canvas",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=Y.ref(null),i=`${e.canvasId}-${e.page-1}`,n=Y.computed(()=>e.fileZoom*e.canvasScale),{createCanvas:r,specifyPage:o,addFabric:h,addTextFabric:l,renderImage:d,clearActive:u,deleteCanvas:g,scaleFabric:f,setCloseSvgOptions:p}=ib(i);m(),IS(m);async function m(){const{file:S,page:C,fileScale:E}=e;window.requestAnimationFrame(async()=>{if(await Y.nextTick(),r(),S.PDFBase64.startsWith("data:image")||S.canvas){const{canvas:M}=S,k=M?7:3,O=M!=null&&M.length?M[C-1]:S.PDFBase64;d({url:O,scale:E/k});return}await o({page:C,PDFBase64:S.PDFBase64,scale:E,password:e.password})})}function _(S){if(!e.isDrop||!S.dataTransfer)return;const{dataTransfer:C,offsetX:E,offsetY:M}=S,k=C.getData("text"),O=C.getData("image"),P={left:E-71,top:M-55};O&&y(O,P),k&&x(k,P)}function y(S,C){h(S,{...C,...e.dropImageOptions})}function x(S,C){l(S,{...C,...e.dropTextOptions})}return Y.watch([()=>e.fileScale,()=>e.page,()=>e.file,()=>e.password],m),Y.watch(n,S=>f(S),{immediate:!0}),Y.watch(()=>e.closeSvgOptions,p,{immediate:!0}),Y.onBeforeUnmount(g),t({addImage:y,addText:x,clearActive:u,deleteCanvas:g,canvasRef:s}),(S,C)=>(Y.openBlock(),Y.createElementBlock("div",{style:Y.normalizeStyle({transform:`scale(${n.value})`}),onDragover:C[0]||(C[0]=Y.withModifiers(()=>{},["stop","prevent"])),onDragenter:C[1]||(C[1]=Y.withModifiers(()=>{},["stop","prevent"])),onDrop:Y.withModifiers(_,["stop","prevent"])},[Y.createElementVNode("canvas",{id:i,ref_key:"canvasRef",ref:s,class:Y.normalizeClass(S.canvasClass)},null,2)],36))}});Zg.install=function(a){a.component("PdfCanvas",Zg)};const _d=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));rt.default=Zg,rt.useFabric=ib,Object.defineProperties(rt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
509
+ `)){const s=document.createElement("div");s.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(s)}},qb=function(){return c(this,Je).replaceAll(" "," ")},Ff=function(e){return e.replaceAll(" "," ")},$b=function(e){const{value:s,fontSize:i,color:n,pageIndex:r}=this._initialData;return this._hasBeenMoved||e.value!==s||e.fontSize!==i||e.color.some((o,h)=>o!==n[h])||e.pageIndex!==r},w(vt,qi),q(vt,"_freeTextDefaultContent",""),q(vt,"_internalPadding",0),q(vt,"_defaultColor",null),q(vt,"_defaultFontSize",10),q(vt,"_type","freetext"),q(vt,"_editorType",Z.FREETEXT);let Ug=vt;class Z0{toSVGPath(){yt("Abstract method `toSVGPath` must be implemented.")}get box(){yt("Abstract getter `box` must be implemented.")}serialize(t,e){yt("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){yt("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){yt("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}const $i=class $i{constructor({x:t,y:e},s,i,n,r,o=0){w(this,qt);w(this,ts);w(this,js,[]);w(this,wa);w(this,xa);w(this,hi,[]);w(this,it,new Float64Array(18));w(this,to);w(this,eo);w(this,wl);w(this,xl);w(this,Sa);w(this,Ca);w(this,Bn,[]);b(this,ts,s),b(this,Ca,n*i),b(this,xa,r),c(this,it).set([NaN,NaN,NaN,NaN,t,e],6),b(this,wa,o),b(this,xl,c($i,Sl)*i),b(this,wl,c($i,jd)*i),b(this,Sa,i),c(this,Bn).push(t,e)}isEmpty(){return isNaN(c(this,it)[8])}add({x:t,y:e}){var P;b(this,to,t),b(this,eo,e);const[s,i,n,r]=c(this,ts);let[o,h,l,d]=c(this,it).subarray(8,12);const u=t-l,g=e-d,f=Math.hypot(u,g);if(f<c(this,wl))return!1;const p=f-c(this,xl),m=p/f,_=m*u,y=m*g;let x=o,S=h;o=l,h=d,l+=_,d+=y,(P=c(this,Bn))==null||P.push(t,e);const C=-y/p,E=_/p,M=C*c(this,Ca),k=E*c(this,Ca);return c(this,it).set(c(this,it).subarray(2,8),0),c(this,it).set([l+M,d+k],4),c(this,it).set(c(this,it).subarray(14,18),12),c(this,it).set([l-M,d-k],16),isNaN(c(this,it)[6])?(c(this,hi).length===0&&(c(this,it).set([o+M,h+k],2),c(this,hi).push(NaN,NaN,NaN,NaN,(o+M-s)/n,(h+k-i)/r),c(this,it).set([o-M,h-k],14),c(this,js).push(NaN,NaN,NaN,NaN,(o-M-s)/n,(h-k-i)/r)),c(this,it).set([x,S,o,h,l,d],6),!this.isEmpty()):(c(this,it).set([x,S,o,h,l,d],6),Math.abs(Math.atan2(S-h,x-o)-Math.atan2(y,_))<Math.PI/2?([o,h,l,d]=c(this,it).subarray(2,6),c(this,hi).push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+d)/2-i)/r),[o,h,x,S]=c(this,it).subarray(14,18),c(this,js).push(NaN,NaN,NaN,NaN,((x+o)/2-s)/n,((S+h)/2-i)/r),!0):([x,S,o,h,l,d]=c(this,it).subarray(0,6),c(this,hi).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,it).subarray(12,18),c(this,js).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,hi),e=c(this,js);if(isNaN(c(this,it)[6])&&!this.isEmpty())return v(this,qt,Kb).call(this);const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);v(this,qt,Jb).call(this,s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return v(this,qt,Qb).call(this,s),s.join(" ")}newFreeDrawOutline(t,e,s,i,n,r){return new tb(t,e,s,i,n,r)}getOutlines(){var u;const t=c(this,hi),e=c(this,js),s=c(this,it),[i,n,r,o]=c(this,ts),h=new Float64Array((((u=c(this,Bn))==null?void 0:u.length)??0)+2);for(let g=0,f=h.length-2;g<f;g+=2)h[g]=(c(this,Bn)[g]-i)/r,h[g+1]=(c(this,Bn)[g+1]-n)/o;if(h[h.length-2]=(c(this,to)-i)/r,h[h.length-1]=(c(this,eo)-n)/o,isNaN(s[6])&&!this.isEmpty())return v(this,qt,Zb).call(this,h);const l=new Float64Array(c(this,hi).length+24+c(this,js).length);let d=t.length;for(let g=0;g<d;g+=2){if(isNaN(t[g])){l[g]=l[g+1]=NaN;continue}l[g]=t[g],l[g+1]=t[g+1]}d=v(this,qt,ev).call(this,l,d);for(let g=e.length-6;g>=6;g-=6)for(let f=0;f<6;f+=2){if(isNaN(e[g+f])){l[d]=l[d+1]=NaN,d+=2;continue}l[d]=e[g+f],l[d+1]=e[g+f+1],d+=2}return v(this,qt,tv).call(this,l,d),this.newFreeDrawOutline(l,h,c(this,ts),c(this,Sa),c(this,wa),c(this,xa))}};ts=new WeakMap,js=new WeakMap,wa=new WeakMap,xa=new WeakMap,hi=new WeakMap,it=new WeakMap,to=new WeakMap,eo=new WeakMap,wl=new WeakMap,xl=new WeakMap,Sa=new WeakMap,Ca=new WeakMap,Bn=new WeakMap,Sl=new WeakMap,Id=new WeakMap,jd=new WeakMap,qt=new WeakSet,Yl=function(){const t=c(this,it).subarray(4,6),e=c(this,it).subarray(16,18),[s,i,n,r]=c(this,ts);return[(c(this,to)+(t[0]-e[0])/2-s)/n,(c(this,eo)+(t[1]-e[1])/2-i)/r,(c(this,to)+(e[0]-t[0])/2-s)/n,(c(this,eo)+(e[1]-t[1])/2-i)/r]},Kb=function(){const[t,e,s,i]=c(this,ts),[n,r,o,h]=v(this,qt,Yl).call(this);return`M${(c(this,it)[2]-t)/s} ${(c(this,it)[3]-e)/i} L${(c(this,it)[4]-t)/s} ${(c(this,it)[5]-e)/i} L${n} ${r} L${o} ${h} L${(c(this,it)[16]-t)/s} ${(c(this,it)[17]-e)/i} L${(c(this,it)[14]-t)/s} ${(c(this,it)[15]-e)/i} Z`},Qb=function(t){const e=c(this,js);t.push(`L${e[4]} ${e[5]} Z`)},Jb=function(t){const[e,s,i,n]=c(this,ts),r=c(this,it).subarray(4,6),o=c(this,it).subarray(16,18),[h,l,d,u]=v(this,qt,Yl).call(this);t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${d} ${u} L${(o[0]-e)/i} ${(o[1]-s)/n}`)},Zb=function(t){const e=c(this,it),[s,i,n,r]=c(this,ts),[o,h,l,d]=v(this,qt,Yl).call(this),u=new Float64Array(36);return u.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,l,d,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(u,t,c(this,ts),c(this,Sa),c(this,wa),c(this,xa))},tv=function(t,e){const s=c(this,js);return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6},ev=function(t,e){const s=c(this,it).subarray(4,6),i=c(this,it).subarray(16,18),[n,r,o,h]=c(this,ts),[l,d,u,g]=v(this,qt,Yl).call(this);return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,d,NaN,NaN,NaN,NaN,u,g,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24},w($i,Sl,8),w($i,Id,2),w($i,jd,c($i,Sl)+c($i,Id));let bd=$i;class tb extends Z0{constructor(e,s,i,n,r,o){super();w(this,We);w(this,Aa);w(this,so,null);w(this,Ki);w(this,Cl);w(this,es);w(this,Al);w(this,It);b(this,It,e),b(this,es,s),b(this,Aa,i),b(this,Al,n),b(this,Ki,r),b(this,Cl,o),v(this,We,sv).call(this,o);const{x:h,y:l,width:d,height:u}=c(this,so);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,It)[4]} ${c(this,It)[5]}`];for(let s=6,i=c(this,It).length;s<i;s+=6){if(isNaN(c(this,It)[s])){e.push(`L${c(this,It)[s+4]} ${c(this,It)[s+5]}`);continue}e.push(`C${c(this,It)[s]} ${c(this,It)[s+1]} ${c(this,It)[s+2]} ${c(this,It)[s+3]} ${c(this,It)[s+4]} ${c(this,It)[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=v(this,We,Ul).call(this,c(this,It),e,n,o,-h),d=v(this,We,Ul).call(this,c(this,es),e,n,o,-h);break;case 90:l=v(this,We,ql).call(this,c(this,It),e,s,o,h),d=v(this,We,ql).call(this,c(this,es),e,s,o,h);break;case 180:l=v(this,We,Ul).call(this,c(this,It),i,s,-o,h),d=v(this,We,Ul).call(this,c(this,es),i,s,-o,h);break;case 270:l=v(this,We,ql).call(this,c(this,It),i,n,-o,-h),d=v(this,We,ql).call(this,c(this,es),i,n,-o,-h);break}return{outline:Array.from(l),points:[Array.from(d)]}}get box(){return c(this,so)}newOutliner(e,s,i,n,r,o=0){return new bd(e,s,i,n,r,o)}getNewOutline(e,s){const{x:i,y:n,width:r,height:o}=c(this,so),[h,l,d,u]=c(this,Aa),g=r*d,f=o*u,p=i*d+h,m=n*u+l,_=this.newOutliner({x:c(this,es)[0]*g+p,y:c(this,es)[1]*f+m},c(this,Aa),c(this,Al),e,c(this,Cl),s??c(this,Ki));for(let y=2;y<c(this,es).length;y+=2)_.add({x:c(this,es)[y]*g+p,y:c(this,es)[y+1]*f+m});return _.getOutlines()}get mustRemoveSelfIntersections(){return!0}}Aa=new WeakMap,so=new WeakMap,Ki=new WeakMap,Cl=new WeakMap,es=new WeakMap,Al=new WeakMap,It=new WeakMap,We=new WeakSet,Ul=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},sv=function(e){const s=c(this,It);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 y=6,x=s.length;y<x;y+=6){if(isNaN(s[y]))r=Math.min(r,s[y+4]),o=Math.min(o,s[y+5]),h=Math.max(h,s[y+4]),l=Math.max(l,s[y+5]),u<s[y+5]?(d=s[y+4],u=s[y+5]):u===s[y+5]&&(d=g(d,s[y+4]));else{const S=z.bezierBoundingBox(i,n,...s.slice(y,y+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[y+4],n=s[y+5]}const f=r-c(this,Ki),p=o-c(this,Ki),m=h-r+2*c(this,Ki),_=l-o+2*c(this,Ki);b(this,so,{x:f,y:p,width:m,height:_,lastPoint:[d,u]})};class eb{constructor(t,e=0,s=0,i=!0){w(this,De);w(this,Tl);w(this,Hn,[]);w(this,Ns,[]);let n=1/0,r=-1/0,o=1/0,h=-1/0;const d=10**-4;for(const{x:y,y:x,width:S,height:C}of t){const E=Math.floor((y-e)/d)*d,M=Math.ceil((y+S+e)/d)*d,k=Math.floor((x-e)/d)*d,O=Math.ceil((x+C+e)/d)*d,P=[E,k,O,!0],F=[M,k,O,!1];c(this,Hn).push(P,F),n=Math.min(n,E),r=Math.max(r,M),o=Math.min(o,k),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,Hn).at(i?-1:-2),_=[m[0],m[2]];for(const y of c(this,Hn)){const[x,S,C]=y;y[0]=(x-f)/u,y[1]=(S-p)/g,y[2]=(C-p)/g}b(this,Tl,{x:f,y:p,width:u,height:g,lastPoint:_})}getOutlines(){c(this,Hn).sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of c(this,Hn))e[3]?(t.push(...v(this,De,Rf).call(this,e)),v(this,De,nv).call(this,e)):(v(this,De,rv).call(this,e),t.push(...v(this,De,Rf).call(this,e)));return v(this,De,iv).call(this,t)}}Tl=new WeakMap,Hn=new WeakMap,Ns=new WeakMap,De=new WeakSet,iv=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 SS(i,c(this,Tl))},iu=function(t){const e=c(this,Ns);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},nv=function([,t,e]){const s=v(this,De,iu).call(this,t);c(this,Ns).splice(s,0,[t,e])},rv=function([,t,e]){const s=v(this,De,iu).call(this,t);for(let i=s;i<c(this,Ns).length;i++){const[n,r]=c(this,Ns)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ns).splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=c(this,Ns)[i];if(n!==t)break;if(n===t&&r===e){c(this,Ns).splice(i,1);return}}},Rf=function(t){const[e,s,i]=t,n=[[e,s,i]],r=v(this,De,iu).call(this,i);for(let o=0;o<r;o++){const[h,l]=c(this,Ns)[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 SS extends Z0{constructor(e,s){super();w(this,El);w(this,Ta);b(this,Ta,e),b(this,El,s)}toSVGPath(){const e=[];for(const s of c(this,Ta)){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,Ta)){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,El)}get classNamesForDrawing(){return["highlight"]}get classNamesForOutlining(){return["highlightOutline"]}}El=new WeakMap,Ta=new WeakMap;class qg extends bd{newFreeDrawOutline(t,e,s,i,n,r){return new CS(t,e,s,i,n,r)}get classNamesForDrawing(){return["highlight","free"]}}class CS extends tb{get classNamesForDrawing(){return["highlight","free"]}get classNamesForOutlining(){return["highlightOutline","free"]}newOutliner(t,e,s,i,n,r=0){return new qg(t,e,s,i,n,r)}}const ze=class ze{constructor({editor:t=null,uiManager:e=null}){w(this,bt);w(this,Bs,null);w(this,io,null);w(this,Ea);w(this,$t,null);w(this,kl,!1);w(this,ka,!1);w(this,Ml,null);w(this,Ol);w(this,Wn,null);w(this,Hs,null);w(this,Ma);var s;t?(b(this,ka,!1),b(this,Ma,U.HIGHLIGHT_COLOR),b(this,Ml,t)):(b(this,ka,!0),b(this,Ma,U.HIGHLIGHT_DEFAULT_COLOR)),b(this,Hs,(t==null?void 0:t._uiManager)||e),b(this,Ol,c(this,Hs)._eventBus),b(this,Ea,(t==null?void 0:t.color)||((s=c(this,Hs))==null?void 0:s.highlightColors.values().next().value)||"#FFFF98"),c(ze,Dl)||b(ze,Dl,Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"}))}static get _keyboardManager(){return ot(this,"_keyboardManager",new ph([[["Escape","mac+Escape"],ze.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ze.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ze.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ze.prototype._moveToPrevious],[["Home","mac+Home"],ze.prototype._moveToBeginning],[["End","mac+End"],ze.prototype._moveToEnd]]))}renderButton(){const t=b(this,Bs,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,Hs)._signal;t.addEventListener("click",v(this,bt,yo).bind(this),{signal:e}),t.addEventListener("keydown",v(this,bt,jf).bind(this),{signal:e});const s=b(this,io,document.createElement("span"));return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=c(this,Ea),t.append(s),t}renderMainDropdown(){const t=b(this,$t,v(this,bt,Lf).call(this));return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}_colorSelectFromKeyboard(t){if(t.target===c(this,Bs)){v(this,bt,yo).call(this,t);return}const e=t.target.getAttribute("data-color");e&&v(this,bt,If).call(this,e,t)}_moveToNext(t){var e,s;if(!c(this,bt,$n)){v(this,bt,yo).call(this,t);return}if(t.target===c(this,Bs)){(e=c(this,$t).firstChild)==null||e.focus();return}(s=t.target.nextSibling)==null||s.focus()}_moveToPrevious(t){var e,s;if(t.target===((e=c(this,$t))==null?void 0:e.firstChild)||t.target===c(this,Bs)){c(this,bt,$n)&&this._hideDropdownFromKeyboard();return}c(this,bt,$n)||v(this,bt,yo).call(this,t),(s=t.target.previousSibling)==null||s.focus()}_moveToBeginning(t){var e;if(!c(this,bt,$n)){v(this,bt,yo).call(this,t);return}(e=c(this,$t).firstChild)==null||e.focus()}_moveToEnd(t){var e;if(!c(this,bt,$n)){v(this,bt,yo).call(this,t);return}(e=c(this,$t).lastChild)==null||e.focus()}hideDropdown(){var t,e;(t=c(this,$t))==null||t.classList.add("hidden"),(e=c(this,Wn))==null||e.abort(),b(this,Wn,null)}_hideDropdownFromKeyboard(){var t;if(!c(this,ka)){if(!c(this,bt,$n)){(t=c(this,Ml))==null||t.unselect();return}this.hideDropdown(),c(this,Bs).focus({preventScroll:!0,focusVisible:c(this,kl)})}}updateColor(t){if(c(this,io)&&(c(this,io).style.backgroundColor=t),!c(this,$t))return;const e=c(this,Hs).highlightColors.values();for(const s of c(this,$t).children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){var t,e;(t=c(this,Bs))==null||t.remove(),b(this,Bs,null),b(this,io,null),(e=c(this,$t))==null||e.remove(),b(this,$t,null)}};Bs=new WeakMap,io=new WeakMap,Ea=new WeakMap,$t=new WeakMap,kl=new WeakMap,ka=new WeakMap,Ml=new WeakMap,Ol=new WeakMap,Wn=new WeakMap,Hs=new WeakMap,Ma=new WeakMap,Dl=new WeakMap,bt=new WeakSet,Lf=function(){const t=document.createElement("div"),e=c(this,Hs)._signal;t.addEventListener("contextmenu",hs,{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,Hs).highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",c(ze,Dl)[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===c(this,Ea)),n.addEventListener("click",v(this,bt,If).bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",v(this,bt,jf).bind(this),{signal:e}),t},If=function(t,e){e.stopPropagation(),c(this,Ol).dispatch("switchannotationeditorparams",{source:this,type:c(this,Ma),value:t})},jf=function(t){ze._keyboardManager.exec(this,t)},yo=function(t){if(c(this,bt,$n)){this.hideDropdown();return}if(b(this,kl,t.detail===0),c(this,Wn)||(b(this,Wn,new AbortController),window.addEventListener("pointerdown",v(this,bt,ov).bind(this),{signal:c(this,Hs).combinedSignal(c(this,Wn))})),c(this,$t)){c(this,$t).classList.remove("hidden");return}const e=b(this,$t,v(this,bt,Lf).call(this));c(this,Bs).append(e)},ov=function(t){var e;(e=c(this,$t))!=null&&e.contains(t.target)||this.hideDropdown()},$n=function(){return c(this,$t)&&!c(this,$t).classList.contains("hidden")},w(ze,Dl,null);let vd=ze;const ht=class ht extends gt{constructor(e){super({...e,name:"highlightEditor"});w(this,J);w(this,Oa,null);w(this,Pl,0);w(this,Qi);w(this,no,null);w(this,Da,null);w(this,fs,null);w(this,Fl,null);w(this,Rl,0);w(this,ro,null);w(this,Ws,null);w(this,ve,null);w(this,Xe,!1);w(this,Pa,null);w(this,Ji);w(this,Kt,null);w(this,Fa,"");w(this,ps);w(this,Ll,"");this.color=e.color||ht._defaultColor,b(this,ps,e.thickness||ht._defaultThickness),b(this,Ji,e.opacity||ht._defaultOpacity),b(this,Qi,e.boxes||null),b(this,Ll,e.methodOfCreation||""),b(this,Fa,e.text||""),this._isDraggable=!1,e.highlightId>-1?(b(this,Xe,!0),v(this,J,nu).call(this,e),v(this,J,_o).call(this)):c(this,Qi)&&(b(this,Oa,e.anchorNode),b(this,Pl,e.anchorOffset),b(this,Fl,e.focusNode),b(this,Rl,e.focusOffset),v(this,J,Nf).call(this),v(this,J,_o).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const e=ht.prototype;return ot(this,"_keyboardManager",new ph([[["ArrowLeft","mac+ArrowLeft"],e._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],e._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],e._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],e._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:c(this,Xe)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:c(this,ps),methodOfCreation:c(this,Ll)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get("color").size}}static initialize(e,s){var i;gt.initialize(e,s),ht._defaultColor||(ht._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(e,s){switch(e){case U.HIGHLIGHT_DEFAULT_COLOR:ht._defaultColor=s;break;case U.HIGHLIGHT_THICKNESS:ht._defaultThickness=s;break}}translateInPage(e,s){}get toolbarPosition(){return c(this,Pa)}updateParams(e,s){switch(e){case U.HIGHLIGHT_COLOR:v(this,J,av).call(this,s);break;case U.HIGHLIGHT_THICKNESS:v(this,J,hv).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[U.HIGHLIGHT_DEFAULT_COLOR,ht._defaultColor],[U.HIGHLIGHT_THICKNESS,ht._defaultThickness]]}get propertiesToUpdate(){return[[U.HIGHLIGHT_COLOR,this.color||ht._defaultColor],[U.HIGHLIGHT_THICKNESS,c(this,ps)||ht._defaultThickness],[U.HIGHLIGHT_FREE,c(this,Xe)]]}async addEditToolbar(){const e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(b(this,Da,new vd({editor:this})),e.addColorPicker(c(this,Da))),e):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(v(this,J,$l).call(this))}getBaseTranslation(){return[0,0]}getRect(e,s){return super.getRect(e,s,v(this,J,$l).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){v(this,J,Bf).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(v(this,J,_o).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?v(this,J,Bf).call(this):e&&(v(this,J,_o).call(this,e),s=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(e),this.show(this._isVisible),s&&this.select()}rotate(e){var n,r,o;const{drawLayer:s}=this.parent;let i;c(this,Xe)?(e=(e-this.rotation+360)%360,i=v(n=ht,ms,Ga).call(n,c(this,Ws).box,e)):i=v(r=ht,ms,Ga).call(r,this,e),s.rotate(c(this,ve),e),s.rotate(c(this,Kt),e),s.updateBox(c(this,ve),i),s.updateBox(c(this,Kt),v(o=ht,ms,Ga).call(o,c(this,fs).box,e))}render(){if(this.div)return this.div;const e=super.render();c(this,Fa)&&(e.setAttribute("aria-label",c(this,Fa)),e.setAttribute("role","mark")),c(this,Xe)?e.classList.add("free"):this.div.addEventListener("keydown",v(this,J,cv).bind(this),{signal:this._uiManager._signal});const s=b(this,ro,document.createElement("div"));e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=c(this,no);const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),ld(this,c(this,ro),["pointerover","pointerleave"]),this.enableEditing(),e}pointerover(){this.isSelected||this.parent.drawLayer.addClass(c(this,Kt),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(c(this,Kt),"hovered")}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:v(this,J,ru).call(this,!0);break;case 1:case 3:v(this,J,ru).call(this,!1);break}}select(){var e,s;super.select(),c(this,Kt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Kt),"hovered"),(s=this.parent)==null||s.drawLayer.addClass(c(this,Kt),"selected"))}unselect(){var e;super.unselect(),c(this,Kt)&&((e=this.parent)==null||e.drawLayer.removeClass(c(this,Kt),"selected"),c(this,Xe)||v(this,J,ru).call(this,!1))}get _mustFixPosition(){return!c(this,Xe)}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.show(c(this,ve),e),this.parent.drawLayer.show(c(this,Kt),e))}static startHighlighting(e,s,{target:i,x:n,y:r}){const{x:o,y:h,width:l,height:d}=i.getBoundingClientRect(),u=new AbortController,g=e.combinedSignal(u),f=m=>{m.preventDefault(),m.stopPropagation()},p=m=>{u.abort(),v(this,ms,fv).call(this,e,m)};window.addEventListener("blur",p,{signal:g}),window.addEventListener("pointerup",p,{signal:g}),window.addEventListener("pointerdown",f,{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",hs,{signal:g}),i.addEventListener("pointermove",v(this,ms,gv).bind(this,e),{signal:g}),this._freeHighlight=new qg({x:n,y:r},[o,h,l,d],e.scale,this._defaultThickness/2,s,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(e,s,i){var m,_,y,x;let n=null;if(e instanceof Q0){const{data:{quadPoints:S,rect:C,rotation:E,id:M,color:k,opacity:O,popupRef:P},parent:{page:{pageNumber:F}}}=e;n=e={annotationType:Z.HIGHLIGHT,color:Array.from(k),opacity:O,quadPoints:S,boxes:null,pageIndex:F-1,rect:C.slice(0),rotation:E,id:M,deleted:!1,popupRef:P}}else if(e instanceof Yg){const{data:{inkLists:S,rect:C,rotation:E,id:M,color:k,borderStyle:{rawWidth:O},popupRef:P},parent:{page:{pageNumber:F}}}=e;n=e={annotationType:Z.HIGHLIGHT,color:Array.from(k),thickness:O,inkLists:S,boxes:null,pageIndex:F-1,rect:C.slice(0),rotation:E,id:M,deleted:!1,popupRef:P}}const{color:r,quadPoints:o,inkLists:h,opacity:l}=e,d=await super.deserialize(e,s,i);d.color=z.makeHexColor(...r),b(d,Ji,l||1),h&&b(d,ps,e.thickness),d.annotationElementId=e.id||null,d._initialData=n;const[u,g]=d.pageDimensions,[f,p]=d.pageTranslation;if(o){const S=b(d,Qi,[]);for(let C=0;C<o.length;C+=8)S.push({x:(o[C]-f)/u,y:1-(o[C+1]-p)/g,width:(o[C+2]-o[C])/u,height:(o[C+1]-o[C+5])/g});v(m=d,J,Nf).call(m),v(_=d,J,_o).call(_),d.rotate(d.rotation)}else if(h){b(d,Xe,!0);const S=h[0],C={x:S[0]-f,y:g-(S[1]-p)},E=new qg(C,[0,0,u,g],1,c(d,ps)/2,!0,.001);for(let O=0,P=S.length;O<P;O+=2)C.x=S[O]-f,C.y=g-(S[O+1]-p),E.add(C);const{id:M,clipPathId:k}=s.drawLayer.draw(E,d.color,d._defaultOpacity,!0);v(y=d,J,nu).call(y,{highlightOutlines:E.getOutlines(),highlightId:M,clipPathId:k}),v(x=d,J,_o).call(x)}return d}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();const s=this.getRect(0,0),i=gt._colorManager.convert(this.color),n={annotationType:Z.HIGHLIGHT,color:i,opacity:c(this,Ji),thickness:c(this,ps),quadPoints:v(this,J,dv).call(this),outlines:v(this,J,uv).call(this,s),pageIndex:this.pageIndex,rect:s,rotation:v(this,J,$l).call(this),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!v(this,J,pv).call(this,n)?null:(n.id=this.annotationElementId,n)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}};Oa=new WeakMap,Pl=new WeakMap,Qi=new WeakMap,no=new WeakMap,Da=new WeakMap,fs=new WeakMap,Fl=new WeakMap,Rl=new WeakMap,ro=new WeakMap,Ws=new WeakMap,ve=new WeakMap,Xe=new WeakMap,Pa=new WeakMap,Ji=new WeakMap,Kt=new WeakMap,Fa=new WeakMap,ps=new WeakMap,Ll=new WeakMap,J=new WeakSet,Nf=function(){const e=new eb(c(this,Qi),.001);b(this,Ws,e.getOutlines()),{x:this.x,y:this.y,width:this.width,height:this.height}=c(this,Ws).box;const s=new eb(c(this,Qi),.0025,.001,this._uiManager.direction==="ltr");b(this,fs,s.getOutlines());const{lastPoint:i}=c(this,fs).box;b(this,Pa,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height])},nu=function({highlightOutlines:e,highlightId:s,clipPathId:i}){var u,g;if(b(this,Ws,e),b(this,fs,e.getNewOutline(c(this,ps)/2+1.5,.0025)),s>=0)b(this,ve,s),b(this,no,i),this.parent.drawLayer.finalizeLine(s,e),b(this,Kt,this.parent.drawLayer.drawOutline(c(this,fs)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(c(this,ve),e),this.parent.drawLayer.updateBox(c(this,ve),v(u=ht,ms,Ga).call(u,c(this,Ws).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(c(this,Kt),c(this,fs)),this.parent.drawLayer.updateBox(c(this,Kt),v(g=ht,ms,Ga).call(g,c(this,fs).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,fs).box;b(this,Pa,[(d[0]-r)/h,(d[1]-o)/l])},av=function(e){const s=(r,o)=>{var h,l,d;this.color=r,(h=this.parent)==null||h.drawLayer.changeColor(c(this,ve),r),(l=c(this,Da))==null||l.updateColor(r),b(this,Ji,o),(d=this.parent)==null||d.drawLayer.changeOpacity(c(this,ve),o)},i=this.color,n=c(this,Ji);this.addCommands({cmd:s.bind(this,e,ht._defaultOpacity),undo:s.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:U.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(e)},!0)},hv=function(e){const s=c(this,ps),i=n=>{b(this,ps,n),v(this,J,lv).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:U.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:e},!0)},lv=function(e){if(!c(this,Xe))return;v(this,J,nu).call(this,{highlightOutlines:c(this,Ws).getNewOutline(e/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},Bf=function(){c(this,ve)===null||!this.parent||(this.parent.drawLayer.remove(c(this,ve)),b(this,ve,null),this.parent.drawLayer.remove(c(this,Kt)),b(this,Kt,null))},_o=function(e=this.parent){c(this,ve)===null&&({id:Fe(this,ve)._,clipPathId:Fe(this,no)._}=e.drawLayer.draw(c(this,Ws),this.color,c(this,Ji)),b(this,Kt,e.drawLayer.drawOutline(c(this,fs))),c(this,ro)&&(c(this,ro).style.clipPath=c(this,no)))},ms=new WeakSet,Ga=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}},cv=function(e){ht._keyboardManager.exec(this,e)},ru=function(e){if(!c(this,Oa))return;const s=window.getSelection();e?s.setPosition(c(this,Oa),c(this,Pl)):s.setPosition(c(this,Fl),c(this,Rl))},$l=function(){return c(this,Xe)?this.rotation:0},dv=function(){if(c(this,Xe))return null;const[e,s]=this.pageDimensions,[i,n]=this.pageTranslation,r=c(this,Qi),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},uv=function(e){return c(this,Ws).serialize(e,v(this,J,$l).call(this))},gv=function(e,s){this._freeHighlight.add(s)&&e.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},fv=function(e,s){this._freeHighlight.isEmpty()?e.drawLayer.remove(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=""},pv=function(e){const{color:s}=this._initialData;return e.color.some((i,n)=>i!==s[n])},w(ht,ms),q(ht,"_defaultColor",null),q(ht,"_defaultOpacity",1),q(ht,"_defaultThickness",12),q(ht,"_type","highlight"),q(ht,"_editorType",Z.HIGHLIGHT),q(ht,"_freeHighlightId",-1),q(ht,"_freeHighlight",null),q(ht,"_freeHighlightClipId","");let yd=ht;const kt=class kt extends gt{constructor(e){super({...e,name:"inkEditor"});w(this,L);w(this,oo,0);w(this,ao,0);w(this,li,null);w(this,Zi,new Path2D);w(this,bs,!1);w(this,ho,null);w(this,lo,!1);w(this,co,!1);w(this,tn,null);w(this,Ra,null);w(this,uo,0);w(this,go,0);w(this,zn,null);this.color=e.color||null,this.thickness=e.thickness||null,this.opacity=e.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(e,s){gt.initialize(e,s)}static updateDefaultParams(e,s){switch(e){case U.INK_THICKNESS:kt._defaultThickness=s;break;case U.INK_COLOR:kt._defaultColor=s;break;case U.INK_OPACITY:kt._defaultOpacity=s/100;break}}updateParams(e,s){switch(e){case U.INK_THICKNESS:v(this,L,mv).call(this,s);break;case U.INK_COLOR:v(this,L,bv).call(this,s);break;case U.INK_OPACITY:v(this,L,vv).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[U.INK_THICKNESS,kt._defaultThickness],[U.INK_COLOR,kt._defaultColor||gt._defaultLineColor],[U.INK_OPACITY,Math.round(kt._defaultOpacity*100)]]}get propertiesToUpdate(){return[[U.INK_THICKNESS,this.thickness||kt._defaultThickness],[U.INK_COLOR,this.color||kt._defaultColor||gt._defaultLineColor],[U.INK_OPACITY,Math.round(100*(this.opacity??kt._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(v(this,L,ou).call(this),v(this,L,au).call(this)),this.isAttachedToDOM||(this.parent.add(this),v(this,L,Ya).call(this)),v(this,L,Kl).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,li)&&(clearTimeout(c(this,li)),b(this,li,null)),(e=c(this,tn))==null||e.disconnect(),b(this,tn,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,bs)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,v(this,L,zf).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),v(this,L,Xf).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){c(this,bs)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),b(this,bs,!0),this.div.classList.add("disabled"),v(this,L,Kl).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,bs)||(this.setInForeground(),e.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),v(this,L,_v).call(this,e.offsetX,e.offsetY))}canvasPointermove(e){e.preventDefault(),v(this,L,Wf).call(this,e.offsetX,e.offsetY)}canvasPointerup(e){e.preventDefault(),v(this,L,Vf).call(this,e)}canvasPointerleave(e){v(this,L,Vf).call(this,e)}get isResizable(){return!this.isEmpty()&&c(this,bs)}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]=v(this,L,yv).call(this);if(this.setAt(i,n,0,0),this.setDims(r,o),v(this,L,ou).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,co,!0),v(this,L,Ya).call(this),this.setDims(this.width*h,this.height*l),v(this,L,wo).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return v(this,L,au).call(this),this.div}setDimensions(e,s){const i=Math.round(e),n=Math.round(s);if(c(this,uo)===i&&c(this,go)===n)return;b(this,uo,i),b(this,go,n),this.canvas.style.visibility="hidden";const[r,o]=this.parentDimensions;this.width=e/r,this.height=s/o,this.fixAndSetPosition(),c(this,bs)&&v(this,L,Gf).call(this,e,s),v(this,L,Ya).call(this),v(this,L,wo).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(e,s,i){var _,y,x;if(e instanceof Yg)return null;const n=await 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,bs,!0),b(n,uo,Math.round(h)),b(n,go,Math.round(l));const{paths:g,rect:f,rotation:p}=e;for(let{bezier:S}of g){S=v(_=kt,en,Ev).call(_,S,f,p);const C=[];n.paths.push(C);let E=d*(S[0]-u),M=d*(S[1]-u);for(let O=2,P=S.length;O<P;O+=6){const F=d*(S[O]-u),R=d*(S[O+1]-u),W=d*(S[O+2]-u),B=d*(S[O+3]-u),X=d*(S[O+4]-u),K=d*(S[O+5]-u);C.push([[E,M],[F,R],[W,B],[X,K]]),E=X,M=K}const k=v(this,en,Tv).call(this,C);n.bezierPath2D.push(k)}const m=v(y=n,L,Uf).call(y);return b(n,ao,Math.max(gt.MIN_SIZE,m[2]-m[0])),b(n,oo,Math.max(gt.MIN_SIZE,m[3]-m[1])),v(x=n,L,Gf).call(x,h,l),n}serialize(){if(this.isEmpty())return null;const e=this.getRect(0,0),s=gt._colorManager.convert(this.ctx.strokeStyle);return{annotationType:Z.INK,color:s,thickness:this.thickness,opacity:this.opacity,paths:v(this,L,kv).call(this,this.scaleFactor/this.parentScale,this.translationX,this.translationY,e),pageIndex:this.pageIndex,rect:e,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}};oo=new WeakMap,ao=new WeakMap,li=new WeakMap,Zi=new WeakMap,bs=new WeakMap,ho=new WeakMap,lo=new WeakMap,co=new WeakMap,tn=new WeakMap,Ra=new WeakMap,uo=new WeakMap,go=new WeakMap,zn=new WeakMap,L=new WeakSet,mv=function(e){const s=n=>{this.thickness=n,v(this,L,Kl).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:U.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},bv=function(e){const s=n=>{this.color=n,v(this,L,wo).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:U.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},vv=function(e){const s=n=>{this.opacity=n,v(this,L,wo).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:U.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},yv=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]}},Hf=function(){const{ctx:e,color:s,opacity:i,thickness:n,parentScale:r,scaleFactor:o}=this;e.lineWidth=n*r/o,e.lineCap="round",e.lineJoin="round",e.miterLimit=10,e.strokeStyle=`${s}${Yw(i)}`},_v=function(e,s){this.canvas.addEventListener("contextmenu",hs,{signal:this._uiManager._signal}),v(this,L,Xf).call(this),b(this,ho,new AbortController);const i=this._uiManager.combinedSignal(c(this,ho));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,c(this,co)||(b(this,co,!0),v(this,L,Ya).call(this),this.thickness||(this.thickness=kt._defaultThickness),this.color||(this.color=kt._defaultColor||gt._defaultLineColor),this.opacity??(this.opacity=kt._defaultOpacity)),this.currentPath.push([e,s]),b(this,lo,!1),v(this,L,Hf).call(this),b(this,zn,()=>{v(this,L,Sv).call(this),c(this,zn)&&window.requestAnimationFrame(c(this,zn))}),window.requestAnimationFrame(c(this,zn))},Wf=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,Zi);if(r.push([e,s]),b(this,lo,!0),r.length<=2){o.moveTo(...r[0]),o.lineTo(e,s);return}r.length===3&&(b(this,Zi,o=new Path2D),o.moveTo(...r[0])),v(this,L,Cv).call(this,o,...r.at(-3),...r.at(-2),e,s)},wv=function(){if(this.currentPath.length===0)return;const e=this.currentPath.at(-1);c(this,Zi).lineTo(...e)},xv=function(e,s){b(this,zn,null),e=Math.min(Math.max(e,0),this.canvas.width),s=Math.min(Math.max(s,0),this.canvas.height),v(this,L,Wf).call(this,e,s),v(this,L,wv).call(this);let i;if(this.currentPath.length!==1)i=v(this,L,Av).call(this);else{const l=[e,s];i=[[l,l.slice(),l.slice(),l]]}const n=c(this,Zi),r=this.currentPath;this.currentPath=[],b(this,Zi,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||(v(this,L,ou).call(this),v(this,L,au).call(this)),v(this,L,Kl).call(this))};this.addCommands({cmd:o,undo:h,mustExec:!0})},Sv=function(){if(!c(this,lo))return;b(this,lo,!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,Zi)),r.restore()},Cv=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)},Av=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],y=(f+m)/2,x=(p+_)/2,S=[n+2*(f-n)/3,r+2*(p-r)/3],C=[y+2*(f-y)/3,x+2*(p-x)/3];s.push([[n,r],S,C,[y,x]]),[n,r]=[y,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},wo=function(){if(this.isEmpty()){v(this,L,hu).call(this);return}v(this,L,Hf).call(this);const{canvas:e,ctx:s}=this;s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),v(this,L,hu).call(this);for(const i of this.bezierPath2D)s.stroke(i)},zf=function(){if(c(this,Ra))return;b(this,Ra,new AbortController);const e=this._uiManager.combinedSignal(c(this,Ra));this.canvas.addEventListener("pointerdown",this.canvasPointerdown.bind(this),{signal:e})},Xf=function(){var e;(e=this.pointerdownAC)==null||e.abort(),this.pointerdownAC=null},Vf=function(e){var s;(s=c(this,ho))==null||s.abort(),b(this,ho,null),v(this,L,zf).call(this),c(this,li)&&clearTimeout(c(this,li)),b(this,li,setTimeout(()=>{b(this,li,null),this.canvas.removeEventListener("contextmenu",hs)},10)),v(this,L,xv).call(this,e.offsetX,e.offsetY),this.addToAnnotationStorage(),this.setInBackground()},ou=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")},au=function(){b(this,tn,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&this.setDimensions(s.width,s.height)})),c(this,tn).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,tn))==null||e.disconnect(),b(this,tn,null)},{once:!0})},Ya=function(){if(!c(this,co))return;const[e,s]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*e),this.canvas.height=Math.ceil(this.height*s),v(this,L,hu).call(this)},Gf=function(e,s){const i=v(this,L,lu).call(this),n=(e-i)/c(this,ao),r=(s-i)/c(this,oo);this.scaleFactor=Math.min(n,r)},hu=function(){const e=v(this,L,lu).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+e,this.translationY*this.scaleFactor+e)},en=new WeakSet,Tv=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},Ev=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},kv=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[y,x,S,C]=g[m];if(y[0]===C[0]&&y[1]===C[1]&&_===1){const B=e*y[0]+h,X=e*y[1]+l;f.push(B,X),p.push(B,X);break}const E=e*y[0]+h,M=e*y[1]+l,k=e*x[0]+h,O=e*x[1]+l,P=e*S[0]+h,F=e*S[1]+l,R=e*C[0]+h,W=e*C[1]+l;m===0&&(f.push(E,M),p.push(E,M)),f.push(k,O,P,F,R,W),p.push(k,O),m===_-1&&p.push(R,W)}r.push({bezier:v(d=kt,en,Yf).call(d,f,n,this.rotation),points:v(u=kt,en,Yf).call(u,p,n,this.rotation)})}return r},Uf=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]},lu=function(){return c(this,bs)?Math.ceil(this.thickness*this.parentScale):0},Kl=function(e=!1){if(this.isEmpty())return;if(!c(this,bs)){v(this,L,wo).call(this);return}const s=v(this,L,Uf).call(this),i=v(this,L,lu).call(this);b(this,ao,Math.max(gt.MIN_SIZE,s[2]-s[0])),b(this,oo,Math.max(gt.MIN_SIZE,s[3]-s[1]));const n=Math.ceil(i+c(this,ao)*this.scaleFactor),r=Math.ceil(i+c(this,oo)*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],v(this,L,Ya).call(this),v(this,L,wo).call(this),b(this,uo,n),b(this,go,r),this.setDims(n,r);const u=e?i/this.scaleFactor/2:0;this.translate(l-this.translationX-u,d-this.translationY-u)},w(kt,en),q(kt,"_defaultColor",null),q(kt,"_defaultOpacity",1),q(kt,"_defaultThickness",1),q(kt,"_type","ink"),q(kt,"_editorType",Z.INK);let $g=kt;const Il=class Il extends gt{constructor(e){super({...e,name:"stampEditor"});w(this,nt);w(this,Mt,null);w(this,oe,null);w(this,Xn,null);w(this,sn,null);w(this,Vn,null);w(this,La,"");w(this,ci,null);w(this,nn,null);w(this,di,null);w(this,ss,!1);w(this,Ia,!1);b(this,sn,e.bitmapUrl),b(this,Vn,e.bitmapFile)}static initialize(e,s){gt.initialize(e,s)}static get supportedTypes(){return ot(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(s=>`image/${s}`))}static get supportedTypesStr(){return ot(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,s){s.pasteEditor(Z.STAMP,{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var e;return{type:"stamp",hasAltText:!!((e=this.altTextData)!=null&&e.altText)}}static computeTelemetryFinalData(e){const s=e.get("hasAltText");return{hasAltText:s.get(!0)??0,hasNoAltText:s.get(!1)??0}}async mlGuessAltText(e=null,s=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:r,height:o}=e||this.copyCanvas(null,null,!0).imageData,h=await i.guess({name:"altText",request:{data:n,width:r,height:o,channels:n.length/(r*o)}});if(!h)throw new Error("No response from the AI service.");if(h.error)throw new Error("Error from the AI service.");if(h.cancel)return null;if(!h.output)throw new Error("No valid response from the AI service.");const l=h.output;return await this.setGuessedAltText(l),s&&!this.hasAltTextData()&&(this.altTextData={alt:l,decorative:!1}),l}remove(){var e,s;c(this,oe)&&(b(this,Mt,null),this._uiManager.imageManager.deleteId(c(this,oe)),(e=c(this,ci))==null||e.remove(),b(this,ci,null),(s=c(this,nn))==null||s.disconnect(),b(this,nn,null),c(this,di)&&(clearTimeout(c(this,di)),b(this,di,null))),super.remove()}rebuild(){if(!this.parent){c(this,oe)&&v(this,nt,cu).call(this);return}super.rebuild(),this.div!==null&&(c(this,oe)&&c(this,ci)===null&&v(this,nt,cu).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(c(this,Xn)||c(this,Mt)||c(this,sn)||c(this,Vn)||c(this,oe))}get isResizable(){return!0}render(){if(this.div)return this.div;let e,s;if(this.width&&(e=this.x,s=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),c(this,Mt)?v(this,nt,qf).call(this):v(this,nt,cu).call(this),this.width&&!this.annotationElementId){const[i,n]=this.parentDimensions;this.setAt(e*i,s*n,this.width*i,this.height*n)}return this.div}copyCanvas(e,s,i=!1){var f;e||(e=224);const{width:n,height:r}=c(this,Mt),o=new Tg;let h=c(this,Mt),l=n,d=r,u=null;if(s){if(n>s||r>s){const O=Math.min(s/n,s/r);l=Math.floor(n*O),d=Math.floor(r*O)}u=document.createElement("canvas");const p=u.width=Math.ceil(l*o.sx),m=u.height=Math.ceil(d*o.sy);c(this,ss)||(h=v(this,nt,du).call(this,p,m));const _=u.getContext("2d");_.filter=this._uiManager.hcmFilter;let y="white",x="#cfcfd8";this._uiManager.hcmFilter!=="none"?x="black":(f=window.matchMedia)!=null&&f.call(window,"(prefers-color-scheme: dark)").matches&&(y="#8f8f9d",x="#42414d");const S=15,C=S*o.sx,E=S*o.sy,M=new OffscreenCanvas(C*2,E*2),k=M.getContext("2d");k.fillStyle=y,k.fillRect(0,0,C*2,E*2),k.fillStyle=x,k.fillRect(0,0,C,E),k.fillRect(C,E,C,E),_.fillStyle=_.createPattern(M,"repeat"),_.fillRect(0,0,p,m),_.drawImage(h,0,0,h.width,h.height,0,0,p,m)}let g=null;if(i){let p,m;if(o.symmetric&&h.width<e&&h.height<e)p=h.width,m=h.height;else if(h=c(this,Mt),n>e||r>e){const x=Math.min(e/n,e/r);p=Math.floor(n*x),m=Math.floor(r*x),c(this,ss)||(h=v(this,nt,du).call(this,p,m))}const y=new OffscreenCanvas(p,m).getContext("2d",{willReadFrequently:!0});y.drawImage(h,0,0,h.width,h.height,0,0,p,m),g={width:p,height:m,data:y.getImageData(0,0,p,m).data}}return{canvas:u,width:l,height:d,imageData:g}}getImageForAltText(){return c(this,ci)}static async deserialize(e,s,i){var m;let n=null;if(e instanceof J0){const{data:{rect:_,rotation:y,id:x,structParent:S,popupRef:C},container:E,parent:{page:{pageNumber:M}}}=e,k=E.querySelector("canvas"),O=i.imageManager.getFromCanvas(E.id,k);k.remove();const P=((m=await s._structTree.getAriaAttributes(`${wg}${x}`))==null?void 0:m.get("aria-label"))||"";n=e={annotationType:Z.STAMP,bitmapId:O.id,bitmap:O.bitmap,pageIndex:M-1,rect:_.slice(0),rotation:y,id:x,deleted:!1,accessibilityData:{decorative:!1,altText:P},isSvg:!1,structParent:S,popupRef:C}}const r=await super.deserialize(e,s,i),{rect:o,bitmap:h,bitmapUrl:l,bitmapId:d,isSvg:u,accessibilityData:g}=e;d&&i.imageManager.isValidId(d)?(b(r,oe,d),h&&b(r,Mt,h)):b(r,sn,l),b(r,ss,u);const[f,p]=r.pageDimensions;return r.width=(o[2]-o[0])/f,r.height=(o[3]-o[1])/p,r.annotationElementId=e.id||null,g&&(r.altTextData=g),r._initialData=n,b(r,Ia,!!n),r}serialize(e=!1,s=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:Z.STAMP,bitmapId:c(this,oe),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:c(this,ss),structTreeParentId:this._structTreeParentId};if(e)return i.bitmapUrl=v(this,nt,uu).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:n,altText:r}=this.serializeAltText(!1);if(!n&&r&&(i.accessibilityData={type:"Figure",alt:r}),this.annotationElementId){const h=v(this,nt,Dv).call(this,i);if(h.isSame)return null;h.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,s===null)return i;s.stamps||(s.stamps=new Map);const o=c(this,ss)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(c(this,oe)))s.stamps.set(c(this,oe),{area:o,serialized:i}),i.bitmap=v(this,nt,uu).call(this,!1);else if(c(this,ss)){const h=s.stamps.get(c(this,oe));o>h.area&&(h.area=o,h.serialized.bitmap.close(),h.serialized.bitmap=v(this,nt,uu).call(this,!1))}return i}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}};Mt=new WeakMap,oe=new WeakMap,Xn=new WeakMap,sn=new WeakMap,Vn=new WeakMap,La=new WeakMap,ci=new WeakMap,nn=new WeakMap,di=new WeakMap,ss=new WeakMap,Ia=new WeakMap,nt=new WeakSet,Ql=function(e,s=!1){if(!e){this.remove();return}b(this,Mt,e.bitmap),s||(b(this,oe,e.id),b(this,ss,e.isSvg)),e.file&&b(this,La,e.file.name),v(this,nt,qf).call(this)},Jl=function(){if(b(this,Xn,null),this._uiManager.enableWaiting(!1),!!c(this,ci)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&c(this,Mt)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&c(this,Mt)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},cu=function(){if(c(this,oe)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(c(this,oe)).then(i=>v(this,nt,Ql).call(this,i,!0)).finally(()=>v(this,nt,Jl).call(this));return}if(c(this,sn)){const i=c(this,sn);b(this,sn,null),this._uiManager.enableWaiting(!0),b(this,Xn,this._uiManager.imageManager.getFromUrl(i).then(n=>v(this,nt,Ql).call(this,n)).finally(()=>v(this,nt,Jl).call(this)));return}if(c(this,Vn)){const i=c(this,Vn);b(this,Vn,null),this._uiManager.enableWaiting(!0),b(this,Xn,this._uiManager.imageManager.getFromFile(i).then(n=>v(this,nt,Ql).call(this,n)).finally(()=>v(this,nt,Jl).call(this)));return}const e=document.createElement("input");e.type="file",e.accept=Il.supportedTypesStr;const s=this._uiManager._signal;b(this,Xn,new Promise(i=>{e.addEventListener("change",async()=>{if(!e.files||e.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const n=await this._uiManager.imageManager.getFromFile(e.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),v(this,nt,Ql).call(this,n)}i()},{signal:s}),e.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>v(this,nt,Jl).call(this))),e.click()},qf=function(){const{div:e}=this;let{width:s,height:i}=c(this,Mt);const[n,r]=this.pageDimensions,o=.75;if(this.width)s=this.width*n,i=this.height*r;else if(s>o*n||i>o*r){const u=Math.min(o*n/s,o*r/i);s*=u,i*=u}const[h,l]=this.parentDimensions;this.setDims(s*h/n,i*l/r),this._uiManager.enableWaiting(!1);const d=b(this,ci,document.createElement("canvas"));d.setAttribute("role","img"),this.addContainer(d),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),v(this,nt,$f).call(this,s,i),v(this,nt,Ov).call(this),c(this,Ia)||(this.parent.addUndoableEditor(this),b(this,Ia,!0)),this._reportTelemetry({action:"inserted_image"}),c(this,La)&&d.setAttribute("aria-label",c(this,La))},Mv=function(e,s){var o;const[i,n]=this.parentDimensions;this.width=e/i,this.height=s/n,(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,c(this,di)!==null&&clearTimeout(c(this,di)),b(this,di,setTimeout(()=>{b(this,di,null),v(this,nt,$f).call(this,e,s)},200))},du=function(e,s){const{width:i,height:n}=c(this,Mt);let r=i,o=n,h=c(this,Mt);for(;r>2*e||o>2*s;){const l=r,d=o;r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2)),o>2*s&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2));const u=new OffscreenCanvas(r,o);u.getContext("2d").drawImage(h,0,0,l,d,0,0,r,o),h=u.transferToImageBitmap()}return h},$f=function(e,s){const i=new Tg,n=Math.ceil(e*i.sx),r=Math.ceil(s*i.sy),o=c(this,ci);if(!o||o.width===n&&o.height===r)return;o.width=n,o.height=r;const h=c(this,ss)?c(this,Mt):v(this,nt,du).call(this,n,r),l=o.getContext("2d");l.filter=this._uiManager.hcmFilter,l.drawImage(h,0,0,h.width,h.height,0,0,n,r)},uu=function(e){if(e){if(c(this,ss)){const n=this._uiManager.imageManager.getSvgUrl(c(this,oe));if(n)return n}const s=document.createElement("canvas");return{width:s.width,height:s.height}=c(this,Mt),s.getContext("2d").drawImage(c(this,Mt),0,0),s.toDataURL()}if(c(this,ss)){const[s,i]=this.pageDimensions,n=Math.round(this.width*s*bn.PDF_TO_CSS_UNITS),r=Math.round(this.height*i*bn.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(n,r);return o.getContext("2d").drawImage(c(this,Mt),0,0,c(this,Mt).width,c(this,Mt).height,0,0,n,r),o.transferToImageBitmap()}return structuredClone(c(this,Mt))},Ov=function(){this._uiManager._signal&&(b(this,nn,new ResizeObserver(e=>{const s=e[0].contentRect;s.width&&s.height&&v(this,nt,Mv).call(this,s.width,s.height)})),c(this,nn).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var e;(e=c(this,nn))==null||e.disconnect(),b(this,nn,null)},{once:!0}))},Dv=function(e){var l;const{rect:s,pageIndex:i,accessibilityData:{altText:n}}=this._initialData,r=e.rect.every((d,u)=>Math.abs(d-s[u])<1),o=e.pageIndex===i,h=(((l=e.accessibilityData)==null?void 0:l.alt)||"")===n;return{isSame:r&&o&&h,isSameAltText:h}},q(Il,"_type","stamp"),q(Il,"_editorType",Z.STAMP);let Kg=Il;const zs=class zs{constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:d}){w(this,ae);w(this,fo);w(this,ja,!1);w(this,ui,null);w(this,Gn,null);w(this,rn,null);w(this,is,new Map);w(this,Yn,!1);w(this,Na,!1);w(this,Ba,!1);w(this,ye,null);w(this,on,null);w(this,G);const u=[...c(zs,Un).values()];if(!zs._initialized){zs._initialized=!0;for(const g of u)g.initialize(d,t)}t.registerEditorTypes(u),b(this,G,t),this.pageIndex=e,this.div=s,b(this,fo,n),b(this,ui,r),this.viewport=l,b(this,ye,h),this.drawLayer=o,this._structTree=i,c(this,G).addLayer(this)}get isEmpty(){return c(this,is).size===0}get isInvisible(){return this.isEmpty&&c(this,G).getMode()===Z.NONE}updateToolbar(t){c(this,G).updateToolbar(t)}updateMode(t=c(this,G).getMode()){switch(v(this,ae,gu).call(this),t){case Z.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Z.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Z.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(zs,Un).values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){var e;return t===((e=c(this,ye))==null?void 0:e.div)}addInkEditorIfNeeded(t){if(c(this,G).getMode()!==Z.INK)return;if(!t){for(const s of c(this,is).values())if(s.isEmpty()){s.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){c(this,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,ui))==null||e.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of c(this,is).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(c(this,G).removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!c(this,ui))return;const e=c(this,ui).getEditableAnnotations();for(const s of e){if(s.hide(),c(this,G).isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){var i;b(this,Ba,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const n of c(this,is).values())if(n.disableEditing(),!!n.annotationElementId){if(n.serialize()!==null){t.set(n.annotationElementId,n);continue}else e.set(n.annotationElementId,n);(i=this.getEditableAnnotation(n.annotationElementId))==null||i.show(),n.remove()}if(c(this,ui)){const n=c(this,ui).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()}}v(this,ae,gu).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const n of c(zs,Un).values())s.remove(`${n._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),b(this,Ba,!1)}getEditableAnnotation(t){var e;return((e=c(this,ui))==null?void 0:e.getEditableAnnotation(t))||null}setActiveEditor(t){c(this,G).getActive()!==t&&c(this,G).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=c(this,ye))!=null&&t.div&&!c(this,on)){b(this,on,new AbortController);const e=c(this,G).combinedSignal(c(this,on));c(this,ye).div.addEventListener("pointerdown",v(this,ae,Pv).bind(this),{signal:e}),c(this,ye).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=c(this,ye))!=null&&t.div&&c(this,on)&&(c(this,on).abort(),b(this,on,null),c(this,ye).div.classList.remove("highlighting"))}enableClick(){if(c(this,Gn))return;b(this,Gn,new AbortController);const t=c(this,G).combinedSignal(c(this,Gn));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=c(this,Gn))==null||t.abort(),b(this,Gn,null)}attach(t){c(this,is).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,is).delete(t.id),(e=c(this,fo))==null||e.removePointerInTextLayer(t.contentDiv),!c(this,Ba)&&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,Na)||this.addInkEditorIfNeeded(!1)}changeParent(t){var e;t.parent!==this&&(t.parent&&t.annotationElementId&&(c(this,G).addDeletedAnnotationElement(t.annotationElementId),gt.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(e=t.parent)==null||e.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),c(this,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,rn)&&(t._focusEventsAllowed=!1,b(this,rn,setTimeout(()=>{b(this,rn,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,fo))==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()}combinedSignal(t){return c(this,G).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=c(this,ae,Kf))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,e){c(this,G).updateToolbar(t),c(this,G).updateMode(t);const{offsetX:s,offsetY:i}=v(this,ae,Jf).call(this),n=this.getNextId(),r=v(this,ae,Qf).call(this,{parent:this,id:n,x:s,y:i,uiManager:c(this,G),isCentered:!0,...e});r&&this.add(r)}async deserialize(t){var e;return await((e=c(zs,Un).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=v(this,ae,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(v(this,ae,Jf).call(this),!0)}setSelected(t){c(this,G).setSelected(t)}toggleSelected(t){c(this,G).toggleSelected(t)}unselect(t){c(this,G).unselect(t)}pointerup(t){const{isMac:e}=Ee.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&c(this,Yn)){if(b(this,Yn,!1),!c(this,ja)){b(this,ja,!0);return}if(c(this,G).getMode()===Z.STAMP){c(this,G).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(c(this,G).getMode()===Z.HIGHLIGHT&&this.enableTextSelection(),c(this,Yn)){b(this,Yn,!1);return}const{isMac:e}=Ee.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;b(this,Yn,!0);const s=c(this,G).getActive();b(this,ja,!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,rn)&&(clearTimeout(c(this,rn)),b(this,rn,null));for(const s of c(this,is).values())(e=c(this,fo))==null||e.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,c(this,is).clear(),c(this,G).removeLayer(this)}render({viewport:t}){this.viewport=t,dr(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(),v(this,ae,gu).call(this);const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,dr(this.div,{rotation:s}),e!==s)for(const i of c(this,is).values())i.rotate(s);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return c(this,G).viewParameters.realScale}};fo=new WeakMap,ja=new WeakMap,ui=new WeakMap,Gn=new WeakMap,rn=new WeakMap,is=new WeakMap,Yn=new WeakMap,Na=new WeakMap,Ba=new WeakMap,ye=new WeakMap,on=new WeakMap,G=new WeakMap,Un=new WeakMap,ae=new WeakSet,Pv=function(t){c(this,G).unselectAll();const{target:e}=t;if(e===c(this,ye).div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&c(this,ye).div.contains(e)){const{isMac:s}=Ee.platform;if(t.button!==0||t.ctrlKey&&s)return;c(this,G).showAllEditors("highlight",!0,!0),c(this,ye).div.classList.add("free"),this.toggleDrawing(),yd.startHighlighting(this,c(this,G).direction==="ltr",{target:c(this,ye).div,x:t.x,y:t.y}),c(this,ye).div.addEventListener("pointerup",()=>{c(this,ye).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:c(this,G)._signal}),t.preventDefault()}},Kf=function(){return c(zs,Un).get(c(this,G).getMode())},Qf=function(t){const e=c(this,ae,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}},gu=function(){b(this,Na,!0);for(const t of c(this,is).values())t.isEmpty()&&t.remove();b(this,Na,!1)},q(zs,"_initialized",!1),w(zs,Un,new Map([Ug,$g,Kg,yd].map(t=>[t._editorType,t])));let Qg=zs;const he=class he{constructor({pageIndex:t}){w(this,po);w(this,gi,null);w(this,jl,0);w(this,Wt,new Map);w(this,an,new Map);this.pageIndex=t}setParent(t){if(!c(this,gi)){b(this,gi,t);return}if(c(this,gi)!==t){if(c(this,Wt).size>0)for(const e of c(this,Wt).values())e.remove(),t.append(e);b(this,gi,t)}}static get _svgFactory(){return ot(this,"_svgFactory",new Vg)}draw(t,e,s,i=!1){const n=Fe(this,jl)._++,r=v(this,po,tp).call(this,t.box);r.classList.add(...t.classNamesForDrawing);const o=he._svgFactory.createElement("defs");r.append(o);const h=he._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,an).set(n,h);const d=v(this,po,Fv).call(this,o,l),u=he._svgFactory.createElement("use");return r.append(u),r.setAttribute("fill",e),r.setAttribute("fill-opacity",s),u.setAttribute("href",`#${l}`),c(this,Wt).set(n,r),{id:n,clipPathId:`url(#${d})`}}drawOutline(t){const e=Fe(this,jl)._++,s=v(this,po,tp).call(this,t.box);s.classList.add(...t.classNamesForOutlining);const i=he._svgFactory.createElement("defs");s.append(i);const n=he._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.mustRemoveSelfIntersections){const d=he._svgFactory.createElement("mask");i.append(d),o=`mask_p${this.pageIndex}_${e}`,d.setAttribute("id",o),d.setAttribute("maskUnits","objectBoundingBox");const u=he._svgFactory.createElement("rect");d.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const g=he._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=he._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,Wt).set(e,s),e}finalizeLine(t,e){const s=c(this,an).get(t);c(this,an).delete(t),this.updateBox(t,e.box),s.setAttribute("d",e.toSVGPath())}updateLine(t,e){c(this,Wt).get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}updatePath(t,e){c(this,an).get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){var s;v(s=he,Nl,Zf).call(s,c(this,Wt).get(t),e)}show(t,e){c(this,Wt).get(t).classList.toggle("hidden",!e)}rotate(t,e){c(this,Wt).get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){c(this,Wt).get(t).setAttribute("fill",e)}changeOpacity(t,e){c(this,Wt).get(t).setAttribute("fill-opacity",e)}addClass(t,e){c(this,Wt).get(t).classList.add(e)}removeClass(t,e){c(this,Wt).get(t).classList.remove(e)}getSVGRoot(t){return c(this,Wt).get(t)}remove(t){c(this,an).delete(t),c(this,gi)!==null&&(c(this,Wt).get(t).remove(),c(this,Wt).delete(t))}destroy(){b(this,gi,null);for(const t of c(this,Wt).values())t.remove();c(this,Wt).clear(),c(this,an).clear()}};gi=new WeakMap,jl=new WeakMap,Wt=new WeakMap,an=new WeakMap,Nl=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}%`},po=new WeakSet,tp=function(t){var s;const e=he._svgFactory.create(1,1,!0);return c(this,gi).append(e),e.setAttribute("aria-hidden",!0),v(s=he,Nl,Zf).call(s,e,t),e},Fv=function(t,e){const s=he._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=he._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i},w(he,Nl);let Jg=he;$.AbortException,$.AnnotationEditorLayer,$.AnnotationEditorParamsType,$.AnnotationEditorType,$.AnnotationEditorUIManager,$.AnnotationLayer,$.AnnotationMode,$.ColorPicker,$.DOMSVGFactory,$.DrawLayer,$.FeatureTest;var AS=$.GlobalWorkerOptions;$.ImageKind,$.InvalidPDFException,$.MissingPDFException,$.OPS,$.OutputScale,$.PDFDataRangeTransport,$.PDFDateString,$.PDFWorker,$.PasswordResponses,$.PermissionFlag,$.PixelsPerInch,$.RenderingCancelledException,$.TextLayer,$.UnexpectedResponseException,$.Util,$.VerbosityLevel,$.XfaLayer,$.build,$.createValidAbsoluteUrl,$.fetchData;var TS=$.getDocument;$.getFilenameFromUrl,$.getPdfFilenameFromUrl,$.getXfaPageViewport,$.isDataScheme,$.isPdfFile,$.noContextMenu,$.normalizeUnicode,$.setLayerDimensions,$.shadow,$.version;const ES={fabric:"^6.5.0","pdfjs-dist":"^4.8.69"};function kS(a){return new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>t(s.result)),s.addEventListener("error",e),s.readAsDataURL(a)})}const MS=ES["pdfjs-dist"].replace("^","");AS.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${MS}/pdf.worker.min.mjs`;async function OS(a){const t="data:application/pdf;base64,",e=await kS(a);if(typeof e=="string")return window.atob(e.slice(t.length))}function DS(a,t){return TS({data:a,password:t}).promise}const PS={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},FS={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},RS={stroke:"#000",hoverStroke:"#B7EC5D",src:""};function sb(a=""){let t=0,e=null,s=null,i=1,n={...RS};function r(){if(!a||as.has(a))return;const k=fw(a);return k.on("selection:cleared",()=>C(k)),k}function o(k,O){var R;const P=k.type,F={"application/pdf":h,"image/png":u,"image/jpeg":u};return((R=F[P])==null?void 0:R.call(F,k,O))??Promise.reject(new Error(`Unsupported ${P} file type.`))}async function h(k,O){const P=await OS(k);if(!P)return;const F=pw(k,P);try{return await l({page:1,PDFBase64:P,scale:.8,password:O}),{...F,pages:t}}catch(R){return Promise.reject(R)}}async function l({page:k,PDFBase64:O,scale:P,password:F}){try{const R=await DS(O,F),W=await Y.toRaw(R).getPage(k),{renderTask:B,canvas:X}=mw(W,P);return t=R.numPages,B.promise.then(()=>d(X))}catch(R){return Promise.reject(R)}}function d(k){vw(a,k)}async function u(k){return await yw(a,k)}async function g({url:k,scale:O=.5}){await o0(a,{url:k,scale:O})}async function f(k,O){const P=as.get(a);if(!P)return;const F=await ge.fromURL(k,{},{...PS,...O});P.add(F),m(P,F)}function p(k,O){const P=as.get(a);if(!P)return;const F=new ue(k,{...FS,...O});P.add(F),m(P,F)}function m(k,O){O.on("selected",P=>_({canvas:k,target:P.target})),O.on("modified",P=>ch(P.target,e)),O.on("scaling",P=>ch(P.transform.target,e)),O.on("moving",P=>ch(P.transform.target,e)),O.on("rotating",P=>ch(P.transform.target,e))}async function _({canvas:k,target:O,stroke:P=n.stroke,uuid:F=Date.now()}){if((e==null?void 0:e.stroke)===`${P}-${F}`)return;const R=await bw(n.src,P,F);C(k),e=R,s=O,y(k,O,F),x(i,!0),k.add(R)}function y(k,O,P){e&&(e.on("selected",()=>{k.remove(O),C(k)}),e.on("mouseover",()=>{_({canvas:k,target:O,stroke:n.hoverStroke,uuid:P})}),e.on("mouseout",()=>{_({canvas:k,target:O,stroke:n.stroke,uuid:P})}))}function x(k,O=!1){const P=as.get(a);i=k,P&&(ww(s,k,n),_w(s,k,e),!O&&P.renderAll())}function S(k){if(!k)return;n={...n,...k};const O=as.get(a);!e||!s||!O||_({target:s,canvas:O})}function C(k){e&&(k.remove(e),e=s=null)}function E(){xw(a)}function M(){Sw(a)}return{createCanvas:r,loadFile:o,specifyPage:l,renderImage:g,addFabric:f,addTextFabric:p,clearActive:E,deleteCanvas:M,scaleFabric:x,setCloseSvgOptions:S}}function LS(a){let t=0;const e=gw(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});Y.onMounted(()=>{window.addEventListener("resize",e)}),Y.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const IS=Y.defineComponent({__name:"pdf-canvas",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=Y.ref(null),i=`${e.canvasId}-${e.page-1}`,n=Y.computed(()=>e.fileZoom*e.canvasScale),{createCanvas:r,specifyPage:o,addFabric:h,addTextFabric:l,renderImage:d,clearActive:u,deleteCanvas:g,scaleFabric:f,setCloseSvgOptions:p}=sb(i);m(),LS(m);async function m(){const{file:S,page:C,fileScale:E}=e;window.requestAnimationFrame(async()=>{if(await Y.nextTick(),r(),S.PDFBase64.startsWith("data:image")||S.canvas){const{canvas:M}=S,k=M?7:3,O=M!=null&&M.length?M[C-1]:S.PDFBase64;d({url:O,scale:E/k});return}await o({page:C,PDFBase64:S.PDFBase64,scale:E,password:e.password})})}function _(S){if(!e.isDrop||!S.dataTransfer)return;const{dataTransfer:C,offsetX:E,offsetY:M}=S,k=C.getData("text"),O=C.getData("image"),P={left:E-71,top:M-55};O&&y(O,P),k&&x(k,P)}function y(S,C){h(S,{...C,...e.dropImageOptions})}function x(S,C){l(S,{...C,...e.dropTextOptions})}return Y.watch([()=>e.fileScale,()=>e.page,()=>e.file,()=>e.password],m),Y.watch(n,S=>f(S),{immediate:!0}),Y.watch(()=>e.closeSvgOptions,p,{immediate:!0}),Y.onBeforeUnmount(g),t({addImage:y,addText:x,clearActive:u,deleteCanvas:g,canvasRef:s}),(S,C)=>(Y.openBlock(),Y.createElementBlock("div",{style:Y.normalizeStyle({transform:`scale(${n.value})`}),onDragover:C[0]||(C[0]=Y.withModifiers(()=>{},["stop","prevent"])),onDragenter:C[1]||(C[1]=Y.withModifiers(()=>{},["stop","prevent"])),onDrop:Y.withModifiers(_,["stop","prevent"])},[Y.createElementVNode("canvas",{id:i,ref_key:"canvasRef",ref:s,class:Y.normalizeClass(S.canvasClass)},null,2)],36))}}),_d=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));rt.default=IS,rt.useFabric=sb,Object.defineProperties(rt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});