@component-hook/pdf-canvas 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(dt,tt){typeof exports=="object"&&typeof module<"u"?tt(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],tt):(dt=typeof globalThis<"u"?globalThis:dt||self,tt(dt["pdf-canvas"]={},dt.React))})(this,function(dt,tt){"use strict";var eT=Object.defineProperty;var $b=dt=>{throw TypeError(dt)};var sT=(dt,tt,Ht)=>tt in dt?eT(dt,tt,{enumerable:!0,configurable:!0,writable:!0,value:Ht}):dt[tt]=Ht;var Q=(dt,tt,Ht)=>sT(dt,typeof tt!="symbol"?tt+"":tt,Ht),Tp=(dt,tt,Ht)=>tt.has(dt)||$b("Cannot "+Ht);var l=(dt,tt,Ht)=>(Tp(dt,tt,"read from private field"),Ht?Ht.call(dt):tt.get(dt)),_=(dt,tt,Ht)=>tt.has(dt)?$b("Cannot add the same private member more than once"):tt instanceof WeakSet?tt.add(dt):tt.set(dt,Ht),v=(dt,tt,Ht,qi)=>(Tp(dt,tt,"write to private field"),qi?qi.call(dt,Ht):tt.set(dt,Ht),Ht),w=(dt,tt,Ht)=>(Tp(dt,tt,"access private method"),Ht);var es=(dt,tt,Ht,qi)=>({set _(Dr){v(dt,tt,Dr,Ht)},get _(){return l(dt,tt,qi)}});var ln,tf,Ep,Sl,Qn,Zr,ri,to,Cl,Al,Od,qb,Ye,Kb,Jb,ef,Qb,kp,Tl,eo,so,Zn,Zb,ty,ey,Dd,Ma,El,Fe,Oa,sf,Jt,tr,kl,Gt,Rd,sy,Da,ys,ce,_e,Ra,un,Fa,js,er,io,La,no,Mi,oi,ro,Pl,Ml,Ia,Ol,Oi,sr,ja,ir,Di,Ld,nr,Dl,rr,oo,Rl,Fl,ge,Ct,dn,ao,Ll,Il,or,Ri,fn,jl,Ns,B,nf,Pp,iy,ny,rf,ry,oy,ay,Mp,hy,Op,Dp,ly,ss,Hn,cy,uy,Rp,dy,Kc,Fp,pe,Fi,ai,Ba,Li,_s,Ha,Ii,ls,gn,ho,ji,ar,hi,Jc,of,Nl,lo,Bl,Hl,zl,Vl,Gl,za,pn,co,hr,mn,fy,gy,Lp,uo,li,Rt,Va,lr,Wl,fo,we,go,vn,cr,Xl,po,ws,Ul,mo,bn,Ni,Ga,Wa,Bs,vo,Yl,Id,J,Ip,$l,jp,af,py,my,Np,hf,Bp,vy,by,yy,Hp,_y,zp,wy,xy,Sy,Vp,Qc,bo,yo,me,jd,Cy,ql,Xa,Ua,Hs,Ay,Ty,Ey,lf,Kl,_o,Ya,yn,_n,Le,wo,xo,W,Be,Zc,Bh,cf,Hh,ky,Gp,zh,tu,eu,Wp,su,ci,Xp,Up,Yp,Jl,Ql,So,Zl,tc,ec,sc,$a,ur,At,qa,Ka,ic,$p,Rb,dr,cs,nc,rc,Co,wn,oc,ac,Ao,Ja,Qa,fr,Za,hc,th,To,lc,cc,Eo,ko,uc,gr,eh,xn,Py,My,qp,xs,uf,Kp,Oy,Dy,Bd,pr,Sn,zs,Vh,df,Cn,zd,Vd,Po,Mo,sh,ff,ih,gf,An,Bi,nh,rh,Tn,Oo,iu,Ss,dc,Jp,mr,vr,Do,Fo,oh,ah,fc,Qp,Cs,ha,Ry,Fy,hh,Gd,Wd,lh,Lo,Yt,En,ch,gc,pc,uh,kn,ui,Pn,mc,Mn,vc,Io,jo,Tt,pf,Zp,Ly,Iy,jy,Ny,mf,vf,tm,bc,yc,_c,wc,xc,No,Sc,em,Cc,Ac,sm,Tc,Bo,Ho,Ec,zo,By,im,di,As,kc,Vo,Ts,re,Hy,zy,Vy,bf,On,yf,_f,Gy,nm,Wy,Es,fi,dh,fh,Hi,ut,Go,Wo,Pc,Mc,gh,ph,br,Oc,Xd,Ud,de,nu,Xy,Uy,Yy,$y,qy,Ky,mh,Xo,Rn,Dc,ks,Rc,Qt,Yd,Jy,Fc,Lc,yr,gi,qe,Qy,wf,Zy,t_,rm,Ic,vh,pi,Uo,bh,fe,jc,yh,Nc,Bc,_r,mi,_h,Hc,Et,om,am,hm,la,e_,Or,wh,zc,Fn,Yo,xh,ds,Vc,Gc,$o,Vs,Ps,xe,Sh,Ln,Ie,Ch,Gs,Wc,ot,lm,xf,s_,i_,n_,cm,ca,Ws,Gh,r_,Sf,ru,o_,a_,h_,l_,c_,qo,Ms,Ah,ve,Ko,Jo,wr,xr,Sr,Qo,vt,um,dm,fm,ou,u_,Cf,au,Wh,zi,be,ye,Zo,Th,Ke,Se,Xs,ta,ea,sa,Eh,Af,Je,Xc,Uc,Os,Vi,Gi,kh,Ph,Mh,Ce,zn,d_,f_,g_,Oh,$d,p_,Wt,Ae,Cr,In,Ar,Rh,Wi,Xi,Ds,Fh,bt,hu,lu,Tf,gm,Ef,pm,kf,m_,ia,Lh,Ui,Tr,jn,Us,Er,Ih,na,vi,Nn,je,Bn,$,kr,Nt,v_,$i,mm,vm,Pf,yi,$c,Qe,ra,qd,b_,Yi,bm,y_,ym;var Ht=typeof document<"u"?document.currentScript:null,qi={exports:{}},Dr={};/**
1
+ (function(at,Z){typeof exports=="object"&&typeof module<"u"?Z(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],Z):(at=typeof globalThis<"u"?globalThis:at||self,Z(at["pdf-canvas"]={},at.React))})(this,function(at,Z){"use strict";var Oc=at=>{throw TypeError(at)};var eo=(at,Z,jt)=>Z.has(at)||Oc("Cannot "+jt);var De=(at,Z,jt)=>(eo(at,Z,"read from private field"),jt?jt.call(at):Z.get(at)),hi=(at,Z,jt)=>Z.has(at)?Oc("Cannot add the same private member more than once"):Z instanceof WeakSet?Z.add(at):Z.set(at,jt),Wi=(at,Z,jt,We)=>(eo(at,Z,"write to private field"),We?We.call(at,jt):Z.set(at,jt),jt),gr=(at,Z,jt)=>(eo(at,Z,"access private method"),jt);var Dc=(at,Z,jt,We)=>({set _(gs){Wi(at,Z,gs,jt)},get _(){return De(at,Z,We)}});var hr,Fs,Ls,ri,mr,ai,vr;var jt=typeof document<"u"?document.currentScript:null,We={exports:{}},gs={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var _m;function __(){if(_m)return Dr;_m=1;var a=tt,t=Symbol.for("react.element"),e=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,i=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n={key:!0,ref:!0,__self:!0,__source:!0};function r(o,h,c){var u,d={},f=null,g=null;c!==void 0&&(f=""+c),h.key!==void 0&&(f=""+h.key),h.ref!==void 0&&(g=h.ref);for(u in h)s.call(h,u)&&!n.hasOwnProperty(u)&&(d[u]=h[u]);if(o&&o.defaultProps)for(u in h=o.defaultProps,h)d[u]===void 0&&(d[u]=h[u]);return{$$typeof:t,type:o,key:f,ref:g,props:d,_owner:i.current}}return Dr.Fragment=e,Dr.jsx=r,Dr.jsxs=r,Dr}var Xh={};/**
9
+ */var so;function Rc(){if(so)return gs;so=1;var o=Z,t=Symbol.for("react.element"),e=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,i=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n={key:!0,ref:!0,__self:!0,__source:!0};function r(a,l,h){var c,u={},d=null,f=null;h!==void 0&&(d=""+h),l.key!==void 0&&(d=""+l.key),l.ref!==void 0&&(f=l.ref);for(c in l)s.call(l,c)&&!n.hasOwnProperty(c)&&(u[c]=l[c]);if(a&&a.defaultProps)for(c in l=a.defaultProps,l)u[c]===void 0&&(u[c]=l[c]);return{$$typeof:t,type:a,key:d,ref:f,props:u,_owner:i.current}}return gs.Fragment=e,gs.jsx=r,gs.jsxs=r,gs}var ci={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,48 +14,48 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var wm;function w_(){return wm||(wm=1,process.env.NODE_ENV!=="production"&&function(){var a=tt,t=Symbol.for("react.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.provider"),o=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.suspense_list"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),g=Symbol.for("react.offscreen"),p=Symbol.iterator,m="@@iterator";function y(A){if(A===null||typeof A!="object")return null;var N=p&&A[p]||A[m];return typeof N=="function"?N:null}var b=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function x(A){{for(var N=arguments.length,X=new Array(N>1?N-1:0),st=1;st<N;st++)X[st-1]=arguments[st];C("error",A,X)}}function C(A,N,X){{var st=b.ReactDebugCurrentFrame,xt=st.getStackAddendum();xt!==""&&(N+="%s",X=X.concat([xt]));var Mt=X.map(function(pt){return String(pt)});Mt.unshift("Warning: "+N),Function.prototype.apply.call(console[A],console,Mt)}}var S=!1,T=!1,P=!1,M=!1,D=!1,R;R=Symbol.for("react.module.reference");function V(A){return!!(typeof A=="string"||typeof A=="function"||A===s||A===n||D||A===i||A===c||A===u||M||A===g||S||T||P||typeof A=="object"&&A!==null&&(A.$$typeof===f||A.$$typeof===d||A.$$typeof===r||A.$$typeof===o||A.$$typeof===h||A.$$typeof===R||A.getModuleId!==void 0))}function H(A,N,X){var st=A.displayName;if(st)return st;var xt=N.displayName||N.name||"";return xt!==""?X+"("+xt+")":X}function F(A){return A.displayName||"Context"}function I(A){if(A==null)return null;if(typeof A.tag=="number"&&x("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof A=="function")return A.displayName||A.name||null;if(typeof A=="string")return A;switch(A){case s:return"Fragment";case e:return"Portal";case n:return"Profiler";case i:return"StrictMode";case c:return"Suspense";case u:return"SuspenseList"}if(typeof A=="object")switch(A.$$typeof){case o:var N=A;return F(N)+".Consumer";case r:var X=A;return F(X._context)+".Provider";case h:return H(A,A.render,"ForwardRef");case d:var st=A.displayName||null;return st!==null?st:I(A.type)||"Memo";case f:{var xt=A,Mt=xt._payload,pt=xt._init;try{return I(pt(Mt))}catch{return null}}}return null}var j=Object.assign,K=0,L,z,Z,Dt,Bt,Xt,Ft;function _t(){}_t.__reactDisabledLog=!0;function oe(){{if(K===0){L=console.log,z=console.info,Z=console.warn,Dt=console.error,Bt=console.group,Xt=console.groupCollapsed,Ft=console.groupEnd;var A={configurable:!0,enumerable:!0,value:_t,writable:!0};Object.defineProperties(console,{info:A,log:A,warn:A,error:A,group:A,groupCollapsed:A,groupEnd:A})}K++}}function Ze(){{if(K--,K===0){var A={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:j({},A,{value:L}),info:j({},A,{value:z}),warn:j({},A,{value:Z}),error:j({},A,{value:Dt}),group:j({},A,{value:Bt}),groupCollapsed:j({},A,{value:Xt}),groupEnd:j({},A,{value:Ft})})}K<0&&x("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var it=b.ReactCurrentDispatcher,nt;function Zt(A,N,X){{if(nt===void 0)try{throw Error()}catch(xt){var st=xt.stack.trim().match(/\n( *(at )?)/);nt=st&&st[1]||""}return`
18
- `+nt+A}}var Ys=!1,Te;{var Kd=typeof WeakMap=="function"?WeakMap:Map;Te=new Kd}function qc(A,N){if(!A||Ys)return"";{var X=Te.get(A);if(X!==void 0)return X}var st;Ys=!0;var xt=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var Mt;Mt=it.current,it.current=null,oe();try{if(N){var pt=function(){throw Error()};if(Object.defineProperty(pt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(pt,[])}catch(fs){st=fs}Reflect.construct(A,[],pt)}else{try{pt.call()}catch(fs){st=fs}A.call(pt.prototype)}}else{try{throw Error()}catch(fs){st=fs}A()}}catch(fs){if(fs&&st&&typeof fs.stack=="string"){for(var ft=fs.stack.split(`
19
- `),ts=st.stack.split(`
20
- `),te=ft.length-1,ae=ts.length-1;te>=1&&ae>=0&&ft[te]!==ts[ae];)ae--;for(;te>=1&&ae>=0;te--,ae--)if(ft[te]!==ts[ae]){if(te!==1||ae!==1)do if(te--,ae--,ae<0||ft[te]!==ts[ae]){var $s=`
21
- `+ft[te].replace(" at new "," at ");return A.displayName&&$s.includes("<anonymous>")&&($s=$s.replace("<anonymous>",A.displayName)),typeof A=="function"&&Te.set(A,$s),$s}while(te>=1&&ae>=0);break}}}finally{Ys=!1,it.current=Mt,Ze(),Error.prepareStackTrace=xt}var Nh=A?A.displayName||A.name:"",aa=Nh?Zt(Nh):"";return typeof A=="function"&&Te.set(A,aa),aa}function Jd(A,N,X){return qc(A,!1)}function Pr(A){var N=A.prototype;return!!(N&&N.isReactComponent)}function oa(A,N,X){if(A==null)return"";if(typeof A=="function")return qc(A,Pr(A));if(typeof A=="string")return Zt(A);switch(A){case c:return Zt("Suspense");case u:return Zt("SuspenseList")}if(typeof A=="object")switch(A.$$typeof){case h:return Jd(A.render);case d:return oa(A.type,N,X);case f:{var st=A,xt=st._payload,Mt=st._init;try{return oa(Mt(xt),N,X)}catch{}}}return""}var Mr=Object.prototype.hasOwnProperty,Fb={},Lb=b.ReactDebugCurrentFrame;function Qd(A){if(A){var N=A._owner,X=oa(A.type,A._source,N?N.type:null);Lb.setExtraStackFrame(X)}else Lb.setExtraStackFrame(null)}function RA(A,N,X,st,xt){{var Mt=Function.call.bind(Mr);for(var pt in A)if(Mt(A,pt)){var ft=void 0;try{if(typeof A[pt]!="function"){var ts=Error((st||"React class")+": "+X+" type `"+pt+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof A[pt]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw ts.name="Invariant Violation",ts}ft=A[pt](N,pt,st,X,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(te){ft=te}ft&&!(ft instanceof Error)&&(Qd(xt),x("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",st||"React class",X,pt,typeof ft),Qd(null)),ft instanceof Error&&!(ft.message in Fb)&&(Fb[ft.message]=!0,Qd(xt),x("Failed %s type: %s",X,ft.message),Qd(null))}}}var FA=Array.isArray;function wp(A){return FA(A)}function LA(A){{var N=typeof Symbol=="function"&&Symbol.toStringTag,X=N&&A[Symbol.toStringTag]||A.constructor.name||"Object";return X}}function IA(A){try{return Ib(A),!1}catch{return!0}}function Ib(A){return""+A}function jb(A){if(IA(A))return x("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",LA(A)),Ib(A)}var Nb=b.ReactCurrentOwner,jA={key:!0,ref:!0,__self:!0,__source:!0},Bb,Hb;function NA(A){if(Mr.call(A,"ref")){var N=Object.getOwnPropertyDescriptor(A,"ref").get;if(N&&N.isReactWarning)return!1}return A.ref!==void 0}function BA(A){if(Mr.call(A,"key")){var N=Object.getOwnPropertyDescriptor(A,"key").get;if(N&&N.isReactWarning)return!1}return A.key!==void 0}function HA(A,N){typeof A.ref=="string"&&Nb.current}function zA(A,N){{var X=function(){Bb||(Bb=!0,x("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",N))};X.isReactWarning=!0,Object.defineProperty(A,"key",{get:X,configurable:!0})}}function VA(A,N){{var X=function(){Hb||(Hb=!0,x("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",N))};X.isReactWarning=!0,Object.defineProperty(A,"ref",{get:X,configurable:!0})}}var GA=function(A,N,X,st,xt,Mt,pt){var ft={$$typeof:t,type:A,key:N,ref:X,props:pt,_owner:Mt};return ft._store={},Object.defineProperty(ft._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ft,"_self",{configurable:!1,enumerable:!1,writable:!1,value:st}),Object.defineProperty(ft,"_source",{configurable:!1,enumerable:!1,writable:!1,value:xt}),Object.freeze&&(Object.freeze(ft.props),Object.freeze(ft)),ft};function WA(A,N,X,st,xt){{var Mt,pt={},ft=null,ts=null;X!==void 0&&(jb(X),ft=""+X),BA(N)&&(jb(N.key),ft=""+N.key),NA(N)&&(ts=N.ref,HA(N,xt));for(Mt in N)Mr.call(N,Mt)&&!jA.hasOwnProperty(Mt)&&(pt[Mt]=N[Mt]);if(A&&A.defaultProps){var te=A.defaultProps;for(Mt in te)pt[Mt]===void 0&&(pt[Mt]=te[Mt])}if(ft||ts){var ae=typeof A=="function"?A.displayName||A.name||"Unknown":A;ft&&zA(pt,ae),ts&&VA(pt,ae)}return GA(A,ft,ts,xt,st,Nb.current,pt)}}var xp=b.ReactCurrentOwner,zb=b.ReactDebugCurrentFrame;function jh(A){if(A){var N=A._owner,X=oa(A.type,A._source,N?N.type:null);zb.setExtraStackFrame(X)}else zb.setExtraStackFrame(null)}var Sp;Sp=!1;function Cp(A){return typeof A=="object"&&A!==null&&A.$$typeof===t}function Vb(){{if(xp.current){var A=I(xp.current.type);if(A)return`
17
+ */var io;function Fc(){return io||(io=1,process.env.NODE_ENV!=="production"&&function(){var o=Z,t=Symbol.for("react.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),c=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),g=Symbol.iterator,p="@@iterator";function v(y){if(y===null||typeof y!="object")return null;var D=g&&y[g]||y[p];return typeof D=="function"?D:null}var m=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(y){{for(var D=arguments.length,j=new Array(D>1?D-1:0),U=1;U<D;U++)j[U-1]=arguments[U];_("error",y,j)}}function _(y,D,j){{var U=m.ReactDebugCurrentFrame,lt=U.getStackAddendum();lt!==""&&(D+="%s",j=j.concat([lt]));var dt=j.map(function(it){return String(it)});dt.unshift("Warning: "+D),Function.prototype.apply.call(console[y],console,dt)}}var w=!1,C=!1,T=!1,E=!1,k=!1,O;O=Symbol.for("react.module.reference");function H(y){return!!(typeof y=="string"||typeof y=="function"||y===s||y===n||k||y===i||y===h||y===c||E||y===f||w||C||T||typeof y=="object"&&y!==null&&(y.$$typeof===d||y.$$typeof===u||y.$$typeof===r||y.$$typeof===a||y.$$typeof===l||y.$$typeof===O||y.getModuleId!==void 0))}function N(y,D,j){var U=y.displayName;if(U)return U;var lt=D.displayName||D.name||"";return lt!==""?j+"("+lt+")":j}function P(y){return y.displayName||"Context"}function R(y){if(y==null)return null;if(typeof y.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof y=="function")return y.displayName||y.name||null;if(typeof y=="string")return y;switch(y){case s:return"Fragment";case e:return"Portal";case n:return"Profiler";case i:return"StrictMode";case h:return"Suspense";case c:return"SuspenseList"}if(typeof y=="object")switch(y.$$typeof){case a:var D=y;return P(D)+".Consumer";case r:var j=y;return P(j._context)+".Provider";case l:return N(y,y.render,"ForwardRef");case u:var U=y.displayName||null;return U!==null?U:R(y.type)||"Memo";case d:{var lt=y,dt=lt._payload,it=lt._init;try{return R(it(dt))}catch{return null}}}return null}var F=Object.assign,V=0,M,L,Y,ft,bt,_t,gt;function rt(){}rt.__reactDisabledLog=!0;function Dt(){{if(V===0){M=console.log,L=console.info,Y=console.warn,ft=console.error,bt=console.group,_t=console.groupCollapsed,gt=console.groupEnd;var y={configurable:!0,enumerable:!0,value:rt,writable:!0};Object.defineProperties(console,{info:y,log:y,warn:y,error:y,group:y,groupCollapsed:y,groupEnd:y})}V++}}function ee(){{if(V--,V===0){var y={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:F({},y,{value:M}),info:F({},y,{value:L}),warn:F({},y,{value:Y}),error:F({},y,{value:ft}),group:F({},y,{value:bt}),groupCollapsed:F({},y,{value:_t}),groupEnd:F({},y,{value:gt})})}V<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var K=m.ReactCurrentDispatcher,$;function Tt(y,D,j){{if($===void 0)try{throw Error()}catch(lt){var U=lt.stack.trim().match(/\n( *(at )?)/);$=U&&U[1]||""}return`
18
+ `+$+y}}var _e=!1,Nt;{var cr=typeof WeakMap=="function"?WeakMap:Map;Nt=new cr}function Gi(y,D){if(!y||_e)return"";{var j=Nt.get(y);if(j!==void 0)return j}var U;_e=!0;var lt=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var dt;dt=K.current,K.current=null,Dt();try{if(D){var it=function(){throw Error()};if(Object.defineProperty(it.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(it,[])}catch(he){U=he}Reflect.construct(y,[],it)}else{try{it.call()}catch(he){U=he}y.call(it.prototype)}}else{try{throw Error()}catch(he){U=he}y()}}catch(he){if(he&&U&&typeof he.stack=="string"){for(var et=he.stack.split(`
19
+ `),se=U.stack.split(`
20
+ `),Et=et.length-1,Rt=se.length-1;Et>=1&&Rt>=0&&et[Et]!==se[Rt];)Rt--;for(;Et>=1&&Rt>=0;Et--,Rt--)if(et[Et]!==se[Rt]){if(Et!==1||Rt!==1)do if(Et--,Rt--,Rt<0||et[Et]!==se[Rt]){var we=`
21
+ `+et[Et].replace(" at new "," at ");return y.displayName&&we.includes("<anonymous>")&&(we=we.replace("<anonymous>",y.displayName)),typeof y=="function"&&Nt.set(y,we),we}while(Et>=1&&Rt>=0);break}}}finally{_e=!1,K.current=dt,ee(),Error.prepareStackTrace=lt}var li=y?y.displayName||y.name:"",js=li?Tt(li):"";return typeof y=="function"&&Nt.set(y,js),js}function ur(y,D,j){return Gi(y,!1)}function dr(y){var D=y.prototype;return!!(D&&D.isReactComponent)}function Is(y,D,j){if(y==null)return"";if(typeof y=="function")return Gi(y,dr(y));if(typeof y=="string")return Tt(y);switch(y){case h:return Tt("Suspense");case c:return Tt("SuspenseList")}if(typeof y=="object")switch(y.$$typeof){case l:return ur(y.render);case u:return Is(y.type,D,j);case d:{var U=y,lt=U._payload,dt=U._init;try{return Is(dt(lt),D,j)}catch{}}}return""}var fs=Object.prototype.hasOwnProperty,vc={},bc=m.ReactDebugCurrentFrame;function fr(y){if(y){var D=y._owner,j=Is(y.type,y._source,D?D.type:null);bc.setExtraStackFrame(j)}else bc.setExtraStackFrame(null)}function Yp(y,D,j,U,lt){{var dt=Function.call.bind(fs);for(var it in y)if(dt(y,it)){var et=void 0;try{if(typeof y[it]!="function"){var se=Error((U||"React class")+": "+j+" type `"+it+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof y[it]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw se.name="Invariant Violation",se}et=y[it](D,it,U,j,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Et){et=Et}et&&!(et instanceof Error)&&(fr(lt),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",U||"React class",j,it,typeof et),fr(null)),et instanceof Error&&!(et.message in vc)&&(vc[et.message]=!0,fr(lt),b("Failed %s type: %s",j,et.message),fr(null))}}}var $p=Array.isArray;function Ka(y){return $p(y)}function qp(y){{var D=typeof Symbol=="function"&&Symbol.toStringTag,j=D&&y[Symbol.toStringTag]||y.constructor.name||"Object";return j}}function Kp(y){try{return yc(y),!1}catch{return!0}}function yc(y){return""+y}function _c(y){if(Kp(y))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",qp(y)),yc(y)}var wc=m.ReactCurrentOwner,Jp={key:!0,ref:!0,__self:!0,__source:!0},xc,Sc;function Qp(y){if(fs.call(y,"ref")){var D=Object.getOwnPropertyDescriptor(y,"ref").get;if(D&&D.isReactWarning)return!1}return y.ref!==void 0}function Zp(y){if(fs.call(y,"key")){var D=Object.getOwnPropertyDescriptor(y,"key").get;if(D&&D.isReactWarning)return!1}return y.key!==void 0}function tm(y,D){typeof y.ref=="string"&&wc.current}function em(y,D){{var j=function(){xc||(xc=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",D))};j.isReactWarning=!0,Object.defineProperty(y,"key",{get:j,configurable:!0})}}function sm(y,D){{var j=function(){Sc||(Sc=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",D))};j.isReactWarning=!0,Object.defineProperty(y,"ref",{get:j,configurable:!0})}}var im=function(y,D,j,U,lt,dt,it){var et={$$typeof:t,type:y,key:D,ref:j,props:it,_owner:dt};return et._store={},Object.defineProperty(et._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(et,"_self",{configurable:!1,enumerable:!1,writable:!1,value:U}),Object.defineProperty(et,"_source",{configurable:!1,enumerable:!1,writable:!1,value:lt}),Object.freeze&&(Object.freeze(et.props),Object.freeze(et)),et};function nm(y,D,j,U,lt){{var dt,it={},et=null,se=null;j!==void 0&&(_c(j),et=""+j),Zp(D)&&(_c(D.key),et=""+D.key),Qp(D)&&(se=D.ref,tm(D,lt));for(dt in D)fs.call(D,dt)&&!Jp.hasOwnProperty(dt)&&(it[dt]=D[dt]);if(y&&y.defaultProps){var Et=y.defaultProps;for(dt in Et)it[dt]===void 0&&(it[dt]=Et[dt])}if(et||se){var Rt=typeof y=="function"?y.displayName||y.name||"Unknown":y;et&&em(it,Rt),se&&sm(it,Rt)}return im(y,et,se,lt,U,wc.current,it)}}var Ja=m.ReactCurrentOwner,Cc=m.ReactDebugCurrentFrame;function oi(y){if(y){var D=y._owner,j=Is(y.type,y._source,D?D.type:null);Cc.setExtraStackFrame(j)}else Cc.setExtraStackFrame(null)}var Qa;Qa=!1;function Za(y){return typeof y=="object"&&y!==null&&y.$$typeof===t}function Ac(){{if(Ja.current){var y=R(Ja.current.type);if(y)return`
22
22
 
23
- Check the render method of \``+A+"`."}return""}}function XA(A){return""}var Gb={};function UA(A){{var N=Vb();if(!N){var X=typeof A=="string"?A:A.displayName||A.name;X&&(N=`
23
+ Check the render method of \``+y+"`."}return""}}function rm(y){return""}var Tc={};function am(y){{var D=Ac();if(!D){var j=typeof y=="string"?y:y.displayName||y.name;j&&(D=`
24
24
 
25
- Check the top-level render call using <`+X+">.")}return N}}function Wb(A,N){{if(!A._store||A._store.validated||A.key!=null)return;A._store.validated=!0;var X=UA(N);if(Gb[X])return;Gb[X]=!0;var st="";A&&A._owner&&A._owner!==xp.current&&(st=" It was passed a child from "+I(A._owner.type)+"."),jh(A),x('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',X,st),jh(null)}}function Xb(A,N){{if(typeof A!="object")return;if(wp(A))for(var X=0;X<A.length;X++){var st=A[X];Cp(st)&&Wb(st,N)}else if(Cp(A))A._store&&(A._store.validated=!0);else if(A){var xt=y(A);if(typeof xt=="function"&&xt!==A.entries)for(var Mt=xt.call(A),pt;!(pt=Mt.next()).done;)Cp(pt.value)&&Wb(pt.value,N)}}}function YA(A){{var N=A.type;if(N==null||typeof N=="string")return;var X;if(typeof N=="function")X=N.propTypes;else if(typeof N=="object"&&(N.$$typeof===h||N.$$typeof===d))X=N.propTypes;else return;if(X){var st=I(N);RA(X,A.props,"prop",st,A)}else if(N.PropTypes!==void 0&&!Sp){Sp=!0;var xt=I(N);x("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",xt||"Unknown")}typeof N.getDefaultProps=="function"&&!N.getDefaultProps.isReactClassApproved&&x("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function $A(A){{for(var N=Object.keys(A.props),X=0;X<N.length;X++){var st=N[X];if(st!=="children"&&st!=="key"){jh(A),x("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",st),jh(null);break}}A.ref!==null&&(jh(A),x("Invalid attribute `ref` supplied to `React.Fragment`."),jh(null))}}var Ub={};function Yb(A,N,X,st,xt,Mt){{var pt=V(A);if(!pt){var ft="";(A===void 0||typeof A=="object"&&A!==null&&Object.keys(A).length===0)&&(ft+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var ts=XA();ts?ft+=ts:ft+=Vb();var te;A===null?te="null":wp(A)?te="array":A!==void 0&&A.$$typeof===t?(te="<"+(I(A.type)||"Unknown")+" />",ft=" Did you accidentally export a JSX literal instead of a component?"):te=typeof A,x("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",te,ft)}var ae=WA(A,N,X,xt,Mt);if(ae==null)return ae;if(pt){var $s=N.children;if($s!==void 0)if(st)if(wp($s)){for(var Nh=0;Nh<$s.length;Nh++)Xb($s[Nh],A);Object.freeze&&Object.freeze($s)}else x("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Xb($s,A)}if(Mr.call(N,"key")){var aa=I(A),fs=Object.keys(N).filter(function(tT){return tT!=="key"}),Ap=fs.length>0?"{key: someKey, "+fs.join(": ..., ")+": ...}":"{key: someKey}";if(!Ub[aa+Ap]){var ZA=fs.length>0?"{"+fs.join(": ..., ")+": ...}":"{}";x(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+j+">.")}return D}}function Ec(y,D){{if(!y._store||y._store.validated||y.key!=null)return;y._store.validated=!0;var j=am(D);if(Tc[j])return;Tc[j]=!0;var U="";y&&y._owner&&y._owner!==Ja.current&&(U=" It was passed a child from "+R(y._owner.type)+"."),oi(y),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',j,U),oi(null)}}function kc(y,D){{if(typeof y!="object")return;if(Ka(y))for(var j=0;j<y.length;j++){var U=y[j];Za(U)&&Ec(U,D)}else if(Za(y))y._store&&(y._store.validated=!0);else if(y){var lt=v(y);if(typeof lt=="function"&&lt!==y.entries)for(var dt=lt.call(y),it;!(it=dt.next()).done;)Za(it.value)&&Ec(it.value,D)}}}function om(y){{var D=y.type;if(D==null||typeof D=="string")return;var j;if(typeof D=="function")j=D.propTypes;else if(typeof D=="object"&&(D.$$typeof===l||D.$$typeof===u))j=D.propTypes;else return;if(j){var U=R(D);Yp(j,y.props,"prop",U,y)}else if(D.PropTypes!==void 0&&!Qa){Qa=!0;var lt=R(D);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",lt||"Unknown")}typeof D.getDefaultProps=="function"&&!D.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function lm(y){{for(var D=Object.keys(y.props),j=0;j<D.length;j++){var U=D[j];if(U!=="children"&&U!=="key"){oi(y),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",U),oi(null);break}}y.ref!==null&&(oi(y),b("Invalid attribute `ref` supplied to `React.Fragment`."),oi(null))}}var Pc={};function Mc(y,D,j,U,lt,dt){{var it=H(y);if(!it){var et="";(y===void 0||typeof y=="object"&&y!==null&&Object.keys(y).length===0)&&(et+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var se=rm();se?et+=se:et+=Ac();var Et;y===null?Et="null":Ka(y)?Et="array":y!==void 0&&y.$$typeof===t?(Et="<"+(R(y.type)||"Unknown")+" />",et=" Did you accidentally export a JSX literal instead of a component?"):Et=typeof y,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Et,et)}var Rt=nm(y,D,j,lt,dt);if(Rt==null)return Rt;if(it){var we=D.children;if(we!==void 0)if(U)if(Ka(we)){for(var li=0;li<we.length;li++)kc(we[li],y);Object.freeze&&Object.freeze(we)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else kc(we,y)}if(fs.call(D,"key")){var js=R(y),he=Object.keys(D).filter(function(gm){return gm!=="key"}),to=he.length>0?"{key: someKey, "+he.join(": ..., ")+": ...}":"{key: someKey}";if(!Pc[js+to]){var fm=he.length>0?"{"+he.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
26
26
  let props = %s;
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
- <%s key={someKey} {...props} />`,Ap,aa,ZA,aa),Ub[aa+Ap]=!0}}return A===s?$A(ae):YA(ae),ae}}function qA(A,N,X){return Yb(A,N,X,!0)}function KA(A,N,X){return Yb(A,N,X,!1)}var JA=KA,QA=qA;Xh.Fragment=s,Xh.jsx=JA,Xh.jsxs=QA}()),Xh}var xm;function x_(){return xm||(xm=1,process.env.NODE_ENV==="production"?qi.exports=__():qi.exports=w_()),qi.exports}var Sm=x_();const S_="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",C_={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},A_={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},T_={borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},E_={stroke:"#000",hoverStroke:"#B7EC5D",src:S_},k_=["borderColor","cornerStrokeColor","cornerSize","_cornerSize","selectionBackgroundColor"];function k(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);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 Cm(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 E(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Cm(Object(e),!0).forEach(function(s){k(a,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):Cm(Object(e)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(e,s))})}return a}function Lt(a,t){if(a==null)return{};var e,s,i=function(r,o){if(r==null)return{};var h={};for(var c in r)if({}.hasOwnProperty.call(r,c)){if(o.indexOf(c)>=0)continue;h[c]=r[c]}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 _i(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class Am{constructor(){k(this,"browserShadowBlurConstant",1),k(this,"DPI",96),k(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),k(this,"perfLimitSizeTotal",2097152),k(this,"maxCacheSideLimit",4096),k(this,"minCacheSideLimit",256),k(this,"disableStyleCopyPaste",!1),k(this,"enableGLFiltering",!0),k(this,"textureSize",4096),k(this,"forceGLPutImageData",!1),k(this,"cachesBoundsOfCurve",!1),k(this,"fontPaths",{}),k(this,"NUM_FRACTION_DIGITS",4)}}const mt=new class extends Am{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=E(E({},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 Am,e=(a==null?void 0:a.reduce((s,i)=>(s[i]=t[i],s),{}))||t;this.configure(e)}},Ki=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 wi extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class Mf extends wi{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class P_{}class M_ extends P_{testPrecision(t,e){const s="precision ".concat(e,` float;
31
- 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(),Ki("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const O_={};let Tm;const xi=()=>Tm||(Tm={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new M_,dispose(){},copyPasteData:O_}),ua=()=>xi().document,Uh=()=>xi().window,Em=()=>{var a;return Math.max((a=mt.devicePixelRatio)!==null&&a!==void 0?a:Uh().devicePixelRatio,1)},Yh=new class{constructor(){k(this,"charWidthsCache",{}),k(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}=mt,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},Of="6.7.0";function Rr(){}const Vn=Math.PI/2,Ji=2*Math.PI,Df=Math.PI/180,He=Object.freeze([1,0,0,1,0,0]),Rf=16,Gn=.4477152502,rt="center",wt="left",is="top",Ff="bottom",$t="right",ze="none",Lf=/\r?\n/,km="moving",cu="scaling",Pm="rotating",If="rotate",Mm="skewing",$h="resizing",D_="modifyPoly",R_="modifyPath",uu="changed",du="scale",Ve="scaleX",gs="scaleY",da="skewX",fa="skewY",ee="fill",Ge="stroke",fu="modified",ga="json",jf="svg",G=new class{constructor(){this[ga]=new Map,this[jf]=new Map}has(a){return this[ga].has(a)}getClass(a){const t=this[ga].get(a);if(!t)throw new wi("No class registered for ".concat(a));return t}setClass(a,t){t?this[ga].set(t,a):(this[ga].set(a.type,a),this[ga].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[jf].get(a)}setSVGClass(a,t){this[jf].set(t??a.type.toLowerCase(),a)}},gu=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 F_{constructor(){k(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 Fr=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},qs=a=>{if(a===0)return 1;switch(Math.abs(a)/Vn){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},Ks=a=>{if(a===0)return 0;const t=a/Vn,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class O{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 O(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new O(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new O(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new O(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new O(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new O(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new O(this.x/t.x,this.y/t.y)}scalarDivide(t){return new O(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 O(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 O(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new O(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 O(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Nf;const s=Ks(t),i=qs(t),n=this.subtract(e);return new O(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 O(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 Nf=new O(0,0),pu=a=>!!a&&Array.isArray(a._objects);function Om(a){class t extends a{constructor(){super(...arguments),k(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 c=s.indexOf(h);c!==-1&&(s.splice(c,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])&&(Fr(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Fr(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 Fr(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 Fr(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Fr(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 c=[],u=new O(i,n),d=u.add(new O(r,o));for(let f=this._objects.length-1;f>=0;f--){const g=this._objects[f];g.selectable&&g.visible&&(h&&g.intersectsWithRect(u,d)||g.isContainedWithinRect(u,d)||h&&g.containsPoint(u)||h&&g.containsPoint(d))&&c.push(g)}return c}}return t}class Dm extends F_{_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 qh(a){return Uh().requestAnimationFrame(a)}function Rm(a){return Uh().cancelAnimationFrame(a)}let L_=0;const Wn=()=>L_++,Si=()=>{const a=ua().createElement("canvas");if(!a||a.getContext===void 0)throw new wi("Failed to create `canvas` element");return a},Fm=()=>ua().createElement("img"),ps=a=>{const t=Si();return t.width=a.width,t.height=a.height,t},Bf=(a,t,e)=>a.toDataURL("image/".concat(t),e),Hf=(a,t,e)=>new Promise((s,i)=>{a.toBlob(s,"image/".concat(t),e)}),Ut=a=>a*Df,Ci=a=>a/Df,Lm=a=>a.every((t,e)=>t===He[e]),Ee=(a,t,e)=>new O(a).transform(t,e),ns=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 O(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},qt=(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]],mu=(a,t)=>a.reduceRight((e,s)=>s&&e?qt(s,e,t):s||e,void 0)||He.concat(),Im=a=>{let[t,e]=a;return Math.atan2(e,t)},Lr=a=>{const t=Im(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:Ci(t),scaleX:s,scaleY:i,skewX:Ci(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},pa=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function Ir(){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=Ut(a),i=qs(s),n=Ks(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const vu=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},jm=a=>Math.tan(Ut(a)),zf=a=>[1,0,jm(a),1,0,0],Vf=a=>[1,jm(a),0,1,0,0],Kh=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=vu(s?-t:t,i?-e:e);return n&&(o=qt(o,zf(n),!0)),r&&(o=qt(o,Vf(r),!0)),o},Nm=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=pa(t,e);s&&(i=qt(i,Ir({angle:s})));const n=Kh(a);return Lm(n)||(i=qt(i,n)),i},Jh=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 Mf("loadImage"));const n=Fm();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 wi("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()})},ma=function(a){let{signal:t,reviver:e=Rr}=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=>G.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)})})},Qh=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&&G.has(o.type)?ma([o],{signal:t}).then(h=>{let[c]=h;return i.push(c),c}):o),r=Object.keys(a);Promise.all(n).then(o=>o.reduce((h,c,u)=>(h[r[u]]=c,h),{})).then(e).catch(o=>{i.forEach(h=>{h.dispose&&h.dispose()}),s(o)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},jr=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in a&&(t[e]=a[e]),t),{})},Gf=(a,t)=>Object.keys(a).reduce((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e),{}),kt=(a,t)=>parseFloat(Number(a).toFixed(t)),va=a=>"matrix("+a.map(t=>kt(t,mt.NUM_FRACTION_DIGITS)).join(" ")+")",Rs=a=>!!a&&a.toLive!==void 0,Bm=a=>!!a&&typeof a.toObject=="function",Hm=a=>!!a&&a.offsetX!==void 0&&"source"in a,Nr=a=>!!a&&"multiSelectionStacking"in a;function zm(a){const t=a&&Js(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 Js=a=>a.ownerDocument||null,Vm=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},Gm=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))},Wf=(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 Wm(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=ze,a}class Xm{constructor(t){k(this,"_originalCanvasStyle",void 0),k(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&&ua().getElementById(t)||Si();var s;if(e.hasAttribute("data-fabric"))throw new wi("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;Gm(s,i,t,e)}setCSSDimensions(t){Wf(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&Js(t),i={left:0,top:0};if(!s)return i;const n=((e=Vm(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=zm(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(){xi().dispose(this.lower.el),delete this.lower}}const I_={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...He]};class Zh extends Om(Dm){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 Zh.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 Xm(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&&(Ki("warn",`Canvas is trying to add an object that belongs to a different canvas.
32
- 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?Em():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=E({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=Ee(t,ns(i));i[0]=e,i[3]=e;const r=Ee(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new O(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 O(-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=qh(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=ns(this.viewportTransform),i=Ee({x:0,y:0},s),n=Ee({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new O(o.x,r.y),bl:new O(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(Rm(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 O(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new O(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new O(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 O(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new O(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Ee(this.getCenterPoint(),ns(this.viewportTransform))}_centerObject(t,e){t.setXY(e,rt,rt),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 E(E(E({version:Of},jr(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,`)" >
30
+ <%s key={someKey} {...props} />`,to,js,fm,js),Pc[js+to]=!0}}return y===s?lm(Rt):om(Rt),Rt}}function hm(y,D,j){return Mc(y,D,j,!0)}function cm(y,D,j){return Mc(y,D,j,!1)}var um=cm,dm=hm;ci.Fragment=s,ci.jsx=um,ci.jsxs=dm}()),ci}var no;function Lc(){return no||(no=1,process.env.NODE_ENV==="production"?We.exports=Rc():We.exports=Fc()),We.exports}var ro=Lc();const Ic="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",jc={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Nc={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Bc={borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Hc={stroke:"#000",hoverStroke:"#B7EC5D",src:Ic},zc=["borderColor","cornerStrokeColor","cornerSize","_cornerSize","selectionBackgroundColor"];function S(o,t,e){return(t=function(s){var i=function(n,r){if(typeof n!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var l=a.call(n,r);if(typeof l!="object")return l;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 o?Object.defineProperty(o,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):o[t]=e,o}function ao(o,t){var e=Object.keys(o);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(o);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(o,i).enumerable})),e.push.apply(e,s)}return e}function x(o){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?ao(Object(e),!0).forEach(function(s){S(o,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(e)):ao(Object(e)).forEach(function(s){Object.defineProperty(o,s,Object.getOwnPropertyDescriptor(e,s))})}return o}function pt(o,t){if(o==null)return{};var e,s,i=function(r,a){if(r==null)return{};var l={};for(var h in r)if({}.hasOwnProperty.call(r,h)){if(a.indexOf(h)>=0)continue;l[h]=r[h]}return l}(o,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(o);for(s=0;s<n.length;s++)e=n[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(o,e)&&(i[e]=o[e])}return i}function Re(o,t){return t||(t=o.slice(0)),Object.freeze(Object.defineProperties(o,{raw:{value:Object.freeze(t)}}))}class oo{constructor(){S(this,"browserShadowBlurConstant",1),S(this,"DPI",96),S(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),S(this,"perfLimitSizeTotal",2097152),S(this,"maxCacheSideLimit",4096),S(this,"minCacheSideLimit",256),S(this,"disableStyleCopyPaste",!1),S(this,"enableGLFiltering",!0),S(this,"textureSize",4096),S(this,"forceGLPutImageData",!1),S(this,"cachesBoundsOfCurve",!1),S(this,"fontPaths",{}),S(this,"NUM_FRACTION_DIGITS",4)}}const nt=new class extends oo{constructor(o){super(),this.configure(o)}configure(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,o)}addFonts(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths=x(x({},this.fontPaths),o)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(o=>{delete this.fontPaths[o]})}clearFonts(){this.fontPaths={}}restoreDefaults(o){const t=new oo,e=o?.reduce((s,i)=>(s[i]=t[i],s),{})||t;this.configure(e)}},Xe=function(o){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[o]("fabric",...e)};class Fe extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class br extends Fe{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class Vc{}class Gc extends Vc{testPrecision(t,e){const s="precision ".concat(e,` float;
31
+ 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(),Xe("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Wc={};let lo;const Le=()=>lo||(lo={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Gc,dispose(){},copyPasteData:Wc}),Ns=()=>Le().document,ui=()=>Le().window,ho=()=>{var o;return Math.max((o=nt.devicePixelRatio)!==null&&o!==void 0?o:ui().devicePixelRatio,1)},di=new class{constructor(){S(this,"charWidthsCache",{}),S(this,"boundsOfCurveCache",{})}getFontCache(o){let{fontFamily:t,fontStyle:e,fontWeight:s}=o;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(o){(o=(o||"").toLowerCase())?this.charWidthsCache[o]&&delete this.charWidthsCache[o]:this.charWidthsCache={}}limitDimsByArea(o){const{perfLimitSizeTotal:t}=nt,e=Math.sqrt(t*o);return[Math.floor(e),Math.floor(t/e)]}},yr="6.7.0";function ps(){}const is=Math.PI/2,Ue=2*Math.PI,_r=Math.PI/180,Ut=Object.freeze([1,0,0,1,0,0]),wr=16,ns=.4477152502,q="center",ot="left",ie="top",xr="bottom",xt="right",Yt="none",Sr=/\r?\n/,co="moving",Xi="scaling",uo="rotating",Cr="rotate",fo="skewing",fi="resizing",Xc="modifyPoly",Uc="modifyPath",Ui="changed",Yi="scale",$t="scaleX",ce="scaleY",Bs="skewX",Hs="skewY",kt="fill",qt="stroke",$i="modified",zs="json",Ar="svg",I=new class{constructor(){this[zs]=new Map,this[Ar]=new Map}has(o){return this[zs].has(o)}getClass(o){const t=this[zs].get(o);if(!t)throw new Fe("No class registered for ".concat(o));return t}setClass(o,t){t?this[zs].set(t,o):(this[zs].set(o.type,o),this[zs].set(o.type.toLowerCase(),o))}getSVGClass(o){return this[Ar].get(o)}setSVGClass(o,t){this[Ar].set(t??o.type.toLowerCase(),o)}},qi=new class extends Array{remove(o){const t=this.indexOf(o);t>-1&&this.splice(t,1)}cancelAll(){const o=this.splice(0);return o.forEach(t=>t.abort()),o}cancelByCanvas(o){if(!o)return[];const t=this.filter(e=>{var s;return e.target===o||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===o});return t.forEach(e=>e.abort()),t}cancelByTarget(o){if(!o)return[];const t=this.filter(e=>e.target===o);return t.forEach(e=>e.abort()),t}};class Yc{constructor(){S(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 ms=(o,t)=>{const e=o.indexOf(t);return e!==-1&&o.splice(e,1),o},xe=o=>{if(o===0)return 1;switch(Math.abs(o)/is){case 1:case 3:return 0;case 2:return-1}return Math.cos(o)},Se=o=>{if(o===0)return 0;const t=o/is,e=Math.sign(o);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(o)};class A{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 A(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new A(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new A(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new A(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new A(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new A(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new A(this.x/t.x,this.y/t.y)}scalarDivide(t){return new A(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 A(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 A(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new A(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 A(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Tr;const s=Se(t),i=xe(t),n=this.subtract(e);return new A(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 A(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 Tr=new A(0,0),Ki=o=>!!o&&Array.isArray(o._objects);function go(o){class t extends o{constructor(){super(...arguments),S(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(a=>this._onObjectAdded(a)),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(a=>this._onObjectAdded(a)),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return r.forEach(l=>{const h=s.indexOf(l);h!==-1&&(s.splice(h,1),i.push(l),this._onObjectRemoved(l))}),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])&&(ms(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(ms(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 ms(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 ms(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(ms(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 a=i-1;a>=0;--a)if(s.isOverlapping(this._objects[a])){r=a;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let a=i+1;a<this._objects.length;++a)if(s.isOverlapping(this._objects[a])){r=a;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:a}=s,{includeIntersecting:l=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const h=[],c=new A(i,n),u=c.add(new A(r,a));for(let d=this._objects.length-1;d>=0;d--){const f=this._objects[d];f.selectable&&f.visible&&(l&&f.intersectsWithRect(c,u)||f.isContainedWithinRect(c,u)||l&&f.containsPoint(c)||l&&f.containsPoint(u))&&h.push(f)}return h}}return t}class po extends Yc{_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 gi(o){return ui().requestAnimationFrame(o)}function mo(o){return ui().cancelAnimationFrame(o)}let $c=0;const rs=()=>$c++,Ie=()=>{const o=Ns().createElement("canvas");if(!o||o.getContext===void 0)throw new Fe("Failed to create `canvas` element");return o},vo=()=>Ns().createElement("img"),ue=o=>{const t=Ie();return t.width=o.width,t.height=o.height,t},Er=(o,t,e)=>o.toDataURL("image/".concat(t),e),kr=(o,t,e)=>new Promise((s,i)=>{o.toBlob(s,"image/".concat(t),e)}),wt=o=>o*_r,je=o=>o/_r,bo=o=>o.every((t,e)=>t===Ut[e]),Bt=(o,t,e)=>new A(o).transform(t,e),ne=o=>{const t=1/(o[0]*o[3]-o[1]*o[2]),e=[t*o[3],-t*o[1],-t*o[2],t*o[0],0,0],{x:s,y:i}=new A(o[4],o[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},St=(o,t,e)=>[o[0]*t[0]+o[2]*t[1],o[1]*t[0]+o[3]*t[1],o[0]*t[2]+o[2]*t[3],o[1]*t[2]+o[3]*t[3],e?0:o[0]*t[4]+o[2]*t[5]+o[4],e?0:o[1]*t[4]+o[3]*t[5]+o[5]],Ji=(o,t)=>o.reduceRight((e,s)=>s&&e?St(s,e,t):s||e,void 0)||Ut.concat(),yo=o=>{let[t,e]=o;return Math.atan2(e,t)},vs=o=>{const t=yo(o),e=Math.pow(o[0],2)+Math.pow(o[1],2),s=Math.sqrt(e),i=(o[0]*o[3]-o[2]*o[1])/s,n=Math.atan2(o[0]*o[2]+o[1]*o[3],e);return{angle:je(t),scaleX:s,scaleY:i,skewX:je(n),skewY:0,translateX:o[4]||0,translateY:o[5]||0}},Vs=function(o){return[1,0,0,1,o,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function bs(){let{angle:o=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=wt(o),i=xe(s),n=Se(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const Qi=function(o){return[o,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:o,0,0]},_o=o=>Math.tan(wt(o)),Pr=o=>[1,0,_o(o),1,0,0],Mr=o=>[1,_o(o),0,1,0,0],pi=o=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=o,a=Qi(s?-t:t,i?-e:e);return n&&(a=St(a,Pr(n),!0)),r&&(a=St(a,Mr(r),!0)),a},wo=o=>{const{translateX:t=0,translateY:e=0,angle:s=0}=o;let i=Vs(t,e);s&&(i=St(i,bs({angle:s})));const n=pi(o);return bo(n)||(i=St(i,n)),i},mi=function(o){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 br("loadImage"));const n=vo();let r;t&&(r=function(l){n.src="",i(l)},t.addEventListener("abort",r,{once:!0}));const a=function(){n.onload=n.onerror=null,r&&t?.removeEventListener("abort",r),s(n)};o?(n.onload=a,n.onerror=function(){r&&t?.removeEventListener("abort",r),i(new Fe("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=o):a()})},Gs=function(o){let{signal:t,reviver:e=ps}=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(o.map(r=>I.getClass(r.type).fromObject(r,{signal:t}).then(a=>(e(r,a),n.push(a),a)))).then(s).catch(r=>{n.forEach(a=>{a.dispose&&a.dispose()}),i(r)}).finally(()=>{t&&t.removeEventListener("abort",i)})})},vi=function(o){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(o).map(a=>a&&a.type&&I.has(a.type)?Gs([a],{signal:t}).then(l=>{let[h]=l;return i.push(h),h}):a),r=Object.keys(o);Promise.all(n).then(a=>a.reduce((l,h,c)=>(l[r[c]]=h,l),{})).then(e).catch(a=>{i.forEach(l=>{l.dispose&&l.dispose()}),s(a)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},ys=function(o){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in o&&(t[e]=o[e]),t),{})},Or=(o,t)=>Object.keys(o).reduce((e,s)=>(t(o[s],s,o)&&(e[s]=o[s]),e),{}),ct=(o,t)=>parseFloat(Number(o).toFixed(t)),Ws=o=>"matrix("+o.map(t=>ct(t,nt.NUM_FRACTION_DIGITS)).join(" ")+")",pe=o=>!!o&&o.toLive!==void 0,xo=o=>!!o&&typeof o.toObject=="function",So=o=>!!o&&o.offsetX!==void 0&&"source"in o,_s=o=>!!o&&"multiSelectionStacking"in o;function Co(o){const t=o&&Ce(o);let e=0,s=0;if(!o||!t)return{left:e,top:s};let i=o;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 Ce=o=>o.ownerDocument||null,Ao=o=>{var t;return((t=o.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},To=function(o,t,e){let{width:s,height:i}=e,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;o.width=s,o.height=i,n>1&&(o.setAttribute("width",(s*n).toString()),o.setAttribute("height",(i*n).toString()),t.scale(n,n))},Dr=(o,t)=>{let{width:e,height:s}=t;e&&(o.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(o.style.height=typeof s=="number"?"".concat(s,"px"):s)};function Eo(o){return o.onselectstart!==void 0&&(o.onselectstart=()=>!1),o.style.userSelect=Yt,o}class ko{constructor(t){S(this,"_originalCanvasStyle",void 0),S(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&&Ns().getElementById(t)||Ie();var s;if(e.hasAttribute("data-fabric"))throw new Fe("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;To(s,i,t,e)}setCSSDimensions(t){Dr(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&Ce(t),i={left:0,top:0};if(!s)return i;const n=((e=Ao(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 a=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const l=Co(t);return{left:r.left+l.left-(a.clientLeft||0)+i.left,top:r.top+l.top-(a.clientTop||0)+i.top}}(this.lower.el)}dispose(){Le().dispose(this.lower.el),delete this.lower}}const qc={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...Ut]};class bi extends go(po){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 bi.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 ko(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&&(Xe("warn",`Canvas is trying to add an object that belongs to a different canvas.
32
+ 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?ho():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=x({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=Bt(t,ne(i));i[0]=e,i[3]=e;const r=Bt(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new A(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 A(-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=gi(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=ne(this.viewportTransform),i=Bt({x:0,y:0},s),n=Bt({x:t,y:e},s),r=i.min(n),a=i.max(n);return this.vptCoords={tl:r,tr:new A(a.x,r.y),bl:new A(r.x,a.y),br:a}}cancelRequestedRender(){this.nextRenderHandle&&(mo(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 a=pe(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=a?s.toLive(t):s,r&&t.transform(...n),a){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const l=s.gradientTransform||s.patternTransform;l&&t.transform(...l)}t.fill(),t.restore()}if(i){t.save();const{skipOffscreen:l}=this;this.skipOffscreen=r,r&&t.transform(...n),i.render(t),this.skipOffscreen=l,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 A(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new A(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new A(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 A(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new A(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Bt(this.getCenterPoint(),ne(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 x(x(x({version:yr},ys(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,a=this.overlayColor;return pe(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),pe(a)?a.excludeFromExport||(s.overlay=a.toObject(e)):a&&(s.overlay=a),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,`)" >
33
33
  `)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
34
34
  `),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" ?>
35
35
  `,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
36
- `)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=mt.NUM_FRACTION_DIGITS,r=e.viewBox;let o;if(r)o='viewBox="'.concat(r.x," ").concat(r.y," ").concat(r.width," ").concat(r.height,'" ');else if(this.svgViewportTransformation){const h=this.viewportTransform;o='viewBox="'.concat(kt(-h[4]/h[0],n)," ").concat(kt(-h[5]/h[3],n)," ").concat(kt(this.width/h[0],n)," ").concat(kt(this.height/h[3],n),'" ')}else o='viewBox="0 0 '.concat(this.width," ").concat(this.height,'" ');t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',i,'" ',o,`xml:space="preserve">
37
- `,"<desc>Created with Fabric.js ",Of,`</desc>
36
+ `)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=nt.NUM_FRACTION_DIGITS,r=e.viewBox;let a;if(r)a='viewBox="'.concat(r.x," ").concat(r.y," ").concat(r.width," ").concat(r.height,'" ');else if(this.svgViewportTransformation){const l=this.viewportTransform;a='viewBox="'.concat(ct(-l[4]/l[0],n)," ").concat(ct(-l[5]/l[3],n)," ").concat(ct(this.width/l[0],n)," ").concat(ct(this.height/l[3],n),'" ')}else a='viewBox="0 0 '.concat(this.width," ").concat(this.height,'" ');t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',i,'" ',a,`xml:space="preserve">
37
+ `,"<desc>Created with Fabric.js ",yr,`</desc>
38
38
  `,`<defs>
39
39
  `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
40
- `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(Wn()),'<clipPath id="'.concat(e.clipPathId,`" >
40
+ `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(rs()),'<clipPath id="'.concat(e.clipPathId,`" >
41
41
  `).concat(e.toClipPathSVG(t.reviver),`</clipPath>
42
- `)):""}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?va(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=mt.fontPaths;this._objects.forEach(function n(r){t.push(r),pu(r)&&r._objects.forEach(n)}),t.forEach(n=>{if(!(r=n)||typeof r._renderText!="function")return;var r;const{styles:o,fontFamily:h}=n;!e[h]&&s[h]&&(e[h]=!0,o&&Object.values(o).forEach(c=>{Object.values(c).forEach(u=>{let{fontFamily:d=""}=u;!e[d]&&s[d]&&(e[d]=!0)})}))});const i=Object.keys(e).map(n=>` @font-face {
42
+ `)):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this["".concat(t,"Color")];if(pe(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?Ws(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=nt.fontPaths;this._objects.forEach(function n(r){t.push(r),Ki(r)&&r._objects.forEach(n)}),t.forEach(n=>{if(!(r=n)||typeof r._renderText!="function")return;var r;const{styles:a,fontFamily:l}=n;!e[l]&&s[l]&&(e[l]=!0,a&&Object.values(a).forEach(h=>{Object.values(h).forEach(c=>{let{fontFamily:u=""}=c;!e[u]&&s[u]&&(e[u]=!0)})}))});const i=Object.keys(e).map(n=>` @font-face {
43
43
  font-family: '`.concat(n,`';
44
44
  src: url('`).concat(s[n],`');
45
45
  }
46
46
  `)).join("");return i?` <style type="text/css"><![CDATA[
47
47
  `.concat(i,`]]></style>
48
- `):""}_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")]?va(ns(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"||!Hm(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!Hm(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
48
+ `):""}_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(pe(s)){const i=s.repeat||"",n=this.width,r=this.height,a=this["".concat(e,"Vpt")]?Ws(ne(this.viewportTransform)):"";t.push('<rect transform="'.concat(a," 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"||!So(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!So(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
49
49
  `))}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',s,'"',`></rect>
50
- `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new wi("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[],backgroundImage:r,background:o,overlayImage:h,overlay:c,clipPath:u}=i,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([ma(n,{reviver:e,signal:s}),Qh({backgroundImage:r,backgroundColor:o,overlayImage:h,overlayColor:c,clipPath:u},{signal:s})]).then(f=>{let[g,p]=f;return this.clear(),this.add(...g),this.set(i),this.set(p),this.renderOnAddRemove=d,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=ps(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 Bf(this.toCanvasElement(r,t),e,s)}toBlob(){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 Hf(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,c=this.getZoom(),u=this.width,d=this.height,f=this.skipControlsDrawing,g=c*t,p=this.viewportTransform,m=[g,0,0,g,(p[4]-(i||0))*t,(p[5]-(n||0))*t],y=this.enableRetinaScaling,b=ps({width:o,height:h}),x=r?this._objects.filter(C=>r(C)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(b.getContext("2d"),x),this.viewportTransform=p,this.width=u,this.height=d,this.calcViewportBoundaries(),this.enableRetinaScaling=y,this.skipControlsDrawing=f,b}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),gu.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," }>")}}k(Zh,"ownDefaults",I_);const j_=["touchstart","touchmove","touchend"],Um=a=>{const t=zm(a.target),e=function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s}(a);return new O(e.clientX+t.left,e.clientY+t.top)},bu=a=>j_.includes(a.type)||a.pointerType==="touch",Ym=a=>{a.preventDefault(),a.stopPropagation()},Ai=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}},N_=["translateX","translateY","scaleX","scaleY"],$m=(a,t)=>ba(a,qt(t,a.calcOwnMatrix())),ba=(a,t)=>{const e=Lr(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=Lt(e,N_),h=new O(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,rt,rt)},qm=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},Xf=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}),yu=(a,t,e)=>{const s=a/2,i=t/2,n=[new O(-s,-i),new O(s,-i),new O(-s,i),new O(s,i)].map(o=>o.transform(e)),r=Ai(n);return new O(r.width,r.height)},tl=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:He;return qt(ns(arguments.length>1&&arguments[1]!==void 0?arguments[1]:He),a)},Br=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:He,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:He;return a.transform(tl(t,e))},Km=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:He,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:He;return a.transform(tl(t,e),!0)},Uf=(a,t,e)=>{const s=tl(t,e);return ba(a,qt(s,a.calcOwnMatrix())),s},Jm=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),E(E({},t),{},{target:s})),s.fire(a,t)},B_={left:-.5,top:-.5,center:0,bottom:.5,right:.5},se=a=>typeof a=="string"?B_[a]:a-.5,_u="not-allowed";function Qm(a){return se(a.originX)===se(rt)&&se(a.originY)===se(rt)}function Zm(a){return .5-se(a)}const Qs=(a,t)=>a[t],tv=(a,t,e,s)=>({e:a,transform:t,pointer:new O(e,s)});function ev(a,t){const e=a.getTotalAngle()+Ci(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Yf(a,t,e,s,i){var n;let{target:r,corner:o}=a;const h=r.controls[o],c=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,u=r.padding/c,d=function(f,g,p,m){const y=f.getRelativeCenterPoint(),b=p!==void 0&&m!==void 0?f.translateToGivenOrigin(y,rt,rt,p,m):new O(f.left,f.top);return(f.angle?g.rotate(-Ut(f.angle),y):g).subtract(b)}(r,new O(s,i),t,e);return d.x>=u&&(d.x-=u),d.x<=-u&&(d.x+=u),d.y>=u&&(d.y-=u),d.y<=u&&(d.y+=u),d.x-=h.offsetX,d.y-=h.offsetY,d}const H_=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,c=!Qs(i,"lockMovementX")&&i.left!==o,u=!Qs(i,"lockMovementY")&&i.top!==h;return c&&i.set(wt,o),u&&i.set(is,h),(c||u)&&Jm(km,tv(a,t,e,s)),c||u},sv={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"},$f=(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),iv=(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 c=i-n;switch(o=h>.5?c/(2-i-n):c/(i+n),i){case a:r=(t-e)/c+(t<e?6:0);break;case t:r=(e-a)/c+2;break;case e:r=(a-t)/c+4}r/=6}return[Math.round(360*r),Math.round(100*o),Math.round(100*h),s]},nv=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},wu=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),rv=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class St{constructor(t){if(k(this,"isUnrecognised",!1),t)if(t instanceof St)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=t.toLowerCase())in sv&&(t=sv[t]),t==="transparent"?[255,255,255,0]:St.sourceFromHex(t)||St.sourceFromRgb(t)||St.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]=iv(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=iv(...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(wu(t)).concat(wu(e)).concat(wu(s)).concat(wu(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(rv(this.getSource())),this}toBlackWhite(t){const[e,,,s]=rv(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof St||(t=new St(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 St.fromRgba(t)}static fromRgba(t){return new St(St.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,nv(e[4])]}}static fromHsl(t){return St.fromHsla(t)}static fromHsla(t){return new St(St.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=(St.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 c=n<=.5?n*(i+1):n+i-n*i,u=2*n-c;r=$f(u,c,s+1/3),o=$f(u,c,s),h=$f(u,c,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),nv(e[4])]}static fromHex(t){return new St(St.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")?Ci(s):e.includes("turn")?360*s:s}}const We=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rf;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=mt.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}},qf=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==ze?[n.slice(1,4),n.slice(5,8)]:n===ze?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},el=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 St(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,'" '):"")};class ov{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):ze,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",c=this.opacity!==void 0?this.opacity:"1",u=this.visible?"":" visibility: hidden;",d=t?"":this.getSvgFilter(),f=el(ee,this.fill);return[el(Ge,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",h,"; ",f,"fill-rule: ",e,"; ","opacity: ",c,";",d,u].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(va(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,c=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",u=h&&h.absolutePositioned,d=this.stroke,f=this.fill,g=this.shadow,p=[],m=t.indexOf("COMMON_PARTS");let y;h&&(h.clipPathId="CLIPPATH_".concat(Wn()),y='<clipPath id="'.concat(h.clipPathId,`" >
51
- `).concat(h.toClipPathSVG(s),`</clipPath>
52
- `)),u&&p.push("<g ",o,this.getSvgCommons(),` >
53
- `),p.push("<g ",this.getSvgTransform(!1),u?"":o+this.getSvgCommons(),` >
54
- `);const b=[r,c,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[m]=b,Rs(f)&&p.push(f.toSVG(this)),Rs(d)&&p.push(d.toSVG(this)),g&&p.push(g.toSVG(this)),h&&p.push(y),p.push(t.join("")),p.push(`</g>
55
- `),u&&p.push(`</g>
56
- `),s?s(p.join("")):p.join("")}addPaintOrder(){return this.paintFirst!==ee?' paint-order="'.concat(this.paintFirst,'" '):""}}function xu(a){return new RegExp("^("+a.join("|")+")\\b","i")}const Hr="textDecorationThickness",av=["fontSize","fontWeight","fontFamily","fontStyle"],hv=["underline","overline","linethrough"],lv=[...av,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],cv=[...lv,...hv,"textBackgroundColor","direction",Hr],z_=[...av,...hv,Ge,"strokeWidth",ee,"deltaY","textBackgroundColor",Hr],V_={_reNewline:Lf,_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:wt,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:wt,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[Hr]:66.667},Ti="justify",Su="justify-left",sl="justify-right",il="justify-center";var uv,dv,fv;const Zs=String.raw(uv||(uv=_i(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),Kf=String.raw(dv||(dv=_i(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),Jf="http://www.w3.org/2000/svg",G_=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Zs+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Zs+"))?\\s+(.*)"),W_={cx:wt,x:wt,r:"radius",cy:is,y:is,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","text-decoration-thickness":Hr},Qf="font-size",Zf="clip-path",X_=xu(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),U_=xu(["symbol","image","marker","pattern","view","svg"]),gv=xu(["symbol","g","a","svg","clipPath","defs"]),pv=new RegExp(String.raw(fv||(fv=_i(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),Zs,Kf,Zs,Kf,Zs,Kf,Zs)),Y_=new O(1,0),mv=new O,tg=(a,t)=>a.rotate(t),Cu=(a,t)=>new O(t).subtract(a),Au=a=>a.distanceFrom(mv),Tu=(a,t)=>Math.atan2(ya(a,t),bv(a,t)),vv=a=>Tu(Y_,a),Eu=a=>a.eq(mv)?a:a.scalarDivide(Au(a)),eg=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return Eu(new O(-a.y,a.x).scalarMultiply(t?1:-1))},ya=(a,t)=>a.x*t.y-a.y*t.x,bv=(a,t)=>a.x*t.x+a.y*t.y,sg=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=ya(t,e),i=ya(t,a),n=ya(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},yv="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",_v=new RegExp("(?:\\s|^)"+yv+yv+"("+Zs+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Qi{constructor(t){const e=typeof t=="string"?Qi.parseShadow(t):t;Object.assign(this,Qi.ownDefaults,e),this.id=Wn()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(_v.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(_v,"")||"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=tg(new O(this.offsetX,this.offsetY),Ut(-t.angle)),s=new St(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*kt((Math.abs(e.x)+this.blur)/t.width,mt.NUM_FRACTION_DIGITS)+20,n=100*kt((Math.abs(e.y)+this.blur)/t.height,mt.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,`%" >
57
- <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(kt(this.blur?this.blur/2:0,mt.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
58
- <feOffset dx="`).concat(kt(e.x,mt.NUM_FRACTION_DIGITS),'" dy="').concat(kt(e.y,mt.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
50
+ `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new Fe("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[],backgroundImage:r,background:a,overlayImage:l,overlay:h,clipPath:c}=i,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Gs(n,{reviver:e,signal:s}),vi({backgroundImage:r,backgroundColor:a,overlayImage:l,overlayColor:h,clipPath:c},{signal:s})]).then(d=>{let[f,g]=d;return this.clear(),this.add(...f),this.set(i),this.set(g),this.renderOnAddRemove=u,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=ue(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 Er(this.toCanvasElement(r,t),e,s)}toBlob(){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 kr(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 a=(e||this.width)*t,l=(s||this.height)*t,h=this.getZoom(),c=this.width,u=this.height,d=this.skipControlsDrawing,f=h*t,g=this.viewportTransform,p=[f,0,0,f,(g[4]-(i||0))*t,(g[5]-(n||0))*t],v=this.enableRetinaScaling,m=ue({width:a,height:l}),b=r?this._objects.filter(_=>r(_)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=a,this.height=l,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),b),this.viewportTransform=g,this.width=c,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=v,this.skipControlsDrawing=d,m}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),qi.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," }>")}}S(bi,"ownDefaults",qc);const Kc=["touchstart","touchmove","touchend"],Po=o=>{const t=Co(o.target),e=function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s}(o);return new A(e.clientX+t.left,e.clientY+t.top)},Zi=o=>Kc.includes(o.type)||o.pointerType==="touch",Mo=o=>{o.preventDefault(),o.stopPropagation()},Ne=o=>{let t=0,e=0,s=0,i=0;for(let n=0,r=o.length;n<r;n++){const{x:a,y:l}=o[n];(a>s||!n)&&(s=a),(a<t||!n)&&(t=a),(l>i||!n)&&(i=l),(l<e||!n)&&(e=l)}return{left:t,top:e,width:s-t,height:i-e}},Jc=["translateX","translateY","scaleX","scaleY"],Oo=(o,t)=>Xs(o,St(t,o.calcOwnMatrix())),Xs=(o,t)=>{const e=vs(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,a=pt(e,Jc),l=new A(s,i);o.flipX=!1,o.flipY=!1,Object.assign(o,a),o.set({scaleX:n,scaleY:r}),o.setPositionByOrigin(l,q,q)},Do=o=>{o.scaleX=1,o.scaleY=1,o.skewX=0,o.skewY=0,o.flipX=!1,o.flipY=!1,o.rotate(0)},Rr=o=>({scaleX:o.scaleX,scaleY:o.scaleY,skewX:o.skewX,skewY:o.skewY,angle:o.angle,left:o.left,flipX:o.flipX,flipY:o.flipY,top:o.top}),tn=(o,t,e)=>{const s=o/2,i=t/2,n=[new A(-s,-i),new A(s,-i),new A(-s,i),new A(s,i)].map(a=>a.transform(e)),r=Ne(n);return new A(r.width,r.height)},yi=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ut;return St(ne(arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ut),o)},ws=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ut,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ut;return o.transform(yi(t,e))},Ro=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ut,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ut;return o.transform(yi(t,e),!0)},Fr=(o,t,e)=>{const s=yi(t,e);return Xs(o,St(s,o.calcOwnMatrix())),s},Fo=(o,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(o),x(x({},t),{},{target:s})),s.fire(o,t)},Qc={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Pt=o=>typeof o=="string"?Qc[o]:o-.5,en="not-allowed";function Lo(o){return Pt(o.originX)===Pt(q)&&Pt(o.originY)===Pt(q)}function Io(o){return .5-Pt(o)}const Ae=(o,t)=>o[t],jo=(o,t,e,s)=>({e:o,transform:t,pointer:new A(e,s)});function No(o,t){const e=o.getTotalAngle()+je(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Lr(o,t,e,s,i){var n;let{target:r,corner:a}=o;const l=r.controls[a],h=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,c=r.padding/h,u=function(d,f,g,p){const v=d.getRelativeCenterPoint(),m=g!==void 0&&p!==void 0?d.translateToGivenOrigin(v,q,q,g,p):new A(d.left,d.top);return(d.angle?f.rotate(-wt(d.angle),v):f).subtract(m)}(r,new A(s,i),t,e);return u.x>=c&&(u.x-=c),u.x<=-c&&(u.x+=c),u.y>=c&&(u.y-=c),u.y<=c&&(u.y+=c),u.x-=l.offsetX,u.y-=l.offsetY,u}const Zc=(o,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,a=e-n,l=s-r,h=!Ae(i,"lockMovementX")&&i.left!==a,c=!Ae(i,"lockMovementY")&&i.top!==l;return h&&i.set(ot,a),c&&i.set(ie,l),(h||c)&&Fo(co,jo(o,t,e,s)),h||c},Bo={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"},Ir=(o,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+6*(t-o)*e:e<.5?t:e<2/3?o+(t-o)*(2/3-e)*6:o),Ho=(o,t,e,s)=>{o/=255,t/=255,e/=255;const i=Math.max(o,t,e),n=Math.min(o,t,e);let r,a;const l=(i+n)/2;if(i===n)r=a=0;else{const h=i-n;switch(a=l>.5?h/(2-i-n):h/(i+n),i){case o:r=(t-e)/h+(t<e?6:0);break;case t:r=(e-o)/h+2;break;case e:r=(o-t)/h+4}r/=6}return[Math.round(360*r),Math.round(100*a),Math.round(100*l),s]},zo=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(o)/(o.endsWith("%")?100:1)},sn=o=>Math.min(Math.round(o),255).toString(16).toUpperCase().padStart(2,"0"),Vo=o=>{let[t,e,s,i=1]=o;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class ht{constructor(t){if(S(this,"isUnrecognised",!1),t)if(t instanceof ht)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=t.toLowerCase())in Bo&&(t=Bo[t]),t==="transparent"?[255,255,255,0]:ht.sourceFromHex(t)||ht.sourceFromRgb(t)||ht.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]=Ho(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=Ho(...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(sn(t)).concat(sn(e)).concat(sn(s)).concat(sn(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(Vo(this.getSource())),this}toBlackWhite(t){const[e,,,s]=Vo(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof ht||(t=new ht(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map((a,l)=>Math.round(.5*a+.5*s[l]));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return ht.fromRgba(t)}static fromRgba(t){return new ht(ht.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 a=parseFloat(r);return r.endsWith("%")?Math.round(2.55*a):a});return[s,i,n,zo(e[4])]}}static fromHsl(t){return ht.fromHsla(t)}static fromHsla(t){return new ht(ht.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=(ht.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,a,l;if(i===0)r=a=l=n;else{const h=n<=.5?n*(i+1):n+i-n*i,c=2*n-h;r=Ir(c,h,s+1/3),a=Ir(c,h,s),l=Ir(c,h,s-1/3)}return[Math.round(255*r),Math.round(255*a),Math.round(255*l),zo(e[4])]}static fromHex(t){return new ht(ht.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(l=>l+l):e.match(/.{2}/g);const[i,n,r,a=255]=s.map(l=>parseInt(l,16));return[i,n,r,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?je(s):e.includes("turn")?360*s:s}}const Kt=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:wr;const e=/\D{0,2}$/.exec(o),s=parseFloat(o),i=nt.DPI;switch(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}},jr=o=>{const[t,e]=o.trim().split(" "),[s,i]=(n=t)&&n!==Yt?[n.slice(1,4),n.slice(5,8)]:n===Yt?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},_i=function(o,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 ht(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(o,": ").concat(e,"; ").concat(s?"".concat(o,"-opacity: ").concat(s,"; "):""):"".concat(o,'="').concat(e,'" ').concat(s?"".concat(o,'-opacity="').concat(s,'" '):"")};class Go{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):Yt,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",l=this.strokeMiterLimit?this.strokeMiterLimit:"4",h=this.opacity!==void 0?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),d=_i(kt,this.fill);return[_i(qt,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",l,"; ",d,"fill-rule: ",e,"; ","opacity: ",h,";",u,c].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(Ws(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(),'" '),a=i?'style="'.concat(this.getSvgFilter(),'" '):"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],p=t.indexOf("COMMON_PARTS");let v;l&&(l.clipPathId="CLIPPATH_".concat(rs()),v='<clipPath id="'.concat(l.clipPathId,`" >
51
+ `).concat(l.toClipPathSVG(s),`</clipPath>
52
+ `)),c&&g.push("<g ",a,this.getSvgCommons(),` >
53
+ `),g.push("<g ",this.getSvgTransform(!1),c?"":a+this.getSvgCommons(),` >
54
+ `);const m=[r,h,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[p]=m,pe(d)&&g.push(d.toSVG(this)),pe(u)&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(v),g.push(t.join("")),g.push(`</g>
55
+ `),c&&g.push(`</g>
56
+ `),s?s(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==kt?' paint-order="'.concat(this.paintFirst,'" '):""}}function nn(o){return new RegExp("^("+o.join("|")+")\\b","i")}const xs="textDecorationThickness",Wo=["fontSize","fontWeight","fontFamily","fontStyle"],Xo=["underline","overline","linethrough"],Uo=[...Wo,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],Yo=[...Uo,...Xo,"textBackgroundColor","direction",xs],tu=[...Wo,...Xo,qt,"strokeWidth",kt,"deltaY","textBackgroundColor",xs],eu={_reNewline:Sr,_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:ot,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:ot,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[xs]:66.667},Be="justify",rn="justify-left",wi="justify-right",xi="justify-center";var $o,qo,Ko;const Te=String.raw($o||($o=Re(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),Nr=String.raw(qo||(qo=Re(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),Br="http://www.w3.org/2000/svg",su=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Te+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Te+"))?\\s+(.*)"),iu={cx:ot,x:ot,r:"radius",cy:ie,y:ie,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","text-decoration-thickness":xs},Hr="font-size",zr="clip-path",nu=nn(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),ru=nn(["symbol","image","marker","pattern","view","svg"]),Jo=nn(["symbol","g","a","svg","clipPath","defs"]),Qo=new RegExp(String.raw(Ko||(Ko=Re(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),Te,Nr,Te,Nr,Te,Nr,Te)),au=new A(1,0),Zo=new A,Vr=(o,t)=>o.rotate(t),an=(o,t)=>new A(t).subtract(o),on=o=>o.distanceFrom(Zo),ln=(o,t)=>Math.atan2(Us(o,t),el(o,t)),tl=o=>ln(au,o),hn=o=>o.eq(Zo)?o:o.scalarDivide(on(o)),Gr=function(o){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return hn(new A(-o.y,o.x).scalarMultiply(t?1:-1))},Us=(o,t)=>o.x*t.y-o.y*t.x,el=(o,t)=>o.x*t.x+o.y*t.y,Wr=(o,t,e)=>{if(o.eq(t)||o.eq(e))return!0;const s=Us(t,e),i=Us(t,o),n=Us(e,o);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},sl="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",il=new RegExp("(?:\\s|^)"+sl+sl+"("+Te+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Ye{constructor(t){const e=typeof t=="string"?Ye.parseShadow(t):t;Object.assign(this,Ye.ownDefaults,e),this.id=rs()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(il.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(il,"")||"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=Vr(new A(this.offsetX,this.offsetY),wt(-t.angle)),s=new ht(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*ct((Math.abs(e.x)+this.blur)/t.width,nt.NUM_FRACTION_DIGITS)+20,n=100*ct((Math.abs(e.y)+this.blur)/t.height,nt.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,`%" >
57
+ <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(ct(this.blur?this.blur/2:0,nt.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
58
+ <feOffset dx="`).concat(ct(e.x,nt.NUM_FRACTION_DIGITS),'" dy="').concat(ct(e.y,nt.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
59
59
  <feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
60
60
  <feComposite in2="oBlur" operator="in" />
61
61
  <feMerge>
@@ -63,44 +63,44 @@ Resulting to default behavior: removing object from previous canvas and adding t
63
63
  <feMergeNode in="SourceGraphic"></feMergeNode>
64
64
  </feMerge>
65
65
  </filter>
66
- `)}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=Qi.ownDefaults;return this.includeDefaultValues?t:Gf(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}k(Qi,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),k(Qi,"type","shadow"),G.setClass(Qi,"shadow");const zr=(a,t,e)=>Math.max(a,Math.min(t,e)),$_=[is,wt,Ve,gs,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",da,fa],Zi=[ee,Ge,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],q_={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:wt,originY:is,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:ee,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},ig=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/Ji*Math.asin(1):e/Ji*Math.asin(t/a),{a,c:t,p:e,s}),wv=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*Ji/e),xv=(a,t,e,s)=>-e*Math.cos(a/s*Vn)+e+t,ng=(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,Sv=(a,t,e,s)=>e-ng(s-a,0,e,s)+t;var K_=Object.freeze({__proto__:null,defaultEasing:xv,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:Sv,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}=ig(i,e,n,1.70158);return-wv(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*Sv(2*a,0,e,s)+t:.5*ng(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}=ig(i,e,n,1.70158);return a<1?-.5*wv(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*Ji/h)*.5+c+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*Vn)+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:ng,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}=ig(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*Ji/h)+c+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*Vn)+t});const J_=()=>!1;class rg{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=xv,onStart:o=Rr,onChange:h=Rr,onComplete:c=Rr,abort:u=J_,target:d}=t;k(this,"_state","pending"),k(this,"durationProgress",0),k(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=c,this._abort=u,this.target=d,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(()=>qh(t),this.delay):qh(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),qh(this.tick)))}register(){gu.push(this)}unregister(){gu.remove(this)}abort(){this._state="aborted",this.unregister()}}const Q_=["startValue","endValue"];class Z_ extends rg{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(E(E({},Lt(t,Q_)),{},{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 tw=["startValue","endValue"];class ew extends rg{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(E(E({},Lt(t,tw)),{},{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 sw=["startValue","endValue","easing","onChange","onComplete","abort"],iw=(a,t,e,s)=>t+e*(1-Math.cos(a/s*Vn)),og=a=>a&&((t,e,s)=>a(new St(t).toRgba(),e,s));class nw extends rg{constructor(t){let{startValue:e,endValue:s,easing:i=iw,onChange:n,onComplete:r,abort:o}=t,h=Lt(t,sw);const c=new St(e).getSource(),u=new St(s).getSource();super(E(E({},h),{},{startValue:c,byValue:u.map((d,f)=>d-c[f]),easing:i,onChange:og(n),onComplete:og(r),abort:og(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),zr(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 ag(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new ew(a):new Z_(a);return t.start(),t}function Cv(a){const t=new nw(a);return t.start(),t}class zt{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=Cu(e,s),r=Cu(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 O(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,c=i.x-s.x,u=i.y-s.y,d=t.x-s.x,f=t.y-s.y,g=c*f-u*d,p=o*f-h*d,m=u*o-c*h;if(m!==0){const y=g/m,b=p/m;return(n||0<=y&&y<=1)&&(r||0<=b&&b<=1)?new zt("Intersection").append(new O(t.x+y*o,t.y+y*h)):new zt}if(g===0||p===0){const y=n||r||zt.isPointContained(t,s,i)||zt.isPointContained(e,s,i)||zt.isPointContained(s,t,e)||zt.isPointContained(i,t,e);return new zt(y?"Coincident":void 0)}return new zt("Parallel")}static intersectSegmentLine(t,e,s,i){return zt.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return zt.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 zt,r=s.length;for(let o,h,c,u=0;u<r;u++){if(o=s[u],h=s[(u+1)%r],c=zt.intersectLineLine(t,e,o,h,i,!1),c.status==="Coincident")return c;n.append(...c.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return zt.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new zt,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],c=zt.intersectSegmentPolygon(o,h,e);c.status==="Coincident"?(n.push(c),s.append(o,h)):s.append(...c.points)}return n.length>0&&n.length===t.length?new zt("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 O(n.x,i.y),o=new O(i.x,n.y);return zt.intersectPolygonPolygon(t,[i,r,n,o])}}class rw extends Dm{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?Ee(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Ee(t,ns(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new O(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=>Ee(o,r))}return n}intersectsWithRect(t,e){return zt.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=zt.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 zt.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 Ai(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Ve,t),this._set(gs,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?Ci(Im(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||He.concat()}calcACoords(){const t=Ir({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=pa(e,s),n=qt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:Ee({x:-o,y:-h},n),tr:Ee({x:o,y:-h},n),bl:Ee({x:-o,y:h},n),br:Ee({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,se(this.originX),se(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=qt(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=Nm(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new O(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=E({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 O(r*e.scaleX,o*e.scaleY):yu(r,o,Kh(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=se(i)-se(e),c=se(n)-se(s);if(h||c){const u=this._getTransformedDimensions();r+=h*u.x,o+=c*u.y}return new O(r,o)}translateToCenterPoint(t,e,s){if(e===rt&&s===rt)return t;const i=this.translateToGivenOrigin(t,e,s,rt,rt);return this.angle?i.rotate(Ut(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,rt,rt,e,s);return this.angle?i.rotate(Ut(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Ee(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new O(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(),wt,is)}}const ow=["type"],aw=["extraParam"];let tn=class Zd extends rw{static getDefaults(){return Zd.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){Ki("warn","Setting type has no effect",t)}constructor(t){super(),k(this,"_cacheContext",null),Object.assign(this,Zd.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Si(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=mt.maxCacheSideLimit,n=mt.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=mt.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=Yh.limitDimsByArea(r),c=zr(n,o,i),u=zr(n,h,i);return e>c&&(t.zoomX/=e/c,t.width=c,t.capped=!0),s>u&&(t.zoomY/=s/u,t.height=u,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:Math.ceil(s+2),height:Math.ceil(i+2),zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:i,zoomX:n,zoomY:r,x:o,y:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),c=s!==t.width||i!==t.height,u=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(c||u){s!==t.width||i!==t.height?(t.width=s,t.height=i):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const d=o/2,f=h/2;return this.cacheTranslationX=Math.round(t.width/2-d)+d,this.cacheTranslationY=Math.round(t.height/2-f)+f,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}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 O(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Lr(this.calcTransformMatrix());return new O(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!==Ve&&t!==gs||(e=this._constrainScale(e)),t===Ve&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Qi||(e=new Qi(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===Ge&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),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=ps(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=ns(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&&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)||He,o=n*i,h=r*i,c=e.nonScaling?new O(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*mt.browserShadowBlurConstant*(o+h)*(c.x+c.y)/4,t.shadowOffsetX=e.offsetX*o*c.x,t.shadowOffsetY=e.offsetY*h*c.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===Ge?(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=ps({width:Math.ceil(r),height:Math.ceil(o)}),c=h.getContext("2d");c&&(c.beginPath(),c.moveTo(0,0),c.lineTo(r,0),c.lineTo(r,o),c.lineTo(0,o),c.closePath(),c.translate(r/2,o/2),c.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(c,e),c.fillStyle=e.toLive(t),c.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=c.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new O(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(G.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Xf(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?Em():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(x=>new Zh(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&qm(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Uf(this,this.getViewportTransform()),this.setCoords();const c=Si(),u=this.getBoundingRect(),d=this.shadow,f=new O;if(d){const x=d.blur,C=d.nonScaling?new O(1,1):this.getObjectScaling();f.x=2*Math.round(n(d.offsetX)+x)*n(C.x),f.y=2*Math.round(n(d.offsetY)+x)*n(C.y)}const g=u.width+f.x,p=u.height+f.y;c.width=Math.ceil(g),c.height=Math.ceil(p);const m=h(c);t.format==="jpeg"&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new O(m.width/2,m.height/2),rt,rt);const y=this.canvas;m._objects=[this],this.set("canvas",m),this.setCoords();const b=m.toCanvasElement(o||1,t);return this.set("canvas",y),this.shadow=i,s&&(this.group=s),this.set(e),this.setCoords(),m._objects=[],m.destroy(),b}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Bf(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Hf(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=rt,this.originY=rt,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(){gu.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&xi().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:c}=s,u=E(E({},s),{},{target:this,startValue:o??i.reduce((d,f)=>d[f],this),endValue:e,abort:r==null?void 0:r.bind(this),onChange:(d,f,g)=>{i.reduce((p,m,y)=>(y===i.length-1&&(p[m]=d),p[m]),this),h&&h(d,f,g)},onComplete:(d,f,g)=>{this.setCoords(),c&&c(d,f,g)}});return n?Cv(u):ag(u)}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(Zd.customProperties,this.constructor.customProperties||[]);let e;const s=mt.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:c,top:u,originX:d,originY:f,width:g,height:p,strokeWidth:m,strokeLineCap:y,strokeDashOffset:b,strokeLineJoin:x,strokeUniform:C,strokeMiterLimit:S,scaleX:T,scaleY:P,angle:M,flipX:D,flipY:R,opacity:V,visible:H,backgroundColor:F,fillRule:I,paintFirst:j,globalCompositeOperation:K,skewX:L,skewY:z}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const Z=Bt=>kt(Bt,s),Dt=E(E({},jr(this,t)),{},{type:this.constructor.type,version:Of,originX:d,originY:f,left:Z(c),top:Z(u),width:Z(g),height:Z(p),fill:Bm(n)?n.toObject():n,stroke:Bm(r)?r.toObject():r,strokeWidth:Z(m),strokeDashArray:h&&h.concat(),strokeLineCap:y,strokeDashOffset:b,strokeLineJoin:x,strokeUniform:C,strokeMiterLimit:Z(S),scaleX:Z(T),scaleY:Z(P),angle:Z(M),flipX:D,flipY:R,opacity:Z(V),shadow:o&&o.toObject(),visible:H,backgroundColor:F,fillRule:I,paintFirst:j,globalCompositeOperation:K,skewX:Z(L),skewY:Z(z)},e?{clipPath:e}:null);return this.includeDefaultValues?Dt:this._removeDefaultValues(Dt)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Gf(t,(i,n)=>{if(n===wt||n===is||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=Lt(t,ow),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=Lt(s,aw);return Qh(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)}};k(tn,"stateProperties",$_),k(tn,"cacheProperties",Zi),k(tn,"ownDefaults",q_),k(tn,"type","FabricObject"),k(tn,"colorProperties",[ee,Ge,"backgroundColor"]),k(tn,"customProperties",[]),G.setClass(tn),G.setClass(tn,"object");const _a=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Jm(a,E(E({},tv(s,i,n,r)),e)),o};function wa(a){return(t,e,s,i)=>{const{target:n,originX:r,originY:o}=e,h=n.getRelativeCenterPoint(),c=n.translateToOriginPoint(h,r,o),u=a(t,e,s,i);return n.setPositionByOrigin(c,e.originX,e.originY),u}}const Av=_a($h,wa((a,t,e,s)=>{const i=Yf(t,t.originX,t.originY,e,s);if(se(t.originX)===se(rt)||se(t.originX)===se($t)&&i.x<0||se(t.originX)===se(wt)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=Qm(t)?2:1,h=n.width,c=Math.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(c,1)),h!==n.width}return!1}));function hw(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?Ge:ee,c=!o&&(s.cornerStrokeColor||i.cornerStrokeColor);let u,d=t,f=e;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(u=n,a.scale(1,r/n),f=e*n/r):r>n?(u=r,a.scale(n/r,1),d=t*r/n):u=n,a.beginPath(),a.arc(d,f,u/2,0,Ji,!1),a[h](),c&&a.stroke(),a.restore()}function lw(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?Ge:ee,c=!o&&(s.cornerStrokeColor||i.cornerStrokeColor),u=n/2,d=r/2;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",a.translate(t,e);const f=i.getTotalAngle();a.rotate(Ut(f)),a["".concat(h,"Rect")](-u,-d,n,r),c&&a.strokeRect(-u,-d,n,r),a.restore()}class ti{constructor(t){k(this,"visible",!0),k(this,"actionName",du),k(this,"angle",0),k(this,"x",0),k(this,"y",0),k(this,"offsetX",0),k(this,"offsetY",0),k(this,"sizeX",0),k(this,"sizeY",0),k(this,"touchSizeX",0),k(this,"touchSizeY",0),k(this,"cursorStyle","crosshair"),k(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:c}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&zt.isPointInPolygon(s,[r,o,h,c])}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 O(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=mu([pa(s,i),Ir({angle:t}),vu((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new O(-.5,-.5).transform(o),tr:new O(.5,-.5).transform(o),br:new O(.5,.5).transform(o),bl:new O(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?hw.call(this,t,e,s,i,n):lw.call(this,t,e,s,i,n)}}const cw=(a,t,e)=>e.lockRotation?_u:t.cursorStyle,uw=_a(Pm,wa((a,t,e,s)=>{let{target:i,ex:n,ey:r,theta:o,originX:h,originY:c}=t;const u=i.translateToOriginPoint(i.getRelativeCenterPoint(),h,c);if(Qs(i,"lockRotation"))return!1;const d=Math.atan2(r-u.y,n-u.x),f=Math.atan2(s-u.y,e-u.x);let g=Ci(f-d+o);if(i.snapAngle&&i.snapAngle>0){const m=i.snapAngle,y=i.snapThreshold||m,b=Math.ceil(g/m)*m,x=Math.floor(g/m)*m;Math.abs(g-x)<y?g=x:Math.abs(g-b)<y&&(g=b)}g<0&&(g=360+g),g%=360;const p=i.angle!==g;return i.angle=g,p}));function Tv(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Ev(a,t,e){const s=Qs(a,"lockScalingX"),i=Qs(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 dw=["e","se","s","sw","w","nw","n","ne","e"],nl=(a,t,e)=>{const s=Tv(a,e);if(Ev(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return _u;const i=ev(e,t);return"".concat(dw[i],"-resize")};function hg(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Tv(a,n);let h,c,u,d,f,g;if(Ev(n,r,o))return!1;if(t.gestureScale)c=t.scaleX*t.gestureScale,u=t.scaleY*t.gestureScale;else{if(h=Yf(t,t.originX,t.originY,e,s),f=r!=="y"?Math.sign(h.x||t.signX||1):1,g=r!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=f),t.signY||(t.signY=g),Qs(n,"lockScalingFlip")&&(t.signX!==f||t.signY!==g))return!1;if(d=n._getTransformedDimensions(),o&&!r){const y=Math.abs(h.x)+Math.abs(h.y),{original:b}=t,x=y/(Math.abs(d.x*b.scaleX/n.scaleX)+Math.abs(d.y*b.scaleY/n.scaleY));c=b.scaleX*x,u=b.scaleY*x}else c=Math.abs(h.x*n.scaleX/d.x),u=Math.abs(h.y*n.scaleY/d.y);Qm(t)&&(c*=2,u*=2),t.signX!==f&&r!=="y"&&(t.originX=Zm(t.originX),c*=-1,t.signX=f),t.signY!==g&&r!=="x"&&(t.originY=Zm(t.originY),u*=-1,t.signY=g)}const p=n.scaleX,m=n.scaleY;return r?(r==="x"&&n.set(Ve,c),r==="y"&&n.set(gs,u)):(!Qs(n,"lockScalingX")&&n.set(Ve,c),!Qs(n,"lockScalingY")&&n.set(gs,u)),p!==n.scaleX||m!==n.scaleY}const ku=_a(cu,wa((a,t,e,s)=>hg(a,t,e,s))),fw=_a(cu,wa((a,t,e,s)=>hg(a,t,e,s,{by:"x"}))),gw=_a(cu,wa((a,t,e,s)=>hg(a,t,e,s,{by:"y"}))),pw=["target","ex","ey","skewingSide"],lg={x:{counterAxis:"y",scale:Ve,skew:da,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:gs,skew:fa,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},mw=["ns","nesw","ew","nwse"],vw=(a,t,e)=>{if(t.x!==0&&Qs(e,"lockSkewingY")||t.y!==0&&Qs(e,"lockSkewingX"))return _u;const s=ev(e,t)%4;return"".concat(mw[s],"-resize")};function kv(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:c,flip:u}=lg[a];if(Qs(n,h))return!1;const{origin:d,flip:f}=lg[r],g=se(e[d])*(n[f]?-1:1),p=-Math.sign(g)*(n[u]?-1:1),m=.5*-((n[c]===0&&Yf(e,rt,rt,s,i)[a]>0||n[c]>0?1:-1)*p)+.5;return _a(Mm,wa((b,x,C,S)=>function(T,P,M){let{target:D,ex:R,ey:V,skewingSide:H}=P,F=Lt(P,pw);const{skew:I}=lg[T],j=M.subtract(new O(R,V)).divide(new O(D.scaleX,D.scaleY))[T],K=D[I],L=F[I],z=Math.tan(Ut(L)),Z=T==="y"?D._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:D._getTransformedDimensions({scaleX:1,scaleY:1}).y,Dt=2*j*H/Math.max(Z,1)+z,Bt=Ci(Math.atan(Dt));D.set(I,Bt);const Xt=K!==D[I];if(Xt&&T==="y"){const{skewX:Ft,scaleX:_t}=D,oe=D._getTransformedDimensions({skewY:K}),Ze=D._getTransformedDimensions(),it=Ft!==0?oe.x/Ze.x:1;it!==1&&D.set(Ve,it*_t)}return Xt}(a,x,new O(C,S))))(t,E(E({},e),{},{[o]:m,skewingSide:p}),s,i)}const bw=(a,t,e,s)=>kv("x",a,t,e,s),yw=(a,t,e,s)=>kv("y",a,t,e,s);function Pu(a,t){return a[t.canvas.altActionKey]}const Mu=(a,t,e)=>{const s=Pu(a,e);return t.x===0?s?da:gs:t.y===0?s?fa:Ve:""},xa=(a,t,e)=>Pu(a,e)?vw(0,t,e):nl(a,t,e),Pv=(a,t,e,s)=>Pu(a,t.target)?yw(a,t,e,s):fw(a,t,e,s),Mv=(a,t,e,s)=>Pu(a,t.target)?bw(a,t,e,s):gw(a,t,e,s),Ov=()=>({ml:new ti({x:-.5,y:0,cursorStyleHandler:xa,actionHandler:Pv,getActionName:Mu}),mr:new ti({x:.5,y:0,cursorStyleHandler:xa,actionHandler:Pv,getActionName:Mu}),mb:new ti({x:0,y:.5,cursorStyleHandler:xa,actionHandler:Mv,getActionName:Mu}),mt:new ti({x:0,y:-.5,cursorStyleHandler:xa,actionHandler:Mv,getActionName:Mu}),tl:new ti({x:-.5,y:-.5,cursorStyleHandler:nl,actionHandler:ku}),tr:new ti({x:.5,y:-.5,cursorStyleHandler:nl,actionHandler:ku}),bl:new ti({x:-.5,y:.5,cursorStyleHandler:nl,actionHandler:ku}),br:new ti({x:.5,y:.5,cursorStyleHandler:nl,actionHandler:ku}),mtr:new ti({x:0,y:-.5,actionHandler:uw,cursorStyleHandler:cw,offsetY:-40,withConnection:!0,actionName:If})}),_w=()=>({mr:new ti({x:.5,y:0,actionHandler:Av,cursorStyleHandler:xa,actionName:$h}),ml:new ti({x:-.5,y:0,actionHandler:Av,cursorStyleHandler:xa,actionName:$h})}),ww=()=>E(E({},Ov()),_w());class rl extends tn{static getDefaults(){return E(E({},super.getDefaults()),rl.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),rl.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Ov()}}_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(du))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=pa(e.x,e.y),i=Ir({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=qt(s,i),r=qt(t,n),o=qt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Lr(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const c=this._calculateCurrentDimensions(h),u={};return this.forEachControl((d,f)=>{const g=d.positionHandler(c,o,this,d);u[f]=Object.assign(g,this._calcCornerCoords(d,g))}),u}_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(Ut(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=E({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=E({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,c=qt(r,this.calcTransformMatrix()),u=Lr(c);t.save(),t.translate(u.translateX,u.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(u.angle-=180),t.rotate(Ut(this.group?u.angle:this.angle)),o&&this.drawBorders(t,u,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=yu(this.width,this.height,Kh(e)),r=this.isStrokeAccountedForInDimensions()?Nf:(this.strokeUniform?new O().scalarAdd(this.canvas?this.canvas.getZoom():1):new O(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=E({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,c)=>{if(h.getVisibility(this,c)){const u=this.oCoords[c];h.render(t,u.x,u.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 Dv(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}k(rl,"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 ke extends rl{}Dv(ke,[ov]),G.setClass(ke),G.setClass(ke,"object");const Rv=(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 Fv{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new O(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new O(1/this.options.scaleX,1/this.options.scaleY):new O(1,1)}createSideVector(t,e){const s=Cu(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 O(t);return e.y+=e.x*Math.tan(Ut(this.options.skewY)),e.x+=e.y*Math.tan(Ut(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const xw=new O;class Sa extends Fv{static getOrthogonalRotationFactor(t,e){const s=e?Tu(t,e):vv(t);return Math.abs(s)<Vn?-1:1}constructor(t,e,s,i){super(i),k(this,"AB",void 0),k(this,"AC",void 0),k(this,"alpha",void 0),k(this,"bisector",void 0),this.A=new O(t),this.B=new O(e),this.C=new O(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Tu(this.AB,this.AC),this.bisector=Eu(tg(this.AB.eq(xw)?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=eg(i),r=Sa.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%Ji==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?Au(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Au(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new O(Sa.getOrthogonalRotationFactor(this.bisector),Sa.getOrthogonalRotationFactor(new O(this.bisector.y,this.bisector.x)));return[new O(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new O(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{sg(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,c=new O(Math.tan(Ut(i)),Math.tan(Ut(n))),u=this.strokeProjectionMagnitude,d=h?u/o/Math.sqrt(1/o**2+1/r**2*c.y**2):u/Math.sqrt(1+c.y**2),f=new O(Math.sqrt(Math.max(u**2-d**2,0)),d),g=h?u/Math.sqrt(1+c.x**2*(1/o)**2/(1/r+1/r*c.x*c.y)**2):u/Math.sqrt(1+c.x**2/(1+c.x*c.y)**2),p=new O(g,Math.sqrt(Math.max(u**2-g**2,0)));return[p,p.scalarMultiply(-1),f,f.scalarMultiply(-1)].map(m=>this.applySkew(h?m.multiply(this.strokeUniformScalar):m)).forEach(m=>{sg(m,t,e)&&s.push(this.applySkew(this.A).add(m))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Ji==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=ya(i,r)>0,h=o?i:n,c=o?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,c)):t.push(...this.projectRoundNoSkew(h,c)),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 Lv extends Fv{constructor(t,e,s){super(s),this.A=new O(t),this.T=new O(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(eg(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 O(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 Sa(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new O(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(Eu(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 Iv=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 O(r)),n),[new O(a[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((o,h)=>{for(let c=o.length-1;c>=0;c--)if(h(o[c],c,o))return c;return-1})(i,o=>!o.eq(n));i.splice(r+1)}return i.forEach((n,r,o)=>{let h,c;r===0?(c=o[1],h=e?n:o[o.length-1]):r===o.length-1?(h=o[r-1],c=e?n:o[0]):(h=o[r-1],c=o[r+1]),e&&o.length===1?s.push(...new Lv(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Sa(n,h,c,t).project()):s.push(...new Lv(n,r===0?c:h,t).project())}),s},cg=a=>{const t={};return Object.keys(a).forEach(e=>{t[e]={},Object.keys(a[e]).forEach(s=>{t[e][s]=E({},a[e][s])})}),t},jv=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let ol;const Ou=a=>{if(ol||ol||(ol="Intl"in Uh()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),ol){const t=ol.segment(a);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return Sw(a)},Sw=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=Cw(a,s))!==!1&&t.push(e);return t},Cw=(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 Aw=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:jv,graphemeSplit:Ou});const Du=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.textDecorationThickness!==t.textDecorationThickness||a.textBackgroundColor!==t.textBackgroundColor||a.deltaY!==t.deltaY||e&&(a.overline!==t.overline||a.underline!==t.underline||a.linethrough!==t.linethrough)},Nv=(a,t)=>{const e=t.split(`
67
- `),s=[];let i=-1,n={};a=cg(a);for(let r=0;r<e.length;r++){const o=Ou(e[r]);if(a[r])for(let h=0;h<o.length;h++){i++;const c=a[r][h];c&&Object.keys(c).length>0&&(Du(n,c,!0)?s.push({start:i,end:i+1,style:c}):s[s.length-1].end++),n=c||{}}else i+=o.length,n={}}return s},Bv=(a,t)=>{if(!Array.isArray(a))return cg(a);const e=t.split(Lf),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=Ou(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]=E({},a[n].style),i===a[n].end-1&&n++)}return s},Xn=["display","transform",ee,"fill-opacity","fill-rule","opacity",Ge,"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 Hv(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 Tw(a,t){let e=!0;const s=Hv(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=Hv(i=i.parentElement,r);return n.length===0}(a,t)),s&&e&&t.length===0}const Ew=a=>{var t;return(t=W_[a])!==null&&t!==void 0?t:a},kw=new RegExp("(".concat(Zs,")"),"gi"),Pw=a=>a.replace(kw," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var zv,Vv,Gv,Wv,Xv,Uv,Yv;const Xe="(".concat(Zs,")"),Mw=String.raw(zv||(zv=_i(["(skewX)(",")"],["(skewX)\\(","\\)"])),Xe),Ow=String.raw(Vv||(Vv=_i(["(skewY)(",")"],["(skewY)\\(","\\)"])),Xe),Dw=String.raw(Gv||(Gv=_i(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Xe,Xe,Xe),Rw=String.raw(Wv||(Wv=_i(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Xe,Xe),Fw=String.raw(Xv||(Xv=_i(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Xe,Xe),Lw=String.raw(Uv||(Uv=_i(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Xe,Xe,Xe,Xe,Xe,Xe),ug="(?:".concat(Lw,"|").concat(Fw,"|").concat(Dw,"|").concat(Rw,"|").concat(Mw,"|").concat(Ow,")"),Iw="(?:".concat(ug,"*)"),jw=String.raw(Yv||(Yv=_i(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),Iw),Nw=new RegExp(jw),Bw=new RegExp(ug),Hw=new RegExp(ug,"g");function Ru(a){const t=[];if(!(a=Pw(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!Nw.test(a))return[...He];for(const e of a.matchAll(Hw)){const s=Bw.exec(e[0]);if(!s)continue;let i=He;const n=s.filter(p=>!!p),[,r,...o]=n,[h,c,u,d,f,g]=o.map(p=>parseFloat(p));switch(r){case"translate":i=pa(h,c);break;case If:i=Ir({angle:h},{x:c,y:u});break;case du:i=vu(h,c);break;case da:i=zf(h);break;case fa:i=Vf(h);break;case"matrix":i=[h,c,u,d,f,g]}t.push(i)}return mu(t)}function zw(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==ee&&a!==Ge||t!==ze){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===ze?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?qt(e.transformMatrix,Ru(t)):Ru(t);else if(a==="visible")r=t!==ze&&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"?wt:t==="end"?$t:rt;else if(a==="charSpacing"||a===Hr)n=We(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(ee),h=t.indexOf(Ge);r=ee,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=Ge)}else{if(a==="href"||a==="xlink:href"||a==="font"||a==="id")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(We):We(t,s)}}else r="";return!i&&isNaN(n)?r:n}function Vw(a,t){const e=a.match(G_);if(!e)return;const s=e[1],i=e[3],n=e[4],r=e[5],o=e[6];s&&(t.fontStyle=s),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),n&&(t.fontSize=We(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function dg(a,t){a.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function Gw(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?dg(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 Ww={stroke:"strokeOpacity",fill:"fillOpacity"};function en(a,t,e){if(!a)return{};let s,i={},n=Rf;a.parentNode&&gv.test(a.parentNode.nodeName)&&(i=en(a.parentElement,t,e),i.fontSize&&(s=n=We(i.fontSize)));const r=E(E(E({},t.reduce((c,u)=>{const d=a.getAttribute(u);return d&&(c[u]=d),c},{})),function(c){let u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d={};for(const f in u)Tw(c,f.split(" "))&&(d=E(E({},d),u[f]));return d}(a,e)),Gw(a));r[Zf]&&a.setAttribute(Zf,r[Zf]),r[Qf]&&(s=We(r[Qf],n),r[Qf]="".concat(s));const o={};for(const c in r){const u=Ew(c),d=zw(u,r[c],i,s);o[u]=d}o&&o.font&&Vw(o.font,o);const h=E(E({},i),o);return gv.test(a.nodeName)?h:function(c){const u=ke.getDefaults();return Object.entries(Ww).forEach(d=>{let[f,g]=d;if(c[g]===void 0||c[f]==="")return;if(c[f]===void 0){if(!u[f])return;c[f]=u[f]}if(c[f].indexOf("url(")===0)return;const p=new St(c[f]);c[f]=p.setAlpha(kt(p.getAlpha()*c[g],2)).toRgba()}),c}(h)}const Xw=["left","top","width","height","visible"],$v=["rx","ry"];class Ei extends ke{static getDefaults(){return E(E({},super.getDefaults()),Ei.ownDefaults)}constructor(t){super(),Object.assign(this,Ei.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-Gn*r,n,i+e,n+Gn*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-Gn*o,i+e-Gn*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+Gn*r,n+s,i,n+s-Gn*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+Gn*o,i+Gn*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([...$v,...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,`" />
68
- `)]}static async fromElement(t,e,s){const i=en(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:c=!0}=i,u=Lt(i,Xw);return new this(E(E(E({},e),u),{},{left:n,top:r,width:o,height:h,visible:!!(c&&o&&h)}))}}k(Ei,"type","Rect"),k(Ei,"cacheProperties",[...Zi,...$v]),k(Ei,"ownDefaults",{rx:0,ry:0}),k(Ei,"ATTRIBUTE_NAMES",[...Xn,"x","y","rx","ry","width","height"]),G.setClass(Ei),G.setSVGClass(Ei);const sn="initialization",Fu="added",fg="removed",Lu="imperative",qv=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?tl(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),c=!t.isStrokeAccountedForInDimensions(),u=e&&c?Km(new O(s,s),void 0,a.calcTransformMatrix()):Nf,d=!e&&c?s:0,f=yu(i+d,n+d,mu([o,t.calcOwnMatrix()],!0)).add(u).scalarDivide(2);return[h.subtract(f),h.add(f)]};class Iu{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===sn||e===Lu||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==sn&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Lu&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Ai(t.map(d=>qv(i,d)).reduce((d,f)=>d.concat(f),[])),c=new O(o,h),u=new O(n,r).add(c.scalarDivide(2));if(s===sn){const d=this.getInitialSize(e,{size:c,center:u});return{center:u,relativeCorrection:new O(0,0),size:d}}return{center:u.transform(i.calcOwnMatrix()),size:c}}}k(Iu,"type","strategy");class gg extends Iu{shouldPerformLayout(t){return!0}}k(gg,"type","fit-content"),G.setClass(gg);const Uw=["strategy"],Yw=["target","strategy","bubbles","prevStrategy"],Kv="layoutManager";class al{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new gg;k(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=E(E({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[fu,km,$h,Pm,cu,Mm,uu,D_,R_].map(i=>t.on(i,n=>this.performLayout(i===fu?{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===sn||s===Fu?this.subscribeTargets(t):s===fg&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Lu&&t.deep){const n=Lt(t,Uw);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(E(E({},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===sn?new O:e.getRelativeCenterPoint(),{center:o,correction:h=new O,relativeCorrection:c=new O}=n,u=r.subtract(o).add(h).transform(i===sn?He:ns(e.calcOwnMatrix()),!0).add(c);return{result:n,prevCenter:r,nextCenter:o,offset:u}}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===sn?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*se(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*se(s.originY)}):(s.setPositionByOrigin(n,rt,rt),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=Lt(t,Yw),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const c=s.parent;n&&c!=null&&c.layoutManager&&((o.path||(o.path=[])).push(s),c.layoutManager.performLayout(E(E({},o),{},{target:c}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Kv,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}G.setClass(al,Kv);const $w=["type","objects","layoutManager"];class qw extends al{performLayout(){}}class Fs extends Om(ke){static getDefaults(){return E(E({},super.getDefaults()),Fs.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),k(this,"_activeObjects",[]),k(this,"__objectSelectionTracker",void 0),k(this,"__objectSelectionDisposer",void 0),Object.assign(this,Fs.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 al,this.layoutManager.performLayout({type:sn,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(Ki("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(Ki("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(Fu,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(Fu,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(fg,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&&ba(t,qt(ns(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||(ba(t,qt(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=ke.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(...ns(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(E({target:this,type:Lu},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 E(E(E({},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=Ei.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",` >
66
+ `)}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=Ye.ownDefaults;return this.includeDefaultValues?t:Or(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}S(Ye,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),S(Ye,"type","shadow"),I.setClass(Ye,"shadow");const Ss=(o,t,e)=>Math.max(o,Math.min(t,e)),ou=[ie,ot,$t,ce,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Bs,Hs],$e=[kt,qt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],lu={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:ot,originY:ie,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:kt,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},Xr=(o,t,e,s)=>(o<Math.abs(t)?(o=t,s=e/4):s=t===0&&o===0?e/Ue*Math.asin(1):e/Ue*Math.asin(t/o),{a:o,c:t,p:e,s}),nl=(o,t,e,s,i)=>o*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*Ue/e),rl=(o,t,e,s)=>-e*Math.cos(o/s*is)+e+t,Ur=(o,t,e,s)=>(o/=s)<1/2.75?e*(7.5625*o*o)+t:o<2/2.75?e*(7.5625*(o-=1.5/2.75)*o+.75)+t:o<2.5/2.75?e*(7.5625*(o-=2.25/2.75)*o+.9375)+t:e*(7.5625*(o-=2.625/2.75)*o+.984375)+t,al=(o,t,e,s)=>e-Ur(s-o,0,e,s)+t;var hu=Object.freeze({__proto__:null,defaultEasing:rl,easeInBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*(o/=s)*o*((i+1)*o-i)+t},easeInBounce:al,easeInCirc:(o,t,e,s)=>-e*(Math.sqrt(1-(o/=s)*o)-1)+t,easeInCubic:(o,t,e,s)=>e*(o/s)**3+t,easeInElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:a,p:l}=Xr(i,e,n,1.70158);return-nl(r,a,l,o,s)+t},easeInExpo:(o,t,e,s)=>o===0?t:e*2**(10*(o/s-1))+t,easeInOutBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(o/=s/2)<1?e/2*(o*o*((1+(i*=1.525))*o-i))+t:e/2*((o-=2)*o*((1+(i*=1.525))*o+i)+2)+t},easeInOutBounce:(o,t,e,s)=>o<s/2?.5*al(2*o,0,e,s)+t:.5*Ur(2*o-s,0,e,s)+.5*e+t,easeInOutCirc:(o,t,e,s)=>(o/=s/2)<1?-e/2*(Math.sqrt(1-o**2)-1)+t:e/2*(Math.sqrt(1-(o-=2)*o)+1)+t,easeInOutCubic:(o,t,e,s)=>(o/=s/2)<1?e/2*o**3+t:e/2*((o-2)**3+2)+t,easeInOutElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:a,p:l,c:h}=Xr(i,e,n,1.70158);return o<1?-.5*nl(r,a,l,o,s)+t:r*Math.pow(2,-10*(o-=1))*Math.sin((o*s-a)*Ue/l)*.5+h+t},easeInOutExpo:(o,t,e,s)=>o===0?t:o===s?t+e:(o/=s/2)<1?e/2*2**(10*(o-1))+t:e/2*-(2**(-10*--o)+2)+t,easeInOutQuad:(o,t,e,s)=>(o/=s/2)<1?e/2*o**2+t:-e/2*(--o*(o-2)-1)+t,easeInOutQuart:(o,t,e,s)=>(o/=s/2)<1?e/2*o**4+t:-e/2*((o-=2)*o**3-2)+t,easeInOutQuint:(o,t,e,s)=>(o/=s/2)<1?e/2*o**5+t:e/2*((o-2)**5+2)+t,easeInOutSine:(o,t,e,s)=>-e/2*(Math.cos(Math.PI*o/s)-1)+t,easeInQuad:(o,t,e,s)=>e*(o/=s)*o+t,easeInQuart:(o,t,e,s)=>e*(o/=s)*o**3+t,easeInQuint:(o,t,e,s)=>e*(o/s)**5+t,easeInSine:(o,t,e,s)=>-e*Math.cos(o/s*is)+e+t,easeOutBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*((o=o/s-1)*o*((i+1)*o+i)+1)+t},easeOutBounce:Ur,easeOutCirc:(o,t,e,s)=>e*Math.sqrt(1-(o=o/s-1)*o)+t,easeOutCubic:(o,t,e,s)=>e*((o/s-1)**3+1)+t,easeOutElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:a,p:l,c:h}=Xr(i,e,n,1.70158);return r*2**(-10*o)*Math.sin((o*s-a)*Ue/l)+h+t},easeOutExpo:(o,t,e,s)=>o===s?t+e:e*-(2**(-10*o/s)+1)+t,easeOutQuad:(o,t,e,s)=>-e*(o/=s)*(o-2)+t,easeOutQuart:(o,t,e,s)=>-e*((o=o/s-1)*o**3-1)+t,easeOutQuint:(o,t,e,s)=>e*((o/s-1)**5+1)+t,easeOutSine:(o,t,e,s)=>e*Math.sin(o/s*is)+t});const cu=()=>!1;class Yr{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=rl,onStart:a=ps,onChange:l=ps,onComplete:h=ps,abort:c=cu,target:u}=t;S(this,"_state","pending"),S(this,"durationProgress",0),S(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=a,this._onChange=l,this._onComplete=h,this._abort=c,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(()=>gi(t),this.delay):gi(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),gi(this.tick)))}register(){qi.push(this)}unregister(){qi.remove(this)}abort(){this._state="aborted",this.unregister()}}const uu=["startValue","endValue"];class du extends Yr{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(x(x({},pt(t,uu)),{},{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 fu=["startValue","endValue"];class gu extends Yr{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(x(x({},pt(t,fu)),{},{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 pu=["startValue","endValue","easing","onChange","onComplete","abort"],mu=(o,t,e,s)=>t+e*(1-Math.cos(o/s*is)),$r=o=>o&&((t,e,s)=>o(new ht(t).toRgba(),e,s));class vu extends Yr{constructor(t){let{startValue:e,endValue:s,easing:i=mu,onChange:n,onComplete:r,abort:a}=t,l=pt(t,pu);const h=new ht(e).getSource(),c=new ht(s).getSource();super(x(x({},l),{},{startValue:h,byValue:c.map((u,d)=>u-h[d]),easing:i,onChange:$r(n),onComplete:$r(r),abort:$r(a)}))}calculate(t){const[e,s,i,n]=this.startValue.map((a,l)=>this.easing(t,a,this.byValue[l],this.duration,l)),r=[...[e,s,i].map(Math.round),Ss(0,n,1)];return{value:r,valueProgress:r.map((a,l)=>this.byValue[l]!==0?Math.abs((a-this.startValue[l])/this.byValue[l]):0).find(a=>a!==0)||0}}}function qr(o){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(o)?new gu(o):new du(o);return t.start(),t}function ol(o){const t=new vu(o);return t.start(),t}class yt{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=an(e,s),r=an(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 A(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 a=e.x-t.x,l=e.y-t.y,h=i.x-s.x,c=i.y-s.y,u=t.x-s.x,d=t.y-s.y,f=h*d-c*u,g=a*d-l*u,p=c*a-h*l;if(p!==0){const v=f/p,m=g/p;return(n||0<=v&&v<=1)&&(r||0<=m&&m<=1)?new yt("Intersection").append(new A(t.x+v*a,t.y+v*l)):new yt}if(f===0||g===0){const v=n||r||yt.isPointContained(t,s,i)||yt.isPointContained(e,s,i)||yt.isPointContained(s,t,e)||yt.isPointContained(i,t,e);return new yt(v?"Coincident":void 0)}return new yt("Parallel")}static intersectSegmentLine(t,e,s,i){return yt.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return yt.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 yt,r=s.length;for(let a,l,h,c=0;c<r;c++){if(a=s[c],l=s[(c+1)%r],h=yt.intersectLineLine(t,e,a,l,i,!1),h.status==="Coincident")return h;n.append(...h.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return yt.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new yt,i=t.length,n=[];for(let r=0;r<i;r++){const a=t[r],l=t[(r+1)%i],h=yt.intersectSegmentPolygon(a,l,e);h.status==="Coincident"?(n.push(h),s.append(a,l)):s.append(...h.points)}return n.length>0&&n.length===t.length?new yt("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 A(n.x,i.y),a=new A(i.x,n.y);return yt.intersectPolygonPolygon(t,[i,r,n,a])}}class bu extends po{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?Bt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Bt(t,ne(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new A(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(a=>Bt(a,r))}return n}intersectsWithRect(t,e){return yt.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=yt.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 yt.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 Ne(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set($t,t),this._set(ce,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?je(yo(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||Ut.concat()}calcACoords(){const t=bs({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=Vs(e,s),n=St(i,t),r=this._getTransformedDimensions(),a=r.x/2,l=r.y/2;return{tl:Bt({x:-a,y:-l},n),tr:Bt({x:a,y:-l},n),bl:Bt({x:-a,y:l},n),br:Bt({x:a,y:l},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,Pt(this.originX),Pt(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=St(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=wo(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new A(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=x({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,a=e.height+i;let l;return l=e.skewX===0&&e.skewY===0?new A(r*e.scaleX,a*e.scaleY):tn(r,a,pi(e)),l.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,a=t.y;const l=Pt(i)-Pt(e),h=Pt(n)-Pt(s);if(l||h){const c=this._getTransformedDimensions();r+=l*c.x,a+=h*c.y}return new A(r,a)}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(wt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,q,q,e,s);return this.angle?i.rotate(wt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Bt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new A(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(),ot,ie)}}const yu=["type"],_u=["extraParam"];let qe=class pr extends bu{static getDefaults(){return pr.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){Xe("warn","Setting type has no effect",t)}constructor(t){super(),S(this,"_cacheContext",null),Object.assign(this,pr.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Ie(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=nt.maxCacheSideLimit,n=nt.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=nt.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[a,l]=di.limitDimsByArea(r),h=Ss(n,a,i),c=Ss(n,l,i);return e>h&&(t.zoomX/=e/h,t.width=h,t.capped=!0),s>c&&(t.zoomY/=s/c,t.height=c,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:Math.ceil(s+2),height:Math.ceil(i+2),zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:i,zoomX:n,zoomY:r,x:a,y:l}=this._limitCacheSize(this._getCacheCanvasDimensions()),h=s!==t.width||i!==t.height,c=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(h||c){s!==t.width||i!==t.height?(t.width=s,t.height=i):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const u=a/2,d=l/2;return this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-d)+d,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}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 A(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=vs(this.calcTransformMatrix());return new A(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!==$t&&t!==ce||(e=this._constrainScale(e)),t===$t&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Ye||(e=new Ye(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:a}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n,width:r,height:a,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===qt&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),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=ue(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=ne(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,pe(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&&(pe(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&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,i=this.getCanvasRetinaScaling(),[n,,,r]=s?.viewportTransform||Ut,a=n*i,l=r*i,h=e.nonScaling?new A(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*nt.browserShadowBlurConstant*(a+l)*(h.x+h.y)/4,t.shadowOffsetX=e.offsetX*a*h.x,t.shadowOffsetY=e.offsetY*l*h.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!pe(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===qt?(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,a=i.y/this.scaleY/n,l=ue({width:Math.ceil(r),height:Math.ceil(a)}),h=l.getContext("2d");h&&(h.beginPath(),h.moveTo(0,0),h.lineTo(r,0),h.lineTo(r,a),h.lineTo(0,a),h.closePath(),h.translate(r/2,a/2),h.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(h,e),h.fillStyle=e.toLive(t),h.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=h.createPattern(l,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new A(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(I.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Rr(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?ho():1,a=(t.multiplier||1)*r,l=t.canvasProvider||(b=>new bi(b,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Do(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Fr(this,this.getViewportTransform()),this.setCoords();const h=Ie(),c=this.getBoundingRect(),u=this.shadow,d=new A;if(u){const b=u.blur,_=u.nonScaling?new A(1,1):this.getObjectScaling();d.x=2*Math.round(n(u.offsetX)+b)*n(_.x),d.y=2*Math.round(n(u.offsetY)+b)*n(_.y)}const f=c.width+d.x,g=c.height+d.y;h.width=Math.ceil(f),h.height=Math.ceil(g);const p=l(h);t.format==="jpeg"&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new A(p.width/2,p.height/2),q,q);const v=this.canvas;p._objects=[this],this.set("canvas",p),this.setCoords();const m=p.toCanvasElement(a||1,t);return this.set("canvas",v),this.shadow=i,s&&(this.group=s),this.set(e),this.setCoords(),p._objects=[],p.destroy(),m}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Er(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return kr(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(){qi.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Le().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:a,onChange:l,onComplete:h}=s,c=x(x({},s),{},{target:this,startValue:a??i.reduce((u,d)=>u[d],this),endValue:e,abort:r?.bind(this),onChange:(u,d,f)=>{i.reduce((g,p,v)=>(v===i.length-1&&(g[p]=u),g[p]),this),l&&l(u,d,f)},onComplete:(u,d,f)=>{this.setCoords(),h&&h(u,d,f)}});return n?ol(c):qr(c)}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),a=s._objects.indexOf(n);return r>-1&&r>a}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(pr.customProperties,this.constructor.customProperties||[]);let e;const s=nt.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:a,strokeDashArray:l,left:h,top:c,originX:u,originY:d,width:f,height:g,strokeWidth:p,strokeLineCap:v,strokeDashOffset:m,strokeLineJoin:b,strokeUniform:_,strokeMiterLimit:w,scaleX:C,scaleY:T,angle:E,flipX:k,flipY:O,opacity:H,visible:N,backgroundColor:P,fillRule:R,paintFirst:F,globalCompositeOperation:V,skewX:M,skewY:L}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const Y=bt=>ct(bt,s),ft=x(x({},ys(this,t)),{},{type:this.constructor.type,version:yr,originX:u,originY:d,left:Y(h),top:Y(c),width:Y(f),height:Y(g),fill:xo(n)?n.toObject():n,stroke:xo(r)?r.toObject():r,strokeWidth:Y(p),strokeDashArray:l&&l.concat(),strokeLineCap:v,strokeDashOffset:m,strokeLineJoin:b,strokeUniform:_,strokeMiterLimit:Y(w),scaleX:Y(C),scaleY:Y(T),angle:Y(E),flipX:k,flipY:O,opacity:Y(H),shadow:a&&a.toObject(),visible:N,backgroundColor:P,fillRule:R,paintFirst:F,globalCompositeOperation:V,skewX:Y(M),skewY:Y(L)},e?{clipPath:e}:null);return this.includeDefaultValues?ft:this._removeDefaultValues(ft)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Or(t,(i,n)=>{if(n===ot||n===ie||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=pt(t,yu),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=pt(s,_u);return vi(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)}};S(qe,"stateProperties",ou),S(qe,"cacheProperties",$e),S(qe,"ownDefaults",lu),S(qe,"type","FabricObject"),S(qe,"colorProperties",[kt,qt,"backgroundColor"]),S(qe,"customProperties",[]),I.setClass(qe),I.setClass(qe,"object");const Ys=(o,t,e)=>(s,i,n,r)=>{const a=t(s,i,n,r);return a&&Fo(o,x(x({},jo(s,i,n,r)),e)),a};function $s(o){return(t,e,s,i)=>{const{target:n,originX:r,originY:a}=e,l=n.getRelativeCenterPoint(),h=n.translateToOriginPoint(l,r,a),c=o(t,e,s,i);return n.setPositionByOrigin(h,e.originX,e.originY),c}}const ll=Ys(fi,$s((o,t,e,s)=>{const i=Lr(t,t.originX,t.originY,e,s);if(Pt(t.originX)===Pt(q)||Pt(t.originX)===Pt(xt)&&i.x<0||Pt(t.originX)===Pt(ot)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),a=Lo(t)?2:1,l=n.width,h=Math.abs(i.x*a/n.scaleX)-r;return n.set("width",Math.max(h,1)),l!==n.width}return!1}));function wu(o,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,l=a?qt:kt,h=!a&&(s.cornerStrokeColor||i.cornerStrokeColor);let c,u=t,d=e;o.save(),o.fillStyle=s.cornerColor||i.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(c=n,o.scale(1,r/n),d=e*n/r):r>n?(c=r,o.scale(n/r,1),u=t*r/n):c=n,o.beginPath(),o.arc(u,d,c/2,0,Ue,!1),o[l](),h&&o.stroke(),o.restore()}function xu(o,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,l=a?qt:kt,h=!a&&(s.cornerStrokeColor||i.cornerStrokeColor),c=n/2,u=r/2;o.save(),o.fillStyle=s.cornerColor||i.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",o.translate(t,e);const d=i.getTotalAngle();o.rotate(wt(d)),o["".concat(l,"Rect")](-c,-u,n,r),h&&o.strokeRect(-c,-u,n,r),o.restore()}class Ee{constructor(t){S(this,"visible",!0),S(this,"actionName",Yi),S(this,"angle",0),S(this,"x",0),S(this,"y",0),S(this,"offsetX",0),S(this,"offsetY",0),S(this,"sizeX",0),S(this,"sizeY",0),S(this,"touchSizeX",0),S(this,"touchSizeY",0),S(this,"cursorStyle","crosshair"),S(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:a,br:l,bl:h}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&yt.isPointInPolygon(s,[r,a,l,h])}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 A(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const a=Ji([Vs(s,i),bs({angle:t}),Qi((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new A(-.5,-.5).transform(a),tr:new A(.5,-.5).transform(a),br:new A(.5,.5).transform(a),bl:new A(-.5,.5).transform(a)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?wu.call(this,t,e,s,i,n):xu.call(this,t,e,s,i,n)}}const Su=(o,t,e)=>e.lockRotation?en:t.cursorStyle,Cu=Ys(uo,$s((o,t,e,s)=>{let{target:i,ex:n,ey:r,theta:a,originX:l,originY:h}=t;const c=i.translateToOriginPoint(i.getRelativeCenterPoint(),l,h);if(Ae(i,"lockRotation"))return!1;const u=Math.atan2(r-c.y,n-c.x),d=Math.atan2(s-c.y,e-c.x);let f=je(d-u+a);if(i.snapAngle&&i.snapAngle>0){const p=i.snapAngle,v=i.snapThreshold||p,m=Math.ceil(f/p)*p,b=Math.floor(f/p)*p;Math.abs(f-b)<v?f=b:Math.abs(f-m)<v&&(f=m)}f<0&&(f=360+f),f%=360;const g=i.angle!==f;return i.angle=f,g}));function hl(o,t){const e=t.canvas,s=o[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function cl(o,t,e){const s=Ae(o,"lockScalingX"),i=Ae(o,"lockScalingY");if(s&&i||!t&&(s||i)&&e||s&&t==="x"||i&&t==="y")return!0;const{width:n,height:r,strokeWidth:a}=o;return n===0&&a===0&&t!=="y"||r===0&&a===0&&t!=="x"}const Au=["e","se","s","sw","w","nw","n","ne","e"],Si=(o,t,e)=>{const s=hl(o,e);if(cl(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return en;const i=No(e,t);return"".concat(Au[i],"-resize")};function Kr(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,a=hl(o,n);let l,h,c,u,d,f;if(cl(n,r,a))return!1;if(t.gestureScale)h=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(l=Lr(t,t.originX,t.originY,e,s),d=r!=="y"?Math.sign(l.x||t.signX||1):1,f=r!=="x"?Math.sign(l.y||t.signY||1):1,t.signX||(t.signX=d),t.signY||(t.signY=f),Ae(n,"lockScalingFlip")&&(t.signX!==d||t.signY!==f))return!1;if(u=n._getTransformedDimensions(),a&&!r){const v=Math.abs(l.x)+Math.abs(l.y),{original:m}=t,b=v/(Math.abs(u.x*m.scaleX/n.scaleX)+Math.abs(u.y*m.scaleY/n.scaleY));h=m.scaleX*b,c=m.scaleY*b}else h=Math.abs(l.x*n.scaleX/u.x),c=Math.abs(l.y*n.scaleY/u.y);Lo(t)&&(h*=2,c*=2),t.signX!==d&&r!=="y"&&(t.originX=Io(t.originX),h*=-1,t.signX=d),t.signY!==f&&r!=="x"&&(t.originY=Io(t.originY),c*=-1,t.signY=f)}const g=n.scaleX,p=n.scaleY;return r?(r==="x"&&n.set($t,h),r==="y"&&n.set(ce,c)):(!Ae(n,"lockScalingX")&&n.set($t,h),!Ae(n,"lockScalingY")&&n.set(ce,c)),g!==n.scaleX||p!==n.scaleY}const cn=Ys(Xi,$s((o,t,e,s)=>Kr(o,t,e,s))),Tu=Ys(Xi,$s((o,t,e,s)=>Kr(o,t,e,s,{by:"x"}))),Eu=Ys(Xi,$s((o,t,e,s)=>Kr(o,t,e,s,{by:"y"}))),ku=["target","ex","ey","skewingSide"],Jr={x:{counterAxis:"y",scale:$t,skew:Bs,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:ce,skew:Hs,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Pu=["ns","nesw","ew","nwse"],Mu=(o,t,e)=>{if(t.x!==0&&Ae(e,"lockSkewingY")||t.y!==0&&Ae(e,"lockSkewingX"))return en;const s=No(e,t)%4;return"".concat(Pu[s],"-resize")};function ul(o,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:a,lockSkewing:l,skew:h,flip:c}=Jr[o];if(Ae(n,l))return!1;const{origin:u,flip:d}=Jr[r],f=Pt(e[u])*(n[d]?-1:1),g=-Math.sign(f)*(n[c]?-1:1),p=.5*-((n[h]===0&&Lr(e,q,q,s,i)[o]>0||n[h]>0?1:-1)*g)+.5;return Ys(fo,$s((m,b,_,w)=>function(C,T,E){let{target:k,ex:O,ey:H,skewingSide:N}=T,P=pt(T,ku);const{skew:R}=Jr[C],F=E.subtract(new A(O,H)).divide(new A(k.scaleX,k.scaleY))[C],V=k[R],M=P[R],L=Math.tan(wt(M)),Y=C==="y"?k._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:k._getTransformedDimensions({scaleX:1,scaleY:1}).y,ft=2*F*N/Math.max(Y,1)+L,bt=je(Math.atan(ft));k.set(R,bt);const _t=V!==k[R];if(_t&&C==="y"){const{skewX:gt,scaleX:rt}=k,Dt=k._getTransformedDimensions({skewY:V}),ee=k._getTransformedDimensions(),K=gt!==0?Dt.x/ee.x:1;K!==1&&k.set($t,K*rt)}return _t}(o,b,new A(_,w))))(t,x(x({},e),{},{[a]:p,skewingSide:g}),s,i)}const Ou=(o,t,e,s)=>ul("x",o,t,e,s),Du=(o,t,e,s)=>ul("y",o,t,e,s);function un(o,t){return o[t.canvas.altActionKey]}const dn=(o,t,e)=>{const s=un(o,e);return t.x===0?s?Bs:ce:t.y===0?s?Hs:$t:""},qs=(o,t,e)=>un(o,e)?Mu(0,t,e):Si(o,t,e),dl=(o,t,e,s)=>un(o,t.target)?Du(o,t,e,s):Tu(o,t,e,s),fl=(o,t,e,s)=>un(o,t.target)?Ou(o,t,e,s):Eu(o,t,e,s),gl=()=>({ml:new Ee({x:-.5,y:0,cursorStyleHandler:qs,actionHandler:dl,getActionName:dn}),mr:new Ee({x:.5,y:0,cursorStyleHandler:qs,actionHandler:dl,getActionName:dn}),mb:new Ee({x:0,y:.5,cursorStyleHandler:qs,actionHandler:fl,getActionName:dn}),mt:new Ee({x:0,y:-.5,cursorStyleHandler:qs,actionHandler:fl,getActionName:dn}),tl:new Ee({x:-.5,y:-.5,cursorStyleHandler:Si,actionHandler:cn}),tr:new Ee({x:.5,y:-.5,cursorStyleHandler:Si,actionHandler:cn}),bl:new Ee({x:-.5,y:.5,cursorStyleHandler:Si,actionHandler:cn}),br:new Ee({x:.5,y:.5,cursorStyleHandler:Si,actionHandler:cn}),mtr:new Ee({x:0,y:-.5,actionHandler:Cu,cursorStyleHandler:Su,offsetY:-40,withConnection:!0,actionName:Cr})}),Ru=()=>({mr:new Ee({x:.5,y:0,actionHandler:ll,cursorStyleHandler:qs,actionName:fi}),ml:new Ee({x:-.5,y:0,actionHandler:ll,cursorStyleHandler:qs,actionName:fi})}),Fu=()=>x(x({},gl()),Ru());class Ci extends qe{static getDefaults(){return x(x({},super.getDefaults()),Ci.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),Ci.ownDefaults),this.setOptions(t)}static createControls(){return{controls:gl()}}_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(Yi))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],a=this.controls[n];if(a.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:a,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=Vs(e.x,e.y),i=bs({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=St(s,i),r=St(t,n),a=St(r,[1/t[0],0,0,1/t[3],0,0]),l=this.group?vs(this.calcTransformMatrix()):void 0;l&&(l.scaleX=Math.abs(l.scaleX),l.scaleY=Math.abs(l.scaleY));const h=this._calculateCurrentDimensions(l),c={};return this.forEachControl((u,d)=>{const f=u.positionHandler(h,a,this,u);c[d]=Object.assign(f,this._calcCornerCoords(u,f))}),c}_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(wt(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=x({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=x({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),a=n.hasBorders,l=n.hasControls,h=St(r,this.calcTransformMatrix()),c=vs(h);t.save(),t.translate(c.translateX,c.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180),t.rotate(wt(this.group?c.angle:this.angle)),a&&this.drawBorders(t,c,e),l&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=tn(this.width,this.height,pi(e)),r=this.isStrokeAccountedForInDimensions()?Tr:(this.strokeUniform?new A().scalarAdd(this.canvas?this.canvas.getZoom():1):new A(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,a=x({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=a.cornerColor,this.transparentCorners||(t.strokeStyle=a.cornerStrokeColor),this._setLineDash(t,a.cornerDashArray),this.forEachControl((l,h)=>{if(l.getVisibility(this,h)){const c=this.oCoords[h];l.render(t,c.x,c.y,a,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 pl(o,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(o.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),o}S(Ci,"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 Ht extends Ci{}pl(Ht,[Go]),I.setClass(Ht),I.setClass(Ht,"object");const ml=(o,t,e,s)=>{const i=2*(s=Math.round(s))+1,{data:n}=o.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 vl{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new A(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new A(1/this.options.scaleX,1/this.options.scaleY):new A(1,1)}createSideVector(t,e){const s=an(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 A(t);return e.y+=e.x*Math.tan(wt(this.options.skewY)),e.x+=e.y*Math.tan(wt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const Lu=new A;class Ks extends vl{static getOrthogonalRotationFactor(t,e){const s=e?ln(t,e):tl(t);return Math.abs(s)<is?-1:1}constructor(t,e,s,i){super(i),S(this,"AB",void 0),S(this,"AC",void 0),S(this,"alpha",void 0),S(this,"bisector",void 0),this.A=new A(t),this.B=new A(e),this.C=new A(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=ln(this.AB,this.AC),this.bisector=hn(Vr(this.AB.eq(Lu)?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=Gr(i),r=Ks.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%Ue==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?on(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return on(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new A(Ks.getOrthogonalRotationFactor(this.bisector),Ks.getOrthogonalRotationFactor(new A(this.bisector.y,this.bisector.x)));return[new A(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new A(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{Wr(n,t,e)&&s.push(this.A.add(n))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:a,strokeUniform:l}=this.options,h=new A(Math.tan(wt(i)),Math.tan(wt(n))),c=this.strokeProjectionMagnitude,u=l?c/a/Math.sqrt(1/a**2+1/r**2*h.y**2):c/Math.sqrt(1+h.y**2),d=new A(Math.sqrt(Math.max(c**2-u**2,0)),u),f=l?c/Math.sqrt(1+h.x**2*(1/a)**2/(1/r+1/r*h.x*h.y)**2):c/Math.sqrt(1+h.x**2/(1+h.x*h.y)**2),g=new A(f,Math.sqrt(Math.max(c**2-f**2,0)));return[g,g.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(p=>this.applySkew(l?p.multiply(this.strokeUniformScalar):p)).forEach(p=>{Wr(p,t,e)&&s.push(this.applySkew(this.A).add(p))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Ue==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)),a=Us(i,r)>0,l=a?i:n,h=a?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(l,h)):t.push(...this.projectRoundNoSkew(l,h)),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 bl extends vl{constructor(t,e,s){super(s),this.A=new A(t),this.T=new A(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(Gr(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 A(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 Ks(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new A(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(hn(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 yl=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(o.length===0)return s;const i=o.reduce((n,r)=>(n[n.length-1].eq(r)||n.push(new A(r)),n),[new A(o[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((a,l)=>{for(let h=a.length-1;h>=0;h--)if(l(a[h],h,a))return h;return-1})(i,a=>!a.eq(n));i.splice(r+1)}return i.forEach((n,r,a)=>{let l,h;r===0?(h=a[1],l=e?n:a[a.length-1]):r===a.length-1?(l=a[r-1],h=e?n:a[0]):(l=a[r-1],h=a[r+1]),e&&a.length===1?s.push(...new bl(n,n,t).project()):!e||r!==0&&r!==a.length-1?s.push(...new Ks(n,l,h,t).project()):s.push(...new bl(n,r===0?h:l,t).project())}),s},Qr=o=>{const t={};return Object.keys(o).forEach(e=>{t[e]={},Object.keys(o[e]).forEach(s=>{t[e][s]=x({},o[e][s])})}),t},_l=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let Ai;const fn=o=>{if(Ai||Ai||(Ai="Intl"in ui()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),Ai){const t=Ai.segment(o);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return Iu(o)},Iu=o=>{const t=[];for(let e,s=0;s<o.length;s++)(e=ju(o,s))!==!1&&t.push(e);return t},ju=(o,t)=>{const e=o.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return o.charAt(t);if(55296<=e&&e<=56319){if(o.length<=t+1)throw"High surrogate without following low surrogate";const i=o.charCodeAt(t+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return o.charAt(t)+o.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=o.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var Nu=Object.freeze({__proto__:null,capitalize:function(o){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(o.charAt(0).toUpperCase()).concat(t?o.slice(1):o.slice(1).toLowerCase())},escapeXml:_l,graphemeSplit:fn});const gn=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return o.fill!==t.fill||o.stroke!==t.stroke||o.strokeWidth!==t.strokeWidth||o.fontSize!==t.fontSize||o.fontFamily!==t.fontFamily||o.fontWeight!==t.fontWeight||o.fontStyle!==t.fontStyle||o.textDecorationThickness!==t.textDecorationThickness||o.textBackgroundColor!==t.textBackgroundColor||o.deltaY!==t.deltaY||e&&(o.overline!==t.overline||o.underline!==t.underline||o.linethrough!==t.linethrough)},wl=(o,t)=>{const e=t.split(`
67
+ `),s=[];let i=-1,n={};o=Qr(o);for(let r=0;r<e.length;r++){const a=fn(e[r]);if(o[r])for(let l=0;l<a.length;l++){i++;const h=o[r][l];h&&Object.keys(h).length>0&&(gn(n,h,!0)?s.push({start:i,end:i+1,style:h}):s[s.length-1].end++),n=h||{}}else i+=a.length,n={}}return s},xl=(o,t)=>{if(!Array.isArray(o))return Qr(o);const e=t.split(Sr),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const a=fn(e[r]);for(let l=0;l<a.length;l++)i++,o[n]&&o[n].start<=i&&i<o[n].end&&(s[r]=s[r]||{},s[r][l]=x({},o[n].style),i===o[n].end-1&&n++)}return s},as=["display","transform",kt,"fill-opacity","fill-rule","opacity",qt,"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 Sl(o,t){const e=o.nodeName,s=o.getAttribute("class"),i=o.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 a=s.split(" ");for(let l=a.length;l--;)r=new RegExp("\\."+a[l]+n,"i"),t=t.replace(r,"")}return t.length===0}function Bu(o,t){let e=!0;const s=Sl(o,t.pop());return s&&t.length&&(e=function(i,n){let r,a=!0;for(;i.parentElement&&i.parentElement.nodeType===1&&n.length;)a&&(r=n.pop()),a=Sl(i=i.parentElement,r);return n.length===0}(o,t)),s&&e&&t.length===0}const Hu=o=>{var t;return(t=iu[o])!==null&&t!==void 0?t:o},zu=new RegExp("(".concat(Te,")"),"gi"),Vu=o=>o.replace(zu," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var Cl,Al,Tl,El,kl,Pl,Ml;const Jt="(".concat(Te,")"),Gu=String.raw(Cl||(Cl=Re(["(skewX)(",")"],["(skewX)\\(","\\)"])),Jt),Wu=String.raw(Al||(Al=Re(["(skewY)(",")"],["(skewY)\\(","\\)"])),Jt),Xu=String.raw(Tl||(Tl=Re(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Jt,Jt,Jt),Uu=String.raw(El||(El=Re(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Jt,Jt),Yu=String.raw(kl||(kl=Re(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Jt,Jt),$u=String.raw(Pl||(Pl=Re(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Jt,Jt,Jt,Jt,Jt,Jt),Zr="(?:".concat($u,"|").concat(Yu,"|").concat(Xu,"|").concat(Uu,"|").concat(Gu,"|").concat(Wu,")"),qu="(?:".concat(Zr,"*)"),Ku=String.raw(Ml||(Ml=Re(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),qu),Ju=new RegExp(Ku),Qu=new RegExp(Zr),Zu=new RegExp(Zr,"g");function pn(o){const t=[];if(!(o=Vu(o).replace(/\s*([()])\s*/gi,"$1"))||o&&!Ju.test(o))return[...Ut];for(const e of o.matchAll(Zu)){const s=Qu.exec(e[0]);if(!s)continue;let i=Ut;const n=s.filter(g=>!!g),[,r,...a]=n,[l,h,c,u,d,f]=a.map(g=>parseFloat(g));switch(r){case"translate":i=Vs(l,h);break;case Cr:i=bs({angle:l},{x:h,y:c});break;case Yi:i=Qi(l,h);break;case Bs:i=Pr(l);break;case Hs:i=Mr(l);break;case"matrix":i=[l,h,c,u,d,f]}t.push(i)}return Ji(t)}function td(o,t,e,s){const i=Array.isArray(t);let n,r=t;if(o!==kt&&o!==qt||t!==Yt){if(o==="strokeUniform")return t==="non-scaling-stroke";if(o==="strokeDashArray")r=t===Yt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(o==="transformMatrix")r=e&&e.transformMatrix?St(e.transformMatrix,pn(t)):pn(t);else if(o==="visible")r=t!==Yt&&t!=="hidden",e&&e.visible===!1&&(r=!1);else if(o==="opacity")r=parseFloat(t),e&&e.opacity!==void 0&&(r*=e.opacity);else if(o==="textAnchor")r=t==="start"?ot:t==="end"?xt:q;else if(o==="charSpacing"||o===xs)n=Kt(t,s)/s*1e3;else if(o==="paintFirst"){const a=t.indexOf(kt),l=t.indexOf(qt);r=kt,(a>-1&&l>-1&&l<a||a===-1&&l>-1)&&(r=qt)}else{if(o==="href"||o==="xlink:href"||o==="font"||o==="id")return t;if(o==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(Kt):Kt(t,s)}}else r="";return!i&&isNaN(n)?r:n}function ed(o,t){const e=o.match(su);if(!e)return;const s=e[1],i=e[3],n=e[4],r=e[5],a=e[6];s&&(t.fontStyle=s),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),n&&(t.fontSize=Kt(n)),a&&(t.fontFamily=a),r&&(t.lineHeight=r==="normal"?1:r)}function ta(o,t){o.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function sd(o){const t={},e=o.getAttribute("style");return e&&(typeof e=="string"?ta(e,t):function(s,i){Object.entries(s).forEach(n=>{let[r,a]=n;a!==void 0&&(i[r.toLowerCase()]=a)})}(e,t)),t}const id={stroke:"strokeOpacity",fill:"fillOpacity"};function Ke(o,t,e){if(!o)return{};let s,i={},n=wr;o.parentNode&&Jo.test(o.parentNode.nodeName)&&(i=Ke(o.parentElement,t,e),i.fontSize&&(s=n=Kt(i.fontSize)));const r=x(x(x({},t.reduce((h,c)=>{const u=o.getAttribute(c);return u&&(h[c]=u),h},{})),function(h){let c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const d in c)Bu(h,d.split(" "))&&(u=x(x({},u),c[d]));return u}(o,e)),sd(o));r[zr]&&o.setAttribute(zr,r[zr]),r[Hr]&&(s=Kt(r[Hr],n),r[Hr]="".concat(s));const a={};for(const h in r){const c=Hu(h),u=td(c,r[h],i,s);a[c]=u}a&&a.font&&ed(a.font,a);const l=x(x({},i),a);return Jo.test(o.nodeName)?l:function(h){const c=Ht.getDefaults();return Object.entries(id).forEach(u=>{let[d,f]=u;if(h[f]===void 0||h[d]==="")return;if(h[d]===void 0){if(!c[d])return;h[d]=c[d]}if(h[d].indexOf("url(")===0)return;const g=new ht(h[d]);h[d]=g.setAlpha(ct(g.getAlpha()*h[f],2)).toRgba()}),h}(l)}const nd=["left","top","width","height","visible"],Ol=["rx","ry"];class He extends Ht{static getDefaults(){return x(x({},super.getDefaults()),He.ownDefaults)}constructor(t){super(),Object.assign(this,He.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,a=this.ry?Math.min(this.ry,s/2):0,l=r!==0||a!==0;t.beginPath(),t.moveTo(i+r,n),t.lineTo(i+e-r,n),l&&t.bezierCurveTo(i+e-ns*r,n,i+e,n+ns*a,i+e,n+a),t.lineTo(i+e,n+s-a),l&&t.bezierCurveTo(i+e,n+s-ns*a,i+e-ns*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),l&&t.bezierCurveTo(i+ns*r,n+s,i,n+s-ns*a,i,n+s-a),t.lineTo(i,n+a),l&&t.bezierCurveTo(i,n+ns*a,i+ns*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([...Ol,...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,`" />
68
+ `)]}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:a=0,height:l=0,visible:h=!0}=i,c=pt(i,nd);return new this(x(x(x({},e),c),{},{left:n,top:r,width:a,height:l,visible:!!(h&&a&&l)}))}}S(He,"type","Rect"),S(He,"cacheProperties",[...$e,...Ol]),S(He,"ownDefaults",{rx:0,ry:0}),S(He,"ATTRIBUTE_NAMES",[...as,"x","y","rx","ry","width","height"]),I.setClass(He),I.setSVGClass(He);const Je="initialization",mn="added",ea="removed",vn="imperative",Dl=(o,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,a=r&&r!==o?yi(r.calcTransformMatrix(),o.calcTransformMatrix()):null,l=a?t.getRelativeCenterPoint().transform(a):t.getRelativeCenterPoint(),h=!t.isStrokeAccountedForInDimensions(),c=e&&h?Ro(new A(s,s),void 0,o.calcTransformMatrix()):Tr,u=!e&&h?s:0,d=tn(i+u,n+u,Ji([a,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[l.subtract(d),l.add(d)]};class bn{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===Je||e===vn||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Je&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===vn&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:a,height:l}=Ne(t.map(u=>Dl(i,u)).reduce((u,d)=>u.concat(d),[])),h=new A(a,l),c=new A(n,r).add(h.scalarDivide(2));if(s===Je){const u=this.getInitialSize(e,{size:h,center:c});return{center:c,relativeCorrection:new A(0,0),size:u}}return{center:c.transform(i.calcOwnMatrix()),size:h}}}S(bn,"type","strategy");class sa extends bn{shouldPerformLayout(t){return!0}}S(sa,"type","fit-content"),I.setClass(sa);const rd=["strategy"],ad=["target","strategy","bubbles","prevStrategy"],Rl="layoutManager";class Ti{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new sa;S(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=x(x({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[$i,co,fi,uo,Xi,fo,Ui,Xc,Uc].map(i=>t.on(i,n=>this.performLayout(i===$i?{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===Je||s===mn?this.subscribeTargets(t):s===ea&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===vn&&t.deep){const n=pt(t,rd);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(x(x({},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===Je?new A:e.getRelativeCenterPoint(),{center:a,correction:l=new A,relativeCorrection:h=new A}=n,c=r.subtract(a).add(l).transform(i===Je?Ut:ne(e.calcOwnMatrix()),!0).add(h);return{result:n,prevCenter:r,nextCenter:a,offset:c}}commitLayout(t,e){const{target:s}=t,{result:{size:i},nextCenter:n}=e;var r,a;s.set({width:i.x,height:i.y}),this.layoutObjects(t,e),t.type===Je?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*Pt(s.originX),top:(a=t.y)!==null&&a!==void 0?a:n.y+i.y*Pt(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,a=pt(t,ad),{canvas:l}=s;s.fire("layout:after",{context:t,result:e}),l&&l.fire("object:layout:after",{context:t,result:e,target:s});const h=s.parent;n&&h!=null&&h.layoutManager&&((a.path||(a.path=[])).push(s),h.layoutManager.performLayout(x(x({},a),{},{target:h}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Rl,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}I.setClass(Ti,Rl);const od=["type","objects","layoutManager"];class ld extends Ti{performLayout(){}}class me extends go(Ht){static getDefaults(){return x(x({},super.getDefaults()),me.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),S(this,"_activeObjects",[]),S(this,"__objectSelectionTracker",void 0),S(this,"__objectSelectionDisposer",void 0),Object.assign(this,me.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 Ti,this.layoutManager.performLayout({type:Je,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(Xe("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(Xe("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(mn,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(mn,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(ea,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&&Xs(t,St(ne(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||(Xs(t,St(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=Ht.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(...ne(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(x({target:this,type:vn},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 x(x(x({},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=He.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",` >
69
69
  `],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>
70
- `),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=Lt(t,$w);return Promise.all([ma(i,e),Qh(r,e)]).then(o=>{let[h,c]=o;const u=new this(h,E(E(E({},r),c),{},{layoutManager:new qw}));if(n){const d=G.getClass(n.type),f=G.getClass(n.strategy);u.layoutManager=new d(new f)}else u.layoutManager=new al;return u.layoutManager.subscribeTargets({type:sn,target:u,targets:u.getObjects()}),u.setCoords(),u})}}k(Fs,"type","Group"),k(Fs,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),G.setClass(Fs);const Jv=(a,t)=>Math.min(t.width/a.width,t.height/a.height),Qv=(a,t)=>Math.max(t.width/a.width,t.height/a.height),pg="\\s*,?\\s*",hl="".concat(pg,"(").concat(Zs,")"),Kw="".concat(hl).concat(hl).concat(hl).concat(pg,"([01])").concat(pg,"([01])").concat(hl).concat(hl),Jw={m:"l",M:"L"},Qw=(a,t,e,s,i,n,r,o,h,c,u)=>{const d=qs(a),f=Ks(a),g=qs(t),p=Ks(t),m=e*i*g-s*n*p+r,y=s*i*g+e*n*p+o;return["C",c+h*(-e*i*f-s*n*d),u+h*(-s*i*f+e*n*d),m+h*(e*i*p+s*n*g),y+h*(s*i*p-e*n*g),m,y]},Zv=(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 mg(a,t,e,s,i,n,r,o){let h;if(mt.cachesBoundsOfCurve&&(h=[...arguments].join(),Yh.boundsOfCurveCache[h]))return Yh.boundsOfCurveCache[h];const c=Math.sqrt,u=Math.abs,d=[],f=[[0,0],[0,0]];let g=6*a-12*e+6*i,p=-3*a+9*e-9*i+3*r,m=3*e-3*a;for(let S=0;S<2;++S){if(S>0&&(g=6*t-12*s+6*n,p=-3*t+9*s-9*n+3*o,m=3*s-3*t),u(p)<1e-12){if(u(g)<1e-12)continue;const R=-m/g;0<R&&R<1&&d.push(R);continue}const T=g*g-4*m*p;if(T<0)continue;const P=c(T),M=(-g+P)/(2*p);0<M&&M<1&&d.push(M);const D=(-g-P)/(2*p);0<D&&D<1&&d.push(D)}let y=d.length;const b=y,x=e0(a,t,e,s,i,n,r,o);for(;y--;){const{x:S,y:T}=x(d[y]);f[0][y]=S,f[1][y]=T}f[0][b]=a,f[1][b]=t,f[0][b+1]=r,f[1][b+1]=o;const C=[new O(Math.min(...f[0]),Math.min(...f[1])),new O(Math.max(...f[0]),Math.max(...f[1]))];return mt.cachesBoundsOfCurve&&(Yh.boundsOfCurveCache[h]=C),C}const Zw=(a,t,e)=>{let[s,i,n,r,o,h,c,u]=e;const d=((f,g,p,m,y,b,x)=>{if(p===0||m===0)return[];let C=0,S=0,T=0;const P=Math.PI,M=x*Df,D=Ks(M),R=qs(M),V=.5*(-R*f-D*g),H=.5*(-R*g+D*f),F=p**2,I=m**2,j=H**2,K=V**2,L=F*I-F*j-I*K;let z=Math.abs(p),Z=Math.abs(m);if(L<0){const Te=Math.sqrt(1-L/(F*I));z*=Te,Z*=Te}else T=(y===b?-1:1)*Math.sqrt(L/(F*j+I*K));const Dt=T*z*H/Z,Bt=-T*Z*V/z,Xt=R*Dt-D*Bt+.5*f,Ft=D*Dt+R*Bt+.5*g;let _t=Zv(1,0,(V-Dt)/z,(H-Bt)/Z),oe=Zv((V-Dt)/z,(H-Bt)/Z,(-V-Dt)/z,(-H-Bt)/Z);b===0&&oe>0?oe-=2*P:b===1&&oe<0&&(oe+=2*P);const Ze=Math.ceil(Math.abs(oe/P*2)),it=[],nt=oe/Ze,Zt=8/3*Math.sin(nt/4)*Math.sin(nt/4)/Math.sin(nt/2);let Ys=_t+nt;for(let Te=0;Te<Ze;Te++)it[Te]=Qw(_t,Ys,R,D,z,Z,Xt,Ft,Zt,C,S),C=it[Te][5],S=it[Te][6],_t=Ys,Ys+=nt;return it})(c-a,u-t,i,n,o,h,r);for(let f=0,g=d.length;f<g;f++)d[f][1]+=a,d[f][2]+=t,d[f][3]+=a,d[f][4]+=t,d[f][5]+=a,d[f][6]+=t;return d},t0=a=>{let t=0,e=0,s=0,i=0;const n=[];let r,o=0,h=0;for(const c of a){const u=[...c];let d;switch(u[0]){case"l":u[1]+=t,u[2]+=e;case"L":t=u[1],e=u[2],d=["L",t,e];break;case"h":u[1]+=t;case"H":t=u[1],d=["L",t,e];break;case"v":u[1]+=e;case"V":e=u[1],d=["L",t,e];break;case"m":u[1]+=t,u[2]+=e;case"M":t=u[1],e=u[2],s=u[1],i=u[2],d=["M",t,e];break;case"c":u[1]+=t,u[2]+=e,u[3]+=t,u[4]+=e,u[5]+=t,u[6]+=e;case"C":o=u[3],h=u[4],t=u[5],e=u[6],d=["C",u[1],u[2],o,h,t,e];break;case"s":u[1]+=t,u[2]+=e,u[3]+=t,u[4]+=e;case"S":r==="C"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=u[3],e=u[4],d=["C",o,h,u[1],u[2],t,e],o=d[3],h=d[4];break;case"q":u[1]+=t,u[2]+=e,u[3]+=t,u[4]+=e;case"Q":o=u[1],h=u[2],t=u[3],e=u[4],d=["Q",o,h,t,e];break;case"t":u[1]+=t,u[2]+=e;case"T":r==="Q"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=u[1],e=u[2],d=["Q",o,h,t,e];break;case"a":u[6]+=t,u[7]+=e;case"A":Zw(t,e,u).forEach(f=>n.push(f)),t=u[6],e=u[7];break;case"z":case"Z":t=s,e=i,d=["Z"]}d?(n.push(d),r=d[0]):r=""}return n},ju=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),e0=(a,t,e,s,i,n,r,o)=>h=>{const c=h**3,u=(g=>3*g**2*(1-g))(h),d=(g=>3*g*(1-g)**2)(h),f=(g=>(1-g)**3)(h);return new O(r*c+i*u+e*d+a*f,o*c+n*u+s*d+t*f)},s0=a=>a**2,i0=a=>2*a*(1-a),n0=a=>(1-a)**2,tx=(a,t,e,s,i,n,r,o)=>h=>{const c=s0(h),u=i0(h),d=n0(h),f=3*(d*(e-a)+u*(i-e)+c*(r-i)),g=3*(d*(s-t)+u*(n-s)+c*(o-n));return Math.atan2(g,f)},ex=(a,t,e,s,i,n)=>r=>{const o=s0(r),h=i0(r),c=n0(r);return new O(i*o+e*h+a*c,n*o+s*h+t*c)},sx=(a,t,e,s,i,n)=>r=>{const o=1-r,h=2*(o*(e-a)+r*(i-e)),c=2*(o*(s-t)+r*(n-s));return Math.atan2(c,h)},r0=(a,t,e)=>{let s=new O(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=ju(s.x,s.y,r.x,r.y),s=r}return i},ix=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=E({},n),o=.01,h=0;const c=a.iterator,u=a.angleFinder;for(;i<t&&o>1e-4;)r=c(s),h=s,e=ju(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return E(E({},r),{},{angle:u(h)})},vg=a=>{let t,e,s=0,i=0,n=0,r=0,o=0;const h=[];for(const c of a){const u={x:i,y:n,command:c[0],length:0};switch(c[0]){case"M":e=u,e.x=r=i=c[1],e.y=o=n=c[2];break;case"L":e=u,e.length=ju(i,n,c[1],c[2]),i=c[1],n=c[2];break;case"C":t=e0(i,n,c[1],c[2],c[3],c[4],c[5],c[6]),e=u,e.iterator=t,e.angleFinder=tx(i,n,c[1],c[2],c[3],c[4],c[5],c[6]),e.length=r0(t,i,n),i=c[5],n=c[6];break;case"Q":t=ex(i,n,c[1],c[2],c[3],c[4]),e=u,e.iterator=t,e.angleFinder=sx(i,n,c[1],c[2],c[3],c[4]),e.length=r0(t,i,n),i=c[3],n=c[4];break;case"Z":e=u,e.destX=r,e.destY=o,e.length=ju(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},o0=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:vg(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 E(E({},new O(i.x,i.y).lerp(new O(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return E(E({},new O(i.x,i.y).lerp(new O(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return ix(i,t)}},nx=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),a0=new RegExp(Kw,"g"),rx=new RegExp(Zs,"gi"),ox={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},h0=a=>{var t;const e=[],s=(t=a.match(nx))!==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=ox[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){a0.lastIndex=0;for(let h=null;h=a0.exec(i);)o.push(...h.slice(1))}else o=i.match(rx)||[];for(let h=0;h<o.length;h+=r){const c=new Array(r),u=Jw[n];c[0]=h>0&&u?u:n;for(let d=0;d<r;d++)c[d+1]=parseFloat(o[h+d]);e.push(c)}}return e},ax=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new O(a[0]),s=new O(a[1]),i=1,n=0;const r=[],o=a.length,h=o>2;let c;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]),c=1;c<o;c++){if(!e.eq(s)){const u=e.midPointFrom(s);r.push(["Q",e.x,e.y,u.x,u.y])}e=a[c],c+1<a.length&&(s=a[c+1])}return h&&(i=e.x>a[c-2].x?1:e.x===a[c-2].x?0:-1,n=e.y>a[c-2].y?1:e.y===a[c-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},l0=(a,t)=>a.map(e=>e.map((s,i)=>i===0||t===void 0?s:kt(s,t)).join(" ")).join(" ");function Nu(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 hx=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function c0(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||Rr,s=new(Uh()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=Rr};if(i&&i.aborted)throw new Mf("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=Rr)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const Bu=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=Lr(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Ve,i),s.set(gs,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,rt,rt)};var lx=Object.freeze({__proto__:null,addTransformToObject:$m,animate:ag,animateColor:Cv,applyTransformToObject:ba,calcAngleBetweenVectors:Tu,calcDimensionsMatrix:Kh,calcPlaneChangeMatrix:tl,calcVectorRotation:vv,cancelAnimFrame:Rm,capValue:zr,composeMatrix:Nm,copyCanvasElement:a=>{var t;const e=ps(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:qs,createCanvasElement:Si,createImage:Fm,createRotateMatrix:Ir,createScaleMatrix:vu,createSkewXMatrix:zf,createSkewYMatrix:Vf,createTranslateMatrix:pa,createVector:Cu,crossProduct:ya,degreesToRadians:Ut,dotProduct:bv,ease:K_,enlivenObjectEnlivables:Qh,enlivenObjects:ma,findScaleToCover:Qv,findScaleToFit:Jv,getBoundsOfCurve:mg,getOrthonormalVector:eg,getPathSegmentsInfo:vg,getPointOnPath:o0,getPointer:Um,getRandomInt:hx,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-Vn;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 O(qs(r),Ks(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:ax,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:Eu,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new Fs(a,t),hasStyleChanged:Du,invertTransform:ns,isBetweenVectors:sg,isIdentityMatrix:Lm,isTouchEvent:bu,isTransparent:Rv,joinPath:l0,loadImage:Jh,magnitude:Au,makeBoundingBoxFromPoints:Ai,makePathSimpler:t0,matrixToSVG:va,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),Uf(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 Fs([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:qt,multiplyTransformMatrixArray:mu,parsePath:h0,parsePreserveAspectRatioAttribute:qf,parseUnit:We,pick:jr,projectStrokeOnPoints:Iv,qrDecompose:Lr,radiansToDegrees:Ci,removeFromArray:Fr,removeTransformFromObject:(a,t)=>{const e=ns(t),s=qt(e,a.calcOwnMatrix());ba(a,s)},removeTransformMatrixForSvgParsing:Bu,request:c0,requestAnimFrame:qh,resetObjectTransform:qm,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:tg,saveObjectTransform:Xf,sendObjectToPlane:Uf,sendPointToPlane:Br,sendVectorToPlane:Km,setStyle:Nu,sin:Ks,sizeAfterTransform:yu,string:Aw,stylesFromArray:Bv,stylesToArray:Nv,toBlob:Hf,toDataURL:Bf,toFixed:kt,transformPath:(a,t,e)=>(e&&(t=qt(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}=Ee({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i})),transformPoint:Ee});class cx extends Xm{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),k(this,"upper",void 0),k(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=Si();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=ua().createElement("div");return t.setAttribute("data-fabric","wrapper"),Nu(t,{position:"relative"}),Wm(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;Nu(t,E(E({},s),{},{"touch-action":i?"manipulation":ze})),Wm(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;Gm(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Wf(this.upper.el,t),Wf(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(),xi().dispose(this.upper.el),delete this.upper,delete this.container}}class Hu extends Zh{constructor(){super(...arguments),k(this,"targets",[]),k(this,"_hoveredTargets",[]),k(this,"_objectsToRender",void 0),k(this,"_currentTransform",null),k(this,"_groupSelector",null),k(this,"contextTopDirty",!1)}static getDefaults(){return E(E({},super.getDefaults()),Hu.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 cx(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 Rv(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===du||e===Ve||e===gs||e===$h?i=this.centeredScaling||t.centeredScaling:e===If&&(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=$t:["mr","tr","br"].includes(e)&&(s.x=wt),["tl","mt","tr"].includes(e)?s.y=Ff:["bl","mb","br"].includes(e)&&(s.y=is)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?Br(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):H_,c=((g,p,m,y)=>{if(!p||!g)return"drag";const b=y.controls[p];return b.getActionName(m,b,y)})(s,r,t,e),u=t[this.centeredKey],d=this._shouldCenterTransform(e,c,u)?{x:rt,y:rt}:this._getOriginFromCorner(e,r),f={target:e,action:c,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:d.x,originY:d.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:Ut(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:u,original:E(E({},Xf(e)),{},{originX:d.x,originY:d.y})};this._currentTransform=f,this.fire("before:transform",{e:t,transform:f})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new O(e,s).transform(this.viewportTransform),o=new O(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let c=Math.min(r.x,o.x),u=Math.min(r.y,o.y),d=Math.max(r.x,o.x),f=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(c,u,d-c,f-u)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,c+=h,u+=h,d-=h,f-=h,ke.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(c,u,d-c,f-u))}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,bu(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,c]=s,u=Math.atan2(o.y-r.y,o.x-r.x),d=qs(u)*n,f=Ks(u)*n,g=d+f,p=d-f;s=[new O(r.x-p,r.y-g),new O(o.x+g,o.y-p),new O(h.x+p,h.y+g),new O(c.x-g,c.y+p)]}return zt.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,Br(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(pu(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&&pu(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!pu(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=Um(t),r=i.width||0,o=i.height||0;r&&o||(is in i&&Ff in i&&(o=Math.abs(i.top-i.bottom)),$t in i&&wt 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=Br(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const c=r===0||o===0?new O(1,1):new O(s.width/r,s.height/o);return n.multiply(c)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Si(),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 Nr(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,Nr(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),Nr(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(fu,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;Nr(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&&Nr(e)&&this._activeObject===e){const s=jr(t,["angle","flipX","flipY",wt,Ve,gs,da,fa,is]);return $m(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}k(Hu,"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 ux{constructor(t){k(this,"targets",[]),k(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),Fr(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 dx=["target","oldTarget","fireCanvas","e"],ms={passive:!1},Ca=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},Un=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)},Ls=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)},fx={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 bg extends Hu{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),k(this,"_isClick",void 0),k(this,"textEditingManager",new ux(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(Un,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Vm(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,ms),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,"click",this._onClick),t(s,"dblclick",this._onClick),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,ms)}removeListeners(){this.addOrRemove(Ls,"remove");const t=this._getEventPrefix(),e=Js(this.upperCanvasEl);Ls(e,"".concat(t,"up"),this._onMouseUp),Ls(e,"touchend",this._onTouchEnd,ms),Ls(e,"".concat(t,"move"),this._onMouseMove,ms),Ls(e,"touchmove",this._onMouseMove,ms),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=E({e:t},Ca(this,t));this.fire("mouse:out",E(E({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",E({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",E(E({},s),{},{target:i})),i&&i.fire("mouseout",E({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",E({e:t},Ca(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 Un(this.upperCanvasEl,"drag",this._onDragProgress)}Ym(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!==ze,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};Ls(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 c=i[h];c.canDrop(t)&&(o=c),c.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",E({e:t,target:e,subTargets:s,dragSource:this._dragSource},Ca(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&&Ym(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),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=Js(i);Un(r,"touchend",this._onTouchEnd,ms),e&&Un(r,"touchmove",this._onMouseMove,ms),Ls(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();Ls(e,"".concat(s,"move"),this._onMouseMove,ms);const i=Js(e);Un(i,"".concat(s,"up"),this._onMouseUp),Un(i,"".concat(s,"move"),this._onMouseMove,ms)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=Js(this.upperCanvasEl);Ls(s,"touchend",this._onTouchEnd,ms),Ls(s,"touchmove",this._onMouseMove,ms),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{Un(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=Js(this.upperCanvasEl);Ls(i,"".concat(s,"up"),this._onMouseUp),Ls(i,"".concat(s,"move"),this._onMouseMove,ms),Un(e,"".concat(s,"move"),this._onMouseMove,ms)}}_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,c=!1;if(s&&(this._finalizeCurrentTransform(t),c=s.actionPerformed),!i){const u=n===this._activeObject;this.handleSelection(t),c||(c=this._shouldRender(n)||!u&&n===this._activeObject)}if(n){const u=n.findControl(this.getViewportPoint(t),bu(t)),{key:d,control:f}=u||{};if(h=d,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),c=!0;else if(f){const g=f.getMouseUpHandler(t,n,f);g&&(o=this.getScenePoint(t),g.call(f,t,s,o.x,o.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const u=s.target&&s.target.controls[s.corner],d=u&&u.getMouseUpHandler(t,s.target,u);o=o||this.getScenePoint(t),d&&d.call(u,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),c?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,s){const i=this._target,n=this.targets||[],r=E(E(E({e:t,target:i,subTargets:n},Ca(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let o=0;o<n.length;o++)n[o]!==i&&n[o].fire("mouse".concat(e),r)}_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",{alreadySelected:!1})}_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,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const o=this.getScenePoint(t);this._groupSelector={x:o.x,y:o.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const o=e.findControl(this.getViewportPoint(t),bu(t));if(e===this._activeObject&&(o||!r)){this._setupCurrentTransform(t,e,s);const h=o?o.control:void 0,c=this.getScenePoint(t),u=h&&h.getMouseDownHandler(t,e,h);u&&u.call(h,t,this._currentTransform,c.x,c.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=Br(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",E(E({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",E(E({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=Lt(e,dx);const{targetIn:h,targetOut:c,canvasIn:u,canvasOut:d}=fx[t],f=i!==s;if(i&&f){const g=E(E({},o),{},{e:r,target:i,nextTarget:s},Ca(this,r));n&&this.fire(d,g),i.fire(c,g)}if(s&&f){const g=E(E({},o),{},{e:r,target:s,previousTarget:i},Ca(this,r));n&&this.fire(u,g),s.fire(h,g)}}__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?Br(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=Nr(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=Nr(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(G.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 O(e,s),o=r.add(new O(i,n)),h=r.min(o),c=r.max(o).subtract(h),u=this.collectObjects({left:h.x,top:h.y,width:c.x,height:c.y},{includeIntersecting:!this.selectionFullyContained}),d=r.eq(o)?u[0]?[u[0]]:[]:u.length>1?u.filter(f=>!f.onSelect({e:t})).reverse():u;if(d.length===1)this.setActiveObject(d[0],t);else if(d.length>1){const f=G.getClass("ActiveSelection");this.setActiveObject(new f(d,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const u0={x1:0,y1:0,x2:0,y2:0},gx=E(E({},u0),{},{r1:0,r2:0}),Aa=(a,t)=>isNaN(a)&&typeof t=="number"?t:a,px=/^(\d+\.\d+)%|(\d+)%$/;function d0(a){return a&&px.test(a)}function f0(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(d0(a)?100:1):NaN;return zr(0,Aa(e,t),1)}const mx=/\s*;\s*/,vx=/\s*:\s*/;function bx(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(mx);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,c]=r[o].split(vx).map(u=>u.trim());h==="stop-color"?e=c:h==="stop-opacity"&&(s=c)}}const n=new St(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:f0(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Aa(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function yx(a,t){const e=[],s=a.getElementsByTagName("stop"),i=f0(t,1);for(let n=s.length;n--;)e.push(bx(s[n],i));return e}function g0(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function p0(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function ei(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,c)=>{const u=e[c];return u==="Infinity"?i=1:u==="-Infinity"?i=0:(i=typeof u=="string"?parseFloat(u):u,typeof u=="string"&&d0(u)&&(i*=.01,o==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(i*=n),c!=="y1"&&c!=="y2"||(i*=r)))),h[c]=i,h},{})}(g0(a)==="linear"?function(e){return{x1:ei(e,"x1")||0,y1:ei(e,"y1")||0,x2:ei(e,"x2")||"100%",y2:ei(e,"y2")||0}}(a):function(e){return{x1:ei(e,"fx")||ei(e,"cx")||"50%",y1:ei(e,"fy")||ei(e,"cy")||"50%",r1:0,x2:ei(e,"cx")||"50%",y2:ei(e,"cy")||"50%",r2:ei(e,"r")||"50%"}}(a),E(E({},t),{},{gradientUnits:p0(a)}))}class ll{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:c}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:E(E({},e==="radial"?gx:u0),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:c?"".concat(c,"_").concat(Wn()):Wn()})}addColorStop(t){for(const e in t){const s=new St(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return E(E({},jr(this,t)),{},{type:this.type,coords:E({},this.coords),colorStops:this.colorStops.map(e=>E({},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():He.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(d=>E({},d)).sort((d,f)=>d.offset-f.offset);let o=-this.offsetX,h=-this.offsetY;var c;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(c=t)&&typeof c._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const u=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(va(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:d,y1:f,x2:g,y2:p}=this.coords;s.push("<linearGradient ",u,' x1="',d,'" y1="',f,'" x2="',g,'" y2="',p,`">
71
- `)}else if(this.type==="radial"){const{x1:d,y1:f,x2:g,y2:p,r1:m,r2:y}=this.coords,b=m>y;s.push("<radialGradient ",u,' cx="',b?d:g,'" cy="',b?f:p,'" r="',b?m:y,'" fx="',b?g:d,'" fy="',b?p:f,`">
72
- `),b&&(r.reverse(),r.forEach(C=>{C.offset=1-C.offset}));const x=Math.min(m,y);if(x>0){const C=x/Math.max(m,y);r.forEach(S=>{S.offset+=C*(1-S.offset)})}}return r.forEach(d=>{let{color:f,offset:g,opacity:p}=d;s.push("<stop ",'offset="',100*g+"%",'" style="stop-color:',f,p!==void 0?";stop-opacity: "+p:";",`"/>
70
+ `),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=pt(t,od);return Promise.all([Gs(i,e),vi(r,e)]).then(a=>{let[l,h]=a;const c=new this(l,x(x(x({},r),h),{},{layoutManager:new ld}));if(n){const u=I.getClass(n.type),d=I.getClass(n.strategy);c.layoutManager=new u(new d)}else c.layoutManager=new Ti;return c.layoutManager.subscribeTargets({type:Je,target:c,targets:c.getObjects()}),c.setCoords(),c})}}S(me,"type","Group"),S(me,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),I.setClass(me);const Fl=(o,t)=>Math.min(t.width/o.width,t.height/o.height),Ll=(o,t)=>Math.max(t.width/o.width,t.height/o.height),ia="\\s*,?\\s*",Ei="".concat(ia,"(").concat(Te,")"),hd="".concat(Ei).concat(Ei).concat(Ei).concat(ia,"([01])").concat(ia,"([01])").concat(Ei).concat(Ei),cd={m:"l",M:"L"},ud=(o,t,e,s,i,n,r,a,l,h,c)=>{const u=xe(o),d=Se(o),f=xe(t),g=Se(t),p=e*i*f-s*n*g+r,v=s*i*f+e*n*g+a;return["C",h+l*(-e*i*d-s*n*u),c+l*(-s*i*d+e*n*u),p+l*(e*i*g+s*n*f),v+l*(s*i*g-e*n*f),p,v]},Il=(o,t,e,s)=>{const i=Math.atan2(t,o),n=Math.atan2(s,e);return n>=i?n-i:2*Math.PI-(i-n)};function na(o,t,e,s,i,n,r,a){let l;if(nt.cachesBoundsOfCurve&&(l=[...arguments].join(),di.boundsOfCurveCache[l]))return di.boundsOfCurveCache[l];const h=Math.sqrt,c=Math.abs,u=[],d=[[0,0],[0,0]];let f=6*o-12*e+6*i,g=-3*o+9*e-9*i+3*r,p=3*e-3*o;for(let w=0;w<2;++w){if(w>0&&(f=6*t-12*s+6*n,g=-3*t+9*s-9*n+3*a,p=3*s-3*t),c(g)<1e-12){if(c(f)<1e-12)continue;const O=-p/f;0<O&&O<1&&u.push(O);continue}const C=f*f-4*p*g;if(C<0)continue;const T=h(C),E=(-f+T)/(2*g);0<E&&E<1&&u.push(E);const k=(-f-T)/(2*g);0<k&&k<1&&u.push(k)}let v=u.length;const m=v,b=Nl(o,t,e,s,i,n,r,a);for(;v--;){const{x:w,y:C}=b(u[v]);d[0][v]=w,d[1][v]=C}d[0][m]=o,d[1][m]=t,d[0][m+1]=r,d[1][m+1]=a;const _=[new A(Math.min(...d[0]),Math.min(...d[1])),new A(Math.max(...d[0]),Math.max(...d[1]))];return nt.cachesBoundsOfCurve&&(di.boundsOfCurveCache[l]=_),_}const dd=(o,t,e)=>{let[s,i,n,r,a,l,h,c]=e;const u=((d,f,g,p,v,m,b)=>{if(g===0||p===0)return[];let _=0,w=0,C=0;const T=Math.PI,E=b*_r,k=Se(E),O=xe(E),H=.5*(-O*d-k*f),N=.5*(-O*f+k*d),P=g**2,R=p**2,F=N**2,V=H**2,M=P*R-P*F-R*V;let L=Math.abs(g),Y=Math.abs(p);if(M<0){const Nt=Math.sqrt(1-M/(P*R));L*=Nt,Y*=Nt}else C=(v===m?-1:1)*Math.sqrt(M/(P*F+R*V));const ft=C*L*N/Y,bt=-C*Y*H/L,_t=O*ft-k*bt+.5*d,gt=k*ft+O*bt+.5*f;let rt=Il(1,0,(H-ft)/L,(N-bt)/Y),Dt=Il((H-ft)/L,(N-bt)/Y,(-H-ft)/L,(-N-bt)/Y);m===0&&Dt>0?Dt-=2*T:m===1&&Dt<0&&(Dt+=2*T);const ee=Math.ceil(Math.abs(Dt/T*2)),K=[],$=Dt/ee,Tt=8/3*Math.sin($/4)*Math.sin($/4)/Math.sin($/2);let _e=rt+$;for(let Nt=0;Nt<ee;Nt++)K[Nt]=ud(rt,_e,O,k,L,Y,_t,gt,Tt,_,w),_=K[Nt][5],w=K[Nt][6],rt=_e,_e+=$;return K})(h-o,c-t,i,n,a,l,r);for(let d=0,f=u.length;d<f;d++)u[d][1]+=o,u[d][2]+=t,u[d][3]+=o,u[d][4]+=t,u[d][5]+=o,u[d][6]+=t;return u},jl=o=>{let t=0,e=0,s=0,i=0;const n=[];let r,a=0,l=0;for(const h of o){const c=[...h];let u;switch(c[0]){case"l":c[1]+=t,c[2]+=e;case"L":t=c[1],e=c[2],u=["L",t,e];break;case"h":c[1]+=t;case"H":t=c[1],u=["L",t,e];break;case"v":c[1]+=e;case"V":e=c[1],u=["L",t,e];break;case"m":c[1]+=t,c[2]+=e;case"M":t=c[1],e=c[2],s=c[1],i=c[2],u=["M",t,e];break;case"c":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e,c[5]+=t,c[6]+=e;case"C":a=c[3],l=c[4],t=c[5],e=c[6],u=["C",c[1],c[2],a,l,t,e];break;case"s":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"S":r==="C"?(a=2*t-a,l=2*e-l):(a=t,l=e),t=c[3],e=c[4],u=["C",a,l,c[1],c[2],t,e],a=u[3],l=u[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":a=c[1],l=c[2],t=c[3],e=c[4],u=["Q",a,l,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":r==="Q"?(a=2*t-a,l=2*e-l):(a=t,l=e),t=c[1],e=c[2],u=["Q",a,l,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":dd(t,e,c).forEach(d=>n.push(d)),t=c[6],e=c[7];break;case"z":case"Z":t=s,e=i,u=["Z"]}u?(n.push(u),r=u[0]):r=""}return n},yn=(o,t,e,s)=>Math.sqrt((e-o)**2+(s-t)**2),Nl=(o,t,e,s,i,n,r,a)=>l=>{const h=l**3,c=(f=>3*f**2*(1-f))(l),u=(f=>3*f*(1-f)**2)(l),d=(f=>(1-f)**3)(l);return new A(r*h+i*c+e*u+o*d,a*h+n*c+s*u+t*d)},Bl=o=>o**2,Hl=o=>2*o*(1-o),zl=o=>(1-o)**2,fd=(o,t,e,s,i,n,r,a)=>l=>{const h=Bl(l),c=Hl(l),u=zl(l),d=3*(u*(e-o)+c*(i-e)+h*(r-i)),f=3*(u*(s-t)+c*(n-s)+h*(a-n));return Math.atan2(f,d)},gd=(o,t,e,s,i,n)=>r=>{const a=Bl(r),l=Hl(r),h=zl(r);return new A(i*a+e*l+o*h,n*a+s*l+t*h)},pd=(o,t,e,s,i,n)=>r=>{const a=1-r,l=2*(a*(e-o)+r*(i-e)),h=2*(a*(s-t)+r*(n-s));return Math.atan2(h,l)},Vl=(o,t,e)=>{let s=new A(t,e),i=0;for(let n=1;n<=100;n+=1){const r=o(n/100);i+=yn(s.x,s.y,r.x,r.y),s=r}return i},md=(o,t)=>{let e,s=0,i=0,n={x:o.x,y:o.y},r=x({},n),a=.01,l=0;const h=o.iterator,c=o.angleFinder;for(;i<t&&a>1e-4;)r=h(s),l=s,e=yn(n.x,n.y,r.x,r.y),e+i>t?(s-=a,a/=2):(n=r,s+=a,i+=e);return x(x({},r),{},{angle:c(l)})},ra=o=>{let t,e,s=0,i=0,n=0,r=0,a=0;const l=[];for(const h of o){const c={x:i,y:n,command:h[0],length:0};switch(h[0]){case"M":e=c,e.x=r=i=h[1],e.y=a=n=h[2];break;case"L":e=c,e.length=yn(i,n,h[1],h[2]),i=h[1],n=h[2];break;case"C":t=Nl(i,n,h[1],h[2],h[3],h[4],h[5],h[6]),e=c,e.iterator=t,e.angleFinder=fd(i,n,h[1],h[2],h[3],h[4],h[5],h[6]),e.length=Vl(t,i,n),i=h[5],n=h[6];break;case"Q":t=gd(i,n,h[1],h[2],h[3],h[4]),e=c,e.iterator=t,e.angleFinder=pd(i,n,h[1],h[2],h[3],h[4]),e.length=Vl(t,i,n),i=h[3],n=h[4];break;case"Z":e=c,e.destX=r,e.destY=a,e.length=yn(i,n,r,a),i=r,n=a}s+=e.length,l.push(e)}return l.push({length:s,x:i,y:n}),l},Gl=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ra(o),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=o[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return x(x({},new A(i.x,i.y).lerp(new A(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return x(x({},new A(i.x,i.y).lerp(new A(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return md(i,t)}},vd=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Wl=new RegExp(hd,"g"),bd=new RegExp(Te,"gi"),yd={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Xl=o=>{var t;const e=[],s=(t=o.match(vd))!==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=yd[n.toLowerCase()];let a=[];if(n==="a"||n==="A"){Wl.lastIndex=0;for(let l=null;l=Wl.exec(i);)a.push(...l.slice(1))}else a=i.match(bd)||[];for(let l=0;l<a.length;l+=r){const h=new Array(r),c=cd[n];h[0]=l>0&&c?c:n;for(let u=0;u<r;u++)h[u+1]=parseFloat(a[l+u]);e.push(h)}}return e},_d=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new A(o[0]),s=new A(o[1]),i=1,n=0;const r=[],a=o.length,l=a>2;let h;for(l&&(i=o[2].x<s.x?-1:o[2].x===s.x?0:1,n=o[2].y<s.y?-1:o[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),h=1;h<a;h++){if(!e.eq(s)){const c=e.midPointFrom(s);r.push(["Q",e.x,e.y,c.x,c.y])}e=o[h],h+1<o.length&&(s=o[h+1])}return l&&(i=e.x>o[h-2].x?1:e.x===o[h-2].x?0:-1,n=e.y>o[h-2].y?1:e.y===o[h-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},Ul=(o,t)=>o.map(e=>e.map((s,i)=>i===0||t===void 0?s:ct(s,t)).join(" ")).join(" ");function _n(o,t){const e=o.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const wd=(o,t)=>Math.floor(Math.random()*(t-o+1))+o;function Yl(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||ps,s=new(ui()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=ps};if(i&&i.aborted)throw new br("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=ps)},s.onerror=s.ontimeout=r,s.open("get",o,!0),s.send(),s}const wn=(o,t)=>{let e=o._findCenterFromElement();o.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:a}=vs(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set($t,i),s.set(ce,n),s.angle=r,s.skewX=a,s.skewY=0}})(o),e=e.transform(o.transformMatrix)),delete o.transformMatrix,t&&(o.scaleX*=t.scaleX,o.scaleY*=t.scaleY,o.cropX=t.cropX,o.cropY=t.cropY,e.x+=t.offsetLeft,e.y+=t.offsetTop,o.width=t.width,o.height=t.height),o.setPositionByOrigin(e,q,q)};var xd=Object.freeze({__proto__:null,addTransformToObject:Oo,animate:qr,animateColor:ol,applyTransformToObject:Xs,calcAngleBetweenVectors:ln,calcDimensionsMatrix:pi,calcPlaneChangeMatrix:yi,calcVectorRotation:tl,cancelAnimFrame:mo,capValue:Ss,composeMatrix:wo,copyCanvasElement:o=>{var t;const e=ue(o);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(o,0,0),e},cos:xe,createCanvasElement:Ie,createImage:vo,createRotateMatrix:bs,createScaleMatrix:Qi,createSkewXMatrix:Pr,createSkewYMatrix:Mr,createTranslateMatrix:Vs,createVector:an,crossProduct:Us,degreesToRadians:wt,dotProduct:el,ease:hu,enlivenObjectEnlivables:vi,enlivenObjects:Gs,findScaleToCover:Ll,findScaleToFit:Fl,getBoundsOfCurve:na,getOrthonormalVector:Gr,getPathSegmentsInfo:ra,getPointOnPath:Gl,getPointer:Po,getRandomInt:wd,getRegularPolygonPath:(o,t)=>{const e=2*Math.PI/o;let s=-is;o%2==0&&(s+=e/2);const i=new Array(o+1);for(let n=0;n<o;n++){const r=n*e+s,{x:a,y:l}=new A(xe(r),Se(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",a,l]}return i[o]=["Z"],i},getSmoothPathFromPoints:_d,getSvgAttributes:o=>{const t=["instantiated_by_use","style","id","class"];switch(o){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:hn,groupSVGElements:(o,t)=>o&&o.length===1?o[0]:new me(o,t),hasStyleChanged:gn,invertTransform:ne,isBetweenVectors:Wr,isIdentityMatrix:bo,isTouchEvent:Zi,isTransparent:ml,joinPath:Ul,loadImage:mi,magnitude:on,makeBoundingBoxFromPoints:Ne,makePathSimpler:jl,matrixToSVG:Ws,mergeClipPaths:(o,t)=>{var e;let s=o,i=t;s.inverted&&!i.inverted&&(s=t,i=o),Fr(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 me([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:St,multiplyTransformMatrixArray:Ji,parsePath:Xl,parsePreserveAspectRatioAttribute:jr,parseUnit:Kt,pick:ys,projectStrokeOnPoints:yl,qrDecompose:vs,radiansToDegrees:je,removeFromArray:ms,removeTransformFromObject:(o,t)=>{const e=ne(t),s=St(e,o.calcOwnMatrix());Xs(o,s)},removeTransformMatrixForSvgParsing:wn,request:Yl,requestAnimFrame:gi,resetObjectTransform:Do,rotatePoint:(o,t,e)=>o.rotate(e,t),rotateVector:Vr,saveObjectTransform:Rr,sendObjectToPlane:Fr,sendPointToPlane:ws,sendVectorToPlane:Ro,setStyle:_n,sin:Se,sizeAfterTransform:tn,string:Nu,stylesFromArray:xl,stylesToArray:wl,toBlob:kr,toDataURL:Er,toFixed:ct,transformPath:(o,t,e)=>(e&&(t=St(t,[1,0,0,1,-e.x,-e.y])),o.map(s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:a}=Bt({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=a}return i})),transformPoint:Bt});class Sd extends ko{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),S(this,"upper",void 0),S(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=Ie();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=Ns().createElement("div");return t.setAttribute("data-fabric","wrapper"),_n(t,{position:"relative"}),Eo(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;_n(t,x(x({},s),{},{"touch-action":i?"manipulation":Yt})),Eo(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;To(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Dr(this.upper.el,t),Dr(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(),Le().dispose(this.upper.el),delete this.upper,delete this.container}}class xn extends bi{constructor(){super(...arguments),S(this,"targets",[]),S(this,"_hoveredTargets",[]),S(this,"_objectsToRender",void 0),S(this,"_currentTransform",null),S(this,"_groupSelector",null),S(this,"contextTopDirty",!1)}static getDefaults(){return x(x({},super.getDefaults()),xn.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 Sd(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 a=Math.round(i*this.getRetinaScaling());return ml(n,a,a,a)}_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===Yi||e===$t||e===ce||e===fi?i=this.centeredScaling||t.centeredScaling:e===Cr&&(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=xt:["mr","tr","br"].includes(e)&&(s.x=ot),["tl","mt","tr"].includes(e)?s.y=xr:["bl","mb","br"].includes(e)&&(s.y=ie)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?ws(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:a}=e.getActiveControl()||{},l=s&&a?(i=a.getActionHandler(t,e,a))===null||i===void 0?void 0:i.bind(a):Zc,h=((f,g,p,v)=>{if(!g||!f)return"drag";const m=v.controls[g];return m.getActionName(p,m,v)})(s,r,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,h,c)?{x:q,y:q}:this._getOriginFromCorner(e,r),d={target:e,action:h,actionHandler:l,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:wt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:c,original:x(x({},Rr(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new A(e,s).transform(this.viewportTransform),a=new A(e+i,s+n).transform(this.viewportTransform),l=this.selectionLineWidth/2;let h=Math.min(r.x,a.x),c=Math.min(r.y,a.y),u=Math.max(r.x,a.x),d=Math.max(r.y,a.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(h,c,u-h,d-c)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,h+=l,c+=l,u-=l,d-=l,Ht.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(h,c,u-h,d-c))}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,Zi(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,a,l,h]=s,c=Math.atan2(a.y-r.y,a.x-r.x),u=xe(c)*n,d=Se(c)*n,f=u+d,g=u-d;s=[new A(r.x-g,r.y-f),new A(a.x+f,a.y-g),new A(l.x+g,l.y+f),new A(h.x-f,h.y+g)]}return yt.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,ws(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(Ki(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&&Ki(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!Ki(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=Po(t),r=i.width||0,a=i.height||0;r&&a||(ie in i&&xr in i&&(a=Math.abs(i.top-i.bottom)),xt in i&&ot 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=ws(n,void 0,this.viewportTransform));const l=this.getRetinaScaling();l!==1&&(n.x/=l,n.y/=l);const h=r===0||a===0?new A(1,1):new A(s.width/r,s.height/a);return n.multiply(h)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Ie(),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 _s(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],a=[];t.forEach(l=>{n.includes(l)||(s=!0,l.fire("deselected",{e,target:l}),a.push(l))}),n.forEach(l=>{t.includes(l)||(s=!0,l.fire("selected",{e,target:l}),r.push(l))}),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:a})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:a})),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,_s(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),_s(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($i,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;_s(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&&_s(e)&&this._activeObject===e){const s=ys(t,["angle","flipX","flipY",ot,$t,ce,Bs,Hs,ie]);return Oo(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}S(xn,"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 Cd{constructor(t){S(this,"targets",[]),S(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),ms(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 Ad=["target","oldTarget","fireCanvas","e"],de={passive:!1},Js=(o,t)=>{const e=o.getViewportPoint(t),s=o.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},os=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.addEventListener(...e)},ve=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.removeEventListener(...e)},Td={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 aa extends xn{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),S(this,"_isClick",void 0),S(this,"textEditingManager",new Cd(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(os,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Ao(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,de),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,"click",this._onClick),t(s,"dblclick",this._onClick),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,de)}removeListeners(){this.addOrRemove(ve,"remove");const t=this._getEventPrefix(),e=Ce(this.upperCanvasEl);ve(e,"".concat(t,"up"),this._onMouseUp),ve(e,"touchend",this._onTouchEnd,de),ve(e,"".concat(t,"move"),this._onMouseMove,de),ve(e,"touchmove",this._onMouseMove,de),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=x({e:t},Js(this,t));this.fire("mouse:out",x(x({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",x({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",x(x({},s),{},{target:i})),i&&i.fire("mouseout",x({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",x({e:t},Js(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 os(this.upperCanvasEl,"drag",this._onDragProgress)}Mo(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e?.clearContextTop(),s!==e&&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!==Yt,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};ve(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 a;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(a=s),s.fire(e,r));for(let l=0;l<i.length;l++){const h=i[l];h.canDrop(t)&&(a=h),h.fire(e,r)}this._renderDragEffects(t,n,a),this._dropTarget=a}_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",x({e:t,target:e,subTargets:s,dragSource:this._dragSource},Js(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&&Mo(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),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=Ce(i);os(r,"touchend",this._onTouchEnd,de),e&&os(r,"touchmove",this._onMouseMove,de),ve(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();ve(e,"".concat(s,"move"),this._onMouseMove,de);const i=Ce(e);os(i,"".concat(s,"up"),this._onMouseUp),os(i,"".concat(s,"move"),this._onMouseMove,de)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=Ce(this.upperCanvasEl);ve(s,"touchend",this._onTouchEnd,de),ve(s,"touchmove",this._onMouseMove,de),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{os(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=Ce(this.upperCanvasEl);ve(i,"".concat(s,"up"),this._onMouseUp),ve(i,"".concat(s,"move"),this._onMouseMove,de),os(e,"".concat(s,"move"),this._onMouseMove,de)}}_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 a,l,h=!1;if(s&&(this._finalizeCurrentTransform(t),h=s.actionPerformed),!i){const c=n===this._activeObject;this.handleSelection(t),h||(h=this._shouldRender(n)||!c&&n===this._activeObject)}if(n){const c=n.findControl(this.getViewportPoint(t),Zi(t)),{key:u,control:d}=c||{};if(l=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),h=!0;else if(d){const f=d.getMouseUpHandler(t,n,d);f&&(a=this.getScenePoint(t),f.call(d,t,s,a.x,a.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==l)){const c=s.target&&s.target.controls[s.corner],u=c&&c.getMouseUpHandler(t,s.target,c);a=a||this.getScenePoint(t),u&&u.call(c,t,s,a.x,a.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),h?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,s){const i=this._target,n=this.targets||[],r=x(x(x({e:t,target:i,subTargets:n},Js(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let a=0;a<n.length;a++)n[a]!==i&&n[a].fire("mouse".concat(e),r)}_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",{alreadySelected:!1})}_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,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const a=this.getScenePoint(t);this._groupSelector={x:a.x,y:a.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const a=e.findControl(this.getViewportPoint(t),Zi(t));if(e===this._activeObject&&(a||!r)){this._setupCurrentTransform(t,e,s);const l=a?a.control:void 0,h=this.getScenePoint(t),c=l&&l.getMouseDownHandler(t,e,l);c&&c.call(l,t,this._currentTransform,h.x,h.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=ws(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 a=0;a<r;a++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[a],oldTarget:i[a]});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",x(x({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let a=0;a<r;a++)this.fireSyntheticInOutEvents("drag",x(x({},e),{},{target:n[a],oldTarget:i[a]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,a=pt(e,Ad);const{targetIn:l,targetOut:h,canvasIn:c,canvasOut:u}=Td[t],d=i!==s;if(i&&d){const f=x(x({},a),{},{e:r,target:i,nextTarget:s},Js(this,r));n&&this.fire(u,f),i.fire(h,f)}if(s&&d){const f=x(x({},a),{},{e:r,target:s,previousTarget:i},Js(this,r));n&&this.fire(c,f),s.fire(l,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?ws(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,a=!!n&&n(t,e,s.x,s.y);a&&r.setCoords(),i==="drag"&&a&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||a}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const i=_s(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=_s(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(I.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 A(e,s),a=r.add(new A(i,n)),l=r.min(a),h=r.max(a).subtract(l),c=this.collectObjects({left:l.x,top:l.y,width:h.x,height:h.y},{includeIntersecting:!this.selectionFullyContained}),u=r.eq(a)?c[0]?[c[0]]:[]:c.length>1?c.filter(d=>!d.onSelect({e:t})).reverse():c;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const d=I.getClass("ActiveSelection");this.setActiveObject(new d(u,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const $l={x1:0,y1:0,x2:0,y2:0},Ed=x(x({},$l),{},{r1:0,r2:0}),Qs=(o,t)=>isNaN(o)&&typeof t=="number"?t:o,kd=/^(\d+\.\d+)%|(\d+)%$/;function ql(o){return o&&kd.test(o)}function Kl(o,t){const e=typeof o=="number"?o:typeof o=="string"?parseFloat(o)/(ql(o)?100:1):NaN;return Ss(0,Qs(e,t),1)}const Pd=/\s*;\s*/,Md=/\s*:\s*/;function Od(o,t){let e,s;const i=o.getAttribute("style");if(i){const r=i.split(Pd);r[r.length-1]===""&&r.pop();for(let a=r.length;a--;){const[l,h]=r[a].split(Md).map(c=>c.trim());l==="stop-color"?e=h:l==="stop-opacity"&&(s=h)}}const n=new ht(e||o.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Kl(o.getAttribute("offset"),0),color:n.toRgb(),opacity:Qs(parseFloat(s||o.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function Dd(o,t){const e=[],s=o.getElementsByTagName("stop"),i=Kl(t,1);for(let n=s.length;n--;)e.push(Od(s[n],i));return e}function Jl(o){return o.nodeName==="linearGradient"||o.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Ql(o){return o.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function ke(o,t){return o.getAttribute(t)}function Rd(o,t){return function(e,s){let i,{width:n,height:r,gradientUnits:a}=s;return Object.keys(e).reduce((l,h)=>{const c=e[h];return c==="Infinity"?i=1:c==="-Infinity"?i=0:(i=typeof c=="string"?parseFloat(c):c,typeof c=="string"&&ql(c)&&(i*=.01,a==="pixels"&&(h!=="x1"&&h!=="x2"&&h!=="r2"||(i*=n),h!=="y1"&&h!=="y2"||(i*=r)))),l[h]=i,l},{})}(Jl(o)==="linear"?function(e){return{x1:ke(e,"x1")||0,y1:ke(e,"y1")||0,x2:ke(e,"x2")||"100%",y2:ke(e,"y2")||0}}(o):function(e){return{x1:ke(e,"fx")||ke(e,"cx")||"50%",y1:ke(e,"fy")||ke(e,"cy")||"50%",r1:0,x2:ke(e,"cx")||"50%",y2:ke(e,"cy")||"50%",r2:ke(e,"r")||"50%"}}(o),x(x({},t),{},{gradientUnits:Ql(o)}))}class ki{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:a=0,gradientTransform:l,id:h}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:x(x({},e==="radial"?Ed:$l),i),colorStops:n,offsetX:r,offsetY:a,gradientTransform:l,id:h?"".concat(h,"_").concat(rs()):rs()})}addColorStop(t){for(const e in t){const s=new ht(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return x(x({},ys(this,t)),{},{type:this.type,coords:x({},this.coords),colorStops:this.colorStops.map(e=>x({},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():Ut.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(u=>x({},u)).sort((u,d)=>u.offset-d.offset);let a=-this.offsetX,l=-this.offsetY;var h;n==="objectBoundingBox"?(a/=t.width,l/=t.height):(a+=t.width/2,l+=t.height/2),(h=t)&&typeof h._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(a-=t.pathOffset.x,l-=t.pathOffset.y),i[4]-=a,i[5]-=l;const c=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(Ws(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:d,x2:f,y2:g}=this.coords;s.push("<linearGradient ",c,' x1="',u,'" y1="',d,'" x2="',f,'" y2="',g,`">
71
+ `)}else if(this.type==="radial"){const{x1:u,y1:d,x2:f,y2:g,r1:p,r2:v}=this.coords,m=p>v;s.push("<radialGradient ",c,' cx="',m?u:f,'" cy="',m?d:g,'" r="',m?p:v,'" fx="',m?f:u,'" fy="',m?g:d,`">
72
+ `),m&&(r.reverse(),r.forEach(_=>{_.offset=1-_.offset}));const b=Math.min(p,v);if(b>0){const _=b/Math.max(p,v);r.forEach(w=>{w.offset+=_*(1-w.offset)})}}return r.forEach(u=>{let{color:d,offset:f,opacity:g}=u;s.push("<stop ",'offset="',100*f+"%",'" style="stop-color:',d,g!==void 0?";stop-opacity: "+g:";",`"/>
73
73
  `)}),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
74
- `),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(c=>{let{color:u,opacity:d,offset:f}=c;h.addColorStop(f,d!==void 0?new St(u).setAlpha(d).toRgba():u)}),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(E(E({},t),{},{colorStops:e?e.map(i=>E({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=p0(t),n=e._findCenterFromElement();return new this(E({id:t.getAttribute("id")||void 0,type:g0(t),coords:_x(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:yx(t,s.opacity),gradientUnits:i,gradientTransform:Ru(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}k(ll,"type","Gradient"),G.setClass(ll,"gradient"),G.setClass(ll,"linear"),G.setClass(ll,"radial");const wx=["type","source","patternTransform"];class yg{get type(){return"pattern"}set type(t){Ki("warn","Setting type has no effect",t)}constructor(t){k(this,"repeat","repeat"),k(this,"offsetX",0),k(this,"offsetY",0),k(this,"crossOrigin",""),this.id=Wn(),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 E(E({},jr(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:kt(this.offsetX,mt.NUM_FRACTION_DIGITS),offsetY:kt(this.offsetY,mt.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=Aa(this.offsetX/e,0),h=Aa(this.offsetY/s,0),c=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):Aa(i.width/e,0),u=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):Aa(i.height/s,0);return['<pattern id="SVGID_'.concat(r,'" x="').concat(o,'" y="').concat(h,'" width="').concat(c,'" height="').concat(u,'">'),'<image x="0" y="0" width="'.concat(i.width,'" height="').concat(i.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
75
- `)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=Lt(t,wx);const o=await Jh(i,E(E({},e),{},{crossOrigin:r.crossOrigin}));return new this(E(E({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}k(yg,"type","Pattern"),G.setClass(yg),G.setClass(yg,"pattern");const xx=["path","left","top"],Sx=["d"];class Vr extends ke{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=Lt(e,xx);super(),Object.assign(this,Vr.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(wt,i),typeof n=="number"&&this.set(is,n)}_setPath(t,e){this.path=t0(Array.isArray(t)?t:h0(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new O(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 E(E({},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=l0(this.path,mt.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
76
- `)]}_getOffsetTransform(){const t=mt.NUM_FRACTION_DIGITS;return" translate(".concat(kt(-this.pathOffset.x,t),", ").concat(kt(-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,rt,rt)}_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(...mg(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(...mg(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 Ai(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return E(E({},t),{},{pathOffset:new O(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=en(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,E(E(E({},Lt(i,Sx)),e),{},{left:void 0,top:void 0}))}}k(Vr,"type","Path"),k(Vr,"cacheProperties",[...Zi,"path","fillRule"]),k(Vr,"ATTRIBUTE_NAMES",[...Xn,"d"]),G.setClass(Vr),G.setSVGClass(Vr);const Cx=["left","top","radius"],m0=["radius","startAngle","endAngle","counterClockwise"];class nn extends ke{static getDefaults(){return E(E({},super.getDefaults()),nn.ownDefaults)}constructor(t){super(),Object.assign(this,nn.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,Ut(this.startAngle),Ut(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(Ve)}getRadiusY(){return this.get("radius")*this.get(gs)}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([...m0,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
77
- `];{const{radius:e}=this,s=Ut(this.startAngle),i=Ut(this.endAngle),n=qs(s)*e,r=Ks(s)*e,o=qs(i)*e,h=Ks(i)*e,c=t>180?1:0,u=this.counterClockwise?0:1;return['<path d="M '.concat(n," ").concat(r," A ").concat(e," ").concat(e," 0 ").concat(c," ").concat(u," ").concat(o," ").concat(h,'" '),"COMMON_PARTS",` />
78
- `]}}static async fromElement(t,e,s){const i=en(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(E(E({},Lt(i,Cx)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}k(nn,"type","Circle"),k(nn,"cacheProperties",[...Zi,...m0]),k(nn,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),k(nn,"ATTRIBUTE_NAMES",["cx","cy","r",...Xn]),G.setClass(nn),G.setSVGClass(nn);const Ax=["x1","y1","x2","y2"],Tx=["x1","y1","x2","y2"],_g=["x1","x2","y1","y2"];class Gr extends ke{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,Gr.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(wt,r),typeof o=="number"&&this.set(is,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}=Ai([{x:t,y:e},{x:s,y:i}]),c=new O(n+o/2,r+h/2);this.setPositionByOrigin(c,rt,rt)}_set(t,e){return super._set(t,e),_g.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 O((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return E(E({},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,`" />
79
- `)]}static async fromElement(t,e,s){const i=en(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],Lt(i,Ax))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=Lt(t,Tx);return this._fromObject(E(E({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}k(Gr,"type","Line"),k(Gr,"cacheProperties",[...Zi,..._g]),k(Gr,"ATTRIBUTE_NAMES",Xn.concat(_g)),G.setClass(Gr),G.setSVGClass(Gr);class Wr extends ke{static getDefaults(){return E(E({},super.getDefaults()),Wr.ownDefaults)}constructor(t){super(),Object.assign(this,Wr.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),'" />']}}k(Wr,"type","Triangle"),k(Wr,"ownDefaults",{width:100,height:100}),G.setClass(Wr),G.setSVGClass(Wr);const v0=["rx","ry"];class rn extends ke{static getDefaults(){return E(E({},super.getDefaults()),rn.ownDefaults)}constructor(t){super(),Object.assign(this,rn.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(Ve)}getRy(){return this.get("ry")*this.get(gs)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...v0,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
80
- `)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Ji,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=en(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function Ex(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}k(rn,"type","Ellipse"),k(rn,"cacheProperties",[...Zi,...v0]),k(rn,"ownDefaults",{rx:0,ry:0}),k(rn,"ATTRIBUTE_NAMES",[...Xn,"cx","cy","rx","ry"]),G.setClass(rn),G.setSVGClass(rn);const kx=["left","top"],b0={exactBoundingBox:!1};class si extends ke{static getDefaults(){return E(E({},super.getDefaults()),si.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),k(this,"strokeDiff",void 0),Object.assign(this,si.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(wt,s),typeof i=="number"&&this.set(is,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return Iv(this.points,t,this.isOpen())}_calcDimensions(t){t=E({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(c=>c.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new O,strokeOffset:new O,strokeDiff:new O};const s=Ai(e),i=Kh(E(E({},t),{},{scaleX:1,scaleY:1})),n=Ai(this.points.map(c=>Ee(c,i,!0))),r=new O(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(Ut(this.skewX)),h-=o*Math.tan(Ut(this.skewY))),E(E({},s),{},{pathOffset:new O(o,h),strokeOffset:new O(n.left,n.top).subtract(new O(s.left,s.top)).multiply(r),strokeDiff:new O(s.width,s.height).subtract(new O(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Ai(this.points);return new O(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 O(e+i/2,s+n/2),rt,rt)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new O(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 O((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new O((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new O(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===Ve||t===gs)&&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 E(E({},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=mt.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(kt(this.points[n].x-e,i),",",kt(this.points[n].y-s,i)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
81
- `)]}_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(Ex(t.getAttribute("points")),E(E({},Lt(en(t,this.ATTRIBUTE_NAMES,s),kx)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}k(si,"ownDefaults",b0),k(si,"type","Polyline"),k(si,"layoutProperties",[da,fa,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),k(si,"cacheProperties",[...Zi,"points"]),k(si,"ATTRIBUTE_NAMES",[...Xn]),G.setClass(si),G.setSVGClass(si);class zu extends si{isOpen(){return!1}}k(zu,"ownDefaults",b0),k(zu,"type","Polygon"),G.setClass(zu),G.setSVGClass(zu);class y0 extends ke{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 c in e[h]){const u=e[h][c]||{};n++,u[t]!==void 0?(i?u[t]!==i&&(r=!1):i=u[t],u[t]===this[t]&&delete u[t]):r=!1,Object.keys(u).length!==0?s++:delete e[h][c]}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=Gf(E(E({},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 E(E({},jr(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]}}k(y0,"_styleProperties",z_);const Px=/ +/g,Mx=/"/g;function wg(a,t,e,s,i){return" ".concat(function(n,r){let{left:o,top:h,width:c,height:u}=r,d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:mt.NUM_FRACTION_DIGITS;const f=el(ee,n,!1),[g,p,m,y]=[o,h,c,u].map(b=>kt(b,d));return"<rect ".concat(f,' x="').concat(g,'" y="').concat(p,'" width="').concat(m,'" height="').concat(y,'"></rect>')}(a,{left:t,top:e,width:s,height:i}),`
82
- `)}const Ox=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let xg;class Pe extends y0{static getDefaults(){return E(E({},super.getDefaults()),Pe.ownDefaults)}constructor(t,e){super(),k(this,"__charBounds",[]),Object.assign(this,Pe.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=vg(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(Ti)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,o;for(let h=0,c=this._textLines.length;h<c;h++)if((this.textAlign===Ti||h!==c-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 u=0;u<=n.length;u++)r=this.__charBounds[h][u],this._reSpaceAndTab.test(n[u])?(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===Ge?(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 rt:t.textBaseline="middle";break;case"ascender":t.textBaseline=is;break;case"descender":t.textBaseline=Ff}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,c=this._getLineLeftOffset(n);let u,d,f=0,g=0,p=this.getValueOfPropertyAt(n,0,"textBackgroundColor");for(let m=0;m<h;m++){const y=this.__charBounds[n][m];d=this.getValueOfPropertyAt(n,m,"textBackgroundColor"),this.path?(t.save(),t.translate(y.renderLeft,y.renderTop),t.rotate(y.angle),t.fillStyle=d,d&&t.fillRect(-y.width/2,-o/this.lineHeight*(1-this._fontSizeFraction),y.width,o/this.lineHeight),t.restore()):d!==p?(u=s+c+g,this.direction==="rtl"&&(u=this.width-u-f),t.fillStyle=p,p&&t.fillRect(u,i,f,o/this.lineHeight),g=y.left,f=y.width,p=d):f+=y.kernedWidth}d&&!this.path&&(u=s+c+g,this.direction==="rtl"&&(u=this.width-u-f),t.fillStyle=d,t.fillRect(u,i,f,o/this.lineHeight)),i+=o}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=Yh.getFontCache(e),r=this._getFontDeclaration(e),o=s+t,h=s&&r===this._getFontDeclaration(i),c=e.fontSize/this.CACHE_FONT_SIZE;let u,d,f,g;if(s&&n[s]!==void 0&&(f=n[s]),n[t]!==void 0&&(g=u=n[t]),h&&n[o]!==void 0&&(d=n[o],g=d-f),u===void 0||f===void 0||d===void 0){const p=function(){return xg||(xg=ps({width:0,height:0}).getContext("2d")),xg}();this._setTextStyles(p,e,!0),u===void 0&&(g=u=p.measureText(t).width,n[t]=u),f===void 0&&h&&s&&(f=p.measureText(s).width,n[s]=f),h&&d===void 0&&(d=p.measureText(o).width,n[o]=d,g=d-f)}return{width:u*c,kernedWidth:g*c}}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===$t,r=this.path,o=this._textLines[t],h=o.length,c=new Array(h);this.__charBounds[t]=c;for(let u=0;u<h;u++){const d=o[u];s=this._getGraphemeBox(d,t,u,e),c[u]=s,i+=s.kernedWidth,e=d}if(c[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let u=0;const d=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case wt:u=n?d-i:0;break;case rt:u=(d-i)/2;break;case $t:u=n?0:d-i}u+=this.pathStartOffset*(n?-1:1);for(let f=n?h-1:0;n?f>=0:f<h;n?f--:f++)s=c[f],u>d?u%=d:u<0&&(u+=d),this._setGraphemeOnPath(u,s),u+=s.kernedWidth}return{width:i,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,i=this.path,n=o0(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===$t?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 c,u=h.kernedWidth,d=h.width;this.charSpacing!==0&&(c=this._getWidthOfCharSpacing(),d+=c,u+=c);const f={width:d,left:0,height:r.fontSize,kernedWidth:u,deltaY:r.deltaY};if(s>0&&!n){const g=this.__charBounds[e][s-1];f.left=g.left+g.width+h.kernedWidth-h.width}return f}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),c=h/this.lineHeight,u=this._getLineLeftOffset(r);this._renderTextLine(e,t,this._textLines[r],i+u,n+s+c,r),s+=h}t.restore()}_renderTextFill(t){(this.fill||this.styleHas(ee))&&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(Ti),c=this.path,u=!h&&this.charSpacing===0&&this.isEmptyStyles(r)&&!c,d=this.direction==="ltr",f=this.direction==="ltr"?1:-1,g=e.direction;let p,m,y,b,x,C="",S=0;if(e.save(),g!==this.direction&&(e.canvas.setAttribute("dir",d?"ltr":"rtl"),e.direction=d?"ltr":"rtl",e.textAlign=d?wt:$t),n-=o*this._fontSizeFraction/this.lineHeight,u)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let T=0,P=s.length-1;T<=P;T++)b=T===P||this.charSpacing||c,C+=s[T],y=this.__charBounds[r][T],S===0?(i+=f*(y.kernedWidth-y.width),S+=y.width):S+=y.kernedWidth,h&&!b&&this._reSpaceAndTab.test(s[T])&&(b=!0),b||(p=p||this.getCompleteStyleDeclaration(r,T),m=this.getCompleteStyleDeclaration(r,T+1),b=Du(p,m,!1)),b&&(c?(e.save(),e.translate(y.renderLeft,y.renderTop),e.rotate(y.angle),this._renderChar(t,e,r,T,C,-S/2,0),e.restore()):(x=i,this._renderChar(t,e,r,T,C,x,n)),C="",p=m,i+=f*S,S=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=ps({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),c=this.getCompleteStyleDeclaration(s,i),u=t==="fillText"&&c.fill,d=t==="strokeText"&&c.stroke&&c.strokeWidth;if(d||u){if(e.save(),e.font=this._getFontDeclaration(c),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(o+=h.deltaY),u){const f=this._setFillStyles(e,c);e.fillText(n,r-f.offsetX,o-f.offsetY)}if(d){const f=this._setStrokeStyles(e,c);e.strokeText(n,r-f.offsetX,o-f.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===Ti||i===il&&!r||i===sl&&!r||i===Su&&!r?0:(i===rt&&(o=s/2),i===$t&&(o=s),i===il&&(o=s/2),i===sl&&(o=s),n==="rtl"&&(i===$t||i===Ti||i===sl?o=0:i===wt||i===Su?o=-s:i!==rt&&i!==il||(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=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let c=0,u=this._textLines.length;c<u;c++){const d=this.getHeightOfLine(c);if(!this[e]&&!this.styleHas(e,c)){s+=d;continue}const f=this._textLines[c],g=d/this.lineHeight,p=this._getLineLeftOffset(c);let m=0,y=0,b=this.getValueOfPropertyAt(c,0,e),x=this.getValueOfPropertyAt(c,0,ee),C=this.getValueOfPropertyAt(c,0,Hr),S=b,T=x,P=C;const M=s+g*(1-this._fontSizeFraction);let D=this.getHeightOfChar(c,0),R=this.getValueOfPropertyAt(c,0,"deltaY");for(let F=0,I=f.length;F<I;F++){const j=this.__charBounds[c][F];S=this.getValueOfPropertyAt(c,F,e),T=this.getValueOfPropertyAt(c,F,ee),P=this.getValueOfPropertyAt(c,F,Hr);const K=this.getHeightOfChar(c,F),L=this.getValueOfPropertyAt(c,F,"deltaY");if(n&&S&&T){const z=this.fontSize*P/1e3;t.save(),t.fillStyle=x,t.translate(j.renderLeft,j.renderTop),t.rotate(j.angle),t.fillRect(-j.kernedWidth/2,h*K+L-o*z,j.kernedWidth,z),t.restore()}else if((S!==b||T!==x||K!==D||P!==C||L!==R)&&y>0){const z=this.fontSize*C/1e3;let Z=i+p+m;this.direction==="rtl"&&(Z=this.width-Z-y),b&&x&&C&&(t.fillStyle=x,t.fillRect(Z,M+h*D+R-o*z,y,z)),m=j.left,y=j.width,b=S,C=P,x=T,D=K,R=L}else y+=j.kernedWidth}let V=i+p+m;this.direction==="rtl"&&(V=this.width-V-y),t.fillStyle=T;const H=this.fontSize*P/1e3;S&&T&&P&&t.fillRect(V,M+h*D+R-o*H,y-r,H),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(",")||Pe.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 Ou(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
83
- `];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 E(E({},super.toObject([...cv,...t])),{},{styles:Nv(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=en(t,Pe.ATTRIBUTE_NAMES,s),n=E(E({},e),i),{textAnchor:r=wt,textDecoration:o="",dx:h=0,dy:c=0,top:u=0,left:d=0,fontSize:f=Rf,strokeWidth:g=1}=n,p=Lt(n,Ox),m=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),E({left:d+h,top:u+c,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:f},p)),y=m.getScaledHeight()/m.height,b=((m.height+m.strokeWidth)*m.lineHeight-m.height)*y,x=m.getScaledHeight()+b;let C=0;return r===rt&&(C=m.getScaledWidth()/2),r===$t&&(C=m.getScaledWidth()),m.set({left:m.left-C,top:m.top-(x-m.fontSize*(.07+m._fontSizeFraction))/m.lineHeight,strokeWidth:g}),m}static fromObject(t){return this._fromObject(E(E({},t),{},{styles:Bv(t.styles||{},t.text)}),{extraParam:"text"})}}k(Pe,"textLayoutProperties",lv),k(Pe,"cacheProperties",[...Zi,...cv]),k(Pe,"ownDefaults",V_),k(Pe,"type","Text"),k(Pe,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),k(Pe,"ATTRIBUTE_NAMES",Xn.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Dv(Pe,[class extends ov{_toSVG(){const a=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(a.textTop,a.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(a){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:a,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:a,withShadow:!0,additionalTransform:va(this.calcOwnMatrix())}):t}_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" ','font-family="'.concat(this.fontFamily.replace(Mx,"'"),'" '),'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>
84
- `]}_getSVGTextAndBg(a,t){const e=[],s=[];let i,n=a;this.backgroundColor&&s.push(...wg(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,i){const n=mt.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,a!==a.trim()||!!a.match(Px)),o=r?'style="'.concat(r,'"'):"",h=t.deltaY,c=h?' dy="'.concat(kt(h,n),'" '):"",{angle:u,renderLeft:d,renderTop:f,width:g}=i;let p="";if(d!==void 0){const m=g/2;u&&(p=' rotate="'.concat(kt(Ci(u),n),'"'));const y=Ir({angle:Ci(u)});y[4]=d,y[5]=f;const b=new O(-m,0).transform(y);e=b.x,s=b.y}return'<tspan x="'.concat(kt(e,n),'" y="').concat(kt(s,n),'" ').concat(c).concat(p).concat(o,">").concat(jv(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Ti),r=this._textLines[t];let o,h,c,u,d,f="",g=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let p=0,m=r.length-1;p<=m;p++)d=p===m||this.charSpacing||this.path,f+=r[p],c=this.__charBounds[t][p],g===0?(e+=c.kernedWidth-c.width,g+=c.width):g+=c.kernedWidth,n&&!d&&this._reSpaceAndTab.test(r[p])&&(d=!0),d||(o=o||this.getCompleteStyleDeclaration(t,p),h=this.getCompleteStyleDeclaration(t,p+1),d=Du(o,h,!0)),d&&(u=this._getStyleDeclaration(t,p),a.push(this._createTextCharSpan(f,u,e,s,c)),f="",o=h,this.direction==="rtl"?e-=g:e+=g,g=0)}_setSVGTextLineBg(a,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,o=0,h=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let u=0;u<i.length;u++){const{left:d,width:f,kernedWidth:g}=this.__charBounds[t][u];r=this.getValueOfPropertyAt(t,u,"textBackgroundColor"),r!==c?(c&&a.push(...wg(c,e+h,s,o,n)),h=d,o=f,c=r):o+=g}r&&a.push(...wg(c,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)," text-decoration-thickness: ").concat(kt(this.textDecorationThickness*this.getObjectScaling().y/10,mt.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(a,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:o,fontWeight:h,deltaY:c,textDecorationThickness:u,linethrough:d,overline:f,underline:g}=a,p=this.getSvgTextDecoration({underline:g??this.underline,overline:f??this.overline,linethrough:d??this.linethrough}),m=u||this.textDecorationThickness;return[i?el(Ge,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,"; "):"",p?"text-decoration: ".concat(p,"; text-decoration-thickness: ").concat(kt(m*this.getObjectScaling().y/10,mt.NUM_FRACTION_DIGITS),"%; "):"",n?el(ee,n):"",c?"baseline-shift: ".concat(-c,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter(t=>a[t.replace("-","")]).join(" ")}}]),G.setClass(Pe),G.setSVGClass(Pe);class Dx{constructor(t){k(this,"target",void 0),k(this,"__mouseDownInPlace",!1),k(this,"__dragStartFired",!1),k(this,"__isDraggingOver",!1),k(this,"__dragStartSelection",void 0),k(this,"__dragImageDisposer",void 0),k(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 O(r.flipX?-1:1,r.flipY?-1:1),c=r._getCursorBoundaries(i),u=new O(c.left+c.leftOffset,c.top+c.topOffset).multiply(h).transform(r.calcTransformMatrix()),d=o.getScenePoint(t).subtract(u),f=r.getCanvasRetinaScaling(),g=r.getBoundingRect(),p=u.subtract(new O(g.left,g.top)),m=o.viewportTransform,y=p.add(d).transform(m,!0),b=r.backgroundColor,x=cg(r.styles);r.backgroundColor="";const C={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(C,0,i),r.setSelectionStyles(C,n,r.text.length),r.dirty=!0;const S=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=b,r.styles=x,r.dirty=!0,Nu(S,{position:"fixed",left:"".concat(-S.width,"px"),border:ze,width:"".concat(S.width/f,"px"),height:"".concat(S.height/f,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{S.remove()},Js(t.target||this.target.hiddenTextarea).body.appendChild(S),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(S,y.x,y.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=E({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:c}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},u=n[Math.max(0,n.length-1)],d=0;if(this.__dragStartSelection){const f=this.__dragStartSelection.selectionStart,g=this.__dragStartSelection.selectionEnd;h>f&&h<=g?h=f:h>g&&(h-=g-f),r.removeChars(f,g),delete this.__dragStartSelection}r._reNewline.test(u)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,c,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+d,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(uu,{index:h+d,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)||ze;h===ze?(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(uu,{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 _0=/[ \n\.,;!\?\-]/;class Rx extends Pe{constructor(){super(...arguments),k(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 ag({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}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}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||!Lf.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!_0.test(n);)i+=e,n=s[i];return e===-1&&_0.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}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;Js(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(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-r,g=d-r,p=new O(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new O(c.clientWidth/u,c.clientHeight/d));return p.x<0&&(p.x=0),p.x>f&&(p.x=f),p.y<0&&(p.y=0),p.y>g&&(p.y=g),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(fu),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 c=i;c<r;c++)delete o[c];for(const c in this.styles[s]){const u=parseInt(c,10);u>=r&&(o[u-h]=o[c],delete o[c])}}}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 c=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const d in this.styles[t]){const f=parseInt(d,10);f>=e&&(h=!0,n[f-e]=this.styles[t][d],o&&e===0||delete this.styles[t][d])}let u=!1;for(h&&!o&&(this.styles[t+s]=n,u=!0),(u||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:E({},i[s-1])}:c?this.styles[t+s]={0:E({},c)}: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?E({},n):{};s||(s=1);for(const h in r){const c=parseInt(h,10);c>=e&&(n[c+s]=r[c],r[c-s]||delete n[c])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=E({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=E({},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]===`
85
- `?(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=wt:this._selectionDirection===$t&&(this._selectionDirection=wt,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===$t?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=$t:this._selectionDirection===wt&&(this._selectionDirection=$t,this.selectionStart=e),this.selectionEnd=s)}}class Fx extends Rx{initHiddenTextarea(){const t=this.canvas&&Js(this.canvas.getElement())||ua(),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,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(uu),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const o=this._splitTextIntoLines(s).graphemeText,h=this._text.length,c=o.length,u=this.selectionStart,d=this.selectionEnd,f=u!==d;let g,p,m,y,b=c-h;const x=this.fromStringToGraphemeSelection(i,n,s),C=u>x.selectionStart;f?(p=this._text.slice(u,d),b+=d-u):c<h&&(p=C?this._text.slice(d+b,d):this._text.slice(u,u-b));const S=o.slice(x.selectionEnd-b,x.selectionEnd);if(p&&p.length&&(S.length&&(g=this.getSelectionStyles(u,u+1,!1),g=S.map(()=>g[0])),f?(m=u,y=d):C?(m=d-p.length,y=d):(m=d,y=d+p.length),this.removeStyleFromTo(m,y)),S.length){const{copyPasteData:T}=xi();e&&S.join("")===T.copiedText&&!mt.disableStyleCopyPaste&&(g=T.copiedTextStyle),this.insertNewStyleBlock(S,u,g)}r()}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}=xi();t.copiedText=this.getSelectedText(),mt.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),c=this._textLines[n].slice(0,r),u=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-c.length+(1-u)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,c=s.length;h<c;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const u=r-i,d=r,f=Math.abs(u-e);o=Math.abs(d-e)<f?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===$t);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=zr(0,this.selectionStart,i),this.selectionEnd=zr(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===wt?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=wt,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===$t&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=wt,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===wt&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=$t,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=$t,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const w0=a=>!!a.button;class Lx extends Fx{constructor(){super(...arguments),k(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("mousetripleclick",this.tripleClickHandler),this.draggableTextDelegate=new Dx(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!w0(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}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||w0(e)||i||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}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(ns(this.calcTransformMatrix())).add(new O(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let c=0;c<this._textLines.length&&s<=e.y;c++)s+=this.getHeightOfLine(c),n=c,c>0&&(i+=this._textLines[c-1].length+this.missingNewlineOffset(c-1));let r=Math.abs(this._getLineLeftOffset(n));const o=this._textLines[n].length,h=this.__charBounds[n];for(let c=0;c<o;c++){const u=r+h[c].kernedWidth;if(e.x<=u){Math.abs(e.x-u)<=Math.abs(e.x-r)&&i++;break}r=u,i++}return Math.min(this.flipX?o-i:i,this._text.length)}}const Vu="moveCursorUp",Gu="moveCursorDown",Wu="moveCursorLeft",Xu="moveCursorRight",Uu="exitEditing",x0=(a,t)=>{const e=t.getRetinaScaling();a.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;a.transform(s[0],s[1],s[2],s[3],s[4],s[5])},Ix=E({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:Uu,27:Uu,33:Vu,34:Gu,35:Xu,36:Wu,37:Wu,38:Vu,39:Xu,40:Gu},keysMapRtl:{9:Uu,27:Uu,33:Vu,34:Gu,35:Wu,36:Xu,37:Xu,38:Vu,39:Wu,40:Gu},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class on extends Lx{static getDefaults(){return E(E({},super.getDefaults()),on.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,E(E({},on.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 bg&&this.canvas.textEditingManager.remove(this),e instanceof bg&&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||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),i=s.length>0;let n,r=t;if(i){n=ps(t.canvas),r=n.getContext("2d"),x0(r,this.canvas);const o=this.calcTransformMatrix();r.transform(o[0],o[1],o[2],o[3],o[4],o[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const o of s){const h=o.clipPath,c=ps(t.canvas),u=c.getContext("2d");if(x0(u,this.canvas),!h.absolutePositioned){const d=o.calcTransformMatrix();u.transform(d[0],d[1],d[2],d[3],d[4],d[5])}h.transform(u),h.drawObject(u,!0,{}),this.drawClipPathOnCache(r,h,c)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_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 c=0;c<n;c++)e+=this.getHeightOfLine(c);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===$t||this.textAlign===Ti||this.textAlign===sl?h.left*=-1:this.textAlign===wt||this.textAlign===Su?h.left=r-(s>0?s:0):this.textAlign!==rt&&this.textAlign!==il||(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,c=this.getValueOfPropertyAt(i,n,"deltaY"),u=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:u+e.top+c,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:o,width:h,height:c}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,h,c)}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(Ti),o=this.get2DCursorLocation(i),h=this.get2DCursorLocation(n),c=o.lineIndex,u=h.lineIndex,d=o.charIndex<0?0:o.charIndex,f=h.charIndex<0?0:h.charIndex;for(let g=c;g<=u;g++){const p=this._getLineLeftOffset(g)||0;let m=this.getHeightOfLine(g),y=0,b=0,x=0;if(g===c&&(b=this.__charBounds[c][d].left),g>=c&&g<u)x=r&&!this.isEndOfWrapping(g)?this.width:this.getLineWidth(g)||5;else if(g===u)if(f===0)x=this.__charBounds[u][f].left;else{const M=this._getWidthOfCharSpacing();x=this.__charBounds[u][f-1].left+this.__charBounds[u][f-1].width-M}y=m,(this.lineHeight<1||g===u&&this.lineHeight>1)&&(m/=this.lineHeight);let C=s.left+p+b,S=m,T=0;const P=x-b;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,T=m):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===$t||this.textAlign===Ti||this.textAlign===sl?C=this.width-C-P:this.textAlign===wt||this.textAlign===Su?C=s.left+p-x:this.textAlign!==rt&&this.textAlign!==il||(C=s.left+p-x)),t.fillRect(C,s.top+s.topOffset+T,P,S),s.topOffset+=y}}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,ee)}_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()}}k(on,"ownDefaults",Ix),k(on,"type","IText"),G.setClass(on),G.setClass(on,"i-text");class Xr extends on{static getDefaults(){return E(E({},super.getDefaults()),Xr.ownDefaults)}constructor(t,e){super(t,E(E({},Xr.ownDefaults),e))}static createControls(){return{controls:ww()}}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(Ti)&&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]===`
86
- `&&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 c in h)for(const u in h[c]){const d=parseInt(u,10);if(d>=s&&(!n||d<e))for(const f in h[c][u])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(c=>{const u=e?[c]:this.graphemeSplit(c),d=this._measureWord(u,r,o);return i=Math.max(d,i),o+=u.length+s.length,{word:u,width:d}})}),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,c=[],u=h?"":" ";let d=0,f=[],g=0,p=0,m=!0;e-=r;const y=Math.max(e,i,this.dynamicMinWidth),b=n[t];let x;for(g=0,x=0;x<b.length;x++){const{word:C,width:S}=b[x];g+=C.length,d+=p+S-o,d>y&&!m?(c.push(f),f=[],d=S,m=!0):d+=o,m||h||f.push(u),f=f.concat(C),p=h?0:this._measureWord([u],t,g),g++,m=!1}return x&&c.push(f),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),c}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])}}k(Xr,"type","Textbox"),k(Xr,"textLayoutProperties",[...on.textLayoutProperties,"width"]),k(Xr,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),G.setClass(Xr);class S0 extends Iu{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}=Ai(qv(s,i)),h=new O(r,o);if(i.absolutePositioned)return{center:Br(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:h};{const c=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:u=new O,correction:d=new O}=this.calcBoundingBox(e,t)||{};return{center:u.add(c),correction:d.subtract(c),size:h}}return{center:s.getRelativeCenterPoint().add(c),size:h}}}}k(S0,"type","clip-path"),G.setClass(S0);class C0 extends Iu{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new O(s.width||i.x,s.height||i.y)}}k(C0,"type","fixed"),G.setClass(C0);class jx extends al{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 Ur extends Fs{static getDefaults(){return E(E({},super.getDefaults()),Ur.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,Ur.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new jx})}_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))?(Ki("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===fg?s.forEach(i=>{i._onAfterObjectsChange(Fu,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=E(E({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()}}k(Ur,"type","ActiveSelection"),k(Ur,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),G.setClass(Ur),G.setClass(Ur,"activeSelection");class Nx{constructor(){k(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(c=>{c.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 A0{constructor(){let{tileSize:t=mt.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};k(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),k(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=ps({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 c;r&&(c=this.getCachedTexture(r,e));const u={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:i,destinationWidth:s,destinationHeight:i,context:o,sourceTexture:this.createTexture(o,s,i,c?void 0:e),targetTexture:this.createTexture(o,s,i),originalTexture:c||this.createTexture(o,s,i,c?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},d=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,d),t.forEach(f=>{f&&f.applyTo(u)}),function(f){const g=f.targetCanvas,p=g.width,m=g.height,y=f.destinationWidth,b=f.destinationHeight;p===y&&m===b||(g.width=y,g.height=b)}(u),this.copyGLTo2D(o,u),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(u.sourceTexture),o.deleteTexture(u.targetTexture),o.deleteFramebuffer(d),h.setTransform(1,0,0,1,0,0),u}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:c,CLAMP_TO_EDGE:u,TEXTURE_MAG_FILTER:d,TEXTURE_MIN_FILTER:f,TEXTURE_WRAP_S:g,TEXTURE_WRAP_T:p}=t,m=t.createTexture();return t.bindTexture(o,m),t.texParameteri(o,d,n||r),t.texParameteri(o,f,n||r),t.texParameteri(o,g,u),t.texParameteri(o,p,u),i?t.texImage2D(o,0,h,h,c,i):t.texImage2D(o,0,h,e,s,0,h,c,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 c=new ImageData(h,i,n);s.putImageData(c,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let Sg;function Bx(){const{WebGLProbe:a}=xi();return a.queryWebGL(Si()),mt.enableGLFiltering&&a.isSupported(mt.textureSize)?new A0({tileSize:mt.textureSize}):new Nx}function Cg(){return!Sg&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(Sg=Bx()),Sg}const Hx=["filters","resizeFilter","src","crossOrigin","type"],T0=["cropX","cropY"];class Me extends ke{static getDefaults(){return E(E({},super.getDefaults()),Me.ownDefaults)}constructor(t,e){super(),k(this,"_lastScaleX",1),k(this,"_lastScaleY",1),k(this,"_filterScalingX",1),k(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Me.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(Wn()),this.setElement(typeof t=="string"?(this.canvas&&Js(this.canvas.getElement())||ua()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=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(s),(e=t.classList)===null||e===void 0||e.add(Me.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=Cg(!1);e instanceof A0&&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&&xi().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())}),E(E({},super.toObject([...T0,...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 c=Wn();n.push('<clipPath id="imageCrop_'+c+`">
74
+ `),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:a}=this.coords,l=this.type==="linear"?t.createLinearGradient(e,s,i,n):t.createRadialGradient(e,s,r,i,n,a);return this.colorStops.forEach(h=>{let{color:c,opacity:u,offset:d}=h;l.addColorStop(d,u!==void 0?new ht(c).setAlpha(u).toRgba():c)}),l}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(x(x({},t),{},{colorStops:e?e.map(i=>x({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=Ql(t),n=e._findCenterFromElement();return new this(x({id:t.getAttribute("id")||void 0,type:Jl(t),coords:Rd(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:Dd(t,s.opacity),gradientUnits:i,gradientTransform:pn(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}S(ki,"type","Gradient"),I.setClass(ki,"gradient"),I.setClass(ki,"linear"),I.setClass(ki,"radial");const Fd=["type","source","patternTransform"];class oa{get type(){return"pattern"}set type(t){Xe("warn","Setting type has no effect",t)}constructor(t){S(this,"repeat","repeat"),S(this,"offsetX",0),S(this,"offsetY",0),S(this,"crossOrigin",""),this.id=rs(),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 x(x({},ys(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:ct(this.offsetX,nt.NUM_FRACTION_DIGITS),offsetY:ct(this.offsetY,nt.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,a=Qs(this.offsetX/e,0),l=Qs(this.offsetY/s,0),h=n==="repeat-y"||n==="no-repeat"?1+Math.abs(a||0):Qs(i.width/e,0),c=n==="repeat-x"||n==="no-repeat"?1+Math.abs(l||0):Qs(i.height/s,0);return['<pattern id="SVGID_'.concat(r,'" x="').concat(a,'" y="').concat(l,'" width="').concat(h,'" height="').concat(c,'">'),'<image x="0" y="0" width="'.concat(i.width,'" height="').concat(i.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
75
+ `)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=pt(t,Fd);const a=await mi(i,x(x({},e),{},{crossOrigin:r.crossOrigin}));return new this(x(x({},r),{},{patternTransform:n&&n.slice(0),source:a}))}}S(oa,"type","Pattern"),I.setClass(oa),I.setClass(oa,"pattern");const Ld=["path","left","top"],Id=["d"];class Cs extends Ht{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=pt(e,Ld);super(),Object.assign(this,Cs.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(ot,i),typeof n=="number"&&this.set(ie,n)}_setPath(t,e){this.path=jl(Array.isArray(t)?t:Xl(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new A(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 x(x({},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=Ul(this.path,nt.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
76
+ `)]}_getOffsetTransform(){const t=nt.NUM_FRACTION_DIGITS;return" translate(".concat(ct(-this.pathOffset.x,t),", ").concat(ct(-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(...na(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(...na(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 Ne(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return x(x({},t),{},{pathOffset:new A(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=Ke(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,x(x(x({},pt(i,Id)),e),{},{left:void 0,top:void 0}))}}S(Cs,"type","Path"),S(Cs,"cacheProperties",[...$e,"path","fillRule"]),S(Cs,"ATTRIBUTE_NAMES",[...as,"d"]),I.setClass(Cs),I.setSVGClass(Cs);const jd=["left","top","radius"],Zl=["radius","startAngle","endAngle","counterClockwise"];class Qe extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Qe.ownDefaults)}constructor(t){super(),Object.assign(this,Qe.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,wt(this.startAngle),wt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get($t)}getRadiusY(){return this.get("radius")*this.get(ce)}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([...Zl,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
77
+ `];{const{radius:e}=this,s=wt(this.startAngle),i=wt(this.endAngle),n=xe(s)*e,r=Se(s)*e,a=xe(i)*e,l=Se(i)*e,h=t>180?1:0,c=this.counterClockwise?0:1;return['<path d="M '.concat(n," ").concat(r," A ").concat(e," ").concat(e," 0 ").concat(h," ").concat(c," ").concat(a," ").concat(l,'" '),"COMMON_PARTS",` />
78
+ `]}}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:a=0}=i;return new this(x(x({},pt(i,jd)),{},{radius:a,left:n-a,top:r-a}))}static fromObject(t){return super._fromObject(t)}}S(Qe,"type","Circle"),S(Qe,"cacheProperties",[...$e,...Zl]),S(Qe,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),S(Qe,"ATTRIBUTE_NAMES",["cx","cy","r",...as]),I.setClass(Qe),I.setSVGClass(Qe);const Nd=["x1","y1","x2","y2"],Bd=["x1","y1","x2","y2"],la=["x1","x2","y1","y2"];class As extends Ht{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,As.ownDefaults),this.setOptions(n),this.x1=t,this.x2=s,this.y1=e,this.y2=i,this._setWidthHeight();const{left:r,top:a}=n;typeof r=="number"&&this.set(ot,r),typeof a=="number"&&this.set(ie,a)}_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:a,height:l}=Ne([{x:t,y:e},{x:s,y:i}]),h=new A(n+a/2,r+l/2);this.setPositionByOrigin(h,q,q)}_set(t,e){return super._set(t,e),la.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;pe(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 A((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return x(x({},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,a=t<=e?-1:1,l=s<=i?-1:1;return{x1:a*n/2,x2:a*-n/2,y1:l*r/2,y2:l*-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,`" />
79
+ `)]}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s),{x1:n=0,y1:r=0,x2:a=0,y2:l=0}=i;return new this([n,r,a,l],pt(i,Nd))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=pt(t,Bd);return this._fromObject(x(x({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}S(As,"type","Line"),S(As,"cacheProperties",[...$e,...la]),S(As,"ATTRIBUTE_NAMES",as.concat(la)),I.setClass(As),I.setSVGClass(As);class Ts extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Ts.ownDefaults)}constructor(t){super(),Object.assign(this,Ts.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),'" />']}}S(Ts,"type","Triangle"),S(Ts,"ownDefaults",{width:100,height:100}),I.setClass(Ts),I.setSVGClass(Ts);const th=["rx","ry"];class Ze extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Ze.ownDefaults)}constructor(t){super(),Object.assign(this,Ze.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($t)}getRy(){return this.get("ry")*this.get(ce)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...th,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
80
+ `)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Ue,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function Hd(o){if(!o)return[];const t=o.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}S(Ze,"type","Ellipse"),S(Ze,"cacheProperties",[...$e,...th]),S(Ze,"ownDefaults",{rx:0,ry:0}),S(Ze,"ATTRIBUTE_NAMES",[...as,"cx","cy","rx","ry"]),I.setClass(Ze),I.setSVGClass(Ze);const zd=["left","top"],eh={exactBoundingBox:!1};class Pe extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Pe.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),S(this,"strokeDiff",void 0),Object.assign(this,Pe.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(ot,s),typeof i=="number"&&this.set(ie,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return yl(this.points,t,this.isOpen())}_calcDimensions(t){t=x({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(h=>h.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new A,strokeOffset:new A,strokeDiff:new A};const s=Ne(e),i=pi(x(x({},t),{},{scaleX:1,scaleY:1})),n=Ne(this.points.map(h=>Bt(h,i,!0))),r=new A(this.scaleX,this.scaleY);let a=s.left+s.width/2,l=s.top+s.height/2;return this.exactBoundingBox&&(a-=l*Math.tan(wt(this.skewX)),l-=a*Math.tan(wt(this.skewY))),x(x({},s),{},{pathOffset:new A(a,l),strokeOffset:new A(n.left,n.top).subtract(new A(s.left,s.top)).multiply(r),strokeDiff:new A(s.width,s.height).subtract(new A(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Ne(this.points);return new A(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:a,strokeDiff:l}=this._calcDimensions();this.set({width:i,height:n,pathOffset:r,strokeOffset:a,strokeDiff:l}),t&&this.setPositionByOrigin(new A(e+i/2,s+n/2),q,q)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new A(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(a=>this.strokeUniform||this.constructor.layoutProperties.includes(a))){var e,s;const{width:a,height:l}=this._calcDimensions(t);r=new A((e=t.width)!==null&&e!==void 0?e:a,(s=t.height)!==null&&s!==void 0?s:l)}else{var i,n;r=new A((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new A(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===$t||t===ce)&&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 x(x({},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=nt.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(ct(this.points[n].x-e,i),",",ct(this.points[n].y-s,i)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
81
+ `)]}_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(Hd(t.getAttribute("points")),x(x({},pt(Ke(t,this.ATTRIBUTE_NAMES,s),zd)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}S(Pe,"ownDefaults",eh),S(Pe,"type","Polyline"),S(Pe,"layoutProperties",[Bs,Hs,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),S(Pe,"cacheProperties",[...$e,"points"]),S(Pe,"ATTRIBUTE_NAMES",[...as]),I.setClass(Pe),I.setSVGClass(Pe);class Sn extends Pe{isOpen(){return!1}}S(Sn,"ownDefaults",eh),S(Sn,"type","Polygon"),I.setClass(Sn),I.setSVGClass(Sn);class sh extends Ht{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,a=0;for(const l in e){s=0;for(const h in e[l]){const c=e[l][h]||{};n++,c[t]!==void 0?(i?c[t]!==i&&(r=!1):i=c[t],c[t]===this[t]&&delete c[t]):r=!1,Object.keys(c).length!==0?s++:delete e[l][h]}s===0&&delete e[l]}for(let l=0;l<this._textLines.length;l++)a+=this._textLines[l].length;r&&n===a&&(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=Or(x(x({},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 x(x({},ys(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]}}S(sh,"_styleProperties",tu);const Vd=/ +/g,Gd=/"/g;function ha(o,t,e,s,i){return" ".concat(function(n,r){let{left:a,top:l,width:h,height:c}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nt.NUM_FRACTION_DIGITS;const d=_i(kt,n,!1),[f,g,p,v]=[a,l,h,c].map(m=>ct(m,u));return"<rect ".concat(d,' x="').concat(f,'" y="').concat(g,'" width="').concat(p,'" height="').concat(v,'"></rect>')}(o,{left:t,top:e,width:s,height:i}),`
82
+ `)}const Wd=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let ca;class zt extends sh{static getDefaults(){return x(x({},super.getDefaults()),zt.ownDefaults)}constructor(t,e){super(),S(this,"__charBounds",[]),Object.assign(this,zt.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=ra(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(Be)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,a;for(let l=0,h=this._textLines.length;l<h;l++)if((this.textAlign===Be||l!==h-1&&!this.isEndOfWrapping(l))&&(i=0,n=this._textLines[l],e=this.getLineWidth(l),e<this.width&&(a=this.textLines[l].match(this._reSpacesAndTabs)))){s=a.length,t=(this.width-e)/s;for(let c=0;c<=n.length;c++)r=this.__charBounds[l][c],this._reSpaceAndTab.test(n[c])?(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===qt?(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=ie;break;case"descender":t.textBaseline=xr}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 a=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=a;continue}const l=this._textLines[n].length,h=this._getLineLeftOffset(n);let c,u,d=0,f=0,g=this.getValueOfPropertyAt(n,0,"textBackgroundColor");for(let p=0;p<l;p++){const v=this.__charBounds[n][p];u=this.getValueOfPropertyAt(n,p,"textBackgroundColor"),this.path?(t.save(),t.translate(v.renderLeft,v.renderTop),t.rotate(v.angle),t.fillStyle=u,u&&t.fillRect(-v.width/2,-a/this.lineHeight*(1-this._fontSizeFraction),v.width,a/this.lineHeight),t.restore()):u!==g?(c=s+h+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=g,g&&t.fillRect(c,i,d,a/this.lineHeight),f=v.left,d=v.width,g=u):d+=v.kernedWidth}u&&!this.path&&(c=s+h+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=u,t.fillRect(c,i,d,a/this.lineHeight)),i+=a}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=di.getFontCache(e),r=this._getFontDeclaration(e),a=s+t,l=s&&r===this._getFontDeclaration(i),h=e.fontSize/this.CACHE_FONT_SIZE;let c,u,d,f;if(s&&n[s]!==void 0&&(d=n[s]),n[t]!==void 0&&(f=c=n[t]),l&&n[a]!==void 0&&(u=n[a],f=u-d),c===void 0||d===void 0||u===void 0){const g=function(){return ca||(ca=ue({width:0,height:0}).getContext("2d")),ca}();this._setTextStyles(g,e,!0),c===void 0&&(f=c=g.measureText(t).width,n[t]=c),d===void 0&&l&&s&&(d=g.measureText(s).width,n[s]=d),l&&u===void 0&&(u=g.measureText(a).width,n[a]=u,f=u-d)}return{width:c*h,kernedWidth:f*h}}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===xt,r=this.path,a=this._textLines[t],l=a.length,h=new Array(l);this.__charBounds[t]=h;for(let c=0;c<l;c++){const u=a[c];s=this._getGraphemeBox(u,t,c,e),h[c]=s,i+=s.kernedWidth,e=u}if(h[l]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let c=0;const u=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case ot:c=n?u-i:0;break;case q:c=(u-i)/2;break;case xt:c=n?0:u-i}c+=this.pathStartOffset*(n?-1:1);for(let d=n?l-1:0;n?d>=0:d<l;n?d--:d++)s=h[d],c>u?c%=u:c<0&&(c+=u),this._setGraphemeOnPath(c,s),c+=s.kernedWidth}return{width:i,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,i=this.path,n=Gl(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===xt?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),a=i?this.getCompleteStyleDeclaration(e,s-1):{},l=this._measureChar(t,r,i,a);let h,c=l.kernedWidth,u=l.width;this.charSpacing!==0&&(h=this._getWidthOfCharSpacing(),u+=h,c+=h);const d={width:u,left:0,height:r.fontSize,kernedWidth:c,deltaY:r.deltaY};if(s>0&&!n){const f=this.__charBounds[e][s-1];d.left=f.left+f.width+l.kernedWidth-l.width}return d}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,a=this._textLines.length;r<a;r++){const l=this.getHeightOfLine(r),h=l/this.lineHeight,c=this._getLineLeftOffset(r);this._renderTextLine(e,t,this._textLines[r],i+c,n+s+h,r),s+=l}t.restore()}_renderTextFill(t){(this.fill||this.styleHas(kt))&&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 a=this.getHeightOfLine(r),l=this.textAlign.includes(Be),h=this.path,c=!l&&this.charSpacing===0&&this.isEmptyStyles(r)&&!h,u=this.direction==="ltr",d=this.direction==="ltr"?1:-1,f=e.direction;let g,p,v,m,b,_="",w=0;if(e.save(),f!==this.direction&&(e.canvas.setAttribute("dir",u?"ltr":"rtl"),e.direction=u?"ltr":"rtl",e.textAlign=u?ot:xt),n-=a*this._fontSizeFraction/this.lineHeight,c)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let C=0,T=s.length-1;C<=T;C++)m=C===T||this.charSpacing||h,_+=s[C],v=this.__charBounds[r][C],w===0?(i+=d*(v.kernedWidth-v.width),w+=v.width):w+=v.kernedWidth,l&&!m&&this._reSpaceAndTab.test(s[C])&&(m=!0),m||(g=g||this.getCompleteStyleDeclaration(r,C),p=this.getCompleteStyleDeclaration(r,C+1),m=gn(g,p,!1)),m&&(h?(e.save(),e.translate(v.renderLeft,v.renderTop),e.rotate(v.angle),this._renderChar(t,e,r,C,_,-w/2,0),e.restore()):(b=i,this._renderChar(t,e,r,C,_,b,n)),_="",g=p,i+=d*w,w=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=ue({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 pe(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,a){const l=this._getStyleDeclaration(s,i),h=this.getCompleteStyleDeclaration(s,i),c=t==="fillText"&&h.fill,u=t==="strokeText"&&h.stroke&&h.strokeWidth;if(u||c){if(e.save(),e.font=this._getFontDeclaration(h),l.textBackgroundColor&&this._removeShadow(e),l.deltaY&&(a+=l.deltaY),c){const d=this._setFillStyles(e,h);e.fillText(n,r-d.offsetX,a-d.offsetY)}if(u){const d=this._setStrokeStyles(e,h);e.strokeText(n,r-d.offsetX,a-d.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"),a={fontSize:n*s.size,deltaY:r+n*s.baseline};this.setSelectionStyles(a,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,i=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t);let a=0;return i===Be||i===xi&&!r||i===wi&&!r||i===rn&&!r?0:(i===q&&(a=s/2),i===xt&&(a=s),i===xi&&(a=s/2),i===wi&&(a=s),n==="rtl"&&(i===xt||i===Be||i===wi?a=0:i===ot||i===rn?a=-s:i!==q&&i!==xi||(a=-s/2)),a)}_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(),a=e==="linethrough"?.5:e==="overline"?1:0,l=this.offsets[e];for(let h=0,c=this._textLines.length;h<c;h++){const u=this.getHeightOfLine(h);if(!this[e]&&!this.styleHas(e,h)){s+=u;continue}const d=this._textLines[h],f=u/this.lineHeight,g=this._getLineLeftOffset(h);let p=0,v=0,m=this.getValueOfPropertyAt(h,0,e),b=this.getValueOfPropertyAt(h,0,kt),_=this.getValueOfPropertyAt(h,0,xs),w=m,C=b,T=_;const E=s+f*(1-this._fontSizeFraction);let k=this.getHeightOfChar(h,0),O=this.getValueOfPropertyAt(h,0,"deltaY");for(let P=0,R=d.length;P<R;P++){const F=this.__charBounds[h][P];w=this.getValueOfPropertyAt(h,P,e),C=this.getValueOfPropertyAt(h,P,kt),T=this.getValueOfPropertyAt(h,P,xs);const V=this.getHeightOfChar(h,P),M=this.getValueOfPropertyAt(h,P,"deltaY");if(n&&w&&C){const L=this.fontSize*T/1e3;t.save(),t.fillStyle=b,t.translate(F.renderLeft,F.renderTop),t.rotate(F.angle),t.fillRect(-F.kernedWidth/2,l*V+M-a*L,F.kernedWidth,L),t.restore()}else if((w!==m||C!==b||V!==k||T!==_||M!==O)&&v>0){const L=this.fontSize*_/1e3;let Y=i+g+p;this.direction==="rtl"&&(Y=this.width-Y-v),m&&b&&_&&(t.fillStyle=b,t.fillRect(Y,E+l*k+O-a*L,v,L)),p=F.left,v=F.width,m=w,_=T,b=C,k=V,O=M}else v+=F.kernedWidth}let H=i+g+p;this.direction==="rtl"&&(H=this.width-H-v),t.fillStyle=C;const N=this.fontSize*T/1e3;w&&C&&T&&t.fillRect(H,E+l*k+O-a*N,v-r,N),s+=u}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(",")||zt.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 fn(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
83
+ `];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 x(x({},super.toObject([...Yo,...t])),{},{styles:wl(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=Ke(t,zt.ATTRIBUTE_NAMES,s),n=x(x({},e),i),{textAnchor:r=ot,textDecoration:a="",dx:l=0,dy:h=0,top:c=0,left:u=0,fontSize:d=wr,strokeWidth:f=1}=n,g=pt(n,Wd),p=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),x({left:u+l,top:c+h,underline:a.includes("underline"),overline:a.includes("overline"),linethrough:a.includes("line-through"),strokeWidth:0,fontSize:d},g)),v=p.getScaledHeight()/p.height,m=((p.height+p.strokeWidth)*p.lineHeight-p.height)*v,b=p.getScaledHeight()+m;let _=0;return r===q&&(_=p.getScaledWidth()/2),r===xt&&(_=p.getScaledWidth()),p.set({left:p.left-_,top:p.top-(b-p.fontSize*(.07+p._fontSizeFraction))/p.lineHeight,strokeWidth:f}),p}static fromObject(t){return this._fromObject(x(x({},t),{},{styles:xl(t.styles||{},t.text)}),{extraParam:"text"})}}S(zt,"textLayoutProperties",Uo),S(zt,"cacheProperties",[...$e,...Yo]),S(zt,"ownDefaults",eu),S(zt,"type","Text"),S(zt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),S(zt,"ATTRIBUTE_NAMES",as.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),pl(zt,[class extends Go{_toSVG(){const o=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(o.textTop,o.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(o){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:o,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:o,withShadow:!0,additionalTransform:Ws(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(o){let{textBgRects:t,textSpans:e}=o;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ','font-family="'.concat(this.fontFamily.replace(Gd,"'"),'" '),'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>
84
+ `]}_getSVGTextAndBg(o,t){const e=[],s=[];let i,n=o;this.backgroundColor&&s.push(...ha(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let r=0,a=this._textLines.length;r<a;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(o,t,e,s,i){const n=nt.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,o!==o.trim()||!!o.match(Vd)),a=r?'style="'.concat(r,'"'):"",l=t.deltaY,h=l?' dy="'.concat(ct(l,n),'" '):"",{angle:c,renderLeft:u,renderTop:d,width:f}=i;let g="";if(u!==void 0){const p=f/2;c&&(g=' rotate="'.concat(ct(je(c),n),'"'));const v=bs({angle:je(c)});v[4]=u,v[5]=d;const m=new A(-p,0).transform(v);e=m.x,s=m.y}return'<tspan x="'.concat(ct(e,n),'" y="').concat(ct(s,n),'" ').concat(h).concat(g).concat(a,">").concat(_l(o),"</tspan>")}_setSVGTextLineText(o,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Be),r=this._textLines[t];let a,l,h,c,u,d="",f=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let g=0,p=r.length-1;g<=p;g++)u=g===p||this.charSpacing||this.path,d+=r[g],h=this.__charBounds[t][g],f===0?(e+=h.kernedWidth-h.width,f+=h.width):f+=h.kernedWidth,n&&!u&&this._reSpaceAndTab.test(r[g])&&(u=!0),u||(a=a||this.getCompleteStyleDeclaration(t,g),l=this.getCompleteStyleDeclaration(t,g+1),u=gn(a,l,!0)),u&&(c=this._getStyleDeclaration(t,g),o.push(this._createTextCharSpan(d,c,e,s,h)),d="",a=l,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(o,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,a=0,l=0,h=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let c=0;c<i.length;c++){const{left:u,width:d,kernedWidth:f}=this.__charBounds[t][c];r=this.getValueOfPropertyAt(t,c,"textBackgroundColor"),r!==h?(h&&o.push(...ha(h,e+l,s,a,n)),l=u,a=d,h=r):a+=f}r&&o.push(...ha(h,e+l,s,a,n))}_getSVGLineTopOffset(o){let t,e=0;for(t=0;t<o;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(o){return"".concat(super.getSvgStyles(o)," text-decoration-thickness: ").concat(ct(this.textDecorationThickness*this.getObjectScaling().y/10,nt.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(o,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:a,fontWeight:l,deltaY:h,textDecorationThickness:c,linethrough:u,overline:d,underline:f}=o,g=this.getSvgTextDecoration({underline:f??this.underline,overline:d??this.overline,linethrough:u??this.linethrough}),p=c||this.textDecorationThickness;return[i?_i(qt,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",a?"font-style: ".concat(a,"; "):"",l?"font-weight: ".concat(l,"; "):"",g?"text-decoration: ".concat(g,"; text-decoration-thickness: ").concat(ct(p*this.getObjectScaling().y/10,nt.NUM_FRACTION_DIGITS),"%; "):"",n?_i(kt,n):"",h?"baseline-shift: ".concat(-h,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(o){return["overline","underline","line-through"].filter(t=>o[t.replace("-","")]).join(" ")}}]),I.setClass(zt),I.setSVGClass(zt);class Xd{constructor(t){S(this,"target",void 0),S(this,"__mouseDownInPlace",!1),S(this,"__dragStartFired",!1),S(this,"__isDraggingOver",!1),S(this,"__dragStartSelection",void 0),S(this,"__dragImageDisposer",void 0),S(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,a=r.canvas,l=new A(r.flipX?-1:1,r.flipY?-1:1),h=r._getCursorBoundaries(i),c=new A(h.left+h.leftOffset,h.top+h.topOffset).multiply(l).transform(r.calcTransformMatrix()),u=a.getScenePoint(t).subtract(c),d=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),g=c.subtract(new A(f.left,f.top)),p=a.viewportTransform,v=g.add(u).transform(p,!0),m=r.backgroundColor,b=Qr(r.styles);r.backgroundColor="";const _={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(_,0,i),r.setSelectionStyles(_,n,r.text.length),r.dirty=!0;const w=r.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=m,r.styles=b,r.dirty=!0,_n(w,{position:"fixed",left:"".concat(-w.width,"px"),border:Yt,width:"".concat(w.width/d,"px"),height:"".concat(w.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{w.remove()},Ce(t.target||this.target.hiddenTextarea).body.appendChild(w),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(w,v.x,v.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=x({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,a=r.canvas;let l=r.getSelectionStartFromPointer(s);const{styles:h}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},c=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const d=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;l>d&&l<=f?l=d:l>f&&(l-=f-d),r.removeChars(d,f),delete this.__dragStartSelection}r._reNewline.test(c)&&(r._reNewline.test(r._text[l])||l===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,h,l),a.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(l+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(Ui,{index:l+u,action:"drop"}),a.fire("text:changed",{target:r}),a.contextTopDirty=!0,a.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:a}=this.__dragStartSelection,l=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||Yt;l===Yt?(i.selectionStart=r,i.selectionEnd=a,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),l==="move"&&(i.removeChars(r,a),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(Ui,{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 ih=/[ \n\.,;!\?\-]/;class Ud extends zt{constructor(){super(...arguments),S(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 qr({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}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}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||!Sr.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!ih.test(n);)i+=e,n=s[i];return e===-1&&ih.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}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;Ce(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,a=e.leftOffset,l=this.getCanvasRetinaScaling(),h=this.canvas.upperCanvasEl,c=h.width/l,u=h.height/l,d=c-r,f=u-r,g=new A(e.left+a,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new A(h.clientWidth/c,h.clientHeight/u));return g.x<0&&(g.x=0),g.x>d&&(g.x=d),g.y<0&&(g.y=0),g.y>f&&(g.y=f),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:"".concat(g.x,"px"),top:"".concat(g.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($i),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 a=i;a<this._unwrappedTextLines[s].length;a++)delete this.styles[s][a];if(this.styles[n])for(let a=r;a<this._unwrappedTextLines[n].length;a++){const l=this.styles[n][a];l&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+a-r]=l)}for(let a=s+1;a<=n;a++)delete this.styles[a];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const a=this.styles[s],l=r-i;for(let h=i;h<r;h++)delete a[h];for(const h in this.styles[s]){const c=parseInt(h,10);c>=r&&(a[c-l]=a[h],delete a[h])}}}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,a=r===e;let l=!1;s||(s=1),this.shiftLineStyles(t,s);const h=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const d=parseInt(u,10);d>=e&&(l=!0,n[d-e]=this.styles[t][u],a&&e===0||delete this.styles[t][u])}let c=!1;for(l&&!a&&(this.styles[t+s]=n,c=!0),(c||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:x({},i[s-1])}:h?this.styles[t+s]={0:x({},h)}: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?x({},n):{};s||(s=1);for(const l in r){const h=parseInt(l,10);h>=e&&(n[h+s]=r[h],r[h-s]||delete n[h])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=x({},i[s]));return}if(!n)return;const a=n[e?e-1:1];for(;a&&s--;)this.styles[t][e+s]=x({},a)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,a=0;for(let l=0;l<t.length;l++)t[l]===`
85
+ `?(a++,n[a]=0):n[a]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),a&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],a),r=1;r<a;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=ot:this._selectionDirection===xt&&(this._selectionDirection=ot,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===xt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=xt:this._selectionDirection===ot&&(this._selectionDirection=xt,this.selectionStart=e),this.selectionEnd=s)}}class Yd extends Ud{initHiddenTextarea(){const t=this.canvas&&Ce(this.canvas.getElement())||Ns(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off"}).map(r=>{let[a,l]=r;return e.setAttribute(a,l)});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[a,l]=r;return e.addEventListener(a,this[l].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,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(Ui),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const a=this._splitTextIntoLines(s).graphemeText,l=this._text.length,h=a.length,c=this.selectionStart,u=this.selectionEnd,d=c!==u;let f,g,p,v,m=h-l;const b=this.fromStringToGraphemeSelection(i,n,s),_=c>b.selectionStart;d?(g=this._text.slice(c,u),m+=u-c):h<l&&(g=_?this._text.slice(u+m,u):this._text.slice(c,c-m));const w=a.slice(b.selectionEnd-m,b.selectionEnd);if(g&&g.length&&(w.length&&(f=this.getSelectionStyles(c,c+1,!1),f=w.map(()=>f[0])),d?(p=c,v=u):_?(p=u-g.length,v=u):(p=u,v=u+g.length),this.removeStyleFromTo(p,v)),w.length){const{copyPasteData:C}=Le();e&&w.join("")===C.copiedText&&!nt.disableStyleCopyPaste&&(f=C.copiedTextStyle),this.insertNewStyleBlock(w,c,f)}r()}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}=Le();t.copiedText=this.getSelectedText(),nt.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,a=this._getWidthBeforeCursor(n,r),l=this._getIndexOnLine(n+1,a);return this._textLines[n].slice(r).length+l+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,a=this._getWidthBeforeCursor(n,r),l=this._getIndexOnLine(n-1,a),h=this._textLines[n].slice(0,r),c=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+l-h.length+(1-c)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),a=0;for(let l=0,h=s.length;l<h;l++)if(i=this.__charBounds[t][l].width,r+=i,r>e){n=!0;const c=r-i,u=r,d=Math.abs(c-e);a=Math.abs(u-e)<d?l:l-1;break}return n||(a=s.length-1),a}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===xt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=Ss(0,this.selectionStart,i),this.selectionEnd=Ss(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===ot?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=ot,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===xt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=ot,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===ot&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=xt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=xt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const nh=o=>!!o.button;class $d extends Yd{constructor(){super(...arguments),S(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("mousetripleclick",this.tripleClickHandler),this.draggableTextDelegate=new Xd(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!nh(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}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||nh(e)||i||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}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(ne(this.calcTransformMatrix())).add(new A(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let h=0;h<this._textLines.length&&s<=e.y;h++)s+=this.getHeightOfLine(h),n=h,h>0&&(i+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));let r=Math.abs(this._getLineLeftOffset(n));const a=this._textLines[n].length,l=this.__charBounds[n];for(let h=0;h<a;h++){const c=r+l[h].kernedWidth;if(e.x<=c){Math.abs(e.x-c)<=Math.abs(e.x-r)&&i++;break}r=c,i++}return Math.min(this.flipX?a-i:i,this._text.length)}}const Cn="moveCursorUp",An="moveCursorDown",Tn="moveCursorLeft",En="moveCursorRight",kn="exitEditing",rh=(o,t)=>{const e=t.getRetinaScaling();o.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;o.transform(s[0],s[1],s[2],s[3],s[4],s[5])},qd=x({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:kn,27:kn,33:Cn,34:An,35:En,36:Tn,37:Tn,38:Cn,39:En,40:An},keysMapRtl:{9:kn,27:kn,33:Cn,34:An,35:Tn,36:En,37:En,38:Cn,39:Tn,40:An},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class ts extends $d{static getDefaults(){return x(x({},super.getDefaults()),ts.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,x(x({},ts.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 aa&&this.canvas.textEditingManager.remove(this),e instanceof aa&&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||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),i=s.length>0;let n,r=t;if(i){n=ue(t.canvas),r=n.getContext("2d"),rh(r,this.canvas);const a=this.calcTransformMatrix();r.transform(a[0],a[1],a[2],a[3],a[4],a[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const a of s){const l=a.clipPath,h=ue(t.canvas),c=h.getContext("2d");if(rh(c,this.canvas),!l.absolutePositioned){const u=a.calcTransformMatrix();c.transform(u[0],u[1],u[2],u[3],u[4],u[5])}l.transform(c),l.drawObject(c,!0,{}),this.drawClipPathOnCache(r,l,h)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_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 h=0;h<n;h++)e+=this.getHeightOfLine(h);const r=this._getLineLeftOffset(n),a=this.__charBounds[n][i];a&&(s=a.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const l={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===xt||this.textAlign===Be||this.textAlign===wi?l.left*=-1:this.textAlign===ot||this.textAlign===rn?l.left=r-(s>0?s:0):this.textAlign!==q&&this.textAlign!==xi||(l.left=r-(s>0?s:0))),l}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"),a=this.getObjectScaling().x*this.canvas.getZoom(),l=this.cursorWidth/a,h=this.getValueOfPropertyAt(i,n,"deltaY"),c=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-l/2,top:c+e.top+h,width:l,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:a,width:l,height:h}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,a,l,h)}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(Be),a=this.get2DCursorLocation(i),l=this.get2DCursorLocation(n),h=a.lineIndex,c=l.lineIndex,u=a.charIndex<0?0:a.charIndex,d=l.charIndex<0?0:l.charIndex;for(let f=h;f<=c;f++){const g=this._getLineLeftOffset(f)||0;let p=this.getHeightOfLine(f),v=0,m=0,b=0;if(f===h&&(m=this.__charBounds[h][u].left),f>=h&&f<c)b=r&&!this.isEndOfWrapping(f)?this.width:this.getLineWidth(f)||5;else if(f===c)if(d===0)b=this.__charBounds[c][d].left;else{const E=this._getWidthOfCharSpacing();b=this.__charBounds[c][d-1].left+this.__charBounds[c][d-1].width-E}v=p,(this.lineHeight<1||f===c&&this.lineHeight>1)&&(p/=this.lineHeight);let _=s.left+g+m,w=p,C=0;const T=b-m;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",w=1,C=p):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===xt||this.textAlign===Be||this.textAlign===wi?_=this.width-_-T:this.textAlign===ot||this.textAlign===rn?_=s.left+g-b:this.textAlign!==q&&this.textAlign!==xi||(_=s.left+g-b)),t.fillRect(_,s.top+s.topOffset+C,T,w),s.topOffset+=v}}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,kt)}_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()}}S(ts,"ownDefaults",qd),S(ts,"type","IText"),I.setClass(ts),I.setClass(ts,"i-text");class Es extends ts{static getDefaults(){return x(x({},super.getDefaults()),Es.ownDefaults)}constructor(t,e){super(t,x(x({},Es.ownDefaults),e))}static createControls(){return{controls:Fu()}}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(Be)&&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]===`
86
+ `&&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],a=this._styleMap[t+1];r&&(t=r.line,s=r.offset),a&&(i=a.line,n=i===t,e=a.offset);const l=t===void 0?this.styles:{line:this.styles[t]};for(const h in l)for(const c in l[h]){const u=parseInt(c,10);if(u>=s&&(!n||u<e))for(const d in l[h][c])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 a=0;const l=e?this.graphemeSplit(n):this.wordSplit(n);return l.length===0?[{word:[],width:0}]:l.map(h=>{const c=e?[h]:this.graphemeSplit(h),u=this._measureWord(c,r,a);return i=Math.max(u,i),a+=c.length+s.length,{word:c,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,a=t.length;r<a;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 a=this._getWidthOfCharSpacing(),l=this.splitByGrapheme,h=[],c=l?"":" ";let u=0,d=[],f=0,g=0,p=!0;e-=r;const v=Math.max(e,i,this.dynamicMinWidth),m=n[t];let b;for(f=0,b=0;b<m.length;b++){const{word:_,width:w}=m[b];f+=_.length,u+=g+w-a,u>v&&!p?(h.push(d),d=[],u=w,p=!0):u+=a,p||l||d.push(c),d=d.concat(_),g=l?0:this._measureWord([c],t,f),f++,p=!1}return b&&h.push(d),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-a+r),h}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])}}S(Es,"type","Textbox"),S(Es,"textLayoutProperties",[...ts.textLayoutProperties,"width"]),S(Es,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),I.setClass(Es);class ah extends bn{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:a}=Ne(Dl(s,i)),l=new A(r,a);if(i.absolutePositioned)return{center:ws(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:l};{const h=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:c=new A,correction:u=new A}=this.calcBoundingBox(e,t)||{};return{center:c.add(h),correction:u.subtract(h),size:l}}return{center:s.getRelativeCenterPoint().add(h),size:l}}}}S(ah,"type","clip-path"),I.setClass(ah);class oh extends bn{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new A(s.width||i.x,s.height||i.y)}}S(oh,"type","fixed"),I.setClass(oh);class Kd extends Ti{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 ks extends me{static getDefaults(){return x(x({},super.getDefaults()),ks.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,ks.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new Kd})}_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(a=>a.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))?(Xe("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===ea?s.forEach(i=>{i._onAfterObjectsChange(mn,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=x(x({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()}}S(ks,"type","ActiveSelection"),S(ks,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),I.setClass(ks),I.setClass(ks,"activeSelection");class Jd{constructor(){S(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const a={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(h=>{h.applyTo(a)});const{imageData:l}=a;return l.width===s&&l.height===i||(n.width=l.width,n.height=l.height),r.putImageData(l,0,0),a}}class lh{constructor(){let{tileSize:t=nt.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};S(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),S(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=ue({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 a=this.gl,l=n.getContext("2d");if(!a||!l)return;let h;r&&(h=this.getCachedTexture(r,e));const c={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:i,destinationWidth:s,destinationHeight:i,context:a,sourceTexture:this.createTexture(a,s,i,h?void 0:e),targetTexture:this.createTexture(a,s,i),originalTexture:h||this.createTexture(a,s,i,h?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},u=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,u),t.forEach(d=>{d&&d.applyTo(c)}),function(d){const f=d.targetCanvas,g=f.width,p=f.height,v=d.destinationWidth,m=d.destinationHeight;g===v&&p===m||(f.width=v,f.height=m)}(c),this.copyGLTo2D(a,c),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(c.sourceTexture),a.deleteTexture(c.targetTexture),a.deleteFramebuffer(u),l.setTransform(1,0,0,1,0,0),c}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:a,RGBA:l,UNSIGNED_BYTE:h,CLAMP_TO_EDGE:c,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:g}=t,p=t.createTexture();return t.bindTexture(a,p),t.texParameteri(a,u,n||r),t.texParameteri(a,d,n||r),t.texParameteri(a,f,c),t.texParameteri(a,g,c),i?t.texImage2D(a,0,l,l,h,i):t.texImage2D(a,0,l,e,s,0,l,h,null),p}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 a=new Uint8Array(this.imageBuffer,0,r),l=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,a);const h=new ImageData(l,i,n);s.putImageData(h,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 ua;function Qd(){const{WebGLProbe:o}=Le();return o.queryWebGL(Ie()),nt.enableGLFiltering&&o.isSupported(nt.textureSize)?new lh({tileSize:nt.textureSize}):new Jd}function da(){return!ua&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(ua=Qd()),ua}const Zd=["filters","resizeFilter","src","crossOrigin","type"],hh=["cropX","cropY"];class Vt extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Vt.ownDefaults)}constructor(t,e){super(),S(this,"_lastScaleX",1),S(this,"_lastScaleY",1),S(this,"_filterScalingX",1),S(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Vt.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(rs()),this.setElement(typeof t=="string"?(this.canvas&&Ce(this.canvas.getElement())||Ns()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=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(s),(e=t.classList)===null||e===void 0||e.add(Vt.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=da(!1);e instanceof lh&&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&&Le().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())}),x(x({},super.toObject([...hh,...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=[],a="",l="";if(!e)return[];if(this.hasCrop()){const h=rs();n.push('<clipPath id="imageCrop_'+h+`">
87
87
  `,' <rect x="'+s+'" y="'+i+'" width="'+this.width+'" height="'+this.height+`" />
88
88
  `,`</clipPath>
89
- `),o=' clip-path="url(#imageCrop_'+c+')" '}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>
90
- `)),this.stroke||this.strokeDashArray){const c=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(),`" />
91
- `)],this.fill=c}return n=this.paintFirst!==ee?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 Jh(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=ps(r),{width:h,height:c}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,Cg().applyFilters([t],r,h,c,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=ps({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);Cg().applyFilters(t,this._originalElement,s,i,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_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),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=o*s,f=h*i,g=Math.min(n*s,c-d),p=Math.min(r*i,u-f),m=-n/2,y=-r/2,b=Math.min(n,c/s-o),x=Math.min(r,u/i-h);e&&t.drawImage(e,d,f,g,p,m,y,b,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=qf(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,c=1,u=0,d=0,f=0,g=0;return!t||t.alignX===ze&&t.alignY===ze?(h=e/r,c=s/o):(t.meetOrSlice==="meet"&&(h=c=Jv(this._element,i),n=(e-r*h)/2,t.alignX==="Min"&&(u=-n),t.alignX==="Max"&&(u=n),n=(s-o*c)/2,t.alignY==="Min"&&(d=-n),t.alignY==="Max"&&(d=n)),t.meetOrSlice==="slice"&&(h=c=Qv(this._element,i),n=r-e/h,t.alignX==="Mid"&&(f=n/2),t.alignX==="Max"&&(f=n),n=o-s/c,t.alignY==="Mid"&&(g=n/2),t.alignY==="Max"&&(g=n),r=e/h,o=s/c)),{width:r,height:o,scaleX:h,scaleY:c,offsetLeft:u,offsetTop:d,cropX:f,cropY:g}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:o}=t,h=Lt(t,Hx);return Promise.all([Jh(n,E(E({},e),{},{crossOrigin:r})),s&&ma(s,e),i&&ma([i],e),Qh(h,e)]).then(c=>{let[u,d=[],[f]=[],g={}]=c;return new this(u,E(E({},h),{},{src:n,filters:d,resizeFilter:f},g))})}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 Jh(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=en(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch(n=>(Ki("log","Unable to parse Image",n),null))}}function Ag(a){if(!U_.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"),c=a.getAttribute("height"),u=a.getAttribute("x")||0,d=a.getAttribute("y")||0,f=!(t&&pv.test(t)),g=!h||!c||h==="100%"||c==="100%";let p="",m=0,y=0;if(f&&(u||d)&&a.parentNode&&a.parentNode.nodeName!=="#document"&&(p=" translate("+We(u||"0")+" "+We(d||"0")+") ",e=(a.getAttribute("transform")||"")+p,a.setAttribute("transform",e),a.removeAttribute("x"),a.removeAttribute("y")),f&&g)return{width:0,height:0};const b={width:0,height:0};if(f)return b.width=We(h),b.height=We(c),b;const x=t.match(pv);r=-parseFloat(x[1]),o=-parseFloat(x[2]);const C=parseFloat(x[3]),S=parseFloat(x[4]);b.minX=r,b.minY=o,b.viewBoxWidth=C,b.viewBoxHeight=S,g?(b.width=C,b.height=S):(b.width=We(h),b.height=We(c),i=b.width/C,n=b.height/S);const T=qf(a.getAttribute("preserveAspectRatio")||"");if(T.alignX!==ze&&(T.meetOrSlice==="meet"&&(n=i=i>n?n:i),T.meetOrSlice==="slice"&&(n=i=i>n?i:n),m=b.width-C*i,y=b.height-S*i,T.alignX==="Mid"&&(m/=2),T.alignY==="Mid"&&(y/=2),T.alignX==="Min"&&(m=0),T.alignY==="Min"&&(y=0)),i===1&&n===1&&r===0&&o===0&&u===0&&d===0)return b;if((u||d)&&a.parentNode.nodeName!=="#document"&&(p=" translate("+We(u||"0")+" "+We(d||"0")+") "),e=p+" matrix("+i+" 0 0 "+n+" "+(r*i+m)+" "+(o*n+y)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(Jf,"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),b}k(Me,"type","Image"),k(Me,"cacheProperties",[...Zi,...T0]),k(Me,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),k(Me,"CSS_CANVAS","canvas-img"),k(Me,"ATTRIBUTE_NAMES",[...Xn,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),G.setClass(Me),G.setSVGClass(Me);const Yu=a=>a.tagName.replace("svg:",""),zx=xu(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function E0(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 Vx=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Tg="xlink:href";function k0(a,t){var e;const s=((e=t.getAttribute(Tg))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(Tg)&&k0(a,i),i&&(Vx.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(Tg)}const Gx=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function Wx(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={},c=o[1].trim().split(";").filter(function(u){return u.trim()});for(e=0,s=c.length;e<s;e++){const u=c[e].split(":"),d=u[0].trim(),f=u[1].trim();h[d]=f}(r=o[0].trim()).split(",").forEach(u=>{(u=u.replace(/^svg/i,"").trim())!==""&&(i[u]=E(E({},i[u]||{}),h))})})}return i}const P0=a=>G.getSVGClass(Yu(a).toLowerCase());class Xx{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=E0(r,Gx),h={};let c=o.length;for(;c--;){const u=o[c];u.getAttribute("xlink:href")&&k0(r,u);const d=u.getAttribute("id");d&&(h[d]=u)}return h}(i),this.cssRules=Wx(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=P0(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,ee),this.resolveGradient(s,t,Ge),s instanceof Me&&s._originalElement?Bu(s,s.parsePreserveAspectRatioAttribute()):Bu(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=ll.fromElement(i,t,E(E({},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=ns(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=Ru("".concat(o.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const c=await Promise.all(i.map(x=>P0(x).fromElement(x,this.options,this.cssRules).then(C=>(Bu(C),C.fillRule=C.clipRule,delete C.clipRule,C)))),u=c.length===1?c[0]:new Fs(c),d=qt(n,u.calcTransformMatrix());u.clipPath&&await this.resolveClipPath(u,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:f,scaleY:g,angle:p,skewX:m,translateX:y,translateY:b}=Lr(d);u.set({flipX:!1,flipY:!1}),u.set({scaleX:f,scaleY:g,angle:p,skewX:m,skewY:0}),u.setPositionByOrigin(new O(y,b),rt,rt),t.clipPath=u}else delete t.clipPath}}const M0=a=>X_.test(Yu(a)),Eg=()=>({objects:[],elements:[],options:{},allElements:[]});async function Ux(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return Ki("log",new Mf("parseSVGDocument")),Eg();const i=a.documentElement;(function(u){const d=E0(u,["use","svg:use"]),f=["x","y","xlink:href","href","transform"];for(const g of d){const p=g.attributes,m={};for(const R of p)R.value&&(m[R.name]=R.value);const y=(m["xlink:href"]||m.href||"").slice(1);if(y==="")return;const b=u.getElementById(y);if(b===null)return;let x=b.cloneNode(!0);const C=x.attributes,S={};for(const R of C)R.value&&(S[R.name]=R.value);const{x:T=0,y:P=0,transform:M=""}=m,D="".concat(M," ").concat(S.transform||""," translate(").concat(T,", ").concat(P,")");if(Ag(x),/^svg$/i.test(x.nodeName)){const R=x.ownerDocument.createElementNS(Jf,"g");Object.entries(S).forEach(V=>{let[H,F]=V;return R.setAttributeNS(Jf,H,F)}),R.append(...x.childNodes),x=R}for(const R of p){if(!R)continue;const{name:V,value:H}=R;if(!f.includes(V))if(V==="style"){const F={};dg(H,F),Object.entries(S).forEach(j=>{let[K,L]=j;F[K]=L}),dg(S.style||"",F);const I=Object.entries(F).map(j=>j.join(":")).join(";");x.setAttribute(V,I)}else!S[V]&&x.setAttribute(V,H)}x.setAttribute("transform",D),x.setAttribute("instantiated_by_use","1"),x.removeAttribute("id"),g.parentNode.replaceChild(x,g)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=E(E({},Ag(i)),{},{crossOrigin:e,signal:s}),o=n.filter(u=>(Ag(u),M0(u)&&!function(d){let f=d;for(;f&&(f=f.parentElement);)if(f&&f.nodeName&&zx.test(Yu(f))&&!f.getAttribute("instantiated_by_use"))return!0;return!1}(u)));if(!o||o&&!o.length)return E(E({},Eg()),{},{options:r,allElements:n});const h={};return n.filter(u=>Yu(u)==="clipPath").forEach(u=>{u.setAttribute("originalTransform",u.getAttribute("transform")||"");const d=u.getAttribute("id");h[d]=Array.from(u.getElementsByTagName("*")).filter(f=>M0(f))}),{objects:await new Xx(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function Yx(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{c0(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>Ux(s,t,e)).catch(()=>Eg())}const $u=a=>a.webgl!==void 0,kg="precision highp float",$x=`
92
- `.concat(kg,`;
89
+ `),a=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(l=' 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(l).concat(a,`></image>
90
+ `)),this.stroke||this.strokeDashArray){const h=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(),`" />
91
+ `)],this.fill=h}return n=this.paintFirst!==kt?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 mi(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 a=ue(r),{width:l,height:h}=r;this._element=a,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,da().applyFilters([t],r,l,h,this._element),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.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=ue({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);da().applyFilters(t,this._originalElement,s,i,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_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,a=Math.max(this.cropX,0),l=Math.max(this.cropY,0),h=e.naturalWidth||e.width,c=e.naturalHeight||e.height,u=a*s,d=l*i,f=Math.min(n*s,h-u),g=Math.min(r*i,c-d),p=-n/2,v=-r/2,m=Math.min(n,h/s-a),b=Math.min(r,c/i-l);e&&t.drawImage(e,u,d,f,g,p,v,m,b)}_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=jr(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,a=this._element.height,l=1,h=1,c=0,u=0,d=0,f=0;return!t||t.alignX===Yt&&t.alignY===Yt?(l=e/r,h=s/a):(t.meetOrSlice==="meet"&&(l=h=Fl(this._element,i),n=(e-r*l)/2,t.alignX==="Min"&&(c=-n),t.alignX==="Max"&&(c=n),n=(s-a*h)/2,t.alignY==="Min"&&(u=-n),t.alignY==="Max"&&(u=n)),t.meetOrSlice==="slice"&&(l=h=Ll(this._element,i),n=r-e/l,t.alignX==="Mid"&&(d=n/2),t.alignX==="Max"&&(d=n),n=a-s/h,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/l,a=s/h)),{width:r,height:a,scaleX:l,scaleY:h,offsetLeft:c,offsetTop:u,cropX:d,cropY:f}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:a}=t,l=pt(t,Zd);return Promise.all([mi(n,x(x({},e),{},{crossOrigin:r})),s&&Gs(s,e),i&&Gs([i],e),vi(l,e)]).then(h=>{let[c,u=[],[d]=[],f={}]=h;return new this(c,x(x({},l),{},{src:n,filters:u,resizeFilter:d},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 mi(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=Ke(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch(n=>(Xe("log","Unable to parse Image",n),null))}}function fa(o){if(!ru.test(o.nodeName))return{};const t=o.getAttribute("viewBox");let e,s,i=1,n=1,r=0,a=0;const l=o.getAttribute("width"),h=o.getAttribute("height"),c=o.getAttribute("x")||0,u=o.getAttribute("y")||0,d=!(t&&Qo.test(t)),f=!l||!h||l==="100%"||h==="100%";let g="",p=0,v=0;if(d&&(c||u)&&o.parentNode&&o.parentNode.nodeName!=="#document"&&(g=" translate("+Kt(c||"0")+" "+Kt(u||"0")+") ",e=(o.getAttribute("transform")||"")+g,o.setAttribute("transform",e),o.removeAttribute("x"),o.removeAttribute("y")),d&&f)return{width:0,height:0};const m={width:0,height:0};if(d)return m.width=Kt(l),m.height=Kt(h),m;const b=t.match(Qo);r=-parseFloat(b[1]),a=-parseFloat(b[2]);const _=parseFloat(b[3]),w=parseFloat(b[4]);m.minX=r,m.minY=a,m.viewBoxWidth=_,m.viewBoxHeight=w,f?(m.width=_,m.height=w):(m.width=Kt(l),m.height=Kt(h),i=m.width/_,n=m.height/w);const C=jr(o.getAttribute("preserveAspectRatio")||"");if(C.alignX!==Yt&&(C.meetOrSlice==="meet"&&(n=i=i>n?n:i),C.meetOrSlice==="slice"&&(n=i=i>n?i:n),p=m.width-_*i,v=m.height-w*i,C.alignX==="Mid"&&(p/=2),C.alignY==="Mid"&&(v/=2),C.alignX==="Min"&&(p=0),C.alignY==="Min"&&(v=0)),i===1&&n===1&&r===0&&a===0&&c===0&&u===0)return m;if((c||u)&&o.parentNode.nodeName!=="#document"&&(g=" translate("+Kt(c||"0")+" "+Kt(u||"0")+") "),e=g+" matrix("+i+" 0 0 "+n+" "+(r*i+p)+" "+(a*n+v)+") ",o.nodeName==="svg"){for(s=o.ownerDocument.createElementNS(Br,"g");o.firstChild;)s.appendChild(o.firstChild);o.appendChild(s)}else s=o,s.removeAttribute("x"),s.removeAttribute("y"),e=s.getAttribute("transform")+e;return s.setAttribute("transform",e),m}S(Vt,"type","Image"),S(Vt,"cacheProperties",[...$e,...hh]),S(Vt,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),S(Vt,"CSS_CANVAS","canvas-img"),S(Vt,"ATTRIBUTE_NAMES",[...as,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),I.setClass(Vt),I.setSVGClass(Vt);const Pn=o=>o.tagName.replace("svg:",""),tf=nn(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function ch(o,t){let e,s,i,n,r=[];for(i=0,n=t.length;i<n;i++)e=t[i],s=o.getElementsByTagNameNS("http://www.w3.org/2000/svg",e),r=r.concat(Array.from(s));return r}const ef=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],ga="xlink:href";function uh(o,t){var e;const s=((e=t.getAttribute(ga))===null||e===void 0?void 0:e.slice(1))||"",i=o.getElementById(s);if(i&&i.getAttribute(ga)&&uh(o,i),i&&(ef.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(ga)}const sf=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function nf(o){const t=o.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,a,l)=>l.length>1&&r.trim()).forEach(r=>{if((r.match(/{/g)||[]).length>1&&r.trim().startsWith("@"))return;const a=r.split("{"),l={},h=a[1].trim().split(";").filter(function(c){return c.trim()});for(e=0,s=h.length;e<s;e++){const c=h[e].split(":"),u=c[0].trim(),d=c[1].trim();l[u]=d}(r=a[0].trim()).split(",").forEach(c=>{(c=c.replace(/^svg/i,"").trim())!==""&&(i[c]=x(x({},i[c]||{}),l))})})}return i}const dh=o=>I.getSVGClass(Pn(o).toLowerCase());class rf{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 a=ch(r,sf),l={};let h=a.length;for(;h--;){const c=a[h];c.getAttribute("xlink:href")&&uh(r,c);const u=c.getAttribute("id");u&&(l[u]=c)}return l}(i),this.cssRules=nf(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=dh(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,kt),this.resolveGradient(s,t,qt),s instanceof Vt&&s._originalElement?wn(s,s.parsePreserveAspectRatioAttribute()):wn(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=ki.fromElement(i,t,x(x({},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=ne(t.calcTransformMatrix()),r=i[0].parentElement;let a=e;for(;!s&&a.parentElement&&a.getAttribute("clip-path")!==t.clipPath;)a=a.parentElement;a.parentElement.appendChild(r);const l=pn("".concat(a.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(l.join(","),")"));const h=await Promise.all(i.map(b=>dh(b).fromElement(b,this.options,this.cssRules).then(_=>(wn(_),_.fillRule=_.clipRule,delete _.clipRule,_)))),c=h.length===1?h[0]:new me(h),u=St(n,c.calcTransformMatrix());c.clipPath&&await this.resolveClipPath(c,a,r.getAttribute("clip-path")?a:void 0);const{scaleX:d,scaleY:f,angle:g,skewX:p,translateX:v,translateY:m}=vs(u);c.set({flipX:!1,flipY:!1}),c.set({scaleX:d,scaleY:f,angle:g,skewX:p,skewY:0}),c.setPositionByOrigin(new A(v,m),q,q),t.clipPath=c}else delete t.clipPath}}const fh=o=>nu.test(Pn(o)),pa=()=>({objects:[],elements:[],options:{},allElements:[]});async function af(o,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return Xe("log",new br("parseSVGDocument")),pa();const i=o.documentElement;(function(c){const u=ch(c,["use","svg:use"]),d=["x","y","xlink:href","href","transform"];for(const f of u){const g=f.attributes,p={};for(const O of g)O.value&&(p[O.name]=O.value);const v=(p["xlink:href"]||p.href||"").slice(1);if(v==="")return;const m=c.getElementById(v);if(m===null)return;let b=m.cloneNode(!0);const _=b.attributes,w={};for(const O of _)O.value&&(w[O.name]=O.value);const{x:C=0,y:T=0,transform:E=""}=p,k="".concat(E," ").concat(w.transform||""," translate(").concat(C,", ").concat(T,")");if(fa(b),/^svg$/i.test(b.nodeName)){const O=b.ownerDocument.createElementNS(Br,"g");Object.entries(w).forEach(H=>{let[N,P]=H;return O.setAttributeNS(Br,N,P)}),O.append(...b.childNodes),b=O}for(const O of g){if(!O)continue;const{name:H,value:N}=O;if(!d.includes(H))if(H==="style"){const P={};ta(N,P),Object.entries(w).forEach(F=>{let[V,M]=F;P[V]=M}),ta(w.style||"",P);const R=Object.entries(P).map(F=>F.join(":")).join(";");b.setAttribute(H,R)}else!w[H]&&b.setAttribute(H,N)}b.setAttribute("transform",k),b.setAttribute("instantiated_by_use","1"),b.removeAttribute("id"),f.parentNode.replaceChild(b,f)}})(o);const n=Array.from(i.getElementsByTagName("*")),r=x(x({},fa(i)),{},{crossOrigin:e,signal:s}),a=n.filter(c=>(fa(c),fh(c)&&!function(u){let d=u;for(;d&&(d=d.parentElement);)if(d&&d.nodeName&&tf.test(Pn(d))&&!d.getAttribute("instantiated_by_use"))return!0;return!1}(c)));if(!a||a&&!a.length)return x(x({},pa()),{},{options:r,allElements:n});const l={};return n.filter(c=>Pn(c)==="clipPath").forEach(c=>{c.setAttribute("originalTransform",c.getAttribute("transform")||"");const u=c.getAttribute("id");l[u]=Array.from(c.getElementsByTagName("*")).filter(d=>fh(d))}),{objects:await new rf(a,r,t,o,l).parse(),elements:a,options:r,allElements:n}}function of(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{Yl(o.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>af(s,t,e)).catch(()=>pa())}const Mn=o=>o.webgl!==void 0,ma="precision highp float",lf=`
92
+ `.concat(ma,`;
93
93
  varying vec2 vTexCoord;
94
94
  uniform sampler2D uTexture;
95
95
  void main() {
96
96
  gl_FragColor = texture2D(uTexture, vTexCoord);
97
- }`),qx=["type"],Kx=["type"],Jx=new RegExp(kg,"g");class he{get type(){return this.constructor.type}constructor(){let t=Lt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},qx);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return $x}getVertexSource(){return`
97
+ }`),hf=["type"],cf=["type"],uf=new RegExp(ma,"g");class Ft{get type(){return this.constructor.type}constructor(){let t=pt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},hf);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return lf}getVertexSource(){return`
98
98
  attribute vec2 aPosition;
99
99
  varying vec2 vTexCoord;
100
100
  void main() {
101
101
  vTexCoord = aPosition;
102
102
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
103
- }`}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"}}=xi();i!=="highp"&&(e=e.replace(Jx,kg.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 wi("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new wi("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 wi("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 wi('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){$u(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=ps({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return E({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(Lt(t,Kx))}}k(he,"type","BaseFilter"),k(he,"uniformLocations",[]);const Qx={multiply:`gl_FragColor.rgb *= uColor.rgb;
103
+ }`}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"}}=Le();i!=="highp"&&(e=e.replace(uf,ma.replace("highp",i)));const n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER),a=t.createProgram();if(!n||!r||!a)throw new Fe("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Fe("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 Fe("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(r)));if(t.attachShader(a,n),t.attachShader(a,r),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS))throw new Fe('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(a)));const l=this.getUniformLocations(t,a)||{};return l.uStepW=t.getUniformLocation(a,"uStepW"),l.uStepH=t.getUniformLocation(a,"uStepH"),{program:a,attributeLocations:this.getAttributeLocations(t,a),uniformLocations:l}}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){Mn(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=ue({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return x({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(pt(t,cf))}}S(Ft,"type","BaseFilter"),S(Ft,"uniformLocations",[]);const df={multiply:`gl_FragColor.rgb *= uColor.rgb;
104
104
  `,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
105
105
  `,add:`gl_FragColor.rgb += uColor.rgb;
106
106
  `,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
@@ -127,7 +127,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
127
127
  `,tint:`
128
128
  gl_FragColor.rgb *= (1.0 - uColor.a);
129
129
  gl_FragColor.rgb += uColor.rgb;
130
- `};class qu extends he{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
130
+ `};class On extends Ft{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
131
131
  precision highp float;
132
132
  uniform sampler2D uTexture;
133
133
  uniform vec4 uColor;
@@ -136,10 +136,10 @@ Resulting to default behavior: removing object from previous canvas and adding t
136
136
  vec4 color = texture2D(uTexture, vTexCoord);
137
137
  gl_FragColor = color;
138
138
  if (color.a > 0.0) {
139
- `.concat(Qx[this.mode],`
139
+ `.concat(df[this.mode],`
140
140
  }
141
141
  }
142
- `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new St(this.color).getSource(),i=this.alpha,n=s[0]*i,r=s[1]*i,o=s[2]*i,h=1-i;for(let c=0;c<e.length;c+=4){const u=e[c],d=e[c+1],f=e[c+2];let g,p,m;switch(this.mode){case"multiply":g=u*n/255,p=d*r/255,m=f*o/255;break;case"screen":g=255-(255-u)*(255-n)/255,p=255-(255-d)*(255-r)/255,m=255-(255-f)*(255-o)/255;break;case"add":g=u+n,p=d+r,m=f+o;break;case"difference":g=Math.abs(u-n),p=Math.abs(d-r),m=Math.abs(f-o);break;case"subtract":g=u-n,p=d-r,m=f-o;break;case"darken":g=Math.min(u,n),p=Math.min(d,r),m=Math.min(f,o);break;case"lighten":g=Math.max(u,n),p=Math.max(d,r),m=Math.max(f,o);break;case"overlay":g=n<128?2*u*n/255:255-2*(255-u)*(255-n)/255,p=r<128?2*d*r/255:255-2*(255-d)*(255-r)/255,m=o<128?2*f*o/255:255-2*(255-f)*(255-o)/255;break;case"exclusion":g=n+u-2*n*u/255,p=r+d-2*r*d/255,m=o+f-2*o*f/255;break;case"tint":g=n+u*h,p=r+d*h,m=o+f*h}e[c]=g,e[c+1]=p,e[c+2]=m}}sendUniformData(t,e){const s=new St(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)}}k(qu,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),k(qu,"type","BlendColor"),k(qu,"uniformLocations",["uColor"]),G.setClass(qu);const Zx={multiply:`
142
+ `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new ht(this.color).getSource(),i=this.alpha,n=s[0]*i,r=s[1]*i,a=s[2]*i,l=1-i;for(let h=0;h<e.length;h+=4){const c=e[h],u=e[h+1],d=e[h+2];let f,g,p;switch(this.mode){case"multiply":f=c*n/255,g=u*r/255,p=d*a/255;break;case"screen":f=255-(255-c)*(255-n)/255,g=255-(255-u)*(255-r)/255,p=255-(255-d)*(255-a)/255;break;case"add":f=c+n,g=u+r,p=d+a;break;case"difference":f=Math.abs(c-n),g=Math.abs(u-r),p=Math.abs(d-a);break;case"subtract":f=c-n,g=u-r,p=d-a;break;case"darken":f=Math.min(c,n),g=Math.min(u,r),p=Math.min(d,a);break;case"lighten":f=Math.max(c,n),g=Math.max(u,r),p=Math.max(d,a);break;case"overlay":f=n<128?2*c*n/255:255-2*(255-c)*(255-n)/255,g=r<128?2*u*r/255:255-2*(255-u)*(255-r)/255,p=a<128?2*d*a/255:255-2*(255-d)*(255-a)/255;break;case"exclusion":f=n+c-2*n*c/255,g=r+u-2*r*u/255,p=a+d-2*a*d/255;break;case"tint":f=n+c*l,g=r+u*l,p=a+d*l}e[h]=f,e[h+1]=g,e[h+2]=p}}sendUniformData(t,e){const s=new ht(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)}}S(On,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),S(On,"type","BlendColor"),S(On,"uniformLocations",["uColor"]),I.setClass(On);const ff={multiply:`
143
143
  precision highp float;
144
144
  uniform sampler2D uTexture;
145
145
  uniform sampler2D uImage;
@@ -165,7 +165,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
165
165
  color.a = color2.a;
166
166
  gl_FragColor = color;
167
167
  }
168
- `},tS=["type","image"];class Ku extends he{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return Zx[this.mode]}getVertexSource(){return`
168
+ `},gf=["type","image"];class Dn extends Ft{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return ff[this.mode]}getVertexSource(){return`
169
169
  attribute vec2 aPosition;
170
170
  varying vec2 vTexCoord;
171
171
  varying vec2 vTexCoord2;
@@ -175,7 +175,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
175
175
  vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
176
176
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
177
177
  }
178
- `}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=Si());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 c=h.getImageData(0,0,s,i).data;for(let u=0;u<e.length;u+=4){const d=e[u],f=e[u+1],g=e[u+2],p=e[u+3],m=c[u],y=c[u+1],b=c[u+2],x=c[u+3];switch(this.mode){case"multiply":e[u]=d*m/255,e[u+1]=f*y/255,e[u+2]=g*b/255,e[u+3]=p*x/255;break;case"mask":e[u+3]=x}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return E(E({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=Lt(t,tS);return Me.fromObject(i,e).then(r=>new this(E(E({},n),{},{image:r})))}}k(Ku,"type","BlendImage"),k(Ku,"defaults",{mode:"multiply",alpha:1}),k(Ku,"uniformLocations",["uTransformMatrix","uImage"]),G.setClass(Ku);class Ju extends he{getFragmentSource(){return`
178
+ `}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=Ie());const a=n.blendImage,l=a.getContext("2d");a.width!==s||a.height!==i?(a.width=s,a.height=i):l.clearRect(0,0,s,i),l.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),l.drawImage(r.getElement(),0,0,s,i);const h=l.getImageData(0,0,s,i).data;for(let c=0;c<e.length;c+=4){const u=e[c],d=e[c+1],f=e[c+2],g=e[c+3],p=h[c],v=h[c+1],m=h[c+2],b=h[c+3];switch(this.mode){case"multiply":e[c]=u*p/255,e[c+1]=d*v/255,e[c+2]=f*m/255,e[c+3]=g*b/255;break;case"mask":e[c+3]=b}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return x(x({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=pt(t,gf);return Vt.fromObject(i,e).then(r=>new this(x(x({},n),{},{image:r})))}}S(Dn,"type","BlendImage"),S(Dn,"defaults",{mode:"multiply",alpha:1}),S(Dn,"uniformLocations",["uTransformMatrix","uImage"]),I.setClass(Dn);class Rn extends Ft{getFragmentSource(){return`
179
179
  precision highp float;
180
180
  uniform sampler2D uTexture;
181
181
  uniform vec2 uDelta;
@@ -204,7 +204,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
204
204
  gl_FragColor.rgb = color.rgb / totalC;
205
205
  gl_FragColor.a = color.a / totalA;
206
206
  }
207
- `}applyTo(t){$u(t)?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;this.aspectRatio=s/i,this.horizontal=!0;let n=this.getBlurValue()*s;const r=new Uint8ClampedArray(e),o=15,h=4*s;for(let c=0;c<e.length;c+=4){let u=0,d=0,f=0,g=0,p=0;const m=c-c%h,y=m+h;for(let b=-14;b<o;b++){const x=b/o,C=4*Math.floor(n*x),S=1-Math.abs(x);let T=c+C;T<m?T=m:T>y&&(T=y);const P=e[T+3]*S;u+=e[T]*P,d+=e[T+1]*P,f+=e[T+2]*P,g+=P,p+=S}r[c]=u/g,r[c+1]=d/g,r[c+2]=f/g,r[c+3]=g/p}this.horizontal=!1,n=this.getBlurValue()*i;for(let c=0;c<r.length;c+=4){let u=0,d=0,f=0,g=0,p=0;const m=c%h,y=r.length-h+m;for(let b=-14;b<o;b++){const x=b/o,C=Math.floor(n*x)*h,S=1-Math.abs(x);let T=c+C;T<m?T=m:T>y&&(T=y);const P=r[T+3]*S;u+=r[T]*P,d+=r[T+1]*P,f+=r[T+2]*P,g+=P,p+=S}e[c]=u/g,e[c+1]=d/g,e[c+2]=f/g,e[c+3]=g/p}}sendUniformData(t,e){const s=this.chooseRightDelta();t.uniform2fv(e.uDelta,s)}isNeutralState(){return this.blur===0}getBlurValue(){let t=1;const{horizontal:e,aspectRatio:s}=this;return e?s>1&&(t=1/s):s<1&&(t=s),t*this.blur*.12}chooseRightDelta(){const t=this.getBlurValue();return this.horizontal?[t,0]:[0,t]}}k(Ju,"type","Blur"),k(Ju,"defaults",{blur:0}),k(Ju,"uniformLocations",["uDelta"]),G.setClass(Ju);class Qu extends he{getFragmentSource(){return`
207
+ `}applyTo(t){Mn(t)?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;this.aspectRatio=s/i,this.horizontal=!0;let n=this.getBlurValue()*s;const r=new Uint8ClampedArray(e),a=15,l=4*s;for(let h=0;h<e.length;h+=4){let c=0,u=0,d=0,f=0,g=0;const p=h-h%l,v=p+l;for(let m=-14;m<a;m++){const b=m/a,_=4*Math.floor(n*b),w=1-Math.abs(b);let C=h+_;C<p?C=p:C>v&&(C=v);const T=e[C+3]*w;c+=e[C]*T,u+=e[C+1]*T,d+=e[C+2]*T,f+=T,g+=w}r[h]=c/f,r[h+1]=u/f,r[h+2]=d/f,r[h+3]=f/g}this.horizontal=!1,n=this.getBlurValue()*i;for(let h=0;h<r.length;h+=4){let c=0,u=0,d=0,f=0,g=0;const p=h%l,v=r.length-l+p;for(let m=-14;m<a;m++){const b=m/a,_=Math.floor(n*b)*l,w=1-Math.abs(b);let C=h+_;C<p?C=p:C>v&&(C=v);const T=r[C+3]*w;c+=r[C]*T,u+=r[C+1]*T,d+=r[C+2]*T,f+=T,g+=w}e[h]=c/f,e[h+1]=u/f,e[h+2]=d/f,e[h+3]=f/g}}sendUniformData(t,e){const s=this.chooseRightDelta();t.uniform2fv(e.uDelta,s)}isNeutralState(){return this.blur===0}getBlurValue(){let t=1;const{horizontal:e,aspectRatio:s}=this;return e?s>1&&(t=1/s):s<1&&(t=s),t*this.blur*.12}chooseRightDelta(){const t=this.getBlurValue();return this.horizontal?[t,0]:[0,t]}}S(Rn,"type","Blur"),S(Rn,"defaults",{blur:0}),S(Rn,"uniformLocations",["uDelta"]),I.setClass(Rn);class Fn extends Ft{getFragmentSource(){return`
208
208
  precision highp float;
209
209
  uniform sampler2D uTexture;
210
210
  uniform float uBrightness;
@@ -214,7 +214,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
214
214
  color.rgb += uBrightness;
215
215
  gl_FragColor = color;
216
216
  }
217
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.round(255*this.brightness);for(let i=0;i<e.length;i+=4)e[i]+=s,e[i+1]+=s,e[i+2]+=s}isNeutralState(){return this.brightness===0}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}k(Qu,"type","Brightness"),k(Qu,"defaults",{brightness:0}),k(Qu,"uniformLocations",["uBrightness"]),G.setClass(Qu);const O0={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Ta extends he{getFragmentSource(){return`
217
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.round(255*this.brightness);for(let i=0;i<e.length;i+=4)e[i]+=s,e[i+1]+=s,e[i+2]+=s}isNeutralState(){return this.brightness===0}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}S(Fn,"type","Brightness"),S(Fn,"defaults",{brightness:0}),S(Fn,"uniformLocations",["uBrightness"]),I.setClass(Fn);const gh={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Zs extends Ft{getFragmentSource(){return`
218
218
  precision highp float;
219
219
  uniform sampler2D uTexture;
220
220
  varying vec2 vTexCoord;
@@ -225,7 +225,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
225
225
  color *= uColorMatrix;
226
226
  color += uConstants;
227
227
  gl_FragColor = color;
228
- }`}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(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],!i){const c=e[n+3];e[n]+=c*s[3],e[n+1]+=c*s[8],e[n+2]+=c*s[13],e[n+3]=r*s[15]+o*s[16]+h*s[17]+c*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 E(E({},super.toObject()),{},{matrix:[...this.matrix]})}}function Yr(a,t){var e;const s=(k(e=class extends Ta{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),k(e,"defaults",{colorsOnly:!1,matrix:t}),e);return G.setClass(s,a),s}k(Ta,"type","ColorMatrix"),k(Ta,"defaults",O0),k(Ta,"uniformLocations",["uColorMatrix","uConstants"]),G.setClass(Ta),Yr("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),Yr("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),Yr("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),Yr("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),Yr("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),Yr("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),Yr("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 D0 extends he{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){$u(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=>G.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}k(D0,"type","Composed"),G.setClass(D0);class Zu extends he{getFragmentSource(){return`
228
+ }`}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],a=e[n+1],l=e[n+2];if(e[n]=r*s[0]+a*s[1]+l*s[2]+255*s[4],e[n+1]=r*s[5]+a*s[6]+l*s[7]+255*s[9],e[n+2]=r*s[10]+a*s[11]+l*s[12]+255*s[14],!i){const h=e[n+3];e[n]+=h*s[3],e[n+1]+=h*s[8],e[n+2]+=h*s[13],e[n+3]=r*s[15]+a*s[16]+l*s[17]+h*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 x(x({},super.toObject()),{},{matrix:[...this.matrix]})}}function Ps(o,t){var e;const s=(S(e=class extends Zs{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",o),S(e,"defaults",{colorsOnly:!1,matrix:t}),e);return I.setClass(s,o),s}S(Zs,"type","ColorMatrix"),S(Zs,"defaults",gh),S(Zs,"uniformLocations",["uColorMatrix","uConstants"]),I.setClass(Zs),Ps("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),Ps("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),Ps("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),Ps("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),Ps("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),Ps("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),Ps("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 ph extends Ft{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){Mn(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=>I.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}S(ph,"type","Composed"),I.setClass(ph);class Ln extends Ft{getFragmentSource(){return`
229
229
  precision highp float;
230
230
  uniform sampler2D uTexture;
231
231
  uniform float uContrast;
@@ -235,7 +235,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
235
235
  float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
236
236
  color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
237
237
  gl_FragColor = color;
238
- }`}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)}}k(Zu,"type","Contrast"),k(Zu,"defaults",{contrast:0}),k(Zu,"uniformLocations",["uContrast"]),G.setClass(Zu);const eS={Convolute_3_1:`
238
+ }`}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)}}S(Ln,"type","Contrast"),S(Ln,"defaults",{contrast:0}),S(Ln,"uniformLocations",["uContrast"]),I.setClass(Ln);const pf={Convolute_3_1:`
239
239
  precision highp float;
240
240
  uniform sampler2D uTexture;
241
241
  uniform float uMatrix[9];
@@ -379,7 +379,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
379
379
  gl_FragColor = color;
380
380
  gl_FragColor.a = alpha;
381
381
  }
382
- `};class td extends he{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return eS[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,c=t.ctx.createImageData(o,h),u=c.data,d=this.opaque?1:0;let f,g,p,m,y,b,x,C,S,T,P,M,D;for(P=0;P<h;P++)for(T=0;T<o;T++){for(y=4*(P*o+T),f=0,g=0,p=0,m=0,D=0;D<n;D++)for(M=0;M<n;M++)x=P+D-r,b=T+M-r,x<0||x>=h||b<0||b>=o||(C=4*(x*o+b),S=i[D*n+M],f+=s[C]*S,g+=s[C+1]*S,p+=s[C+2]*S,d||(m+=s[C+3]*S));u[y]=f,u[y+1]=g,u[y+2]=p,u[y+3]=d?s[y+3]:m}t.imageData=c}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return E(E({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}k(td,"type","Convolute"),k(td,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),k(td,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),G.setClass(td);const R0="Gamma";class ed extends he{getFragmentSource(){return`
382
+ `};class In extends Ft{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return pf[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),a=e.width,l=e.height,h=t.ctx.createImageData(a,l),c=h.data,u=this.opaque?1:0;let d,f,g,p,v,m,b,_,w,C,T,E,k;for(T=0;T<l;T++)for(C=0;C<a;C++){for(v=4*(T*a+C),d=0,f=0,g=0,p=0,k=0;k<n;k++)for(E=0;E<n;E++)b=T+k-r,m=C+E-r,b<0||b>=l||m<0||m>=a||(_=4*(b*a+m),w=i[k*n+E],d+=s[_]*w,f+=s[_+1]*w,g+=s[_+2]*w,u||(p+=s[_+3]*w));c[v]=d,c[v+1]=f,c[v+2]=g,c[v+3]=u?s[v+3]:p}t.imageData=h}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return x(x({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}S(In,"type","Convolute"),S(In,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),S(In,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),I.setClass(In);const mh="Gamma";class jn extends Ft{getFragmentSource(){return`
383
383
  precision highp float;
384
384
  uniform sampler2D uTexture;
385
385
  uniform vec3 uGamma;
@@ -393,7 +393,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
393
393
  gl_FragColor = color;
394
394
  gl_FragColor.rgb *= color.a;
395
395
  }
396
- `}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()}}}k(ed,"type",R0),k(ed,"defaults",{gamma:[1,1,1]}),k(ed,"uniformLocations",["uGamma"]),G.setClass(ed);const sS={average:`
396
+ `}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 a=this.rgbValues;for(let l=0;l<256;l++)a.r[l]=255*Math.pow(l/255,i),a.g[l]=255*Math.pow(l/255,n),a.b[l]=255*Math.pow(l/255,r);for(let l=0;l<e.length;l+=4)e[l]=a.r[e[l]],e[l+1]=a.g[e[l+1]],e[l+2]=a.b[e[l+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:mh,gamma:this.gamma.concat()}}}S(jn,"type",mh),S(jn,"defaults",{gamma:[1,1,1]}),S(jn,"uniformLocations",["uGamma"]),I.setClass(jn);const mf={average:`
397
397
  precision highp float;
398
398
  uniform sampler2D uTexture;
399
399
  varying vec2 vTexCoord;
@@ -422,7 +422,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
422
422
  float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
423
423
  gl_FragColor = vec4(average, average, average, col.a);
424
424
  }
425
- `};class sd extends he{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2];switch(this.mode){case"average":s=(n+r+o)/3;break;case"lightness":s=(Math.min(n,r,o)+Math.max(n,r,o))/2;break;case"luminosity":s=.21*n+.72*r+.07*o}e[i+2]=e[i+1]=e[i]=s}}getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return sS[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}k(sd,"type","Grayscale"),k(sd,"defaults",{mode:"average"}),k(sd,"uniformLocations",["uMode"]),G.setClass(sd);const iS=E(E({},O0),{},{rotation:0});class Pg extends Ta{calculateMatrix(){const t=this.rotation*Math.PI,e=qs(t),s=Ks(t),i=1/3,n=Math.sqrt(i)*s,r=1-e;this.matrix=[e+r/3,i*r-n,i*r+n,0,0,i*r+n,e+i*r,i*r-n,0,0,i*r-n,i*r+n,e+i*r,0,0,0,0,0,1,0]}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}k(Pg,"type","HueRotation"),k(Pg,"defaults",iS),G.setClass(Pg);class id extends he{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`
425
+ `};class Nn extends Ft{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2];switch(this.mode){case"average":s=(n+r+a)/3;break;case"lightness":s=(Math.min(n,r,a)+Math.max(n,r,a))/2;break;case"luminosity":s=.21*n+.72*r+.07*a}e[i+2]=e[i+1]=e[i]=s}}getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return mf[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}S(Nn,"type","Grayscale"),S(Nn,"defaults",{mode:"average"}),S(Nn,"uniformLocations",["uMode"]),I.setClass(Nn);const vf=x(x({},gh),{},{rotation:0});class va extends Zs{calculateMatrix(){const t=this.rotation*Math.PI,e=xe(t),s=Se(t),i=1/3,n=Math.sqrt(i)*s,r=1-e;this.matrix=[e+r/3,i*r-n,i*r+n,0,0,i*r+n,e+i*r,i*r-n,0,0,i*r-n,i*r+n,e+i*r,0,0,0,0,0,1,0]}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}S(va,"type","HueRotation"),S(va,"defaults",vf),I.setClass(va);class Bn extends Ft{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`
426
426
  precision highp float;
427
427
  uniform sampler2D uTexture;
428
428
  uniform int uInvert;
@@ -440,7 +440,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
440
440
  gl_FragColor = color;
441
441
  }
442
442
  }
443
- `}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}k(id,"type","Invert"),k(id,"defaults",{alpha:!1,invert:!0}),k(id,"uniformLocations",["uInvert","uAlpha"]),G.setClass(id);class nd extends he{getFragmentSource(){return`
443
+ `}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}S(Bn,"type","Invert"),S(Bn,"defaults",{alpha:!1,invert:!0}),S(Bn,"uniformLocations",["uInvert","uAlpha"]),I.setClass(Bn);class Hn extends Ft{getFragmentSource(){return`
444
444
  precision highp float;
445
445
  uniform sampler2D uTexture;
446
446
  uniform float uStepH;
@@ -455,7 +455,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
455
455
  color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
456
456
  gl_FragColor = color;
457
457
  }
458
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.noise;for(let i=0;i<e.length;i+=4){const n=(.5-Math.random())*s;e[i]+=n,e[i+1]+=n,e[i+2]+=n}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return this.noise===0}}k(nd,"type","Noise"),k(nd,"defaults",{noise:0}),k(nd,"uniformLocations",["uNoise","uSeed"]),G.setClass(nd);class rd extends he{applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;for(let n=0;n<i;n+=this.blocksize)for(let r=0;r<s;r+=this.blocksize){const o=4*n*s+4*r,h=e[o],c=e[o+1],u=e[o+2],d=e[o+3];for(let f=n;f<Math.min(n+this.blocksize,i);f++)for(let g=r;g<Math.min(r+this.blocksize,s);g++){const p=4*f*s+4*g;e[p]=h,e[p+1]=c,e[p+2]=u,e[p+3]=d}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
458
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.noise;for(let i=0;i<e.length;i+=4){const n=(.5-Math.random())*s;e[i]+=n,e[i+1]+=n,e[i+2]+=n}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return this.noise===0}}S(Hn,"type","Noise"),S(Hn,"defaults",{noise:0}),S(Hn,"uniformLocations",["uNoise","uSeed"]),I.setClass(Hn);class zn extends Ft{applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;for(let n=0;n<i;n+=this.blocksize)for(let r=0;r<s;r+=this.blocksize){const a=4*n*s+4*r,l=e[a],h=e[a+1],c=e[a+2],u=e[a+3];for(let d=n;d<Math.min(n+this.blocksize,i);d++)for(let f=r;f<Math.min(r+this.blocksize,s);f++){const g=4*d*s+4*f;e[g]=l,e[g+1]=h,e[g+2]=c,e[g+3]=u}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
459
459
  precision highp float;
460
460
  uniform sampler2D uTexture;
461
461
  uniform float uBlocksize;
@@ -473,7 +473,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
473
473
  vec4 color = texture2D(uTexture, squareCoords);
474
474
  gl_FragColor = color;
475
475
  }
476
- `}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}k(rd,"type","Pixelate"),k(rd,"defaults",{blocksize:4}),k(rd,"uniformLocations",["uBlocksize"]),G.setClass(rd);class od extends he{getFragmentSource(){return`
476
+ `}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}S(zn,"type","Pixelate"),S(zn,"defaults",{blocksize:4}),S(zn,"uniformLocations",["uBlocksize"]),I.setClass(zn);class Vn extends Ft{getFragmentSource(){return`
477
477
  precision highp float;
478
478
  uniform sampler2D uTexture;
479
479
  uniform vec4 uLow;
@@ -485,7 +485,7 @@ void main() {
485
485
  gl_FragColor.a = 0.0;
486
486
  }
487
487
  }
488
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new St(this.color).getSource(),n=[i[0]-s,i[1]-s,i[2]-s],r=[i[0]+s,i[1]+s,i[2]+s];for(let o=0;o<e.length;o+=4){const h=e[o],c=e[o+1],u=e[o+2];h>n[0]&&c>n[1]&&u>n[2]&&h<r[0]&&c<r[1]&&u<r[2]&&(e[o+3]=0)}}sendUniformData(t,e){const s=new St(this.color).getSource(),i=this.distance,n=[0+s[0]/255-i,0+s[1]/255-i,0+s[2]/255-i,1],r=[s[0]/255+i,s[1]/255+i,s[2]/255+i,1];t.uniform4fv(e.uLow,n),t.uniform4fv(e.uHigh,r)}}k(od,"type","RemoveColor"),k(od,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),k(od,"uniformLocations",["uLow","uHigh"]),G.setClass(od);class ad extends he{sendUniformData(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)}getFilterWindow(){const t=this.tempScale;return Math.ceil(this.lanczosLobes/t)}getCacheKey(){const t=this.getFilterWindow();return"".concat(this.type,"_").concat(t)}getFragmentSource(){const t=this.getFilterWindow();return this.generateShader(t)}getTaps(){const t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,s=this.getFilterWindow(),i=new Array(s);for(let n=1;n<=s;n++)i[n-1]=t(n*e);return i}generateShader(t){const e=new Array(t);for(let s=1;s<=t;s++)e[s-1]="".concat(s,".0 * uDelta");return`
488
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new ht(this.color).getSource(),n=[i[0]-s,i[1]-s,i[2]-s],r=[i[0]+s,i[1]+s,i[2]+s];for(let a=0;a<e.length;a+=4){const l=e[a],h=e[a+1],c=e[a+2];l>n[0]&&h>n[1]&&c>n[2]&&l<r[0]&&h<r[1]&&c<r[2]&&(e[a+3]=0)}}sendUniformData(t,e){const s=new ht(this.color).getSource(),i=this.distance,n=[0+s[0]/255-i,0+s[1]/255-i,0+s[2]/255-i,1],r=[s[0]/255+i,s[1]/255+i,s[2]/255+i,1];t.uniform4fv(e.uLow,n),t.uniform4fv(e.uHigh,r)}}S(Vn,"type","RemoveColor"),S(Vn,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),S(Vn,"uniformLocations",["uLow","uHigh"]),I.setClass(Vn);class Gn extends Ft{sendUniformData(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)}getFilterWindow(){const t=this.tempScale;return Math.ceil(this.lanczosLobes/t)}getCacheKey(){const t=this.getFilterWindow();return"".concat(this.type,"_").concat(t)}getFragmentSource(){const t=this.getFilterWindow();return this.generateShader(t)}getTaps(){const t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,s=this.getFilterWindow(),i=new Array(s);for(let n=1;n<=s;n++)i[n-1]=t(n*e);return i}generateShader(t){const e=new Array(t);for(let s=1;s<=t;s++)e[s-1]="".concat(s,".0 * uDelta");return`
489
489
  precision highp float;
490
490
  uniform sampler2D uTexture;
491
491
  uniform vec2 uDelta;
@@ -501,7 +501,7 @@ void main() {
501
501
  `),`
502
502
  gl_FragColor = color / sum;
503
503
  }
504
- `)}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){$u(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<11920929e-14&&e>-11920929e-14)return 1;const s=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(s)/s}}applyTo2d(t){const e=t.imageData,s=this.scaleX,i=this.scaleY;this.rcpScaleX=1/s,this.rcpScaleY=1/i;const n=e.width,r=e.height,o=Math.round(n*s),h=Math.round(r*i);let c;c=this.resizeType==="sliceHack"?this.sliceByTwo(t,n,r,o,h):this.resizeType==="hermite"?this.hermiteFastResize(t,n,r,o,h):this.resizeType==="bilinear"?this.bilinearFiltering(t,n,r,o,h):this.resizeType==="lanczos"?this.lanczosResize(t,n,r,o,h):new ImageData(o,h),t.imageData=c}sliceByTwo(t,e,s,i,n){const r=t.imageData,o=.5;let h=!1,c=!1,u=e*o,d=s*o;const f=t.filterBackend.resources;let g=0,p=0;const m=e;let y=0;f.sliceByTwo||(f.sliceByTwo=Si());const b=f.sliceByTwo;(b.width<1.5*e||b.height<s)&&(b.width=1.5*e,b.height=s);const x=b.getContext("2d");for(x.clearRect(0,0,1.5*e,s),x.putImageData(r,0,0),i=Math.floor(i),n=Math.floor(n);!h||!c;)e=u,s=d,i<Math.floor(u*o)?u=Math.floor(u*o):(u=i,h=!0),n<Math.floor(d*o)?d=Math.floor(d*o):(d=n,c=!0),x.drawImage(b,g,p,e,s,m,y,u,d),g=m,p=y,y+=d;return x.getImageData(g,p,i,n)}lanczosResize(t,e,s,i,n){const r=t.imageData.data,o=t.ctx.createImageData(i,n),h=o.data,c=this.lanczosCreate(this.lanczosLobes),u=this.rcpScaleX,d=this.rcpScaleY,f=2/this.rcpScaleX,g=2/this.rcpScaleY,p=Math.ceil(u*this.lanczosLobes/2),m=Math.ceil(d*this.lanczosLobes/2),y={},b={x:0,y:0},x={x:0,y:0};return function C(S){let T,P,M,D,R,V,H,F,I,j,K;for(b.x=(S+.5)*u,x.x=Math.floor(b.x),T=0;T<n;T++){for(b.y=(T+.5)*d,x.y=Math.floor(b.y),R=0,V=0,H=0,F=0,I=0,P=x.x-p;P<=x.x+p;P++)if(!(P<0||P>=e)){j=Math.floor(1e3*Math.abs(P-b.x)),y[j]||(y[j]={});for(let L=x.y-m;L<=x.y+m;L++)L<0||L>=s||(K=Math.floor(1e3*Math.abs(L-b.y)),y[j][K]||(y[j][K]=c(Math.sqrt(Math.pow(j*f,2)+Math.pow(K*g,2))/1e3)),M=y[j][K],M>0&&(D=4*(L*e+P),R+=M,V+=M*r[D],H+=M*r[D+1],F+=M*r[D+2],I+=M*r[D+3]))}D=4*(T*i+S),h[D]=V/R,h[D+1]=H/R,h[D+2]=F/R,h[D+3]=I/R}return++S<i?C(S):o}(0)}bilinearFiltering(t,e,s,i,n){let r,o,h,c,u,d,f,g,p,m,y,b,x,C=0;const S=this.rcpScaleX,T=this.rcpScaleY,P=4*(e-1),M=t.imageData.data,D=t.ctx.createImageData(i,n),R=D.data;for(f=0;f<n;f++)for(g=0;g<i;g++)for(u=Math.floor(S*g),d=Math.floor(T*f),p=S*g-u,m=T*f-d,x=4*(d*e+u),y=0;y<4;y++)r=M[x+y],o=M[x+4+y],h=M[x+P+y],c=M[x+P+4+y],b=r*(1-p)*(1-m)+o*p*(1-m)+h*m*(1-p)+c*p*m,R[C++]=b;return D}hermiteFastResize(t,e,s,i,n){const r=this.rcpScaleX,o=this.rcpScaleY,h=Math.ceil(r/2),c=Math.ceil(o/2),u=t.imageData.data,d=t.ctx.createImageData(i,n),f=d.data;for(let g=0;g<n;g++)for(let p=0;p<i;p++){const m=4*(p+g*i);let y=0,b=0,x=0,C=0,S=0,T=0,P=0;const M=(g+.5)*o;for(let D=Math.floor(g*o);D<(g+1)*o;D++){const R=Math.abs(M-(D+.5))/c,V=(p+.5)*r,H=R*R;for(let F=Math.floor(p*r);F<(p+1)*r;F++){let I=Math.abs(V-(F+.5))/h;const j=Math.sqrt(H+I*I);j>1&&j<-1||(y=2*j*j*j-3*j*j+1,y>0&&(I=4*(F+D*e),P+=y*u[I+3],x+=y,u[I+3]<255&&(y=y*u[I+3]/250),C+=y*u[I],S+=y*u[I+1],T+=y*u[I+2],b+=y))}}f[m]=C/b,f[m+1]=S/b,f[m+2]=T/b,f[m+3]=P/x}return d}}k(ad,"type","Resize"),k(ad,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),k(ad,"uniformLocations",["uDelta","uTaps"]),G.setClass(ad);class hd extends he{getFragmentSource(){return`
504
+ `)}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){Mn(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<11920929e-14&&e>-11920929e-14)return 1;const s=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(s)/s}}applyTo2d(t){const e=t.imageData,s=this.scaleX,i=this.scaleY;this.rcpScaleX=1/s,this.rcpScaleY=1/i;const n=e.width,r=e.height,a=Math.round(n*s),l=Math.round(r*i);let h;h=this.resizeType==="sliceHack"?this.sliceByTwo(t,n,r,a,l):this.resizeType==="hermite"?this.hermiteFastResize(t,n,r,a,l):this.resizeType==="bilinear"?this.bilinearFiltering(t,n,r,a,l):this.resizeType==="lanczos"?this.lanczosResize(t,n,r,a,l):new ImageData(a,l),t.imageData=h}sliceByTwo(t,e,s,i,n){const r=t.imageData,a=.5;let l=!1,h=!1,c=e*a,u=s*a;const d=t.filterBackend.resources;let f=0,g=0;const p=e;let v=0;d.sliceByTwo||(d.sliceByTwo=Ie());const m=d.sliceByTwo;(m.width<1.5*e||m.height<s)&&(m.width=1.5*e,m.height=s);const b=m.getContext("2d");for(b.clearRect(0,0,1.5*e,s),b.putImageData(r,0,0),i=Math.floor(i),n=Math.floor(n);!l||!h;)e=c,s=u,i<Math.floor(c*a)?c=Math.floor(c*a):(c=i,l=!0),n<Math.floor(u*a)?u=Math.floor(u*a):(u=n,h=!0),b.drawImage(m,f,g,e,s,p,v,c,u),f=p,g=v,v+=u;return b.getImageData(f,g,i,n)}lanczosResize(t,e,s,i,n){const r=t.imageData.data,a=t.ctx.createImageData(i,n),l=a.data,h=this.lanczosCreate(this.lanczosLobes),c=this.rcpScaleX,u=this.rcpScaleY,d=2/this.rcpScaleX,f=2/this.rcpScaleY,g=Math.ceil(c*this.lanczosLobes/2),p=Math.ceil(u*this.lanczosLobes/2),v={},m={x:0,y:0},b={x:0,y:0};return function _(w){let C,T,E,k,O,H,N,P,R,F,V;for(m.x=(w+.5)*c,b.x=Math.floor(m.x),C=0;C<n;C++){for(m.y=(C+.5)*u,b.y=Math.floor(m.y),O=0,H=0,N=0,P=0,R=0,T=b.x-g;T<=b.x+g;T++)if(!(T<0||T>=e)){F=Math.floor(1e3*Math.abs(T-m.x)),v[F]||(v[F]={});for(let M=b.y-p;M<=b.y+p;M++)M<0||M>=s||(V=Math.floor(1e3*Math.abs(M-m.y)),v[F][V]||(v[F][V]=h(Math.sqrt(Math.pow(F*d,2)+Math.pow(V*f,2))/1e3)),E=v[F][V],E>0&&(k=4*(M*e+T),O+=E,H+=E*r[k],N+=E*r[k+1],P+=E*r[k+2],R+=E*r[k+3]))}k=4*(C*i+w),l[k]=H/O,l[k+1]=N/O,l[k+2]=P/O,l[k+3]=R/O}return++w<i?_(w):a}(0)}bilinearFiltering(t,e,s,i,n){let r,a,l,h,c,u,d,f,g,p,v,m,b,_=0;const w=this.rcpScaleX,C=this.rcpScaleY,T=4*(e-1),E=t.imageData.data,k=t.ctx.createImageData(i,n),O=k.data;for(d=0;d<n;d++)for(f=0;f<i;f++)for(c=Math.floor(w*f),u=Math.floor(C*d),g=w*f-c,p=C*d-u,b=4*(u*e+c),v=0;v<4;v++)r=E[b+v],a=E[b+4+v],l=E[b+T+v],h=E[b+T+4+v],m=r*(1-g)*(1-p)+a*g*(1-p)+l*p*(1-g)+h*g*p,O[_++]=m;return k}hermiteFastResize(t,e,s,i,n){const r=this.rcpScaleX,a=this.rcpScaleY,l=Math.ceil(r/2),h=Math.ceil(a/2),c=t.imageData.data,u=t.ctx.createImageData(i,n),d=u.data;for(let f=0;f<n;f++)for(let g=0;g<i;g++){const p=4*(g+f*i);let v=0,m=0,b=0,_=0,w=0,C=0,T=0;const E=(f+.5)*a;for(let k=Math.floor(f*a);k<(f+1)*a;k++){const O=Math.abs(E-(k+.5))/h,H=(g+.5)*r,N=O*O;for(let P=Math.floor(g*r);P<(g+1)*r;P++){let R=Math.abs(H-(P+.5))/l;const F=Math.sqrt(N+R*R);F>1&&F<-1||(v=2*F*F*F-3*F*F+1,v>0&&(R=4*(P+k*e),T+=v*c[R+3],b+=v,c[R+3]<255&&(v=v*c[R+3]/250),_+=v*c[R],w+=v*c[R+1],C+=v*c[R+2],m+=v))}}d[p]=_/m,d[p+1]=w/m,d[p+2]=C/m,d[p+3]=T/b}return u}}S(Gn,"type","Resize"),S(Gn,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),S(Gn,"uniformLocations",["uDelta","uTaps"]),I.setClass(Gn);class Wn extends Ft{getFragmentSource(){return`
505
505
  precision highp float;
506
506
  uniform sampler2D uTexture;
507
507
  uniform float uSaturation;
@@ -515,7 +515,7 @@ void main() {
515
515
  color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
516
516
  gl_FragColor = color;
517
517
  }
518
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o);e[i]+=h!==n?(h-n)*s:0,e[i+1]+=h!==r?(h-r)*s:0,e[i+2]+=h!==o?(h-o)*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}k(hd,"type","Saturation"),k(hd,"defaults",{saturation:0}),k(hd,"uniformLocations",["uSaturation"]),G.setClass(hd);class ld extends he{getFragmentSource(){return`
518
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2],l=Math.max(n,r,a);e[i]+=l!==n?(l-n)*s:0,e[i+1]+=l!==r?(l-r)*s:0,e[i+2]+=l!==a?(l-a)*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}S(Wn,"type","Saturation"),S(Wn,"defaults",{saturation:0}),S(Wn,"uniformLocations",["uSaturation"]),I.setClass(Wn);class Xn extends Ft{getFragmentSource(){return`
519
519
  precision highp float;
520
520
  uniform sampler2D uTexture;
521
521
  uniform float uVibrance;
@@ -530,15 +530,15 @@ void main() {
530
530
  color.b += max != color.b ? (max - color.b) * amt : 0.00;
531
531
  gl_FragColor = color;
532
532
  }
533
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o),c=(n+r+o)/3,u=2*Math.abs(h-c)/255*s;e[i]+=h!==n?(h-n)*u:0,e[i+1]+=h!==r?(h-r)*u:0,e[i+2]+=h!==o?(h-o)*u:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}k(ld,"type","Vibrance"),k(ld,"defaults",{vibrance:0}),k(ld,"uniformLocations",["uVibrance"]),G.setClass(ld);let F0=null;function nS(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function rS(){const a=F0??nS();return F0=a,a/72}function oS(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)}}function aS(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 hS(i))}),i.addEventListener("error",n=>{window.URL.revokeObjectURL(s),e(n)})})}function hS(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))})}var cl={};cl.d=(a,t)=>{for(var e in t)cl.o(t,e)&&!cl.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},cl.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var et=globalThis.pdfjsLib={};cl.d(et,{AbortException:()=>qn,AnnotationEditorLayer:()=>dp,AnnotationEditorParamsType:()=>gt,AnnotationEditorType:()=>at,AnnotationEditorUIManager:()=>qr,AnnotationLayer:()=>iA,AnnotationMode:()=>Yn,ColorPicker:()=>kd,DOMSVGFactory:()=>sp,DrawLayer:()=>fp,FeatureTest:()=>Ue,GlobalWorkerOptions:()=>hn,ImageKind:()=>cd,InvalidPDFException:()=>Rg,MissingPDFException:()=>dl,OPS:()=>ii,OutputScale:()=>Vg,PDFDataRangeTransport:()=>pb,PDFDateString:()=>Hg,PDFWorker:()=>Pa,PasswordResponses:()=>dS,PermissionFlag:()=>uS,PixelsPerInch:()=>Kn,RenderingCancelledException:()=>Ng,TextLayer:()=>bl,TouchManager:()=>_d,UnexpectedResponseException:()=>gd,Util:()=>q,VerbosityLevel:()=>ud,XfaLayer:()=>yb,build:()=>jC,createValidAbsoluteUrl:()=>mS,fetchData:()=>md,getDocument:()=>kC,getFilenameFromUrl:()=>AS,getPdfFilenameFromUrl:()=>TS,getXfaPageViewport:()=>ES,isDataScheme:()=>vd,isPdfFile:()=>Bg,noContextMenu:()=>ni,normalizeUnicode:()=>xS,setLayerDimensions:()=>$r,shadow:()=>ct,stopEvent:()=>bs,version:()=>IC});const Oe=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),L0=[1,0,0,1,0,0],Mg=[.001,0,0,.001,0,0],lS=1e7,Og=1.35,vs={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Yn={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},cS="pdfjs_internal_editor_",at={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},gt={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,DRAW_STEP:41},uS={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},De={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},cd={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},le={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,WIDGET:20},ul={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},ud={ERRORS:0,WARNINGS:1,INFOS:5},ii={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},dS={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let dd=ud.WARNINGS;function fS(a){Number.isInteger(a)&&(dd=a)}function gS(){return dd}function fd(a){dd>=ud.INFOS&&console.log(`Info: ${a}`)}function ht(a){dd>=ud.WARNINGS&&console.log(`Warning: ${a}`)}function Pt(a){throw new Error(a)}function ie(a,t){a||Pt(t)}function pS(a){switch(a==null?void 0:a.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function mS(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=wS(a)}catch{}}const s=t?new URL(a,t):new URL(a);if(pS(s))return s}catch{}return null}function ct(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const $n=function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class I0 extends $n{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Dg extends $n{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Rg extends $n{constructor(t){super(t,"InvalidPDFException")}}class dl extends $n{constructor(t){super(t,"MissingPDFException")}}class gd extends $n{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class vS extends $n{constructor(t){super(t,"FormatError")}}class qn extends $n{constructor(t){super(t,"AbortException")}}function j0(a){(typeof a!="object"||(a==null?void 0:a.length)===void 0)&&Pt("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 pd(a){typeof a!="string"&&Pt("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 bS(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function Fg(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function yS(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function _S(){try{return new Function(""),!0}catch{return!1}}class Ue{static get isLittleEndian(){return ct(this,"isLittleEndian",yS())}static get isEvalSupported(){return ct(this,"isEvalSupported",_S())}static get isOffscreenCanvasSupported(){return ct(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return ct(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?ct(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")}):ct(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,e;return ct(this,"isCSSRoundSupported",(e=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:e.call(t,"width: round(1.5px, 1px)"))}}const Lg=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class q{static makeHexColor(t,e,s){return`#${Lg[t]}${Lg[e]}${Lg[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,c=o+h||1,u=o-h||1;return[Math.sqrt(c),Math.sqrt(u)]}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,c){return c?(c[0]=Math.min(c[0],t,o),c[1]=Math.min(c[1],e,h),c[2]=Math.max(c[2],t,o),c[3]=Math.max(c[3],e,h)):c=[Math.min(t,o),Math.min(e,h),Math.max(t,o),Math.max(e,h)],w(this,ln,Ep).call(this,t,s,n,o,e,i,r,h,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),c),w(this,ln,Ep).call(this,t,s,n,o,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),c),c}}ln=new WeakSet,tf=function(t,e,s,i,n,r,o,h,c,u){if(c<=0||c>=1)return;const d=1-c,f=c*c,g=f*c,p=d*(d*(d*t+3*c*e)+3*f*s)+g*i,m=d*(d*(d*n+3*c*r)+3*f*o)+g*h;u[0]=Math.min(u[0],p),u[1]=Math.min(u[1],m),u[2]=Math.max(u[2],p),u[3]=Math.max(u[3],m)},Ep=function(t,e,s,i,n,r,o,h,c,u,d,f){if(Math.abs(c)<1e-12){Math.abs(u)>=1e-12&&w(this,ln,tf).call(this,t,e,s,i,n,r,o,h,-d/u,f);return}const g=u**2-4*d*c;if(g<0)return;const p=Math.sqrt(g),m=2*c;w(this,ln,tf).call(this,t,e,s,i,n,r,o,h,(-u+p)/m,f),w(this,ln,tf).call(this,t,e,s,i,n,r,o,h,(-u-p)/m,f)},_(q,ln);function wS(a){return decodeURIComponent(escape(a))}let Ig=null,N0=null;function xS(a){return Ig||(Ig=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,N0=new Map([["ſt","ſt"]])),a.replaceAll(Ig,(t,e,s)=>e?e.normalize("NFKC"):N0.get(s))}function SS(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const a=new Uint8Array(32);return crypto.getRandomValues(a),j0(a)}const jg="pdfjs_internal_id_";function CS(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(j0(a))}typeof Promise.try!="function"&&(Promise.try=function(a,...t){return new Promise(e=>{e(a(...t))})});const an="http://www.w3.org/2000/svg",Qr=class Qr{};Q(Qr,"CSS",96),Q(Qr,"PDF",72),Q(Qr,"PDF_TO_CSS_UNITS",Qr.CSS/Qr.PDF);let Kn=Qr;async function md(a,t="text"){if(gl(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 fl{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const h=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let u,d,f,g;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,d=0,f=0,g=1;break;case 90:u=0,d=1,f=1,g=0;break;case 270:u=0,d=-1,f=-1,g=0;break;case 0:u=1,d=0,f=0,g=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}o&&(f=-f,g=-g);let p,m,y,b;u===0?(p=Math.abs(c-t[1])*s+n,m=Math.abs(h-t[0])*s+r,y=(t[3]-t[1])*s,b=(t[2]-t[0])*s):(p=Math.abs(h-t[0])*s+n,m=Math.abs(c-t[1])*s+r,y=(t[2]-t[0])*s,b=(t[3]-t[1])*s),this.transform=[u*s,d*s,f*s,g*s,p-u*s*h-f*s*c,m-d*s*h-g*s*c],this.width=y,this.height=b}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return ct(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new fl({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return q.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=q.applyTransform([t[0],t[1]],this.transform),s=q.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return q.applyInverseTransform([t,e],this.transform)}}class Ng extends $n{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function vd(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function Bg(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function AS(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function TS(a,t="document.pdf"){if(typeof a!="string")return t;if(vd(a))return ht('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 B0{constructor(){Q(this,"started",Object.create(null));Q(this,"times",[])}time(t){t in this.started&&ht(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||ht(`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
534
- `);return t.join("")}}function gl(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function ni(a){a.preventDefault()}function bs(a){a.preventDefault(),a.stopPropagation()}class Hg{static toDateObject(t){if(!t||typeof t!="string")return null;l(this,Sl)||v(this,Sl,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const e=l(this,Sl).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 c=e[7]||"Z";let u=parseInt(e[8],10);u=u>=0&&u<=23?u:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,c==="-"?(r+=u,o+=d):c==="+"&&(r-=u,o-=d),new Date(Date.UTC(s,i,n,r,o,h))}}Sl=new WeakMap,_(Hg,Sl);function ES(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new fl({viewBox:n,userUnit:1,scale:t,rotation:e})}function zg(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):(ht(`Not a valid color format: "${a}"`),[0,0,0])}function kS(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,zg(s))}t.remove()}function It(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 $r(a,t,e=!1,s=!0){if(t instanceof fl){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Ue.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,c=`var(--scale-factor) * ${n}px`,u=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,d=o?`round(down, ${c}, var(--scale-round-y, 1px))`:`calc(${c})`;!e||t.rotation%180===0?(r.width=u,r.height=d):(r.width=d,r.height=u)}s&&a.setAttribute("data-main-rotation",t.rotation)}class Vg{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 cn=class cn{constructor(t){_(this,Ye);_(this,Qn,null);_(this,Zr,null);_(this,ri);_(this,to,null);_(this,Cl,null);v(this,ri,t),l(cn,Al)||v(cn,Al,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=v(this,Qn,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=l(this,ri)._uiManager._signal;t.addEventListener("contextmenu",ni,{signal:e}),t.addEventListener("pointerdown",w(cn,Od,qb),{signal:e});const s=v(this,to,document.createElement("div"));s.className="buttons",t.append(s);const i=l(this,ri).toolbarPosition;if(i){const{style:n}=t,r=l(this,ri)._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return w(this,Ye,Qb).call(this),t}get div(){return l(this,Qn)}hide(){var t;l(this,Qn).classList.add("hidden"),(t=l(this,Zr))==null||t.hideDropdown()}show(){var t;l(this,Qn).classList.remove("hidden"),(t=l(this,Cl))==null||t.shown()}async addAltText(t){const e=await t.render();w(this,Ye,ef).call(this,e),l(this,to).prepend(e,l(this,Ye,kp)),v(this,Cl,t)}addColorPicker(t){v(this,Zr,t);const e=t.renderButton();w(this,Ye,ef).call(this,e),l(this,to).prepend(e,l(this,Ye,kp))}remove(){var t;l(this,Qn).remove(),(t=l(this,Zr))==null||t.destroy(),v(this,Zr,null)}};Qn=new WeakMap,Zr=new WeakMap,ri=new WeakMap,to=new WeakMap,Cl=new WeakMap,Al=new WeakMap,Od=new WeakSet,qb=function(t){t.stopPropagation()},Ye=new WeakSet,Kb=function(t){l(this,ri)._focusEventsAllowed=!1,bs(t)},Jb=function(t){l(this,ri)._focusEventsAllowed=!0,bs(t)},ef=function(t){const e=l(this,ri)._uiManager._signal;t.addEventListener("focusin",w(this,Ye,Kb).bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",w(this,Ye,Jb).bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ni,{signal:e})},Qb=function(){const{editorType:t,_uiManager:e}=l(this,ri),s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",l(cn,Al)[t]),w(this,Ye,ef).call(this,s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),l(this,to).append(s)},kp=function(){const t=document.createElement("div");return t.className="divider",t},_(cn,Od),_(cn,Al,null);let Gg=cn;class PS{constructor(t){_(this,Zn);_(this,Tl,null);_(this,eo,null);_(this,so);v(this,so,t)}show(t,e,s){const[i,n]=w(this,Zn,ty).call(this,e,s),{style:r}=l(this,eo)||v(this,eo,w(this,Zn,Zb).call(this));t.append(l(this,eo)),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){l(this,eo).remove()}}Tl=new WeakMap,eo=new WeakMap,so=new WeakMap,Zn=new WeakSet,Zb=function(){const t=v(this,eo,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ni,{signal:l(this,so)._signal});const e=v(this,Tl,document.createElement("div"));return e.className="buttons",t.append(e),w(this,Zn,ey).call(this),t},ty=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]},ey=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=l(this,so)._signal;t.addEventListener("contextmenu",ni,{signal:s}),t.addEventListener("click",()=>{l(this,so).highlightSelection("floating_button")},{signal:s}),l(this,Tl).append(t)};function bd(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class MS{constructor(){_(this,Dd,0)}get id(){return`${cS}${es(this,Dd)._++}`}}Dd=new WeakMap;const pp=class pp{constructor(){_(this,Oa);_(this,Ma,SS());_(this,El,0);_(this,Fe,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 ct(this,"_isSVGFittingCanvas",n)}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return w(this,Oa,sf).call(this,`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return w(this,Oa,sf).call(this,t,t)}async getFromBlob(t,e){const s=await e;return w(this,Oa,sf).call(this,t,s)}async getFromId(t){l(this,Fe)||v(this,Fe,new Map);const e=l(this,Fe).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){l(this,Fe)||v(this,Fe,new Map);let s=l(this,Fe).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_${l(this,Ma)}_${es(this,El)._++}`,refCounter:1,isSvg:!1},l(this,Fe).set(t,s),l(this,Fe).set(s.id,s),s}getSvgUrl(t){const e=l(this,Fe).get(t);return e!=null&&e.isSvg?e.svgUrl:null}deleteId(t){var i;l(this,Fe)||v(this,Fe,new Map);const e=l(this,Fe).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_${l(this,Ma)}_`)}};Ma=new WeakMap,El=new WeakMap,Fe=new WeakMap,Oa=new WeakSet,sf=async function(t,e){l(this,Fe)||v(this,Fe,new Map);let s=l(this,Fe).get(t);if(s===null)return null;if(s!=null&&s.bitmap)return s.refCounter+=1,s;try{s||(s={bitmap:null,id:`image_${l(this,Ma)}_${es(this,El)._++}`,refCounter:0,isSvg:!1});let i;if(typeof e=="string"?(s.url=e,i=await md(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=pp._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((c,u)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,c()},r.onload=async()=>{const d=s.svgUrl=r.result;o.src=await n?`${d}#svgView(preserveAspectRatio(none))`:d},o.onerror=r.onerror=u});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){ht(i),s=null}return l(this,Fe).set(t,s),s&&l(this,Fe).set(s.id,s),s};let Wg=pp;class OS{constructor(t=128){_(this,Jt,[]);_(this,tr,!1);_(this,kl);_(this,Gt,-1);v(this,kl,t)}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),l(this,tr))return;const h={cmd:t,undo:e,post:s,type:n};if(l(this,Gt)===-1){l(this,Jt).length>0&&(l(this,Jt).length=0),v(this,Gt,0),l(this,Jt).push(h);return}if(r&&l(this,Jt)[l(this,Gt)].type===n){o&&(h.undo=l(this,Jt)[l(this,Gt)].undo),l(this,Jt)[l(this,Gt)]=h;return}const c=l(this,Gt)+1;c===l(this,kl)?l(this,Jt).splice(0,1):(v(this,Gt,c),c<l(this,Jt).length&&l(this,Jt).splice(c)),l(this,Jt).push(h)}undo(){if(l(this,Gt)===-1)return;v(this,tr,!0);const{undo:t,post:e}=l(this,Jt)[l(this,Gt)];t(),e==null||e(),v(this,tr,!1),v(this,Gt,l(this,Gt)-1)}redo(){if(l(this,Gt)<l(this,Jt).length-1){v(this,Gt,l(this,Gt)+1),v(this,tr,!0);const{cmd:t,post:e}=l(this,Jt)[l(this,Gt)];t(),e==null||e(),v(this,tr,!1)}}hasSomethingToUndo(){return l(this,Gt)!==-1}hasSomethingToRedo(){return l(this,Gt)<l(this,Jt).length-1}cleanType(t){if(l(this,Gt)!==-1){for(let e=l(this,Gt);e>=0;e--)if(l(this,Jt)[e].type!==t){l(this,Jt).splice(e+1,l(this,Gt)-e),v(this,Gt,e);return}l(this,Jt).length=0,v(this,Gt,-1)}}destroy(){v(this,Jt,null)}}Jt=new WeakMap,tr=new WeakMap,kl=new WeakMap,Gt=new WeakMap;class pl{constructor(t){_(this,Rd);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Ue.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(w(this,Rd,sy).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||bs(e))}}Rd=new WeakSet,sy=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 Fd=class Fd{get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return kS(t),ct(this,"_colors",t)}convert(t){const e=zg(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 Fd._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?q.makeHexColor(...e):t}};Q(Fd,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Xg=Fd;const Na=class Na{constructor(t,e,s,i,n,r,o,h,c,u,d,f,g){_(this,B);_(this,Da,new AbortController);_(this,ys,null);_(this,ce,new Map);_(this,_e,new Map);_(this,Ra,null);_(this,un,null);_(this,Fa,null);_(this,js,new OS);_(this,er,null);_(this,io,null);_(this,La,0);_(this,no,new Set);_(this,Mi,null);_(this,oi,null);_(this,ro,new Set);Q(this,"_editorUndoBar",null);_(this,Pl,!1);_(this,Ml,!1);_(this,Ia,!1);_(this,Ol,null);_(this,Oi,null);_(this,sr,null);_(this,ja,null);_(this,ir,!1);_(this,Di,null);_(this,Ld,new MS);_(this,nr,!1);_(this,Dl,!1);_(this,rr,null);_(this,oo,null);_(this,Rl,null);_(this,Fl,null);_(this,ge,at.NONE);_(this,Ct,new Set);_(this,dn,null);_(this,ao,null);_(this,Ll,null);_(this,Il,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});_(this,or,[0,0]);_(this,Ri,null);_(this,fn,null);_(this,jl,null);_(this,Ns,null);const p=this._signal=l(this,Da).signal;v(this,fn,t),v(this,jl,e),v(this,Ra,s),this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:p}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:p}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:p}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p}),i._on("setpreference",this.onSetPreference.bind(this),{signal:p}),i._on("switchannotationeditorparams",m=>this.updateParams(m.type,m.value),{signal:p}),w(this,B,ry).call(this),w(this,B,ly).call(this),w(this,B,Mp).call(this),v(this,un,n.annotationStorage),v(this,Ol,n.filterFactory),v(this,ao,r),v(this,ja,o||null),v(this,Pl,h),v(this,Ml,c),v(this,Ia,u),v(this,Fl,d||null),this.viewParameters={realScale:Kn.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=f||null,this._supportsPinchToZoom=g!==!1}static get _keyboardManager(){const t=Na.prototype,e=r=>l(r,fn).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 ct(this,"_keyboardManager",new pl([[["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)&&l(r,fn).contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&l(r,fn).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,n;(t=l(this,Ns))==null||t.resolve(),v(this,Ns,null),(e=l(this,Da))==null||e.abort(),v(this,Da,null),this._signal=null;for(const r of l(this,_e).values())r.destroy();l(this,_e).clear(),l(this,ce).clear(),l(this,ro).clear(),v(this,ys,null),l(this,Ct).clear(),l(this,js).destroy(),(s=l(this,Ra))==null||s.destroy(),(i=l(this,Di))==null||i.hide(),v(this,Di,null),l(this,Oi)&&(clearTimeout(l(this,Oi)),v(this,Oi,null)),l(this,Ri)&&(clearTimeout(l(this,Ri)),v(this,Ri,null)),(n=this._editorUndoBar)==null||n.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return l(this,Fl)}get useNewAltTextFlow(){return l(this,Ml)}get useNewAltTextWhenAddingImage(){return l(this,Ia)}get hcmFilter(){return ct(this,"hcmFilter",l(this,ao)?l(this,Ol).addHCMFilter(l(this,ao).foreground,l(this,ao).background):"none")}get direction(){return ct(this,"direction",getComputedStyle(l(this,fn)).direction)}get highlightColors(){return ct(this,"highlightColors",l(this,ja)?new Map(l(this,ja).split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return ct(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),v(this,io,t)}setMainHighlightColorPicker(t){v(this,Rl,t)}editAltText(t,e=!1){var s;(s=l(this,Ra))==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":v(this,Ia,e);break}}onPageChanging({pageNumber:t}){v(this,La,t-1)}focusMainContainer(){l(this,fn).focus()}findParent(t,e){for(const s of l(this,_e).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){l(this,jl).classList.toggle("noUserSelect",t)}addShouldRescale(t){l(this,ro).add(t)}removeShouldRescale(t){l(this,ro).delete(t)}onScaleChanging({scale:t}){var e;this.commitOrRemove(),this.viewParameters.realScale=t*Kn.PDF_TO_CSS_UNITS;for(const s of l(this,ro))s.onScaleChanging();(e=l(this,io))==null||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(),c=w(this,B,nf).call(this,e).closest(".textLayer"),u=this.getSelectionBoxes(c);if(!u)return;e.empty();const d=w(this,B,Pp).call(this,c),f=l(this,ge)===at.NONE,g=()=>{d==null||d.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:u,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:o}),f&&this.showAllEditors("highlight",!0,!0)};if(f){this.switchToMode(at.HIGHLIGHT,g);return}g()}addToAnnotationStorage(t){!t.isEmpty()&&l(this,un)&&!l(this,un).has(t.id)&&l(this,un).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,l(this,ir)&&(v(this,ir,!1),w(this,B,rf).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of l(this,Ct))if(e.div.contains(t)){v(this,oo,[e,t]),e._focusEventsAllowed=!1;break}}focus(){if(!l(this,oo))return;const[t,e]=l(this,oo);v(this,oo,null),e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}addEditListeners(){w(this,B,Mp).call(this),w(this,B,Op).call(this)}removeEditListeners(){w(this,B,hy).call(this),w(this,B,Dp).call(this)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of l(this,oi))if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of l(this,oi))if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){var s;if(t.preventDefault(),(s=l(this,ys))==null||s.commitOrRemove(),!this.hasSelection)return;const e=[];for(const i of l(this,Ct)){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 l(this,oi))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){ht(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const c=await i.deserialize(h);if(!c)return;n.push(c)}const r=()=>{for(const h of n)w(this,B,Rp).call(this,h);w(this,B,Fp).call(this,n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){ht(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),l(this,ge)!==at.NONE&&!this.isEditorHandlingKeyboard&&Na._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,l(this,ir)&&(v(this,ir,!1),w(this,B,rf).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?(w(this,B,oy).call(this),w(this,B,Op).call(this),w(this,B,ss).call(this,{isEditing:l(this,ge)!==at.NONE,isEmpty:w(this,B,Kc).call(this),hasSomethingToUndo:l(this,js).hasSomethingToUndo(),hasSomethingToRedo:l(this,js).hasSomethingToRedo(),hasSelectedEditor:!1})):(w(this,B,ay).call(this),w(this,B,Dp).call(this),w(this,B,ss).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!l(this,oi)){v(this,oi,t);for(const e of l(this,oi))w(this,B,Hn).call(this,e.defaultPropertiesToUpdate)}}getId(){return l(this,Ld).id}get currentLayer(){return l(this,_e).get(l(this,La))}getLayer(t){return l(this,_e).get(t)}get currentPageIndex(){return l(this,La)}addLayer(t){l(this,_e).set(t.pageIndex,t),l(this,nr)?t.enable():t.disable()}removeLayer(t){l(this,_e).delete(t.pageIndex)}async updateMode(t,e=null,s=!1){var i;if(l(this,ge)!==t&&!(l(this,Ns)&&(await l(this,Ns).promise,!l(this,Ns)))){if(v(this,Ns,Promise.withResolvers()),v(this,ge,t),t===at.NONE){this.setEditingState(!1),w(this,B,uy).call(this),(i=this._editorUndoBar)==null||i.hide(),l(this,Ns).resolve();return}this.setEditingState(!0),await w(this,B,cy).call(this),this.unselectAll();for(const n of l(this,_e).values())n.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),l(this,Ns).resolve();return}for(const n of l(this,ce).values())n.annotationElementId===e?(this.setSelected(n),n.enterInEditMode()):n.unselect();l(this,Ns).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==l(this,ge)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){var s;if(l(this,oi)){switch(t){case gt.CREATE:this.currentLayer.addNewEditor();return;case gt.HIGHLIGHT_DEFAULT_COLOR:(s=l(this,Rl))==null||s.updateColor(e);break;case gt.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(l(this,Ll)||v(this,Ll,new Map)).set(t,e),this.showAllEditors("highlight",e);break}for(const i of l(this,Ct))i.updateParams(t,e);for(const i of l(this,oi))i.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){var n;for(const r of l(this,ce).values())r.editorType===t&&r.show(e);(((n=l(this,Ll))==null?void 0:n.get(gt.HIGHLIGHT_SHOW_ALL))??!0)!==e&&w(this,B,Hn).call(this,[[gt.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(l(this,Dl)!==t){v(this,Dl,t);for(const e of l(this,_e).values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}getEditors(t){const e=[];for(const s of l(this,ce).values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return l(this,ce).get(t)}addEditor(t){l(this,ce).set(t.id,t)}removeEditor(t){var e;t.div.contains(document.activeElement)&&(l(this,Oi)&&clearTimeout(l(this,Oi)),v(this,Oi,setTimeout(()=>{this.focusMainContainer(),v(this,Oi,null)},0))),l(this,ce).delete(t.id),this.unselect(t),(!t.annotationElementId||!l(this,no).has(t.annotationElementId))&&((e=l(this,un))==null||e.remove(t.id))}addDeletedAnnotationElement(t){l(this,no).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return l(this,no).has(t)}removeDeletedAnnotationElement(t){l(this,no).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){l(this,ys)!==t&&(v(this,ys,t),t&&w(this,B,Hn).call(this,t.propertiesToUpdate))}updateUI(t){l(this,B,dy)===t&&w(this,B,Hn).call(this,t.propertiesToUpdate)}updateUIForDefaultProperties(t){w(this,B,Hn).call(this,t.defaultPropertiesToUpdate)}toggleSelected(t){if(l(this,Ct).has(t)){l(this,Ct).delete(t),t.unselect(),w(this,B,ss).call(this,{hasSelectedEditor:this.hasSelection});return}l(this,Ct).add(t),t.select(),w(this,B,Hn).call(this,t.propertiesToUpdate),w(this,B,ss).call(this,{hasSelectedEditor:!0})}setSelected(t){var e;(e=l(this,io))==null||e.commitOrRemove();for(const s of l(this,Ct))s!==t&&s.unselect();l(this,Ct).clear(),l(this,Ct).add(t),t.select(),w(this,B,Hn).call(this,t.propertiesToUpdate),w(this,B,ss).call(this,{hasSelectedEditor:!0})}isSelected(t){return l(this,Ct).has(t)}get firstSelectedEditor(){return l(this,Ct).values().next().value}unselect(t){t.unselect(),l(this,Ct).delete(t),w(this,B,ss).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return l(this,Ct).size!==0}get isEnterHandled(){return l(this,Ct).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){var t;l(this,js).undo(),w(this,B,ss).call(this,{hasSomethingToUndo:l(this,js).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:w(this,B,Kc).call(this)}),(t=this._editorUndoBar)==null||t.hide()}redo(){l(this,js).redo(),w(this,B,ss).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:l(this,js).hasSomethingToRedo(),isEmpty:w(this,B,Kc).call(this)})}addCommands(t){l(this,js).add(t),w(this,B,ss).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:w(this,B,Kc).call(this)})}cleanUndoStack(t){l(this,js).cleanType(t)}delete(){var n;this.commitOrRemove();const t=(n=this.currentLayer)==null?void 0:n.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...l(this,Ct)],s=()=>{var r;(r=this._editorUndoBar)==null||r.show(i,e.length===1?e[0].editorType:e.length);for(const o of e)o.remove()},i=()=>{for(const r of e)w(this,B,Rp).call(this,r)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){var t;(t=l(this,ys))==null||t.commitOrRemove()}hasSomethingToControl(){return l(this,ys)||this.hasSelection}selectAll(){for(const t of l(this,Ct))t.commit();w(this,B,Fp).call(this,l(this,ce).values())}unselectAll(){var t;if(!(l(this,ys)&&(l(this,ys).commitOrRemove(),l(this,ge)!==at.NONE))&&!((t=l(this,io))!=null&&t.commitOrRemove())&&this.hasSelection){for(const e of l(this,Ct))e.unselect();l(this,Ct).clear(),w(this,B,ss).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;l(this,or)[0]+=t,l(this,or)[1]+=e;const[i,n]=l(this,or),r=[...l(this,Ct)],o=1e3;l(this,Ri)&&clearTimeout(l(this,Ri)),v(this,Ri,setTimeout(()=>{v(this,Ri,null),l(this,or)[0]=l(this,or)[1]=0,this.addCommands({cmd:()=>{for(const h of r)l(this,ce).has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)l(this,ce).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),v(this,Mi,new Map);for(const t of l(this,Ct))l(this,Mi).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!l(this,Mi))return!1;this.disableUserSelect(!1);const t=l(this,Mi);v(this,Mi,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(l(this,ce).has(i.id)){const h=l(this,_e).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(l(this,Mi))for(const s of l(this,Mi).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())||l(this,Ct).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return l(this,ys)===t}getActive(){return l(this,ys)}getMode(){return l(this,ge)}get imageManager(){return ct(this,"imageManager",new Wg)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let c=0,u=e.rangeCount;c<u;c++)if(!t.contains(e.getRangeAt(c).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=(c,u,d,f)=>({x:(u-i)/r,y:1-(c+d-s)/n,width:f/r,height:d/n});break;case"180":o=(c,u,d,f)=>({x:1-(c+d-s)/n,y:1-(u+f-i)/r,width:d/n,height:f/r});break;case"270":o=(c,u,d,f)=>({x:1-(u+f-i)/r,y:(c-s)/n,width:f/r,height:d/n});break;default:o=(c,u,d,f)=>({x:(c-s)/n,y:(u-i)/r,width:d/n,height:f/r});break}const h=[];for(let c=0,u=e.rangeCount;c<u;c++){const d=e.getRangeAt(c);if(!d.collapsed)for(const{x:f,y:g,width:p,height:m}of d.getClientRects())p===0||m===0||h.push(o(f,g,p,m))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(l(this,Fa)||v(this,Fa,new Map)).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){var e;(e=l(this,Fa))==null||e.delete(t)}renderAnnotationElement(t){var i;const e=(i=l(this,Fa))==null?void 0:i.get(t.data.id);if(!e)return;const s=l(this,un).getRawValue(e);s&&(l(this,ge)===at.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}};Da=new WeakMap,ys=new WeakMap,ce=new WeakMap,_e=new WeakMap,Ra=new WeakMap,un=new WeakMap,Fa=new WeakMap,js=new WeakMap,er=new WeakMap,io=new WeakMap,La=new WeakMap,no=new WeakMap,Mi=new WeakMap,oi=new WeakMap,ro=new WeakMap,Pl=new WeakMap,Ml=new WeakMap,Ia=new WeakMap,Ol=new WeakMap,Oi=new WeakMap,sr=new WeakMap,ja=new WeakMap,ir=new WeakMap,Di=new WeakMap,Ld=new WeakMap,nr=new WeakMap,Dl=new WeakMap,rr=new WeakMap,oo=new WeakMap,Rl=new WeakMap,Fl=new WeakMap,ge=new WeakMap,Ct=new WeakMap,dn=new WeakMap,ao=new WeakMap,Ll=new WeakMap,Il=new WeakMap,or=new WeakMap,Ri=new WeakMap,fn=new WeakMap,jl=new WeakMap,Ns=new WeakMap,B=new WeakSet,nf=function({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t},Pp=function(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of l(this,_e).values())if(s.hasTextLayer(t))return s;return null},iy=function(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=w(this,B,nf).call(this,t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(l(this,Di)||v(this,Di,new PS(this)),l(this,Di).show(s,i,this.direction==="ltr"))},ny=function(){var n,r,o;const t=document.getSelection();if(!t||t.isCollapsed){l(this,dn)&&((n=l(this,Di))==null||n.hide(),v(this,dn,null),w(this,B,ss).call(this,{hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===l(this,dn))return;const i=w(this,B,nf).call(this,t).closest(".textLayer");if(!i){l(this,dn)&&((r=l(this,Di))==null||r.hide(),v(this,dn,null),w(this,B,ss).call(this,{hasSelectedText:!1}));return}if((o=l(this,Di))==null||o.hide(),v(this,dn,e),w(this,B,ss).call(this,{hasSelectedText:!0}),!(l(this,ge)!==at.HIGHLIGHT&&l(this,ge)!==at.NONE)&&(l(this,ge)===at.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),v(this,ir,this.isShiftKeyDown),!this.isShiftKeyDown)){const h=l(this,ge)===at.HIGHLIGHT?w(this,B,Pp).call(this,i):null;h==null||h.toggleDrawing();const c=new AbortController,u=this.combinedSignal(c),d=f=>{f.type==="pointerup"&&f.button!==0||(c.abort(),h==null||h.toggleDrawing(!0),f.type==="pointerup"&&w(this,B,rf).call(this,"main_toolbar"))};window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("blur",d,{signal:u})}},rf=function(t=""){l(this,ge)===at.HIGHLIGHT?this.highlightSelection(t):l(this,Pl)&&w(this,B,iy).call(this)},ry=function(){document.addEventListener("selectionchange",w(this,B,ny).bind(this),{signal:this._signal})},oy=function(){if(l(this,sr))return;v(this,sr,new AbortController);const t=this.combinedSignal(l(this,sr));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},ay=function(){var t;(t=l(this,sr))==null||t.abort(),v(this,sr,null)},Mp=function(){if(l(this,rr))return;v(this,rr,new AbortController);const t=this.combinedSignal(l(this,rr));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},hy=function(){var t;(t=l(this,rr))==null||t.abort(),v(this,rr,null)},Op=function(){if(l(this,er))return;v(this,er,new AbortController);const t=this.combinedSignal(l(this,er));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})},Dp=function(){var t;(t=l(this,er))==null||t.abort(),v(this,er,null)},ly=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},ss=function(t){Object.entries(t).some(([s,i])=>l(this,Il)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(l(this,Il),t)}),l(this,ge)===at.HIGHLIGHT&&t.hasSelectedEditor===!1&&w(this,B,Hn).call(this,[[gt.HIGHLIGHT_FREE,!0]]))},Hn=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},cy=async function(){if(!l(this,nr)){v(this,nr,!0);const t=[];for(const e of l(this,_e).values())t.push(e.enable());await Promise.all(t);for(const e of l(this,ce).values())e.enable()}},uy=function(){if(this.unselectAll(),l(this,nr)){v(this,nr,!1);for(const t of l(this,_e).values())t.disable();for(const t of l(this,ce).values())t.disable()}},Rp=function(t){const e=l(this,_e).get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},dy=function(){let t=null;for(t of l(this,Ct));return t},Kc=function(){if(l(this,ce).size===0)return!0;if(l(this,ce).size===1)for(const t of l(this,ce).values())return t.isEmpty();return!1},Fp=function(t){for(const e of l(this,Ct))e.unselect();l(this,Ct).clear();for(const e of t)e.isEmpty()||(l(this,Ct).add(e),e.select());w(this,B,ss).call(this,{hasSelectedEditor:this.hasSelection})},Q(Na,"TRANSLATE_SMALL",1),Q(Na,"TRANSLATE_BIG",10);let qr=Na;const $e=class $e{constructor(t){_(this,hi);_(this,pe,null);_(this,Fi,!1);_(this,ai,null);_(this,Ba,null);_(this,Li,null);_(this,_s,null);_(this,Ha,!1);_(this,Ii,null);_(this,ls,null);_(this,gn,null);_(this,ho,null);_(this,ji,!1);v(this,ls,t),v(this,ji,t._uiManager.useNewAltTextFlow),l($e,ar)||v($e,ar,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){$e._l10n??($e._l10n=t)}async render(){const t=v(this,ai,document.createElement("button"));t.className="altText",t.tabIndex="0";const e=v(this,Ba,document.createElement("span"));t.append(e),l(this,ji)?(t.classList.add("new"),t.setAttribute("data-l10n-id",l($e,ar).missing),e.setAttribute("data-l10n-id",l($e,ar)["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=l(this,ls)._uiManager._signal;t.addEventListener("contextmenu",ni,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),l(this,ls)._uiManager.editAltText(l(this,ls)),l(this,ji)&&l(this,ls)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:l(this,hi,Jc)}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(v(this,Ha,!0),i(n))},{signal:s}),await w(this,hi,of).call(this),t}finish(){l(this,ai)&&(l(this,ai).focus({focusVisible:l(this,Ha)}),v(this,Ha,!1))}isEmpty(){return l(this,ji)?l(this,pe)===null:!l(this,pe)&&!l(this,Fi)}hasData(){return l(this,ji)?l(this,pe)!==null||!!l(this,gn):this.isEmpty()}get guessedText(){return l(this,gn)}async setGuessedText(t){l(this,pe)===null&&(v(this,gn,t),v(this,ho,await $e._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),w(this,hi,of).call(this))}toggleAltTextBadge(t=!1){var e;if(!l(this,ji)||l(this,pe)){(e=l(this,Ii))==null||e.remove(),v(this,Ii,null);return}if(!l(this,Ii)){const s=v(this,Ii,document.createElement("div"));s.className="noAltTextBadge",l(this,ls).div.append(s)}l(this,Ii).classList.toggle("hidden",!t)}serialize(t){let e=l(this,pe);return!t&&l(this,gn)===e&&(e=l(this,ho)),{altText:e,decorative:l(this,Fi),guessedText:l(this,gn),textWithDisclaimer:l(this,ho)}}get data(){return{altText:l(this,pe),decorative:l(this,Fi)}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(v(this,gn,s),v(this,ho,i)),!(l(this,pe)===t&&l(this,Fi)===e)&&(n||(v(this,pe,t),v(this,Fi,e)),w(this,hi,of).call(this))}toggle(t=!1){l(this,ai)&&(!t&&l(this,_s)&&(clearTimeout(l(this,_s)),v(this,_s,null)),l(this,ai).disabled=!t)}shown(){l(this,ls)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:l(this,hi,Jc)}})}destroy(){var t,e;(t=l(this,ai))==null||t.remove(),v(this,ai,null),v(this,Ba,null),v(this,Li,null),(e=l(this,Ii))==null||e.remove(),v(this,Ii,null)}};pe=new WeakMap,Fi=new WeakMap,ai=new WeakMap,Ba=new WeakMap,Li=new WeakMap,_s=new WeakMap,Ha=new WeakMap,Ii=new WeakMap,ls=new WeakMap,gn=new WeakMap,ho=new WeakMap,ji=new WeakMap,ar=new WeakMap,hi=new WeakSet,Jc=function(){return l(this,pe)&&"added"||l(this,pe)===null&&this.guessedText&&"review"||"missing"},of=async function(){var i,n,r;const t=l(this,ai);if(!t)return;if(l(this,ji)){if(t.classList.toggle("done",!!l(this,pe)),t.setAttribute("data-l10n-id",l($e,ar)[l(this,hi,Jc)]),(i=l(this,Ba))==null||i.setAttribute("data-l10n-id",l($e,ar)[`${l(this,hi,Jc)}-label`]),!l(this,pe)){(n=l(this,Li))==null||n.remove();return}}else{if(!l(this,pe)&&!l(this,Fi)){t.classList.remove("done"),(r=l(this,Li))==null||r.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=l(this,Li);if(!e){v(this,Li,e=document.createElement("span")),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${l(this,ls).id}`;const o=100,h=l(this,ls)._uiManager._signal;h.addEventListener("abort",()=>{clearTimeout(l(this,_s)),v(this,_s,null)},{once:!0}),t.addEventListener("mouseenter",()=>{v(this,_s,setTimeout(()=>{v(this,_s,null),l(this,Li).classList.add("show"),l(this,ls)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:h}),t.addEventListener("mouseleave",()=>{var c;l(this,_s)&&(clearTimeout(l(this,_s)),v(this,_s,null)),(c=l(this,Li))==null||c.classList.remove("show")},{signal:h})}l(this,Fi)?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=l(this,pe)),e.parentNode||t.append(e);const s=l(this,ls).getImageForAltText();s==null||s.setAttribute("aria-describedby",e.id)},_($e,ar,null),Q($e,"_l10n",null);let yd=$e;const mp=class mp{constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:o}){_(this,mn);_(this,Nl);_(this,lo,!1);_(this,Bl,null);_(this,Hl);_(this,zl);_(this,Vl);_(this,Gl);_(this,za);_(this,pn,null);_(this,co);_(this,hr,null);v(this,Nl,t),v(this,Bl,s),v(this,Hl,e),v(this,zl,i),v(this,Vl,n),v(this,Gl,r),v(this,co,new AbortController),v(this,za,AbortSignal.any([o,l(this,co).signal])),t.addEventListener("touchstart",w(this,mn,fy).bind(this),{passive:!1,signal:l(this,za)})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return ct(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}destroy(){var t;(t=l(this,co))==null||t.abort(),v(this,co,null)}};Nl=new WeakMap,lo=new WeakMap,Bl=new WeakMap,Hl=new WeakMap,zl=new WeakMap,Vl=new WeakMap,Gl=new WeakMap,za=new WeakMap,pn=new WeakMap,co=new WeakMap,hr=new WeakMap,mn=new WeakSet,fy=function(t){var i,n,r;if((i=l(this,Hl))!=null&&i.call(this)||t.touches.length<2)return;if(!l(this,hr)){v(this,hr,new AbortController);const o=AbortSignal.any([l(this,za),l(this,hr).signal]),h=l(this,Nl),c={signal:o,passive:!1};h.addEventListener("touchmove",w(this,mn,gy).bind(this),c),h.addEventListener("touchend",w(this,mn,Lp).bind(this),c),h.addEventListener("touchcancel",w(this,mn,Lp).bind(this),c),(n=l(this,zl))==null||n.call(this)}if(bs(t),t.touches.length!==2||(r=l(this,Bl))!=null&&r.call(this)){v(this,pn,null);return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),v(this,pn,{touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY})},gy=function(t){var S;if(!l(this,pn)||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:o}=s,h=l(this,pn),{touch0X:c,touch0Y:u,touch1X:d,touch1Y:f}=h,g=d-c,p=f-u,m=r-i,y=o-n,b=Math.hypot(m,y)||1,x=Math.hypot(g,p)||1;if(!l(this,lo)&&Math.abs(x-b)<=mp.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=o,t.preventDefault(),!l(this,lo)){v(this,lo,!0);return}const C=[(i+r)/2,(n+o)/2];(S=l(this,Vl))==null||S.call(this,C,x,b)},Lp=function(t){var e;l(this,hr).abort(),v(this,hr,null),(e=l(this,Gl))==null||e.call(this),l(this,pn)&&(t.preventDefault(),v(this,pn,null),v(this,lo,!1))};let _d=mp;const lt=class lt{constructor(t){_(this,J);_(this,uo,null);_(this,li,null);_(this,Rt,null);_(this,Va,!1);_(this,lr,null);_(this,Wl,"");_(this,fo,!1);_(this,we,null);_(this,go,null);_(this,vn,null);_(this,cr,null);_(this,Xl,"");_(this,po,!1);_(this,ws,null);_(this,Ul,!1);_(this,mo,!1);_(this,bn,!1);_(this,Ni,null);_(this,Ga,0);_(this,Wa,0);_(this,Bs,null);_(this,vo,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);_(this,Yl,!1);_(this,Id,lt._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=lt.prototype._resizeWithKeyboard,e=qr.TRANSLATE_SMALL,s=qr.TRANSLATE_BIG;return ct(this,"_resizerKeyboardManager",new pl([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],lt.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return ct(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new DS({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(lt._l10n??(lt._l10n=t),lt._l10nResizer||(lt._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),lt._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);lt._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){Pt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return l(this,Yl)}set _isDraggable(t){var e;v(this,Yl,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=l(this,Id)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):w(this,J,Qc).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(l(this,po)?v(this,po,!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){w(this,J,Ip).call(this,this.parentDimensions,t,e)}translateInPage(t,e){l(this,ws)||v(this,ws,[this.x,this.y,this.width,this.height]),w(this,J,Ip).call(this,this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){l(this,ws)||v(this,ws,[this.x,this.y,this.width,this.height]);const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:d,y:f}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,f)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[h,c]=this.getBaseTranslation();r+=h,o+=c;const{style:u}=s;u.left=`${(100*r).toFixed(2)}%`,u.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!l(this,ws)&&(l(this,ws)[0]!==this.x||l(this,ws)[1]!==this.y)}get _hasBeenResized(){return!!l(this,ws)&&(l(this,ws)[2]!==this.width||l(this,ws)[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=lt,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-o,n)),r=Math.max(0,Math.min(i-h,r));break;case 90:n=Math.max(0,Math.min(s-h,n)),r=Math.min(i,Math.max(o,r));break;case 180:n=Math.min(s,Math.max(o,n)),r=Math.min(i,Math.max(h,r));break;case 270:n=Math.min(s,Math.max(h,n)),r=Math.max(0,Math.min(i-o,r));break}this.x=n/=s,this.y=r/=i;const[c,u]=this.getBaseTranslation();n+=c,r+=u,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(t,e){var s;return w(s=lt,$l,jp).call(s,t,e,this.parentRotation)}pageTranslationToScreen(t,e){var s;return w(s=lt,$l,jp).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,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,l(this,fo)||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!l(this,fo)&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!l(this,fo)&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}_onResized(){}static _round(t){return Math.round(t*1e4)/1e4}_onResizing(){}altTextFinish(){var t;(t=l(this,Rt))==null||t.finish()}async addEditToolbar(){return this._editToolbar||l(this,mo)?this._editToolbar:(this._editToolbar=new Gg(this),this.div.append(this._editToolbar.render()),l(this,Rt)&&await this._editToolbar.addAltText(l(this,Rt)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=l(this,Rt))==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(){l(this,Rt)||(yd.initialize(lt._l10n),v(this,Rt,new yd(this)),l(this,uo)&&(l(this,Rt).data=l(this,uo),v(this,uo,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=l(this,Rt))==null?void 0:t.data}set altTextData(t){l(this,Rt)&&(l(this,Rt).data=t)}get guessedAltText(){var t;return(t=l(this,Rt))==null?void 0:t.guessedText}async setGuessedAltText(t){var e;await((e=l(this,Rt))==null?void 0:e.setGuessedText(t))}serializeAltText(t){var e;return(e=l(this,Rt))==null?void 0:e.serialize(t)}hasAltText(){return!!l(this,Rt)&&!l(this,Rt).isEmpty()}hasAltTextData(){var t;return((t=l(this,Rt))==null?void 0:t.hasData())??!1}render(){var n;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=l(this,Va)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),w(this,J,zp).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),bd(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(l(this,vo)||v(this,vo,new _d({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:w(this,J,vy).bind(this),onPinching:w(this,J,by).bind(this),onPinchEnd:w(this,J,yy).bind(this),signal:this._uiManager._signal}))),(n=this._uiManager._editorUndoBar)==null||n.hide(),this.div}pointerdown(t){const{isMac:e}=Ue.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(v(this,po,!0),this._isDraggable){w(this,J,_y).call(this,t);return}w(this,J,Hp).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}_onStartDragging(){}_onStopDragging(){}moveInDOM(){l(this,Ni)&&clearTimeout(l(this,Ni)),v(this,Ni,setTimeout(()=>{var t;v(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(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[o,h]=this.pageTranslation,c=t/i,u=e/i,d=this.x*n,f=this.y*r,g=this.width*n,p=this.height*r;switch(s){case 0:return[d+c+o,r-f-u-p+h,d+c+g+o,r-f-u+h];case 90:return[d+u+o,r-f+c+h,d+u+p+o,r-f+c+g+h];case 180:return[d-c-g+o,r-f+u+h,d-c+o,r-f+u+p+h];case 270:return[d-u-p+o,r-f-c-g+h,d-u+o,r-f-c+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(t){}isEmpty(){return!1}enableEditMode(){v(this,mo,!0)}disableEditMode(){v(this,mo,!1)}isInEditMode(){return l(this,mo)}shouldGetKeyboardEvents(){return l(this,bn)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}rebuild(){w(this,J,zp).call(this)}rotate(t){}resize(){}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){Pt("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,v(i,uo,t.accessibilityData);const[n,r]=i.pageDimensions,[o,h,c,u]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=c/n,i.height=u/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t,e;if((t=l(this,cr))==null||t.abort(),v(this,cr,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),l(this,Ni)&&(clearTimeout(l(this,Ni)),v(this,Ni,null)),w(this,J,Qc).call(this),this.removeEditToolbar(),l(this,Bs)){for(const s of l(this,Bs).values())clearTimeout(s);v(this,Bs,null)}this.parent=null,(e=l(this,vo))==null||e.destroy(),v(this,vo,null)}get isResizable(){return!1}makeResizable(){this.isResizable&&(w(this,J,py).call(this),l(this,we).classList.remove("hidden"),bd(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),v(this,vn,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const e=l(this,we).children;if(!l(this,li)){v(this,li,Array.from(e));const r=w(this,J,wy).bind(this),o=w(this,J,xy).bind(this),h=this._uiManager._signal;for(const c of l(this,li)){const u=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",r,{signal:h}),c.addEventListener("blur",o,{signal:h}),c.addEventListener("focus",w(this,J,Sy).bind(this,u),{signal:h}),c.setAttribute("data-l10n-id",lt._l10nResizer[u])}}const s=l(this,li)[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(l(this,li).length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)l(this,we).append(l(this,we).firstChild);else if(n>i)for(let o=0;o<n-i;o++)l(this,we).firstChild.before(l(this,we).lastChild);let r=0;for(const o of e){const c=l(this,li)[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",lt._l10nResizer[c])}}w(this,J,Vp).call(this,0),v(this,bn,!0),l(this,we).firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}_resizeWithKeyboard(t,e){l(this,bn)&&w(this,J,Bp).call(this,l(this,Xl),{deltaX:t,deltaY:e,fromKeyboard:!0})}_stopResizingWithKeyboard(){w(this,J,Qc).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=l(this,Rt))==null||s.toggleAltTextBadge(!1)}unselect(){var t,e,s,i,n;(t=l(this,we))==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=l(this,Rt))==null||n.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return l(this,Ul)}set isEditing(t){v(this,Ul,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){v(this,fo,!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){l(this,Bs)||v(this,Bs,new Map);const{action:s}=t;let i=l(this,Bs).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),l(this,Bs).delete(s),l(this,Bs).size===0&&v(this,Bs,null)},lt._telemetryTimeout),l(this,Bs).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),v(this,Va,!1)}disable(){this.div&&(this.div.tabIndex=-1),v(this,Va,!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()}};uo=new WeakMap,li=new WeakMap,Rt=new WeakMap,Va=new WeakMap,lr=new WeakMap,Wl=new WeakMap,fo=new WeakMap,we=new WeakMap,go=new WeakMap,vn=new WeakMap,cr=new WeakMap,Xl=new WeakMap,po=new WeakMap,ws=new WeakMap,Ul=new WeakMap,mo=new WeakMap,bn=new WeakMap,Ni=new WeakMap,Ga=new WeakMap,Wa=new WeakMap,Bs=new WeakMap,vo=new WeakMap,Yl=new WeakMap,Id=new WeakMap,J=new WeakSet,Ip=function([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()},$l=new WeakSet,jp=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]}},af=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]}},py=function(){if(l(this,we))return;v(this,we,document.createElement("div")),l(this,we).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");l(this,we).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",w(this,J,my).bind(this,s),{signal:e}),i.addEventListener("contextmenu",ni,{signal:e}),i.tabIndex=-1}this.div.prepend(l(this,we))},my=function(t,e){var u;e.preventDefault();const{isMac:s}=Ue.platform;if(e.button!==0||e.ctrlKey&&s)return;(u=l(this,Rt))==null||u.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,v(this,go,[e.screenX,e.screenY]);const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",w(this,J,Bp).bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",bs,{passive:!1,signal:r}),window.addEventListener("contextmenu",ni,{signal:r}),v(this,vn,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const c=()=>{var d;n.abort(),this.parent.togglePointerEvents(!0),(d=l(this,Rt))==null||d.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,w(this,J,hf).call(this)};window.addEventListener("pointerup",c,{signal:r}),window.addEventListener("blur",c,{signal:r})},Np=function(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()},hf=function(){if(!l(this,vn))return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=l(this,vn);v(this,vn,null);const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:w(this,J,Np).bind(this,n,r,o,h),undo:w(this,J,Np).bind(this,t,e,s,i),mustExec:!0})},Bp=function(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,c=lt.MIN_SIZE/s,u=lt.MIN_SIZE/i,d=w(this,J,af).call(this,this.rotation),f=(L,z)=>[d[0]*L+d[2]*z,d[1]*L+d[3]*z],g=w(this,J,af).call(this,360-this.rotation),p=(L,z)=>[g[0]*L+g[2]*z,g[1]*L+g[3]*z];let m,y,b=!1,x=!1;switch(t){case"topLeft":b=!0,m=(L,z)=>[0,0],y=(L,z)=>[L,z];break;case"topMiddle":m=(L,z)=>[L/2,0],y=(L,z)=>[L/2,z];break;case"topRight":b=!0,m=(L,z)=>[L,0],y=(L,z)=>[0,z];break;case"middleRight":x=!0,m=(L,z)=>[L,z/2],y=(L,z)=>[0,z/2];break;case"bottomRight":b=!0,m=(L,z)=>[L,z],y=(L,z)=>[0,0];break;case"bottomMiddle":m=(L,z)=>[L/2,z],y=(L,z)=>[L/2,0];break;case"bottomLeft":b=!0,m=(L,z)=>[0,z],y=(L,z)=>[L,0];break;case"middleLeft":x=!0,m=(L,z)=>[0,z/2],y=(L,z)=>[L,z/2];break}const C=m(o,h),S=y(o,h);let T=f(...S);const P=lt._round(n+T[0]),M=lt._round(r+T[1]);let D=1,R=1,V,H;if(e.fromKeyboard)({deltaX:V,deltaY:H}=e);else{const{screenX:L,screenY:z}=e,[Z,Dt]=l(this,go);[V,H]=this.screenToPageTranslation(L-Z,z-Dt),l(this,go)[0]=L,l(this,go)[1]=z}if([V,H]=p(V/s,H/i),b){const L=Math.hypot(o,h);D=R=Math.max(Math.min(Math.hypot(S[0]-C[0]-V,S[1]-C[1]-H)/L,1/o,1/h),c/o,u/h)}else x?D=Math.max(c,Math.min(1,Math.abs(S[0]-C[0]-V)))/o:R=Math.max(u,Math.min(1,Math.abs(S[1]-C[1]-H)))/h;const F=lt._round(o*D),I=lt._round(h*R);T=f(...y(F,I));const j=P-T[0],K=M-T[1];l(this,ws)||v(this,ws,[this.x,this.y,this.width,this.height]),this.width=F,this.height=I,this.x=j,this.y=K,this.setDims(s*F,i*I),this.fixAndSetPosition(),this._onResizing()},vy=function(){var t;v(this,vn,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height}),(t=l(this,Rt))==null||t.toggle(!1),this.parent.togglePointerEvents(!1)},by=function(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=w(this,J,af).call(this,this.rotation),o=(P,M)=>[r[0]*P+r[2]*M,r[1]*P+r[3]*M],[h,c]=this.parentDimensions,u=this.x,d=this.y,f=this.width,g=this.height,p=lt.MIN_SIZE/h,m=lt.MIN_SIZE/c;n=Math.max(Math.min(n,1/f,1/g),p/f,m/g);const y=lt._round(f*n),b=lt._round(g*n);if(y===f&&b===g)return;l(this,ws)||v(this,ws,[u,d,f,g]);const x=o(f/2,g/2),C=lt._round(u+x[0]),S=lt._round(d+x[1]),T=o(y/2,b/2);this.x=C-T[0],this.y=S-T[1],this.width=y,this.height=b,this.setDims(h*y,c*b),this.fixAndSetPosition(),this._onResizing()},yy=function(){var t;(t=l(this,Rt))==null||t.toggle(!0),this.parent.togglePointerEvents(!0),w(this,J,hf).call(this)},Hp=function(t){const{isMac:e}=Ue.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)},_y=function(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},o=c=>{i.abort(),v(this,lr,null),v(this,po,!1),this._uiManager.endDragSession()||w(this,J,Hp).call(this,c),s&&this._onStopDragging()};e&&(v(this,Ga,t.clientX),v(this,Wa,t.clientY),v(this,lr,t.pointerId),v(this,Wl,t.pointerType),window.addEventListener("pointermove",c=>{s||(s=!0,this._onStartDragging());const{clientX:u,clientY:d,pointerId:f}=c;if(f!==l(this,lr)){bs(c);return}const[g,p]=this.screenToPageTranslation(u-l(this,Ga),d-l(this,Wa));v(this,Ga,u),v(this,Wa,d),this._uiManager.dragSelectedEditors(g,p)},r),window.addEventListener("touchmove",bs,r),window.addEventListener("pointerdown",c=>{c.pointerType===l(this,Wl)&&(l(this,vo)||c.isPrimary)&&o(c),bs(c)},r));const h=c=>{if(!l(this,lr)||l(this,lr)===c.pointerId){o(c);return}bs(c)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})},zp=function(){if(l(this,cr)||!this.div)return;v(this,cr,new AbortController);const t=this._uiManager.combinedSignal(l(this,cr));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},wy=function(t){lt._resizerKeyboardManager.exec(this,t)},xy=function(t){var e;l(this,bn)&&((e=t.relatedTarget)==null?void 0:e.parentNode)!==l(this,we)&&w(this,J,Qc).call(this)},Sy=function(t){v(this,Xl,l(this,bn)?t:"")},Vp=function(t){if(l(this,li))for(const e of l(this,li))e.tabIndex=t},Qc=function(){v(this,bn,!1),w(this,J,Vp).call(this,-1),w(this,J,hf).call(this)},_(lt,$l),Q(lt,"_l10n",null),Q(lt,"_l10nResizer",null),Q(lt,"_borderLineWidth",-1),Q(lt,"_colorManager",new Xg),Q(lt,"_zIndex",1),Q(lt,"_telemetryTimeout",1e3);let Vt=lt;class DS extends Vt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const H0=3285377520,Is=4294901760,Pi=65535;class z0{constructor(t){this.h1=t?t&4294967295:H0,this.h2=t?t&4294967295:H0}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let m=0,y=t.length;m<y;m++){const b=t.charCodeAt(m);b<=255?e[s++]=b:(e[s++]=b>>>8,e[s++]=b&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,c=this.h1,u=this.h2;const d=3432918353,f=461845907,g=d&Pi,p=f&Pi;for(let m=0;m<i;m++)m&1?(o=r[m],o=o*d&Is|o*g&Pi,o=o<<15|o>>>17,o=o*f&Is|o*p&Pi,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(h=r[m],h=h*d&Is|h*g&Pi,h=h<<15|h>>>17,h=h*f&Is|h*p&Pi,u^=h,u=u<<13|u>>>19,u=u*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*d&Is|o*g&Pi,o=o<<15|o>>>17,o=o*f&Is|o*p&Pi,i&1?c^=o:u^=o}this.h1=c,this.h2=u}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&Is|t*36045&Pi,e=e*4283543511&Is|((e<<16|t>>>16)*2950163797&Is)>>>16,t^=e>>>1,t=t*444984403&Is|t*60499&Pi,e=e*3301882366&Is|((e<<16|t>>>16)*3120437893&Is)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Ug=Object.freeze({map:null,hash:"",transfer:void 0});class Yg{constructor(){_(this,jd);_(this,bo,!1);_(this,yo,null);_(this,me,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=l(this,me).get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return l(this,me).get(t)}remove(t){if(l(this,me).delete(t),l(this,me).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of l(this,me).values())if(e instanceof Vt)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=l(this,me).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,l(this,me).set(t,e);i&&w(this,jd,Cy).call(this),e instanceof Vt&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return l(this,me).has(t)}getAll(){return l(this,me).size>0?Fg(l(this,me)):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return l(this,me).size}resetModified(){l(this,bo)&&(v(this,bo,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new V0(this)}get serializable(){if(l(this,me).size===0)return Ug;const t=new Map,e=new z0,s=[],i=Object.create(null);let n=!1;for(const[r,o]of l(this,me)){const h=o instanceof Vt?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}:Ug}get editorStats(){let t=null;const e=new Map;for(const s of l(this,me).values()){if(!(s instanceof Vt))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 c=r.get(o);c||(c=new Map,r.set(o,c));const u=c.get(h)??0;c.set(h,u+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){v(this,yo,null)}get modifiedIds(){if(l(this,yo))return l(this,yo);const t=[];for(const e of l(this,me).values())!(e instanceof Vt)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return v(this,yo,{ids:new Set(t),hash:t.join(",")})}}bo=new WeakMap,yo=new WeakMap,me=new WeakMap,jd=new WeakSet,Cy=function(){l(this,bo)||(v(this,bo,!0),typeof this.onSetModified=="function"&&this.onSetModified())};class V0 extends Yg{constructor(e){super();_(this,ql);const{map:s,hash:i,transfer:n}=e.serializable,r=structuredClone(s,n?{transfer:n}:null);v(this,ql,{map:r,hash:i,transfer:n})}get print(){Pt("Should not call PrintAnnotationStorage.print")}get serializable(){return l(this,ql)}get modifiedIds(){return ct(this,"modifiedIds",{ids:new Set,hash:""})}}ql=new WeakMap;class RS{constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){_(this,Xa,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(),l(this,Xa).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||l(this,Xa).has(t.loadedName))){if(ie(!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(),l(this,Xa).add(s),e==null||e(t)}catch{ht(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}Pt("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 ht(`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 ct(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Oe||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),ct(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(ie(!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 ct(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(S,T){return S.charCodeAt(T)<<24|S.charCodeAt(T+1)<<16|S.charCodeAt(T+2)<<8|S.charCodeAt(T+3)&255}function i(S,T,P,M){const D=S.substring(0,T),R=S.substring(T+P);return D+M+R}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let c=0;function u(S,T){if(++c>30){ht("Load test font never loaded."),T();return}if(h.font="30px "+S,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){T();return}setTimeout(u.bind(null,S,T))}const d=`lt${Date.now()}${this.loadTestFontId++}`;let f=this._loadTestFont;f=i(f,976,d.length,d);const p=16,m=1482184792;let y=s(f,p);for(n=0,r=d.length-3;n<r;n+=4)y=y-m+s(d,n)|0;n<d.length&&(y=y-m+s(d+"XXX",n)|0),f=i(f,p,4,bS(y));const b=`url(data:font/opentype;base64,${btoa(f)});`,x=`@font-face {font-family:"${d}";src:${b}}`;this.insertRule(x);const C=this._document.createElement("div");C.style.visibility="hidden",C.style.width=C.style.height="10px",C.style.position="absolute",C.style.top=C.style.left="0px";for(const S of[t.loadedName,d]){const T=this._document.createElement("span");T.textContent="Hi",T.style.fontFamily=S,C.append(T)}this._document.body.append(C),u(d,()=>{C.remove(),e.complete()})}}Xa=new WeakMap;class FS{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}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,${CS(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];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){ht(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const wd={DATA:1,ERROR:2},ne={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function G0(){}function rs(a){if(a instanceof qn||a instanceof Rg||a instanceof dl||a instanceof I0||a instanceof gd||a instanceof Dg)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||Pt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new qn(a.message);case"InvalidPDFException":return new Rg(a.message);case"MissingPDFException":return new dl(a.message);case"PasswordException":return new I0(a.message,a.code);case"UnexpectedResponseException":return new gd(a.message,a.status);case"UnknownErrorException":return new Dg(a.message,a.details)}return new Dg(a.message,a.toString())}class ml{constructor(t,e,s){_(this,Hs);_(this,Ua,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",w(this,Hs,Ay).bind(this),{signal:l(this,Ua).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:c=>{const u=Promise.withResolvers();return this.streamControllers[n]={controller:c,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:c.desiredSize},i),u.promise},pull:c=>{const u=Promise.withResolvers();return this.streamControllers[n].pullCall=u,h.postMessage({sourceName:r,targetName:o,stream:ne.PULL,streamId:n,desiredSize:c.desiredSize}),u.promise},cancel:c=>{ie(c instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[n].cancelCall=u,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:ne.CANCEL,streamId:n,reason:rs(c)}),u.promise}},s)}destroy(){var t;(t=l(this,Ua))==null||t.abort(),v(this,Ua,null)}}Ua=new WeakMap,Hs=new WeakSet,Ay=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){w(this,Hs,Ey).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===wd.DATA)i.resolve(t.data);else if(t.callback===wd.ERROR)i.reject(rs(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;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:wd.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:wd.ERROR,callbackId:t.callbackId,reason:rs(r)})});return}if(t.streamId){w(this,Hs,Ty).call(this,t);return}e(t.data)},Ty=function(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=this.actionHandler[t.action],h={enqueue(c,u=1,d){if(this.isCancelled)return;const f=this.desiredSize;this.desiredSize-=u,f>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:ne.ENQUEUE,streamId:e,chunk:c},d)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:ne.CLOSE,streamId:e}),delete r.streamSinks[e])},error(c){ie(c instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:ne.ERROR,streamId:e,reason:rs(c)}))},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,Promise.try(o,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ne.START_COMPLETE,streamId:e,success:!0})},function(c){n.postMessage({sourceName:s,targetName:i,stream:ne.START_COMPLETE,streamId:e,reason:rs(c)})})},Ey=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 ne.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(rs(t.reason));break;case ne.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(rs(t.reason));break;case ne.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:ne.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||G0).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ne.PULL_COMPLETE,streamId:e,success:!0})},function(c){n.postMessage({sourceName:s,targetName:i,stream:ne.PULL_COMPLETE,streamId:e,reason:rs(c)})});break;case ne.ENQUEUE:if(ie(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case ne.CLOSE:if(ie(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),w(this,Hs,lf).call(this,r,e);break;case ne.ERROR:ie(r,"error should have stream controller"),r.controller.error(rs(t.reason)),w(this,Hs,lf).call(this,r,e);break;case ne.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(rs(t.reason)),w(this,Hs,lf).call(this,r,e);break;case ne.CANCEL:if(!o)break;const h=rs(t.reason);Promise.try(o.onCancel||G0,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ne.CANCEL_COMPLETE,streamId:e,success:!0})},function(c){n.postMessage({sourceName:s,targetName:i,stream:ne.CANCEL_COMPLETE,streamId:e,reason:rs(c)})}),o.sinkCapability.reject(h),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}},lf=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 W0{constructor({enableHWA:t=!1}){_(this,Kl,!1);v(this,Kl,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:!l(this,Kl)})}}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){Pt("Abstract method `_createCanvas` called.")}}Kl=new WeakMap;class LS extends W0{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 X0{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){Pt("Abstract method `_fetch` called.")}}class U0 extends X0{async _fetch(t){const e=await md(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):pd(e)}}class Y0{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 IS extends Y0{constructor({docId:e,ownerDocument:s=globalThis.document}){super();_(this,W);_(this,_o);_(this,Ya);_(this,yn);_(this,_n);_(this,Le);_(this,wo);_(this,xo,0);v(this,_n,e),v(this,Le,s)}addFilter(e){if(!e)return"none";let s=l(this,W,Be).get(e);if(s)return s;const[i,n,r]=w(this,W,cf).call(this,e),o=e.length===1?i:`${i}${n}${r}`;if(s=l(this,W,Be).get(o),s)return l(this,W,Be).set(e,s),s;const h=`g_${l(this,_n)}_transfer_map_${es(this,xo)._++}`,c=w(this,W,Hh).call(this,h);l(this,W,Be).set(e,c),l(this,W,Be).set(o,c);const u=w(this,W,zh).call(this,h);return w(this,W,eu).call(this,i,n,r,u),c}addHCMFilter(e,s){var p;const i=`${e}-${s}`,n="base";let r=l(this,W,Zc).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},l(this,W,Zc).set(n,r)),!e||!s))return r.url;const o=w(this,W,su).call(this,e);e=q.makeHexColor(...o);const h=w(this,W,su).call(this,s);if(s=q.makeHexColor(...h),l(this,W,Bh).style.color="",e==="#000000"&&s==="#ffffff"||e===s)return r.url;const c=new Array(256);for(let m=0;m<=255;m++){const y=m/255;c[m]=y<=.03928?y/12.92:((y+.055)/1.055)**2.4}const u=c.join(","),d=`g_${l(this,_n)}_hcm_filter`,f=r.filter=w(this,W,zh).call(this,d);w(this,W,eu).call(this,u,u,u,f),w(this,W,Gp).call(this,f);const g=(m,y)=>{const b=o[m]/255,x=h[m]/255,C=new Array(y+1);for(let S=0;S<=y;S++)C[S]=b+S/y*(x-b);return C.join(",")};return w(this,W,eu).call(this,g(0,5),g(1,5),g(2,5),f),r.url=w(this,W,Hh).call(this,d),r.url}addAlphaFilter(e){let s=l(this,W,Be).get(e);if(s)return s;const[i]=w(this,W,cf).call(this,[e]),n=`alpha_${i}`;if(s=l(this,W,Be).get(n),s)return l(this,W,Be).set(e,s),s;const r=`g_${l(this,_n)}_alpha_map_${es(this,xo)._++}`,o=w(this,W,Hh).call(this,r);l(this,W,Be).set(e,o),l(this,W,Be).set(n,o);const h=w(this,W,zh).call(this,r);return w(this,W,Wp).call(this,i,h),o}addLuminosityFilter(e){let s=l(this,W,Be).get(e||"luminosity");if(s)return s;let i,n;if(e?([i]=w(this,W,cf).call(this,[e]),n=`luminosity_${i}`):n="luminosity",s=l(this,W,Be).get(n),s)return l(this,W,Be).set(e,s),s;const r=`g_${l(this,_n)}_luminosity_map_${es(this,xo)._++}`,o=w(this,W,Hh).call(this,r);l(this,W,Be).set(e,o),l(this,W,Be).set(n,o);const h=w(this,W,zh).call(this,r);return w(this,W,ky).call(this,h),e&&w(this,W,Wp).call(this,i,h),o}addHighlightHCMFilter(e,s,i,n,r){var x;const o=`${s}-${i}-${n}-${r}`;let h=l(this,W,Zc).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},l(this,W,Zc).set(e,h)),!s||!i))return h.url;const[c,u]=[s,i].map(w(this,W,su).bind(this));let d=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),f=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[g,p]=[n,r].map(w(this,W,su).bind(this));f<d&&([d,f,g,p]=[f,d,p,g]),l(this,W,Bh).style.color="";const m=(C,S,T)=>{const P=new Array(256),M=(f-d)/T,D=C/255,R=(S-C)/(255*T);let V=0;for(let H=0;H<=T;H++){const F=Math.round(d+H*M),I=D+H*R;for(let j=V;j<=F;j++)P[j]=I;V=F+1}for(let H=V;H<256;H++)P[H]=P[V-1];return P.join(",")},y=`g_${l(this,_n)}_hcm_${e}_filter`,b=h.filter=w(this,W,zh).call(this,y);return w(this,W,Gp).call(this,b),w(this,W,eu).call(this,m(g[0],p[0],5),m(g[1],p[1],5),m(g[2],p[2],5),b),h.url=w(this,W,Hh).call(this,y),h.url}destroy(e=!1){var s,i,n,r;e&&((s=l(this,wo))!=null&&s.size)||((i=l(this,yn))==null||i.parentNode.parentNode.remove(),v(this,yn,null),(n=l(this,Ya))==null||n.clear(),v(this,Ya,null),(r=l(this,wo))==null||r.clear(),v(this,wo,null),v(this,xo,0))}}_o=new WeakMap,Ya=new WeakMap,yn=new WeakMap,_n=new WeakMap,Le=new WeakMap,wo=new WeakMap,xo=new WeakMap,W=new WeakSet,Be=function(){return l(this,Ya)||v(this,Ya,new Map)},Zc=function(){return l(this,wo)||v(this,wo,new Map)},Bh=function(){if(!l(this,yn)){const e=l(this,Le).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=l(this,Le).createElementNS(an,"svg");i.setAttribute("width",0),i.setAttribute("height",0),v(this,yn,l(this,Le).createElementNS(an,"defs")),e.append(i),i.append(l(this,yn)),l(this,Le).body.append(e)}return l(this,yn)},cf=function(e){if(e.length===1){const c=e[0],u=new Array(256);for(let f=0;f<256;f++)u[f]=c[f]/255;const d=u.join(",");return[d,d,d]}const[s,i,n]=e,r=new Array(256),o=new Array(256),h=new Array(256);for(let c=0;c<256;c++)r[c]=s[c]/255,o[c]=i[c]/255,h[c]=n[c]/255;return[r.join(","),o.join(","),h.join(",")]},Hh=function(e){if(l(this,_o)===void 0){v(this,_o,"");const s=l(this,Le).URL;s!==l(this,Le).baseURI&&(vd(s)?ht('#createUrl: ignore "data:"-URL for performance reasons.'):v(this,_o,s.split("#",1)[0]))}return`url(${l(this,_o)}#${e})`},ky=function(e){const s=l(this,Le).createElementNS(an,"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)},Gp=function(e){const s=l(this,Le).createElementNS(an,"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)},zh=function(e){const s=l(this,Le).createElementNS(an,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",e),l(this,W,Bh).append(s),s},tu=function(e,s,i){const n=l(this,Le).createElementNS(an,s);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),e.append(n)},eu=function(e,s,i,n){const r=l(this,Le).createElementNS(an,"feComponentTransfer");n.append(r),w(this,W,tu).call(this,r,"feFuncR",e),w(this,W,tu).call(this,r,"feFuncG",s),w(this,W,tu).call(this,r,"feFuncB",i)},Wp=function(e,s){const i=l(this,Le).createElementNS(an,"feComponentTransfer");s.append(i),w(this,W,tu).call(this,i,"feFuncA",e)},su=function(e){return l(this,W,Bh).style.color=e,zg(getComputedStyle(l(this,W,Bh)).getPropertyValue("color"))};class $0{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){Pt("Abstract method `_fetch` called.")}}class q0 extends $0{async _fetch(t){const e=await md(t,"arraybuffer");return new Uint8Array(e)}}Oe&&ht("Please use the `legacy` build in Node.js environments.");async function K0(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class jS extends Y0{}class NS extends W0{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Ht&&Ht.tagName.toUpperCase()==="SCRIPT"&&Ht.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class BS extends X0{async _fetch(t){return K0(t)}}class HS extends $0{async _fetch(t){return K0(t)}}const Re={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function $g(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 qg{getPattern(){Pt("Abstract method `getPattern` called.")}}class zS extends qg{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===Re.STROKE||i===Re.FILL){const r=e.current.getClippedPathBoundingBox(i,It(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,c=e.cachedCanvases.getCanvas("pattern",o,h),u=c.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-r[0],-r[1]),s=q.transform(s,[1,0,0,1,r[0],r[1]]),u.transform(...e.baseTransform),this.matrix&&u.transform(...this.matrix),$g(u,this._bbox),u.fillStyle=this._createGradient(u),u.fill(),n=t.createPattern(c.canvas,"no-repeat");const d=new DOMMatrix(s);n.setTransform(d)}else $g(t,this._bbox),n=this._createGradient(t);return n}}function Kg(a,t,e,s,i,n,r,o){const h=t.coords,c=t.colors,u=a.data,d=a.width*4;let f;h[e+1]>h[s+1]&&(f=e,e=s,s=f,f=n,n=r,r=f),h[s+1]>h[i+1]&&(f=s,s=i,i=f,f=r,r=o,o=f),h[e+1]>h[s+1]&&(f=e,e=s,s=f,f=n,n=r,r=f);const g=(h[e]+t.offsetX)*t.scaleX,p=(h[e+1]+t.offsetY)*t.scaleY,m=(h[s]+t.offsetX)*t.scaleX,y=(h[s+1]+t.offsetY)*t.scaleY,b=(h[i]+t.offsetX)*t.scaleX,x=(h[i+1]+t.offsetY)*t.scaleY;if(p>=x)return;const C=c[n],S=c[n+1],T=c[n+2],P=c[r],M=c[r+1],D=c[r+2],R=c[o],V=c[o+1],H=c[o+2],F=Math.round(p),I=Math.round(x);let j,K,L,z,Z,Dt,Bt,Xt;for(let Ft=F;Ft<=I;Ft++){if(Ft<y){const nt=Ft<p?0:(p-Ft)/(p-y);j=g-(g-m)*nt,K=C-(C-P)*nt,L=S-(S-M)*nt,z=T-(T-D)*nt}else{let nt;Ft>x?nt=1:y===x?nt=0:nt=(y-Ft)/(y-x),j=m-(m-b)*nt,K=P-(P-R)*nt,L=M-(M-V)*nt,z=D-(D-H)*nt}let _t;Ft<p?_t=0:Ft>x?_t=1:_t=(p-Ft)/(p-x),Z=g-(g-b)*_t,Dt=C-(C-R)*_t,Bt=S-(S-V)*_t,Xt=T-(T-H)*_t;const oe=Math.round(Math.min(j,Z)),Ze=Math.round(Math.max(j,Z));let it=d*Ft+oe*4;for(let nt=oe;nt<=Ze;nt++)_t=(j-nt)/(j-Z),_t<0?_t=0:_t>1&&(_t=1),u[it++]=K-(K-Dt)*_t|0,u[it++]=L-(L-Bt)*_t|0,u[it++]=z-(z-Xt)*_t|0,u[it++]=255}}function VS(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,c=o-1;for(n=0;n<h;n++){let u=n*o;for(let d=0;d<c;d++,u++)Kg(a,e,s[u],s[u+1],s[u+o],i[u],i[u+1],i[u+o]),Kg(a,e,s[u+o+1],s[u+1],s[u+o],i[u+o+1],i[u+1],i[u+o])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)Kg(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 GS extends qg{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]),c=Math.ceil(this._bounds[2])-o,u=Math.ceil(this._bounds[3])-h,d=Math.min(Math.ceil(Math.abs(c*t[0]*1.1)),3e3),f=Math.min(Math.ceil(Math.abs(u*t[1]*1.1)),3e3),g=c/d,p=u/f,m={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/g,scaleY:1/p},y=d+2*2,b=f+2*2,x=s.getCanvas("mesh",y,b),C=x.context,S=C.createImageData(d,f);if(e){const P=S.data;for(let M=0,D=P.length;M<D;M+=4)P[M]=e[0],P[M+1]=e[1],P[M+2]=e[2],P[M+3]=255}for(const P of this._figures)VS(S,P,m);return C.putImageData(S,2,2),{canvas:x.canvas,offsetX:o-2*g,offsetY:h-2*p,scaleX:g,scaleY:p}}getPattern(t,e,s,i){$g(t,this._bbox);let n;if(i===Re.SHADING)n=q.singularValueDecompose2dScale(It(t));else if(n=q.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=q.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Re.SHADING?null:this._background,e.cachedCanvases);return i!==Re.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 WS extends qg{getPattern(){return"hotpink"}}function XS(a){switch(a[0]){case"RadialAxial":return new zS(a);case"Mesh":return new GS(a);case"Dummy":return new WS}throw new Error(`Unknown IR type: ${a[0]}`)}const J0={COLORED:1,UNCOLORED:2},Nd=class Nd{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:c}=this;h=Math.abs(h),c=Math.abs(c),fd("TilingType: "+n);const u=e[0],d=e[1],f=e[2],g=e[3],p=f-u,m=g-d,y=q.singularValueDecompose2dScale(this.matrix),b=q.singularValueDecompose2dScale(this.baseTransform),x=y[0]*b[0],C=y[1]*b[1];let S=p,T=m,P=!1,M=!1;const D=Math.ceil(h*x),R=Math.ceil(c*C),V=Math.ceil(p*x),H=Math.ceil(m*C);D>=V?S=h:P=!0,R>=H?T=c:M=!0;const F=this.getSizeAndScale(S,this.ctx.canvas.width,x),I=this.getSizeAndScale(T,this.ctx.canvas.height,C),j=t.cachedCanvases.getCanvas("pattern",F.size,I.size),K=j.context,L=o.createCanvasGraphics(K);if(L.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(L,i,r),K.translate(-F.scale*u,-I.scale*d),L.transform(F.scale,0,0,I.scale,0,0),K.save(),this.clipBbox(L,u,d,f,g),L.baseTransform=It(L.ctx),L.executeOperatorList(s),L.endDrawing(),K.restore(),P||M){const z=j.canvas;P&&(S=h),M&&(T=c);const Z=this.getSizeAndScale(S,this.ctx.canvas.width,x),Dt=this.getSizeAndScale(T,this.ctx.canvas.height,C),Bt=Z.size,Xt=Dt.size,Ft=t.cachedCanvases.getCanvas("pattern-workaround",Bt,Xt),_t=Ft.context,oe=P?Math.floor(p/h):0,Ze=M?Math.floor(m/c):0;for(let it=0;it<=oe;it++)for(let nt=0;nt<=Ze;nt++)_t.drawImage(z,Bt*it,Xt*nt,Bt,Xt,0,0,Bt,Xt);return{canvas:Ft.canvas,scaleX:Z.scale,scaleY:Dt.scale,offsetX:u,offsetY:d}}return{canvas:j.canvas,scaleX:F.scale,scaleY:I.scale,offsetX:u,offsetY:d}}getSizeAndScale(t,e,s){const i=Math.max(Nd.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(It(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case J0.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case J0.UNCOLORED:const o=q.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new vS(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Re.SHADING&&(n=q.transform(n,e.baseTransform),this.matrix&&(n=q.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(Nd,"MAX_PATTERN_SIZE",3e3);let Jg=Nd;function US({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Ue.isLittleEndian?4278190080:255,[h,c]=r?[n,o]:[o,n],u=s>>3,d=s&7,f=a.length;e=new Uint32Array(e.buffer);let g=0;for(let p=0;p<i;p++){for(const y=t+u;t<y;t++){const b=t<f?a[t]:255;e[g++]=b&128?c:h,e[g++]=b&64?c:h,e[g++]=b&32?c:h,e[g++]=b&16?c:h,e[g++]=b&8?c:h,e[g++]=b&4?c:h,e[g++]=b&2?c:h,e[g++]=b&1?c:h}if(d===0)continue;const m=t<f?a[t++]:255;for(let y=0;y<d;y++)e[g++]=m&1<<7-y?c:h}return{srcPos:t,destPos:g}}const Q0=16,Z0=100,YS=15,tb=10,eb=1e3,os=16;function $S(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 qS{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 xd(a,t,e,s,i,n,r,o,h,c){const[u,d,f,g,p,m]=It(a);if(d===0&&f===0){const x=r*u+p,C=Math.round(x),S=o*g+m,T=Math.round(S),P=(r+h)*u+p,M=Math.abs(Math.round(P)-C)||1,D=(o+c)*g+m,R=Math.abs(Math.round(D)-T)||1;return a.setTransform(Math.sign(u),0,0,Math.sign(g),C,T),a.drawImage(t,e,s,i,n,0,0,M,R),a.setTransform(u,d,f,g,p,m),[M,R]}if(u===0&&g===0){const x=o*f+p,C=Math.round(x),S=r*d+m,T=Math.round(S),P=(o+c)*f+p,M=Math.abs(Math.round(P)-C)||1,D=(r+h)*d+m,R=Math.abs(Math.round(D)-T)||1;return a.setTransform(0,Math.sign(d),Math.sign(f),0,C,T),a.drawImage(t,e,s,i,n,0,0,R,M),a.setTransform(u,d,f,g,p,m),[R,M]}a.drawImage(t,e,s,i,n,r,o,h,c);const y=Math.hypot(u,d),b=Math.hypot(f,g);return[y*h,b*c]}function KS(a){const{width:t,height:e}=a;if(t>eb||e>eb)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,c;const u=t+7&-8;let d=new Uint8Array(u*e),f=0;for(const b of a.data){let x=128;for(;x>0;)d[f++]=b&x?0:255,x>>=1}let g=0;for(f=0,d[f]!==0&&(r[0]=1,++g),h=1;h<t;h++)d[f]!==d[f+1]&&(r[h]=d[f]?2:1,++g),f++;for(d[f]!==0&&(r[h]=2,++g),o=1;o<e;o++){f=o*u,c=o*n,d[f-u]!==d[f]&&(r[c]=d[f]?1:8,++g);let b=(d[f]?4:0)+(d[f-u]?8:0);for(h=1;h<t;h++)b=(b>>2)+(d[f+1]?4:0)+(d[f-u+1]?8:0),i[b]&&(r[c+h]=i[b],++g),f++;if(d[f-u]!==d[f]&&(r[c+h]=d[f]?2:4,++g),g>s)return null}for(f=u*(e-1),c=o*n,d[f]!==0&&(r[c]=8,++g),h=1;h<t;h++)d[f]!==d[f+1]&&(r[c+h]=d[f]?4:8,++g),f++;if(d[f]!==0&&(r[c+h]=4,++g),g>s)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),m=new Path2D;for(o=0;g&&o<=e;o++){let b=o*n;const x=b+t;for(;b<x&&!r[b];)b++;if(b===x)continue;m.moveTo(b%n,o);const C=b;let S=r[b];do{const T=p[S];do b+=T;while(!r[b]);const P=r[b];P!==5&&P!==10?(S=P,r[b]=0):(S=P&51*S>>4,r[b]&=S>>2|S<<2),m.lineTo(b%n,b/n|0),r[b]||--g}while(C!==b);--o}return d=null,r=null,function(b){b.save(),b.scale(1/t,-1/e),b.translate(0,-e),b.fill(m),b.beginPath(),b.restore()}}class sb{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=L0,this.textMatrixScale=1,this.fontMatrix=Mg,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=De.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!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]=q.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=q.applyTransform(e,t),i=q.applyTransform(e.slice(2),t),n=q.applyTransform([e[0],e[3]],t),r=q.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){q.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,c,u){const d=q.bezierBoundingBox(e,s,i,n,r,o,h,c,u);u||this.updateRectMinMax(t,d)}getPathBoundingBox(t=Re.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Re.STROKE){e||Pt("Stroke bounding box must include transform.");const i=q.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=q.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=Re.FILL,e=null){return q.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function ib(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%os,n=(e-i)/os,r=i===0?n:n+1,o=a.createImageData(s,os);let h=0,c;const u=t.data,d=o.data;let f,g,p,m;if(t.kind===cd.GRAYSCALE_1BPP){const y=u.byteLength,b=new Uint32Array(d.buffer,0,d.byteLength>>2),x=b.length,C=s+7>>3,S=4294967295,T=Ue.isLittleEndian?4278190080:255;for(f=0;f<r;f++){for(p=f<n?os:i,c=0,g=0;g<p;g++){const P=y-h;let M=0;const D=P>C?s:P*8-7,R=D&-8;let V=0,H=0;for(;M<R;M+=8)H=u[h++],b[c++]=H&128?S:T,b[c++]=H&64?S:T,b[c++]=H&32?S:T,b[c++]=H&16?S:T,b[c++]=H&8?S:T,b[c++]=H&4?S:T,b[c++]=H&2?S:T,b[c++]=H&1?S:T;for(;M<D;M++)V===0&&(H=u[h++],V=128),b[c++]=H&V?S:T,V>>=1}for(;c<x;)b[c++]=0;a.putImageData(o,0,f*os)}}else if(t.kind===cd.RGBA_32BPP){for(g=0,m=s*os*4,f=0;f<n;f++)d.set(u.subarray(h,h+m)),h+=m,a.putImageData(o,0,g),g+=os;f<r&&(m=s*i*4,d.set(u.subarray(h,h+m)),a.putImageData(o,0,g))}else if(t.kind===cd.RGB_24BPP)for(p=os,m=s*p,f=0;f<r;f++){for(f>=n&&(p=i,m=s*p),c=0,g=m;g--;)d[c++]=u[h++],d[c++]=u[h++],d[c++]=u[h++],d[c++]=255;a.putImageData(o,0,f*os)}else throw new Error(`bad image kind: ${t.kind}`)}function nb(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%os,n=(e-i)/os,r=i===0?n:n+1,o=a.createImageData(s,os);let h=0;const c=t.data,u=o.data;for(let d=0;d<r;d++){const f=d<n?os:i;({srcPos:h}=US({src:c,srcPos:h,dest:u,width:s,height:f,nonBlackColor:0})),a.putImageData(o,0,d*os)}}function vl(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 Sd(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),!Oe){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function rb(a,t){if(t)return!0;const e=q.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*Kn.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const JS=["butt","round","square"],QS=["miter","round","bevel"],ZS={},ob={},vp=class vp{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,c){_(this,ci);this.ctx=t,this.current=new sb(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 qS(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,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(...It(this.compositeCtx))}this.ctx.save(),Sd(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=It(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 c=h-o>tb&&typeof s=="function",u=c?Date.now()+YS:0;let d=0;const f=this.commonObjs,g=this.objs;let p;for(;;){if(i!==void 0&&o===i.nextBreakPoint)return i.breakIt(o,s),o;if(p=r[o],p!==ii.dependency)this[p].apply(this,n[o]);else for(const m of n[o]){const y=m.startsWith("g_")?f:g;if(!y.has(m))return y.get(m,s),o}if(o++,o===h)return o;if(c&&++d>tb){if(Date.now()>u)return s(),o;d=0}}}endDrawing(){w(this,ci,Xp).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(),w(this,ci,Up).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,c="prescale1",u,d;for(;n>2&&o>1||r>2&&h>1;){let f=o,g=h;n>2&&o>1&&(f=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/f),r>2&&h>1&&(g=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/g),u=this.cachedCanvases.getCanvas(c,f,g),d=u.context,d.clearRect(0,0,f,g),d.drawImage(t,0,0,o,h,0,0,f,g),t=u.canvas,o=f,h=g,c=c==="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=It(e);let h,c,u,d;if((t.bitmap||t.data)&&t.count>1){const D=t.bitmap||t.data.buffer;c=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(D),h||(h=new Map,this._cachedBitmapsMap.set(D,h));const R=h.get(c);if(R&&!r){const V=Math.round(Math.min(o[0],o[2])+o[4]),H=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:R,offsetX:V,offsetY:H}}u=R}u||(d=this.cachedCanvases.getCanvas("maskCanvas",s,i),nb(d.context,t));let f=q.transform(o,[1/s,0,0,-1/i,0,0]);f=q.transform(f,[1,0,0,1,0,-i]);const[g,p,m,y]=q.getAxialAlignedBoundingBox([0,0,s,i],f),b=Math.round(m-g)||1,x=Math.round(y-p)||1,C=this.cachedCanvases.getCanvas("fillCanvas",b,x),S=C.context,T=g,P=p;S.translate(-T,-P),S.transform(...f),u||(u=this._scaleImage(d.canvas,ki(S)),u=u.img,h&&r&&h.set(c,u)),S.imageSmoothingEnabled=rb(It(S),t.interpolate),xd(S,u,0,0,u.width,u.height,0,0,s,i),S.globalCompositeOperation="source-in";const M=q.transform(ki(S),[1,0,0,1,-T,-P]);return S.fillStyle=r?n.getPattern(e,this,M,Re.FILL):n,S.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(c,C.canvas)),{canvas:C.canvas,offsetX:Math.round(T),offsetY:Math.round(P)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=JS[t]}setLineJoin(t){this.ctx.lineJoin=QS[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(...It(this.suspendedCtx)),vl(this.suspendedCtx,n),$S(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(),vl(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,c,u,d){let f=t.canvas,g=h-u,p=c-d;if(r){const y=q.makeHexColor(...r);if(g<0||p<0||g+s>f.width||p+i>f.height){const b=this.cachedCanvases.getCanvas("maskExtension",s,i),x=b.context;x.drawImage(f,-g,-p),x.globalCompositeOperation="destination-atop",x.fillStyle=y,x.fillRect(0,0,s,i),x.globalCompositeOperation="source-over",f=b.canvas,g=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const b=new Path2D;b.rect(g,p,s,i),t.clip(b),t.globalCompositeOperation="destination-atop",t.fillStyle=y,t.fillRect(g,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,c,s,i),e.clip(m),e.globalCompositeOperation="destination-in",e.drawImage(f,g,p,s,i,h,c,s,i),e.restore()}save(){this.inSMaskMode?(vl(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(),vl(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,c;const u=It(i),d=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,f=d?s.slice(0):null;for(let g=0,p=0,m=t.length;g<m;g++)switch(t[g]|0){case ii.rectangle:r=e[p++],o=e[p++];const y=e[p++],b=e[p++],x=r+y,C=o+b;i.moveTo(r,o),y===0||b===0?i.lineTo(x,C):(i.lineTo(x,o),i.lineTo(x,C),i.lineTo(r,C)),d||n.updateRectMinMax(u,[r,o,x,C]),i.closePath();break;case ii.moveTo:r=e[p++],o=e[p++],i.moveTo(r,o),d||n.updatePathMinMax(u,r,o);break;case ii.lineTo:r=e[p++],o=e[p++],i.lineTo(r,o),d||n.updatePathMinMax(u,r,o);break;case ii.curveTo:h=r,c=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(u,h,c,e[p],e[p+1],e[p+2],e[p+3],r,o,f),p+=6;break;case ii.curveTo2:h=r,c=o,i.bezierCurveTo(r,o,e[p],e[p+1],e[p+2],e[p+3]),n.updateCurvePathMinMax(u,h,c,r,o,e[p],e[p+1],e[p+2],e[p+3],f),r=e[p+2],o=e[p+3],p+=4;break;case ii.curveTo3:h=r,c=o,r=e[p+2],o=e[p+3],i.bezierCurveTo(e[p],e[p+1],r,o,r,o),n.updateCurvePathMinMax(u,h,c,e[p],e[p+1],r,o,r,o,f),p+=4;break;case ii.closePath:i.closePath();break}d&&n.updateScalingPathMinMax(u,f),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),Re.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),Re.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=ZS}eoClip(){this.pendingClip=ob}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}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:o,fontSize:h,path:c}of t)s.addPath(c,new DOMMatrix(n).preMultiplySelf(i).translate(r,o).scale(h,-h));e.clip(s),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 u;const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||Mg,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&ht("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=((u=s.systemFontInfo)==null?void 0:u.css)||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let c=e;e<Q0?c=Q0:e>Z0&&(c=Z0),this.current.fontSizeScale=e/c,this.ctx.font=`${h} ${o} ${c}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,n){const r=this.ctx,o=this.current,h=o.font,c=o.textRenderingMode,u=o.fontSize/o.fontSizeScale,d=c&De.FILL_STROKE_MASK,f=!!(c&De.ADD_TO_PATH_FLAG),g=o.patternFill&&!h.missingFile,p=o.patternStroke&&!h.missingFile;let m;if((h.disableFontFace||f||g||p)&&(m=h.getPathGenerator(this.commonObjs,t)),h.disableFontFace||g||p){if(r.save(),r.translate(e,s),r.scale(u,-u),d===De.FILL||d===De.FILL_STROKE)if(i){const y=r.getTransform();r.setTransform(...i),r.fill(w(this,ci,Yp).call(this,m,y,i))}else r.fill(m);if(d===De.STROKE||d===De.FILL_STROKE)if(n){const y=r.getTransform();r.setTransform(...n),r.stroke(w(this,ci,Yp).call(this,m,y,n))}else r.lineWidth/=u,r.stroke(m);r.restore()}else(d===De.FILL||d===De.FILL_STROKE)&&r.fillText(t,e,s),(d===De.STROKE||d===De.FILL_STROKE)&&r.strokeText(t,e,s);f&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:It(r),x:e,y:s,fontSize:u,path:m})}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 ct(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,c=e.fontDirection,u=e.textHScale*c,d=t.length,f=s.vertical,g=f?1:-1,p=s.defaultVMetrics,m=i*e.fontMatrix[0],y=e.textRenderingMode===De.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),c>0?n.scale(u,-1):n.scale(u,1);let b,x;if(e.patternFill){n.save();const M=e.fillColor.getPattern(n,this,ki(n),Re.FILL);b=It(n),n.restore(),n.fillStyle=M}if(e.patternStroke){n.save();const M=e.strokeColor.getPattern(n,this,ki(n),Re.STROKE);x=It(n),n.restore(),n.strokeStyle=M}let C=e.lineWidth;const S=e.textMatrixScale;if(S===0||C===0){const M=e.textRenderingMode&De.FILL_STROKE_MASK;(M===De.STROKE||M===De.FILL_STROKE)&&(C=this.getSinglePixelWidth())}else C/=S;if(r!==1&&(n.scale(r,r),C/=r),n.lineWidth=C,s.isInvalidPDFjsFont){const M=[];let D=0;for(const R of t)M.push(R.unicode),D+=R.width;n.fillText(M.join(""),0,0),e.x+=D*m*u,n.restore(),this.compose();return}let T=0,P;for(P=0;P<d;++P){const M=t[P];if(typeof M=="number"){T+=g*M*i/1e3;continue}let D=!1;const R=(M.isSpace?h:0)+o,V=M.fontChar,H=M.accent;let F,I,j=M.width;if(f){const L=M.vmetric||p,z=-(M.vmetric?L[1]:j*.5)*m,Z=L[2]*m;j=L?-L[0]:j,F=z/r,I=(T+Z)/r}else F=T/r,I=0;if(s.remeasure&&j>0){const L=n.measureText(V).width*1e3/i*r;if(j<L&&this.isFontSubpixelAAEnabled){const z=j/L;D=!0,n.save(),n.scale(z,1),F/=z}else j!==L&&(F+=(j-L)/2e3*i/r)}if(this.contentVisible&&(M.isInFont||s.missingFile)){if(y&&!H)n.fillText(V,F,I);else if(this.paintChar(V,F,I,b,x),H){const L=F+i*H.offset.x/r,z=I-i*H.offset.y/r;this.paintChar(H.fontChar,L,z,b,x)}}const K=f?j*m-R*c:j*m+R*c;T+=K,D&&n.restore()}f?e.y-=T:e.x+=T*u,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,c=s.wordSpacing,u=s.textHScale*r,d=s.fontMatrix||Mg,f=t.length,g=s.textRenderingMode===De.INVISIBLE;let p,m,y,b;if(!(g||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(u,r),p=0;p<f;++p){if(m=t[p],typeof m=="number"){b=o*m*n/1e3,this.ctx.translate(b,0),s.x+=b*u;continue}const x=(m.isSpace?c:0)+h,C=i.charProcOperatorList[m.operatorListId];if(!C){ht(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),e.scale(n,n),e.transform(...d),this.executeOperatorList(C),this.restore()),y=q.applyTransform([m.width,0],d)[0]*n+x,e.translate(y,0),s.x+=y*u}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||It(this.ctx),n={createCanvasGraphics:r=>new vp(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new Jg(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=q.makeHexColor(t,e,s),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=q.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=XS(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),Re.SHADING);const i=ki(e);if(i){const{width:n,height:r}=e.canvas,[o,h,c,u]=q.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,h,c-o,u-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){Pt("Should not call beginInlineImage")}beginImageData(){Pt("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=It(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(It(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||fd("TODO: Support non-isolated groups."),t.knockout&&ht("Knockout groups not supported.");const s=It(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=q.getAxialAlignedBoundingBox(t.bbox,It(e));const n=[0,0,e.canvas.width,e.canvas.height];i=q.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),c=Math.max(Math.ceil(i[3])-o,1);this.current.startNewPathAndClipBox([0,0,h,c]);let u="groupAt"+this.groupLevel;t.smask&&(u+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(u,h,c),f=d.context;f.translate(-r,-o),f.transform(...s),t.smask?this.smaskStack.push({canvas:d.canvas,context:f,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()),vl(e,f),this.ctx=f,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=It(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=q.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(w(this,ci,Xp).call(this),Sd(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,c]=q.singularValueDecompose2dScale(It(this.ctx)),{viewportScale:u}=this,d=Math.ceil(r*this.outputScaleX*u),f=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(d,f);const{canvas:g,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,g),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(h,0,0,-c,0,o*c),Sd(this.ctx)}else Sd(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new sb(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),w(this,ci,Up).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=KS(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=It(o);o.transform(e,s,i,n,0,0);const c=this._createMaskCanvas(t);o.setTransform(1,0,0,1,c.offsetX-h[4],c.offsetY-h[5]);for(let u=0,d=r.length;u<d;u+=2){const f=q.transform(h,[e,s,i,n,r[u],r[u+1]]),[g,p]=q.applyTransform([0,0],f);o.drawImage(c.canvas,g,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:c}=n,u=this.cachedCanvases.getCanvas("maskCanvas",o,h),d=u.context;d.save();const f=this.getObject(r,n);nb(d,f),d.globalCompositeOperation="source-in",d.fillStyle=i?s.getPattern(d,this,ki(e),Re.FILL):s,d.fillRect(0,0,o,h),d.restore(),e.save(),e.transform(...c),e.scale(1,-1),xd(e,u.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){ht("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){ht("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let c=0,u=i.length;c<u;c+=2)h.push({transform:[e,0,0,s,i[c],i[c+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(),!Oe){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;ib(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,ki(i));i.imageSmoothingEnabled=rb(It(i),t.interpolate),xd(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;ib(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),xd(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===ob?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=It(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),c=Math.abs(n);if(h===c)if(t===0)r=o=1/h;else{const u=h*t;r=o=u<1?1/u:1}else if(t===0)r=1/h,o=1/c;else{const u=h*t,d=c*t;r=u<1?1/u:1,o=d<1?1/d:1}}else{const h=Math.abs(e*n-s*i),c=Math.hypot(e,s),u=Math.hypot(i,n);if(t===0)r=u/h,o=c/h;else{const d=t*h;r=u>d?u/d:1,o=c>d?c/d: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}};ci=new WeakSet,Xp=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)},Up=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}}},Yp=function(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i};let Ea=vp;for(const a in ii)Ea.prototype[a]!==void 0&&(Ea.prototype[ii[a]]=Ea.prototype[a]);class hn{static get workerPort(){return l(this,Jl)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");v(this,Jl,t)}static get workerSrc(){return l(this,Ql)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");v(this,Ql,t)}}Jl=new WeakMap,Ql=new WeakMap,_(hn,Jl,null),_(hn,Ql,"");class tC{constructor({parsedData:t,rawData:e}){_(this,So);_(this,Zl);v(this,So,t),v(this,Zl,e)}getRaw(){return l(this,Zl)}get(t){return l(this,So).get(t)??null}getAll(){return Fg(l(this,So))}has(t){return l(this,So).has(t)}}So=new WeakMap,Zl=new WeakMap;const ka=Symbol("INTERNAL");class eC{constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){_(this,tc,!1);_(this,ec,!1);_(this,sc,!1);_(this,$a,!0);v(this,tc,!!(t&vs.DISPLAY)),v(this,ec,!!(t&vs.PRINT)),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(l(this,sc))return l(this,$a);if(!l(this,$a))return!1;const{print:t,view:e}=this.usage;return l(this,tc)?(e==null?void 0:e.viewState)!=="OFF":l(this,ec)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,e,s=!1){t!==ka&&Pt("Internal method `_setVisible` called."),v(this,sc,s),v(this,$a,e)}}tc=new WeakMap,ec=new WeakMap,sc=new WeakMap,$a=new WeakMap;class sC{constructor(t,e=vs.DISPLAY){_(this,ic);_(this,ur,null);_(this,At,new Map);_(this,qa,null);_(this,Ka,null);if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,v(this,Ka,t.order);for(const s of t.groups)l(this,At).set(s.id,new eC(e,s));if(t.baseState==="OFF")for(const s of l(this,At).values())s._setVisible(ka,!1);for(const s of t.on)l(this,At).get(s)._setVisible(ka,!0);for(const s of t.off)l(this,At).get(s)._setVisible(ka,!1);v(this,qa,this.getHash())}}isVisible(t){if(l(this,At).size===0)return!0;if(!t)return fd("Optional content group not defined."),!0;if(t.type==="OCG")return l(this,At).has(t.id)?l(this,At).get(t.id).visible:(ht(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return w(this,ic,$p).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(l(this,At).get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(!l(this,At).get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(!l(this,At).get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(l(this,At).get(e).visible)return!1}return!0}return ht(`Unknown optional content policy ${t.policy}.`),!0}return ht(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){var n;const i=l(this,At).get(t);if(!i){ht(`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=l(this,At).get(o))==null||n._setVisible(ka,!1,!0));i._setVisible(ka,!!e,!0),v(this,ur,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=l(this,At).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}}v(this,ur,null)}get hasInitialVisibility(){return l(this,qa)===null||this.getHash()===l(this,qa)}getOrder(){return l(this,At).size?l(this,Ka)?l(this,Ka).slice():[...l(this,At).keys()]:null}getGroups(){return l(this,At).size>0?Fg(l(this,At)):null}getGroup(t){return l(this,At).get(t)||null}getHash(){if(l(this,ur)!==null)return l(this,ur);const t=new z0;for(const[e,s]of l(this,At))t.update(`${e}:${s.visible}`);return v(this,ur,t.hexdigest())}}ur=new WeakMap,At=new WeakMap,qa=new WeakMap,Ka=new WeakMap,ic=new WeakSet,$p=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=w(this,ic,$p).call(this,n);else if(l(this,At).has(n))r=l(this,At).get(n).visible;else return ht(`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 iC{constructor(t,{disableRange:e=!1,disableStream:s=!1}){ie(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,c)=>{this._onReceiveData({begin:h,chunk:c})}),t.addProgressListener((h,c)=>{this._onProgress({loaded:h,total:c})}),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)});ie(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(){ie(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new nC(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new rC(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 nC{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Bg(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 rC{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 oC(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let u=o(e);return u=unescape(u),u=h(u),u=c(u),n(u)}if(e=r(a),e){const u=c(e);return n(u)}if(e=s("filename","i").exec(a),e){e=e[1];let u=o(e);return u=c(u),n(u)}function s(u,d){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',d)}function i(u,d){if(u){if(!/^[\x00-\xFF]+$/.test(d))return d;try{const f=new TextDecoder(u,{fatal:!0}),g=pd(d);d=f.decode(g),t=!1}catch{}}return d}function n(u){return t&&/[\x80-\xff]/.test(u)&&(u=i("utf-8",u),t&&(u=i("iso-8859-1",u))),u}function r(u){const d=[];let f;const g=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(f=g.exec(u))!==null;){let[,m,y,b]=f;if(m=parseInt(m,10),m in d){if(m===0)break;continue}d[m]=[y,b]}const p=[];for(let m=0;m<d.length&&m in d;++m){let[y,b]=d[m];b=o(b),y&&(b=unescape(b),m===0&&(b=h(b))),p.push(b)}return p.join("")}function o(u){if(u.startsWith('"')){const d=u.slice(1).split('\\"');for(let f=0;f<d.length;++f){const g=d[f].indexOf('"');g!==-1&&(d[f]=d[f].slice(0,g),d.length=f+1),d[f]=d[f].replaceAll(/\\(.)/g,"$1")}u=d.join('"')}return u}function h(u){const d=u.indexOf("'");if(d===-1)return u;const f=u.slice(0,d),p=u.slice(d+1).replace(/^[^']*'/,"");return i(f,p)}function c(u){return!u.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(u)?u:u.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(d,f,g,p){if(g==="q"||g==="Q")return p=p.replaceAll("_"," "),p=p.replaceAll(/=([0-9a-fA-F]{2})/g,function(m,y){return String.fromCharCode(parseInt(y,16))}),i(f,p);try{p=atob(p)}catch{}return i(f,p)})}return""}function ab(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 Cd(a){try{return new URL(a).origin}catch{}return null}function hb({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 lb(a){const t=a.get("Content-Disposition");if(t){let e=oC(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Bg(e))return e}return null}function Ad(a,t){return a===404||a===0&&t.startsWith("file:")?new dl('Missing PDF "'+t+'".'):new gd(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function cb(a){return a===200||a===206}function ub(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function db(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(ht(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class fb{constructor(t){Q(this,"_responseOrigin",null);this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=ab(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 ie(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new aC(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new hC(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 aC{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,ub(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=Cd(n.url),!cb(n.status))throw Ad(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=hb({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=lb(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new qn("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:db(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}class hC{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,ub(n,this._withCredentials,this._abortController)).then(o=>{const h=Cd(o.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!cb(o.status))throw Ad(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:db(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}const Qg=200,Zg=206;function lC(a){const t=a.response;return typeof t!="string"?t:pd(t).buffer}class cC{constructor({url:t,httpHeaders:e,withCredentials:s}){Q(this,"_responseOrigin",null);this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=ab(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}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=Zg):i.expectedStatus=Qg,e.responseType="arraybuffer",ie(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{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){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){s.onError(i.status);return}const n=i.status||Qg;if(!(n===Qg&&s.expectedStatus===Zg)&&n!==s.expectedStatus){s.onError(i.status);return}const o=lC(i);if(n===Zg){const h=i.getResponseHeader("Content-Range"),c=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);c?s.onDone({begin:parseInt(c[1],10),chunk:o}):(ht('Missing or invalid "Content-Range" header.'),s.onError(0))}else o?s.onDone({begin:0,chunk:o}):s.onError(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 uC{constructor(t){this._source=t,this._manager=new cC(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 ie(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new dC(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new fC(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 dC{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),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);this._manager._responseOrigin=Cd(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[h,...c]=o.split(": ");return[h,c.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=hb({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=lb(i),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=Ad(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(await this._headersCapability.promise,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 fC{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){var e;const t=Cd((e=this._manager.getRequestXhr(this._requestId))==null?void 0:e.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_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??(this._storedError=Ad(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 gC=/^[a-z][a-z0-9\-+.]+:/i;function pC(a){if(gC.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class mC{constructor(t){this.source=t,this.url=pC(t.url),ie(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return ie(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new vC(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new bC(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 vC{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();const s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new dl(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}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 qn("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class bC{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}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)}}const yC=1e5,as=30,_C=.8,ue=class ue{constructor({textContentSource:t,container:e,viewport:s}){_(this,xn);_(this,dr,Promise.withResolvers());_(this,cs,null);_(this,nc,!1);_(this,rc,!!((Rb=globalThis.FontInspector)!=null&&Rb.enabled));_(this,Co,null);_(this,wn,null);_(this,oc,0);_(this,ac,0);_(this,Ao,null);_(this,Ja,null);_(this,Qa,0);_(this,fr,0);_(this,Za,Object.create(null));_(this,hc,[]);_(this,th,null);_(this,To,[]);_(this,lc,new WeakMap);_(this,cc,null);var h;if(t instanceof ReadableStream)v(this,th,t);else if(typeof t=="object")v(this,th,new ReadableStream({start(c){c.enqueue(t),c.close()}}));else throw new Error('No "textContentSource" parameter specified.');v(this,cs,v(this,Ja,e)),v(this,fr,s.scale*(globalThis.devicePixelRatio||1)),v(this,Qa,s.rotation),v(this,wn,{div:null,properties:null,ctx:null});const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;v(this,cc,[1,0,0,-1,-r,o+n]),v(this,ac,i),v(this,oc,n),w(h=ue,xs,Oy).call(h),$r(e,s),l(this,dr).promise.finally(()=>{l(ue,eh).delete(this),v(this,wn,null),v(this,Za,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Ue.platform;return ct(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{l(this,Ao).read().then(({value:e,done:s})=>{if(s){l(this,dr).resolve();return}l(this,Co)??v(this,Co,e.lang),Object.assign(l(this,Za),e.styles),w(this,xn,Py).call(this,e.items),t()},l(this,dr).reject)};return v(this,Ao,l(this,th).getReader()),l(ue,eh).add(this),t(),l(this,dr).promise}update({viewport:t,onBefore:e=null}){var n;const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==l(this,Qa)&&(e==null||e(),v(this,Qa,i),$r(l(this,Ja),{rotation:i})),s!==l(this,fr)){e==null||e(),v(this,fr,s);const r={div:null,properties:null,ctx:w(n=ue,xs,uf).call(n,l(this,Co))};for(const o of l(this,To))r.properties=l(this,lc).get(o),r.div=o,w(this,xn,qp).call(this,r)}}cancel(){var e;const t=new qn("TextLayer task cancelled.");(e=l(this,Ao))==null||e.cancel(t).catch(()=>{}),v(this,Ao,null),l(this,dr).reject(t)}get textDivs(){return l(this,To)}get textContentItemsStr(){return l(this,hc)}static cleanup(){if(!(l(this,eh).size>0)){l(this,Eo).clear();for(const{canvas:t}of l(this,ko).values())t.remove();l(this,ko).clear()}}};dr=new WeakMap,cs=new WeakMap,nc=new WeakMap,rc=new WeakMap,Co=new WeakMap,wn=new WeakMap,oc=new WeakMap,ac=new WeakMap,Ao=new WeakMap,Ja=new WeakMap,Qa=new WeakMap,fr=new WeakMap,Za=new WeakMap,hc=new WeakMap,th=new WeakMap,To=new WeakMap,lc=new WeakMap,cc=new WeakMap,Eo=new WeakMap,ko=new WeakMap,uc=new WeakMap,gr=new WeakMap,eh=new WeakMap,xn=new WeakSet,Py=function(t){var i,n;if(l(this,nc))return;(n=l(this,wn)).ctx??(n.ctx=w(i=ue,xs,uf).call(i,l(this,Co)));const e=l(this,To),s=l(this,hc);for(const r of t){if(e.length>yC){ht("Ignoring additional textDivs for performance reasons."),v(this,nc,!0);return}if(r.str===void 0){if(r.type==="beginMarkedContentProps"||r.type==="beginMarkedContent"){const o=l(this,cs);v(this,cs,document.createElement("span")),l(this,cs).classList.add("markedContent"),r.id!==null&&l(this,cs).setAttribute("id",`${r.id}`),o.append(l(this,cs))}else r.type==="endMarkedContent"&&v(this,cs,l(this,cs).parentNode);continue}s.push(r.str),w(this,xn,My).call(this,r)}},My=function(t){var m;const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};l(this,To).push(e);const i=q.transform(l(this,cc),t.transform);let n=Math.atan2(i[1],i[0]);const r=l(this,Za)[t.fontName];r.vertical&&(n+=Math.PI/2);let o=l(this,rc)&&r.fontSubstitution||r.fontFamily;o=ue.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),c=h*w(m=ue,xs,Dy).call(m,o,l(this,Co));let u,d;n===0?(u=i[4],d=i[5]-c):(u=i[4]+c*Math.sin(n),d=i[5]-c*Math.cos(n));const f="calc(var(--scale-factor)*",g=e.style;l(this,cs)===l(this,Ja)?(g.left=`${(100*u/l(this,ac)).toFixed(2)}%`,g.top=`${(100*d/l(this,oc)).toFixed(2)}%`):(g.left=`${f}${u.toFixed(2)}px)`,g.top=`${f}${d.toFixed(2)}px)`),g.fontSize=`${f}${(l(ue,gr)*h).toFixed(2)}px)`,g.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,l(this,rc)&&(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 y=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);y!==b&&Math.max(y,b)/Math.min(y,b)>1.5&&(p=!0)}if(p&&(s.canvasWidth=r.vertical?t.height:t.width),l(this,lc).set(e,s),l(this,wn).div=e,l(this,wn).properties=s,w(this,xn,qp).call(this,l(this,wn)),s.hasText&&l(this,cs).append(e),s.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),l(this,cs).append(y)}},qp=function(t){var o;const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(l(ue,gr)>1&&(r=`scale(${1/l(ue,gr)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:h}=n,{canvasWidth:c,fontSize:u}=s;w(o=ue,xs,Kp).call(o,i,u*l(this,fr),h);const{width:d}=i.measureText(e.textContent);d>0&&(r=`scaleX(${c*l(this,fr)/d}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)},xs=new WeakSet,uf=function(t=null){let e=l(this,ko).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}),l(this,ko).set(t,e),l(this,uc).set(e,{size:0,family:""})}return e},Kp=function(t,e,s){const i=l(this,uc).get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)},Oy=function(){if(l(this,gr)!==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),v(this,gr,t.getBoundingClientRect().height),t.remove()},Dy=function(t,e){const s=l(this,Eo).get(t);if(s)return s;const i=w(this,xs,uf).call(this,e);i.canvas.width=i.canvas.height=as,w(this,xs,Kp).call(this,i,as,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const u=r/(r+o);return l(this,Eo).set(t,u),i.canvas.width=i.canvas.height=0,u}i.strokeStyle="red",i.clearRect(0,0,as,as),i.strokeText("g",0,0);let h=i.getImageData(0,0,as,as).data;o=0;for(let u=h.length-1-3;u>=0;u-=4)if(h[u]>0){o=Math.ceil(u/4/as);break}i.clearRect(0,0,as,as),i.strokeText("A",0,as),h=i.getImageData(0,0,as,as).data,r=0;for(let u=0,d=h.length;u<d;u+=4)if(h[u]>0){r=as-Math.floor(u/4/as);break}i.canvas.width=i.canvas.height=0;const c=r?r/(r+o):_C;return l(this,Eo).set(t,c),c},_(ue,xs),_(ue,Eo,new Map),_(ue,ko,new Map),_(ue,uc,new WeakMap),_(ue,gr,null),_(ue,eh,new Set);let bl=ue;class yl{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(yl.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 c of n.children)i(c)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const wC=65536,xC=100,SC=5e3,CC=Oe?NS:LS,AC=Oe?BS:U0,TC=Oe?jS:IS,EC=Oe?HS:q0;function kC(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new tp,{docId:e}=t,s=a.url?PC(a.url):null,i=a.data?MC(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof pb?a.range:null,c=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:wC;let u=a.worker instanceof Pa?a.worker:null;const d=a.verbosity,f=typeof a.docBaseUrl=="string"&&!vd(a.docBaseUrl)?a.docBaseUrl:null,g=typeof a.cMapUrl=="string"?a.cMapUrl:null,p=a.cMapPacked!==!1,m=a.CMapReaderFactory||AC,y=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,b=a.StandardFontDataFactory||EC,x=a.stopAtErrors!==!0,C=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,S=a.isEvalSupported!==!1,T=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Oe,P=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Oe&&(Ue.platform.isFirefox||!globalThis.chrome),M=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,D=typeof a.disableFontFace=="boolean"?a.disableFontFace:Oe,R=a.fontExtraProperties===!0,V=a.enableXfa===!0,H=a.ownerDocument||globalThis.document,F=a.disableRange===!0,I=a.disableStream===!0,j=a.disableAutoFetch===!0,K=a.pdfBug===!0,L=a.CanvasFactory||CC,z=a.FilterFactory||TC,Z=a.enableHWA===!0,Dt=h?h.length:a.length??NaN,Bt=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Oe&&!D,Xt=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:m===U0&&b===q0&&g&&y&&gl(g,document.baseURI)&&gl(y,document.baseURI),Ft=null;fS(d);const _t={canvasFactory:new L({ownerDocument:H,enableHWA:Z}),filterFactory:new z({docId:e,ownerDocument:H}),cMapReaderFactory:Xt?null:new m({baseUrl:g,isCompressed:p}),standardFontDataFactory:Xt?null:new b({baseUrl:y})};if(!u){const it={verbosity:d,port:hn.workerPort};u=it.port?Pa.fromPort(it):new Pa(it),t._worker=u}const oe={docId:e,apiVersion:"4.10.38",data:i,password:o,disableAutoFetch:j,rangeChunkSize:c,length:Dt,docBaseUrl:f,enableXfa:V,evaluatorOptions:{maxImageSize:C,disableFontFace:D,ignoreErrors:x,isEvalSupported:S,isOffscreenCanvasSupported:T,isImageDecoderSupported:P,canvasMaxAreaInBytes:M,fontExtraProperties:R,useSystemFonts:Bt,cMapUrl:Xt?g:null,standardFontDataUrl:Xt?y:null}},Ze={disableFontFace:D,fontExtraProperties:R,ownerDocument:H,pdfBug:K,styleElement:Ft,loadingParams:{disableAutoFetch:j,enableXfa:V}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const it=u.messageHandler.sendWithPromise("GetDocRequest",oe,i?[i.buffer]:null);let nt;if(h)nt=new iC(h,{disableRange:F,disableStream:I});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Zt;if(Oe)if(gl(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");Zt=fb}else Zt=mC;else Zt=gl(s)?fb:uC;nt=new Zt({url:s,length:Dt,httpHeaders:n,withCredentials:r,rangeChunkSize:c,disableRange:F,disableStream:I})}return it.then(Zt=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Ys=new ml(e,Zt,u.port),Te=new FC(Ys,t,nt,Ze,_t);t._transport=Te,Ys.send("Ready",null)})}).catch(t._capability.reject),t}function PC(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(Oe&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function MC(a){if(Oe&&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 pd(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 gb(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 Hd=class Hd{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${es(Hd,Bd)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){var t,e,s,i;this.destroyed=!0;try{(t=this._worker)!=null&&t.port&&(this._worker._pendingDestroy=!0),await((e=this._transport)==null?void 0:e.destroy())}catch(n){throw(s=this._worker)!=null&&s.port&&delete this._worker._pendingDestroy,n}this._transport=null,(i=this._worker)==null||i.destroy(),this._worker=null}};Bd=new WeakMap,_(Hd,Bd,0);let tp=Hd;class pb{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){Pt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class OC{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 ct(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 DC{constructor(t,e,s,i=!1){_(this,zs);_(this,pr,null);_(this,Sn,!1);this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new B0:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new mb,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 fl({viewBox:this.view,userUnit:this.userUnit,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 ct(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=Yn.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:c=null,printAnnotationStorage:u=null,isEditing:d=!1}){var S,T;(S=this._stats)==null||S.time("Overall");const f=this._transport.getRenderingIntent(s,i,u,d),{renderingIntent:g,cacheKey:p}=f;v(this,Sn,!1),w(this,zs,df).call(this),o||(o=this._transport.getOptionalContentConfig(g));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 y=!!(g&vs.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(T=this._stats)==null||T.time("Page Request"),this._pumpOperatorList(f));const b=P=>{var M;m.renderTasks.delete(x),(this._maybeCleanupAfterRender||y)&&v(this,Sn,!0),w(this,zs,Vh).call(this,!y),P?(x.capability.reject(P),this._abortOperatorList({intentState:m,reason:P instanceof Error?P:new Error(P)})):x.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(M=globalThis.Stats)!=null&&M.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},x=new ep({callback:b,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:!y,pdfBug:this._pdfBug,pageColors:c});(m.renderTasks||(m.renderTasks=new Set)).add(x);const C=x.task;return Promise.all([m.displayReadyCapability.promise,o]).then(([P,M])=>{var D;if(this.destroyed){b();return}if((D=this._stats)==null||D.time("Rendering"),!(M.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");x.initializeGraphics({transparency:P,optionalContentConfig:M}),x.operatorListChanged()}).catch(b),C}getOperatorList({intent:t="display",annotationMode:e=Yn.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){var c;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},(c=this._stats)==null||c.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=>yl.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:c}){if(c){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(),v(this,Sn,!1),w(this,zs,df).call(this),Promise.all(t)}cleanup(t=!1){v(this,Sn,!0);const e=w(this,zs,Vh).call(this,!1);return t&&e&&this._stats&&(this._stats=new B0),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&&w(this,zs,Vh).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(),c=this._intentStates.get(e);c.streamReader=h;const u=()=>{h.read().then(({value:d,done:f})=>{if(f){c.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(d,c),u())},d=>{if(c.streamReader=null,!this._transport.destroyed){if(c.operatorList){c.operatorList.lastChunk=!0;for(const f of c.renderTasks)f.operatorListChanged();w(this,zs,Vh).call(this,!0)}if(c.displayReadyCapability)c.displayReadyCapability.reject(d);else if(c.opListReadCapability)c.opListReadCapability.reject(d);else throw d}})};u()}_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 Ng){let i=xC;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 qn(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}}pr=new WeakMap,Sn=new WeakMap,zs=new WeakSet,Vh=function(t=!1){if(w(this,zs,df).call(this),!l(this,Sn)||this.destroyed)return!1;if(t)return v(this,pr,setTimeout(()=>{v(this,pr,null),w(this,zs,Vh).call(this,!1)},SC)),!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(),v(this,Sn,!1),!0},df=function(){l(this,pr)&&(clearTimeout(l(this,pr)),v(this,pr,null))};class RC{constructor(){_(this,Cn,new Map);_(this,zd,Promise.resolve())}postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};l(this,zd).then(()=>{for(const[i]of l(this,Cn))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){ht("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}l(this,Cn).set(e,i)}removeEventListener(t,e){const s=l(this,Cn).get(e);s==null||s(),l(this,Cn).delete(e)}terminate(){for(const[,t]of l(this,Cn))t==null||t();l(this,Cn).clear()}}Cn=new WeakMap,zd=new WeakMap;const jt=class jt{constructor({name:t=null,port:e=null,verbosity:s=gS()}={}){_(this,sh);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=l(jt,Mo))!=null&&i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(l(jt,Mo)||v(jt,Mo,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new ml("main","worker",t),this._messageHandler.on("ready",function(){}),w(this,sh,ff).call(this)}_initialize(){if(l(jt,Po)||l(jt,ih,gf)){this._setupFakeWorker();return}let{workerSrc:t}=jt;try{jt._isSameOrigin(window.location.href,t)||(t=jt._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new ml("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,w(this,sh,ff).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{fd("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){l(jt,Po)||(ht("Setting up fake worker."),v(jt,Po,!0)),jt._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new RC;this._port=e;const s=`fake${es(jt,Vd)._++}`,i=new ml(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new ml(s,s+"_worker",e),w(this,sh,ff).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t,e,s;this.destroyed=!0,(t=this._webWorker)==null||t.terminate(),this._webWorker=null,(e=l(jt,Mo))==null||e.delete(this._port),this._port=null,(s=this._messageHandler)==null||s.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=l(this,Mo))==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 jt(t)}static get workerSrc(){if(hn.workerSrc)return hn.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return ct(this,"_setupFakeWorkerGlobal",(async()=>l(this,ih,gf)?l(this,ih,gf):(await import(this.workerSrc)).WorkerMessageHandler)())}};Vd=new WeakMap,Po=new WeakMap,Mo=new WeakMap,sh=new WeakSet,ff=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},ih=new WeakSet,gf=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},_(jt,ih),_(jt,Vd,0),_(jt,Po,!1),_(jt,Mo),Oe&&(v(jt,Po,!0),hn.workerSrc||(hn.workerSrc="./pdf.worker.mjs")),jt._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},jt._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let Pa=jt;class FC{constructor(t,e,s,i,n){_(this,Oo);_(this,An,new Map);_(this,Bi,new Map);_(this,nh,new Map);_(this,rh,new Map);_(this,Tn,null);this.messageHandler=t,this.loadingTask=e,this.commonObjs=new mb,this.fontLoader=new RS({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 ct(this,"annotationStorage",new Yg)}getRenderingIntent(t,e=Yn.ENABLE,s=null,i=!1,n=!1){let r=vs.DISPLAY,o=Ug;switch(t){case"any":r=vs.ANY;break;case"display":break;case"print":r=vs.PRINT;break;default:ht(`getRenderingIntent - invalid intent: ${t}`)}const h=r&vs.PRINT&&s instanceof V0?s:this.annotationStorage;switch(e){case Yn.DISABLE:r+=vs.ANNOTATIONS_DISABLE;break;case Yn.ENABLE:break;case Yn.ENABLE_FORMS:r+=vs.ANNOTATIONS_FORMS;break;case Yn.ENABLE_STORAGE:r+=vs.ANNOTATIONS_STORAGE,o=h.serializable;break;default:ht(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=vs.IS_EDITING),n&&(r+=vs.OPLIST);const{ids:c,hash:u}=h.modifiedIds,d=[r,o.hash,u];return{renderingIntent:r,cacheKey:d.join("_"),annotationStorageSerializable:o,modifiedIds:c}}destroy(){var s;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(s=l(this,Tn))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const i of l(this,Bi).values())t.push(i._destroy());l(this,Bi).clear(),l(this,nh).clear(),l(this,rh).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{var i,n;this.commonObjs.clear(),this.fontLoader.clear(),l(this,An).clear(),this.filterFactory.destroy(),bl.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new qn("Worker was terminated.")),(n=this.messageHandler)==null||n.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)=>{ie(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}ie(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 c;(c=e.onProgress)==null||c.call(e,{loaded:h.loaded,total:h.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{ie(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}ie(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 OC(s,this))}),t.on("DocException",s=>{e._capability.reject(rs(s))}),t.on("PasswordRequest",s=>{v(this,Tn,Promise.withResolvers());try{if(!e.onPassword)throw rs(s);const i=n=>{n instanceof Error?l(this,Tn).reject(n):l(this,Tn).resolve({password:n})};e.onPassword(i,s.code)}catch(i){l(this,Tn).reject(i)}return l(this,Tn).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;l(this,Bi).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:c}=this._params;if("error"in n){const g=n.error;ht(`Error during font loading: ${g}`),this.commonObjs.resolve(s,g);break}const u=c&&((r=globalThis.FontInspector)!=null&&r.enabled)?(g,p)=>globalThis.FontInspector.fontAdded(g,p):null,d=new FS(n,{disableFontFace:o,fontExtraProperties:h,inspectFont:u});this.fontLoader.bind(d).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!h&&d.data&&(d.data=null),this.commonObjs.resolve(s,d)});break;case"CopyLocalImage":const{imageRef:f}=n;ie(f,"The imageRef must be defined.");for(const g of l(this,Bi).values())for(const[,p]of g.objs)if((p==null?void 0:p.ref)===f)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=l(this,Bi).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)>lS&&(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&&ht("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=l(this,nh).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&&l(this,rh).set(n.refStr,t);const r=new DC(e,n,this,this._params.pdfBug);return l(this,Bi).set(e,r),r});return l(this,nh).set(e,i),i}getPageIndex(t){return gb(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 w(this,Oo,iu).call(this,"GetFieldObjects")}hasJSActions(){return w(this,Oo,iu).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 w(this,Oo,iu).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 w(this,Oo,iu).call(this,"GetOptionalContentConfig").then(e=>new sC(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=l(this,An).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 tC(i[1]):null,contentDispositionFilename:((n=this._fullReader)==null?void 0:n.filename)??null,contentLength:((r=this._fullReader)==null?void 0:r.contentLength)??null}});return l(this,An).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 l(this,Bi).values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),l(this,An).clear(),this.filterFactory.destroy(!0),bl.cleanup()}}cachedPageNumber(t){if(!gb(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return l(this,rh).get(e)??null}}An=new WeakMap,Bi=new WeakMap,nh=new WeakMap,rh=new WeakMap,Tn=new WeakMap,Oo=new WeakSet,iu=function(t,e=null){const s=l(this,An).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return l(this,An).set(t,i),i};const _l=Symbol("INITIAL_DATA");class mb{constructor(){_(this,dc);_(this,Ss,Object.create(null))}get(t,e=null){if(e){const i=w(this,dc,Jp).call(this,t);return i.promise.then(()=>e(i.data)),null}const s=l(this,Ss)[t];if(!s||s.data===_l)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=l(this,Ss)[t];return!!e&&e.data!==_l}delete(t){const e=l(this,Ss)[t];return!e||e.data===_l?!1:(delete l(this,Ss)[t],!0)}resolve(t,e=null){const s=w(this,dc,Jp).call(this,t);s.data=e,s.resolve()}clear(){var t;for(const e in l(this,Ss)){const{data:s}=l(this,Ss)[e];(t=s==null?void 0:s.bitmap)==null||t.close()}v(this,Ss,Object.create(null))}*[Symbol.iterator](){for(const t in l(this,Ss)){const{data:e}=l(this,Ss)[t];e!==_l&&(yield[t,e])}}}Ss=new WeakMap,dc=new WeakSet,Jp=function(t){var e;return(e=l(this,Ss))[t]||(e[t]={...Promise.withResolvers(),data:_l})};class LC{constructor(t){_(this,mr,null);v(this,mr,t),this.onContinue=null}get promise(){return l(this,mr).capability.promise}cancel(t=0){l(this,mr).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=l(this,mr).operatorList;if(!t)return!1;const{annotationCanvasMap:e}=l(this,mr);return t.form||t.canvas&&(e==null?void 0:e.size)>0}}mr=new WeakMap;const Ro=class Ro{constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:c,useRequestAnimationFrame:u=!1,pdfBug:d=!1,pageColors:f=null}){_(this,vr,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=c,this._pdfBug=d,this.pageColors=f,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new LC(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(l(Ro,Do).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.");l(Ro,Do).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 Ea(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(),l(this,vr)&&(window.cancelAnimationFrame(l(this,vr)),v(this,vr,null)),l(Ro,Do).delete(this._canvas),this.callback(t||new Ng(`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?v(this,vr,window.requestAnimationFrame(()=>{v(this,vr,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(),l(Ro,Do).delete(this._canvas),this.callback())))}};vr=new WeakMap,Do=new WeakMap,_(Ro,Do,new WeakSet);let ep=Ro;const IC="4.10.38",jC="f9bea397f";function vb(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function wl(a){return Math.max(0,Math.min(255,255*a))}class bb{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=wl(t),[t,t,t]}static G_HTML([t]){const e=vb(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(wl)}static RGB_HTML(t){return`#${t.map(vb).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[wl(1-Math.min(1,t+i)),wl(1-Math.min(1,s+i)),wl(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 NC{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){Pt("Abstract method `_createSVG` called.")}}class sp extends NC{_createSVG(t){return document.createElementNS(an,t)}}class yb{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,c=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:c})});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,c]of Object.entries(r))if(c!=null)switch(h){case"class":c.length&&t.setAttribute(h,c.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",c);break;case"style":Object.assign(t.style,c);break;case"textContent":t.textContent=c;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,c)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){var d,f;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 g=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=g}o&&h.setAttribute("class","xfaLayer xfaFont");const c=[];if(i.children.length===0){if(i.value){const g=document.createTextNode(i.value);r.append(g),o&&yl.shouldBuildText(i.name)&&c.push(g)}return{textDivs:c}}const u=[[i,-1,r]];for(;u.length>0;){const[g,p,m]=u.at(-1);if(p+1===g.children.length){u.pop();continue}const y=g.children[++u.at(-1)[1]];if(y===null)continue;const{name:b}=y;if(b==="#text"){const C=document.createTextNode(y.value);c.push(C),m.append(C);continue}const x=(d=y==null?void 0:y.attributes)!=null&&d.xmlns?document.createElementNS(y.attributes.xmlns,b):document.createElement(b);if(m.append(x),y.attributes&&this.setAttributes({html:x,element:y,storage:e,intent:n,linkService:s}),((f=y.children)==null?void 0:f.length)>0)u.push([y,-1,x]);else if(y.value){const C=document.createTextNode(y.value);o&&yl.shouldBuildText(b)&&c.push(C),x.append(C)}}for(const g of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))g.setAttribute("readOnly",!0);return{textDivs:c}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const xl=1e3,BC=9,Kr=new WeakSet;function Jn(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class HC{static create(t){switch(t.data.annotationType){case le.LINK:return new _b(t);case le.TEXT:return new zC(t);case le.WIDGET:switch(t.data.fieldType){case"Tx":return new VC(t);case"Btn":return t.data.radioButton?new wb(t):t.data.checkBox?new WC(t):new XC(t);case"Ch":return new UC(t);case"Sig":return new GC(t)}return new Jr(t);case le.POPUP:return new ip(t);case le.FREETEXT:return new xb(t);case le.LINE:return new $C(t);case le.SQUARE:return new qC(t);case le.CIRCLE:return new KC(t);case le.POLYLINE:return new Sb(t);case le.CARET:return new QC(t);case le.INK:return new np(t);case le.POLYGON:return new JC(t);case le.HIGHLIGHT:return new Cb(t);case le.UNDERLINE:return new ZC(t);case le.SQUIGGLY:return new tA(t);case le.STRIKEOUT:return new eA(t);case le.STAMP:return new Ab(t);case le.FILEATTACHMENT:return new sA(t);default:return new Kt(t)}}}const bp=class bp{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){_(this,fc);_(this,Fo,null);_(this,oh,!1);_(this,ah,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 bp._hasPopupData(this.data)}updateEdited(t){var s;if(!this.container)return;l(this,Fo)||v(this,Fo,{rect:this.data.rect.slice(0)});const{rect:e}=t;e&&w(this,fc,Qp).call(this,e),(s=l(this,ah))==null||s.popup.updateEdited(t)}resetEdited(){var t;l(this,Fo)&&(w(this,fc,Qp).call(this,l(this,Fo).rect),(t=l(this,ah))==null||t.popup.resetEdited(),v(this,Fo,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 Jr||(n.tabIndex=xl);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 ip){const{rotation:m}=e;return!e.hasOwnCanvas&&m!==0&&this.setRotation(m,n),n}const{width:o,height:h}=Jn(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const m=e.borderStyle.horizontalCornerRadius,y=e.borderStyle.verticalCornerRadius;if(m>0||y>0){const x=`calc(${m}px * var(--scale-factor)) / calc(${y}px * var(--scale-factor))`;r.borderRadius=x}else if(this instanceof wb){const x=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=x}switch(e.borderStyle.style){case ul.SOLID:r.borderStyle="solid";break;case ul.DASHED:r.borderStyle="dashed";break;case ul.BEVELED:ht("Unimplemented border style: beveled");break;case ul.INSET:ht("Unimplemented border style: inset");break;case ul.UNDERLINE:r.borderBottomStyle="solid";break}const b=e.borderColor||null;b?(v(this,oh,!0),r.borderColor=q.makeHexColor(b[0]|0,b[1]|0,b[2]|0)):r.borderWidth=0}const c=q.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:u,pageHeight:d,pageX:f,pageY:g}=i.rawDims;r.left=`${100*(c[0]-f)/u}%`,r.top=`${100*(c[1]-g)/d}%`;const{rotation:p}=e;return e.hasOwnCanvas||p===0?(r.width=`${100*o/u}%`,r.height=`${100*h/d}%`):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}=Jn(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]=bb[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:bb[`${r}_rgb`](o)})};return ct(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,b,x]=t.subarray(2,6);if(i===m&&n===y&&e===b&&s===x)return}const{style:r}=this.container;let o;if(l(this,oh)){const{borderColor:m,borderWidth:y}=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="${y}">`],this.container.classList.add("hasBorder")}const h=i-e,c=n-s,{svgFactory:u}=this,d=u.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const f=u.createElement("defs");d.append(f);const g=u.createElement("clipPath"),p=`clippath_${this.data.id}`;g.setAttribute("id",p),g.setAttribute("clipPathUnits","objectBoundingBox"),f.append(g);for(let m=2,y=t.length;m<y;m+=8){const b=t[m],x=t[m+1],C=t[m+2],S=t[m+3],T=u.createElement("rect"),P=(C-e)/h,M=(n-x)/c,D=(b-C)/h,R=(x-S)/c;T.setAttribute("x",P),T.setAttribute("y",M),T.setAttribute("width",D),T.setAttribute("height",R),g.append(T),o==null||o.push(`<rect vector-effect="non-scaling-stroke" x="${P}" y="${M}" width="${D}" height="${R}"/>`)}l(this,oh)&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=v(this,ah,new ip({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(){Pt("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,c=document.querySelector(`[data-element-id="${r}"]`);if(c&&!Kr.has(c)){ht(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:c})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&Kr.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})})}};Fo=new WeakMap,oh=new WeakMap,ah=new WeakMap,fc=new WeakSet,Qp=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:c,height:u}=Jn(t);e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*c/n}%`,e.height=`${100*u/r}%`):this.setRotation(i)};let Kt=bp;class _b extends Kt{constructor(e,s=null){super(e,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});_(this,Cs);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?(w(this,Cs,Ry).call(this,i,e.attachment,e.attachmentDest),n=!0):e.setOCGState?(w(this,Cs,Fy).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==="")&&w(this,Cs,ha).call(this)}_bindNamedAction(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(s),!1),w(this,Cs,ha).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),w(this,Cs,ha).call(this)}_bindResetFormAction(e,s){const i=e.onclick;if(i||(e.href=this.linkService.getAnchorUrl("")),w(this,Cs,ha).call(this),!this._fieldObjects){ht('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(e.onclick=()=>!1);return}e.onclick=()=>{var d;i==null||i();const{fields:n,refs:r,include:o}=s,h=[];if(n.length!==0||r.length!==0){const f=new Set(r);for(const g of n){const p=this._fieldObjects[g]||[];for(const{id:m}of p)f.add(m)}for(const g of Object.values(this._fieldObjects))for(const p of g)f.has(p.id)===o&&h.push(p)}else for(const f of Object.values(this._fieldObjects))h.push(...f);const c=this.annotationStorage,u=[];for(const f of h){const{id:g}=f;switch(u.push(g),f.type){case"text":{const m=f.defaultValue||"";c.setValue(g,{value:m});break}case"checkbox":case"radiobutton":{const m=f.defaultValue===f.exportValues;c.setValue(g,{value:m});break}case"combobox":case"listbox":{const m=f.defaultValue||"";c.setValue(g,{value:m});break}default:continue}const p=document.querySelector(`[data-element-id="${g}"]`);if(p){if(!Kr.has(p)){ht(`_bindResetFormAction - element not allowed: ${g}`);continue}}else continue;p.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((d=this.linkService.eventBus)==null||d.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}Cs=new WeakSet,ha=function(){this.container.setAttribute("data-internal-link","")},Ry=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},w(this,Cs,ha).call(this)},Fy=function(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(s),!1),w(this,Cs,ha).call(this)};class zC extends Kt{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 Jr extends Kt{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 Ue.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,c]of s)(c==="Action"||(n=this.data.actions)!=null&&n[c])&&((c==="Focus"||c==="Blur")&&(e||(e={focused:!1})),this._setEventListener(t,e,h,c,i),c==="Focus"&&!((r=this.data.actions)!=null&&r.Blur)?this._setEventListener(t,e,"blur","Blur",null):c==="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":q.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||BC,n=t.style;let r;const o=2,h=c=>Math.round(10*c)/10;if(this.data.multiLine){const c=Math.abs(this.data.rect[3]-this.data.rect[1]-o),u=Math.round(c/(Og*i))||1,d=c/u;r=Math.min(i,h(d/Og))}else{const c=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(c/Og))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=q.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 VC extends Jr{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 c=r.formattedValue||((i=this.data.textContent)==null?void 0:i.join(`
535
- `))||null;c&&this.data.comb&&(c=c.replaceAll(/\s+/g,""));const u={userValue:o,formattedValue:c,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=c??o,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",c??o),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),Kr.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=xl,this._setRequired(s,this.data.required),h&&(s.maxLength=h),s.addEventListener("input",f=>{t.setValue(e,{value:f.target.value}),this.setPropertyOnSiblings(s,"value",f.target.value,"value"),u.formattedValue=null}),s.addEventListener("resetform",f=>{const g=this.data.defaultFieldValue??"";s.value=u.userValue=g,u.formattedValue=null});let d=f=>{const{formattedValue:g}=u;g!=null&&(f.target.value=g),f.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",g=>{var m;if(u.focused)return;const{target:p}=g;u.userValue&&(p.value=u.userValue),u.lastCommittedValue=p.value,u.commitKey=1,(m=this.data.actions)!=null&&m.Focus||(u.focused=!0)}),s.addEventListener("updatefromsandbox",g=>{this.showElementAndHideCanvas(g.target);const p={value(m){u.userValue=m.detail.value??"",t.setValue(e,{value:u.userValue.toString()}),m.target.value=u.userValue},formattedValue(m){const{formattedValue:y}=m.detail;u.formattedValue=y,y!=null&&m.target!==document.activeElement&&(m.target.value=y),t.setValue(e,{formattedValue:y})},selRange(m){m.target.setSelectionRange(...m.detail.selRange)},charLimit:m=>{var C;const{charLimit:y}=m.detail,{target:b}=m;if(y===0){b.removeAttribute("maxLength");return}b.setAttribute("maxLength",y);let x=u.userValue;!x||x.length<=y||(x=x.slice(0,y),b.value=u.userValue=x,t.setValue(e,{value:x}),(C=this.linkService.eventBus)==null||C.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:x,willCommit:!0,commitKey:1,selStart:b.selectionStart,selEnd:b.selectionEnd}}))}};this._dispatchEventFromSandbox(p,g)}),s.addEventListener("keydown",g=>{var y;u.commitKey=1;let p=-1;if(g.key==="Escape"?p=0:g.key==="Enter"&&!this.data.multiLine?p=2:g.key==="Tab"&&(u.commitKey=3),p===-1)return;const{value:m}=g.target;u.lastCommittedValue!==m&&(u.lastCommittedValue=m,u.userValue=m,(y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:m,willCommit:!0,commitKey:p,selStart:g.target.selectionStart,selEnd:g.target.selectionEnd}}))});const f=d;d=null,s.addEventListener("blur",g=>{var m,y;if(!u.focused||!g.relatedTarget)return;(m=this.data.actions)!=null&&m.Blur||(u.focused=!1);const{value:p}=g.target;u.userValue=p,u.lastCommittedValue!==p&&((y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:p,willCommit:!0,commitKey:u.commitKey,selStart:g.target.selectionStart,selEnd:g.target.selectionEnd}})),f(g)}),(n=this.data.actions)!=null&&n.Keystroke&&s.addEventListener("beforeinput",g=>{var T;u.lastCommittedValue=null;const{data:p,target:m}=g,{value:y,selectionStart:b,selectionEnd:x}=m;let C=b,S=x;switch(g.inputType){case"deleteWordBackward":{const P=y.substring(0,b).match(/\w*[^\w]*$/);P&&(C-=P[0].length);break}case"deleteWordForward":{const P=y.substring(b).match(/^[^\w]*\w*/);P&&(S+=P[0].length);break}case"deleteContentBackward":b===x&&(C-=1);break;case"deleteContentForward":b===x&&(S+=1);break}g.preventDefault(),(T=this.linkService.eventBus)==null||T.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:y,change:p||"",willCommit:!1,selStart:C,selEnd:S}})}),this._setEventListeners(s,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],g=>g.target.value)}if(d&&s.addEventListener("blur",d),this.data.comb){const g=(this.data.rect[2]-this.data.rect[0])/h;s.classList.add("comb"),s.style.letterSpacing=`calc(${g}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 GC extends Jr{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class WC extends Jr{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 Kr.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=xl,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const c of this._getElementsByName(o,s)){const u=h&&c.exportValue===e.exportValue;c.domElement&&(c.domElement.checked=u),t.setValue(c.id,{value:u})}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 wb extends Jr{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(Kr.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=xl,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const c of this._getElementsByName(o,s))t.setValue(c.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:c=>{const u=r===c.detail.value;for(const d of this._getElementsByName(c.target.name)){const f=u&&d.id===s;d.domElement&&(d.domElement.checked=f),t.setValue(d.id,{value:f})}}};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 XC extends _b{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 UC extends Jr{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");Kr.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=xl;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",u=>{const d=this.data.defaultFieldValue;for(const f of i.options)f.selected=f.value===d});for(const u of this.data.options){const d=document.createElement("option");d.textContent=u.displayValue,d.value=u.exportValue,s.value.includes(u.exportValue)&&(d.setAttribute("selected",!0),n=!1),i.append(d)}let r=null;if(n){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),i.prepend(u),r=()=>{u.remove(),i.removeEventListener("input",r),r=null},i.addEventListener("input",r)}const o=u=>{const d=u?"value":"textContent",{options:f,multiple:g}=i;return g?Array.prototype.filter.call(f,p=>p.selected).map(p=>p[d]):f.selectedIndex===-1?null:f[f.selectedIndex][d]};let h=o(!1);const c=u=>{const d=u.target.options;return Array.prototype.map.call(d,f=>({displayValue:f.textContent,exportValue:f.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",u=>{const d={value(f){r==null||r();const g=f.detail.value,p=new Set(Array.isArray(g)?g:[g]);for(const m of i.options)m.selected=p.has(m.value);t.setValue(e,{value:o(!0)}),h=o(!1)},multipleSelection(f){i.multiple=!0},remove(f){const g=i.options,p=f.detail.remove;g[p].selected=!1,i.remove(p),g.length>0&&Array.prototype.findIndex.call(g,y=>y.selected)===-1&&(g[0].selected=!0),t.setValue(e,{value:o(!0),items:c(f)}),h=o(!1)},clear(f){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),h=o(!1)},insert(f){const{index:g,displayValue:p,exportValue:m}=f.detail.insert,y=i.children[g],b=document.createElement("option");b.textContent=p,b.value=m,y?y.before(b):i.append(b),t.setValue(e,{value:o(!0),items:c(f)}),h=o(!1)},items(f){const{items:g}=f.detail;for(;i.length!==0;)i.remove(0);for(const p of g){const{displayValue:m,exportValue:y}=p,b=document.createElement("option");b.textContent=m,b.value=y,i.append(b)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:o(!0),items:c(f)}),h=o(!1)},indices(f){const g=new Set(f.detail.indices);for(const p of f.target.options)p.selected=g.has(p.index);t.setValue(e,{value:o(!0)}),h=o(!1)},editable(f){f.target.disabled=!f.detail.editable}};this._dispatchEventFromSandbox(d,u)}),i.addEventListener("input",u=>{var g;const d=o(!0),f=o(!1);t.setValue(e,{value:d}),u.preventDefault(),(g=this.linkService.eventBus)==null||g.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:h,change:f,changeEx:d,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"]],u=>u.target.value)):i.addEventListener("input",function(u){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 ip extends Kt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Kt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new YC({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=>`${jg}${s}`).join(",")),this.container}}class YC{constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:o,parent:h,rect:c,parentRect:u,open:d}){_(this,Tt);_(this,hh,w(this,Tt,jy).bind(this));_(this,Gd,w(this,Tt,tm).bind(this));_(this,Wd,w(this,Tt,vf).bind(this));_(this,lh,w(this,Tt,mf).bind(this));_(this,Lo,null);_(this,Yt,null);_(this,En,null);_(this,ch,null);_(this,gc,null);_(this,pc,null);_(this,uh,null);_(this,kn,!1);_(this,ui,null);_(this,Pn,null);_(this,mc,null);_(this,Mn,null);_(this,vc,null);_(this,Io,null);_(this,jo,!1);var f;v(this,Yt,t),v(this,vc,i),v(this,En,r),v(this,Mn,o),v(this,pc,h),v(this,Lo,e),v(this,mc,c),v(this,uh,u),v(this,gc,s),v(this,ch,Hg.toDateObject(n)),this.trigger=s.flatMap(g=>g.getElementsToTriggerPopup());for(const g of this.trigger)g.addEventListener("click",l(this,lh)),g.addEventListener("mouseenter",l(this,Wd)),g.addEventListener("mouseleave",l(this,Gd)),g.classList.add("popupTriggerArea");for(const g of s)(f=g.container)==null||f.addEventListener("keydown",l(this,hh));l(this,Yt).hidden=!0,d&&w(this,Tt,mf).call(this)}render(){if(l(this,ui))return;const t=v(this,ui,document.createElement("div"));if(t.className="popup",l(this,Lo)){const n=t.style.outlineColor=q.makeHexColor(...l(this,Lo));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=q.makeHexColor(...l(this,Lo).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}=l(this,vc),t.append(e),l(this,ch)){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:l(this,ch).valueOf()})),e.append(n)}const i=l(this,Tt,pf);if(i)yb.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(l(this,En));t.append(n)}l(this,Yt).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;l(this,Io)||v(this,Io,{contentsObj:l(this,En),richText:l(this,Mn)}),t&&v(this,Pn,null),e&&(v(this,Mn,w(this,Tt,Iy).call(this,e)),v(this,En,null)),(s=l(this,ui))==null||s.remove(),v(this,ui,null)}resetEdited(){var t;l(this,Io)&&({contentsObj:es(this,En)._,richText:es(this,Mn)._}=l(this,Io),v(this,Io,null),(t=l(this,ui))==null||t.remove(),v(this,ui,null),v(this,Pn,null))}forceHide(){v(this,jo,this.isVisible),l(this,jo)&&(l(this,Yt).hidden=!0)}maybeShow(){l(this,jo)&&(l(this,ui)||w(this,Tt,vf).call(this),v(this,jo,!1),l(this,Yt).hidden=!1)}get isVisible(){return l(this,Yt).hidden===!1}}hh=new WeakMap,Gd=new WeakMap,Wd=new WeakMap,lh=new WeakMap,Lo=new WeakMap,Yt=new WeakMap,En=new WeakMap,ch=new WeakMap,gc=new WeakMap,pc=new WeakMap,uh=new WeakMap,kn=new WeakMap,ui=new WeakMap,Pn=new WeakMap,mc=new WeakMap,Mn=new WeakMap,vc=new WeakMap,Io=new WeakMap,jo=new WeakMap,Tt=new WeakSet,pf=function(){const t=l(this,Mn),e=l(this,En);return t!=null&&t.str&&(!(e!=null&&e.str)||e.str===t.str)&&l(this,Mn).html||null},Zp=function(){var t,e,s;return((s=(e=(t=l(this,Tt,pf))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.fontSize)||0},Ly=function(){var t,e,s;return((s=(e=(t=l(this,Tt,pf))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.color)||null},Iy=function(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:l(this,Tt,Ly),fontSize:l(this,Tt,Zp)?`calc(${l(this,Tt,Zp)}px * var(--scale-factor))`:""}};for(const n of t.split(`
536
- `))e.push({name:"span",value:n,attributes:i});return s},jy=function(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&l(this,kn))&&w(this,Tt,mf).call(this)},Ny=function(){if(l(this,Pn)!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=l(this,pc);let r=!!l(this,uh),o=r?l(this,uh):l(this,mc);for(const p of l(this,gc))if(!o||q.intersect(p.data.rect,o)!==null){o=p.data.rect,r=!0;break}const h=q.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]),u=r?o[2]-o[0]+5:0,d=h[0]+u,f=h[1];v(this,Pn,[100*(d-i)/e,100*(f-n)/s]);const{style:g}=l(this,Yt);g.left=`${l(this,Pn)[0]}%`,g.top=`${l(this,Pn)[1]}%`},mf=function(){v(this,kn,!l(this,kn)),l(this,kn)?(w(this,Tt,vf).call(this),l(this,Yt).addEventListener("click",l(this,lh)),l(this,Yt).addEventListener("keydown",l(this,hh))):(w(this,Tt,tm).call(this),l(this,Yt).removeEventListener("click",l(this,lh)),l(this,Yt).removeEventListener("keydown",l(this,hh)))},vf=function(){l(this,ui)||this.render(),this.isVisible?l(this,kn)&&l(this,Yt).classList.add("focused"):(w(this,Tt,Ny).call(this),l(this,Yt).hidden=!1,l(this,Yt).style.zIndex=parseInt(l(this,Yt).style.zIndex)+1e3)},tm=function(){l(this,Yt).classList.remove("focused"),!(l(this,kn)||!this.isVisible)&&(l(this,Yt).hidden=!0,l(this,Yt).style.zIndex=parseInt(l(this,Yt).style.zIndex)-1e3)};class xb extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=at.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 $C extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,bc,null)}render(){this.container.classList.add("lineAnnotation");const e=this.data,{width:s,height:i}=Jn(e.rect),n=this.svgFactory.create(s,i,!0),r=v(this,bc,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 l(this,bc)}addHighlightArea(){this.container.classList.add("highlightArea")}}bc=new WeakMap;class qC extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,yc,null)}render(){this.container.classList.add("squareAnnotation");const e=this.data,{width:s,height:i}=Jn(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=v(this,yc,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 l(this,yc)}addHighlightArea(){this.container.classList.add("highlightArea")}}yc=new WeakMap;class KC extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,_c,null)}render(){this.container.classList.add("circleAnnotation");const e=this.data,{width:s,height:i}=Jn(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,o=v(this,_c,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 l(this,_c)}addHighlightArea(){this.container.classList.add("highlightArea")}}_c=new WeakMap;class Sb extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,wc,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}=Jn(e),h=this.svgFactory.create(r,o,!0);let c=[];for(let d=0,f=s.length;d<f;d+=2){const g=s[d]-e[0],p=e[3]-s[d+1];c.push(`${g},${p}`)}c=c.join(" ");const u=v(this,wc,this.svgFactory.createElement(this.svgElementName));return u.setAttribute("points",c),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),h.append(u),this.container.append(h),!n&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return l(this,wc)}addHighlightArea(){this.container.classList.add("highlightArea")}}wc=new WeakMap;class JC extends Sb{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class QC extends Kt{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 np extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,Sc);_(this,xc,null);_(this,No,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?at.HIGHLIGHT:at.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,rotation:s,inkLists:i,borderStyle:n,popupRef:r}}=this,{transform:o,width:h,height:c}=w(this,Sc,em).call(this,s,e),u=this.svgFactory.create(h,c,!0),d=v(this,xc,this.svgFactory.createElement("svg:g"));u.append(d),d.setAttribute("stroke-width",n.width||1),d.setAttribute("stroke-linecap","round"),d.setAttribute("stroke-linejoin","round"),d.setAttribute("stroke-miterlimit",10),d.setAttribute("stroke","transparent"),d.setAttribute("fill","transparent"),d.setAttribute("transform",o);for(let f=0,g=i.length;f<g;f++){const p=this.svgFactory.createElement(this.svgElementName);l(this,No).push(p),p.setAttribute("points",i[f].join(",")),d.append(p)}return!r&&this.hasPopupData&&this._createPopup(),this.container.append(u),this._editOnDoubleClick(),this.container}updateEdited(e){super.updateEdited(e);const{thickness:s,points:i,rect:n}=e,r=l(this,xc);if(s>=0&&r.setAttribute("stroke-width",s||1),i)for(let o=0,h=l(this,No).length;o<h;o++)l(this,No)[o].setAttribute("points",i[o].join(","));if(n){const{transform:o,width:h,height:c}=w(this,Sc,em).call(this,this.data.rotation,n);r.parentElement.setAttribute("viewBox",`0 0 ${h} ${c}`),r.setAttribute("transform",o)}}getElementsToTriggerPopup(){return l(this,No)}addHighlightArea(){this.container.classList.add("highlightArea")}}xc=new WeakMap,No=new WeakMap,Sc=new WeakSet,em=function(e,s){switch(e){case 90:return{transform:`rotate(90) translate(${-s[0]},${s[1]}) scale(1,-1)`,width:s[3]-s[1],height:s[2]-s[0]};case 180:return{transform:`rotate(180) translate(${-s[2]},${s[1]}) scale(1,-1)`,width:s[2]-s[0],height:s[3]-s[1]};case 270:return{transform:`rotate(270) translate(${-s[2]},${s[3]}) scale(1,-1)`,width:s[3]-s[1],height:s[2]-s[0]};default:return{transform:`translate(${-s[0]},${s[3]}) scale(1,-1)`,width:s[2]-s[0],height:s[3]-s[1]}}};class Cb extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=at.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class ZC extends Kt{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 tA extends Kt{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 eA extends Kt{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 Ab extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=at.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 sA extends Kt{constructor(e){var i;super(e,{isRenderable:!0});_(this,Ac);_(this,Cc,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",w(this,Ac,sm).bind(this)),v(this,Cc,i);const{isMac:n}=Ue.platform;return e.addEventListener("keydown",r=>{r.key==="Enter"&&(n?r.metaKey:r.ctrlKey)&&w(this,Ac,sm).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),e.append(i),e}getElementsToTriggerPopup(){return l(this,Cc)}addHighlightArea(){this.container.classList.add("highlightArea")}}Cc=new WeakMap,Ac=new WeakSet,sm=function(){var e;(e=this.downloadManager)==null||e.openOrDownloadData(this.content,this.filename)};class iA{constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){_(this,zo);_(this,Tc,null);_(this,Bo,null);_(this,Ho,new Map);_(this,Ec,null);this.div=t,v(this,Tc,e),v(this,Bo,s),v(this,Ec,o||null),this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return l(this,Ho).size>0}async render(t){var r;const{annotations:e}=t,s=this.div;$r(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 sp,annotationStorage:t.annotationStorage||new Yg,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===le.POPUP;if(h){const d=i.get(o.id);if(!d)continue;n.elements=d}else{const{width:d,height:f}=Jn(o.rect);if(d<=0||f<=0)continue}n.data=o;const c=HC.create(n);if(!c.isRenderable)continue;if(!h&&o.popupRef){const d=i.get(o.popupRef);d?d.push(c):i.set(o.popupRef,[c])}const u=c.render();o.hidden&&(u.style.visibility="hidden"),await w(this,zo,By).call(this,u,o.id),c._isEditable&&(l(this,Ho).set(c.data.id,c),(r=this._annotationEditorUIManager)==null||r.renderAnnotationElement(c))}w(this,zo,im).call(this)}update({viewport:t}){const e=this.div;this.viewport=t,$r(e,{rotation:t.rotation}),w(this,zo,im).call(this),e.hidden=!1}getEditableAnnotations(){return Array.from(l(this,Ho).values())}getEditableAnnotation(t){return l(this,Ho).get(t)}}Tc=new WeakMap,Bo=new WeakMap,Ho=new WeakMap,Ec=new WeakMap,zo=new WeakSet,By=async function(t,e){var r,o;const s=t.firstChild||t,i=s.id=`${jg}${e}`,n=await((r=l(this,Ec))==null?void 0:r.getAriaAttributes(i));if(n)for(const[h,c]of n)s.setAttribute(h,c);this.div.append(t),(o=l(this,Tc))==null||o.moveElementInDOM(this.div,t,s,!1)},im=function(){if(!l(this,Bo))return;const t=this.div;for(const[e,s]of l(this,Bo)){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)}l(this,Bo).clear()};const Td=/\r\n?|\n/g,Ot=class Ot extends Vt{constructor(e){super({...e,name:"freeTextEditor"});_(this,re);_(this,di);_(this,As,"");_(this,kc,`${this.id}-editor`);_(this,Vo,null);_(this,Ts);v(this,di,e.color||Ot._defaultColor||Vt._defaultLineColor),v(this,Ts,e.fontSize||Ot._defaultFontSize)}static get _keyboardManager(){const e=Ot.prototype,s=r=>r.isEmpty(),i=qr.TRANSLATE_SMALL,n=qr.TRANSLATE_BIG;return ct(this,"_keyboardManager",new pl([[["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){Vt.initialize(e,s);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,s){switch(e){case gt.FREETEXT_SIZE:Ot._defaultFontSize=s;break;case gt.FREETEXT_COLOR:Ot._defaultColor=s;break}}updateParams(e,s){switch(e){case gt.FREETEXT_SIZE:w(this,re,Hy).call(this,s);break;case gt.FREETEXT_COLOR:w(this,re,zy).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[gt.FREETEXT_SIZE,Ot._defaultFontSize],[gt.FREETEXT_COLOR,Ot._defaultColor||Vt._defaultLineColor]]}get propertiesToUpdate(){return[[gt.FREETEXT_SIZE,l(this,Ts)],[gt.FREETEXT_COLOR,l(this,di)]]}_translateEmpty(e,s){this._uiManager.translateSelectedEditors(e,s,!0)}getInitialTranslation(){const e=this.parentScale;return[-Ot._internalPadding*e,-(Ot._internalPadding+l(this,Ts))*e]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(at.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),v(this,Vo,new AbortController);const e=this._uiManager.combinedSignal(l(this,Vo));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",l(this,kc)),this._isDraggable=!0,(e=l(this,Vo))==null||e.abort(),v(this,Vo,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(e){var s;this.width||(this.enableEditMode(),e&&this.editorDiv.focus(),(s=this._initialOptions)!=null&&s.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=l(this,As),s=v(this,As,w(this,re,Vy).call(this).trimEnd());if(e===s)return;const i=n=>{if(v(this,As,n),!n){this.remove();return}w(this,re,_f).call(this),this._uiManager.rebuild(this),w(this,re,bf).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(e)},mustExec:!1}),w(this,re,bf).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){Ot._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",l(this,kc)),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(${l(this,Ts)}px * var(--scale-factor))`,i.color=l(this,di),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),bd(this,this.div,["dblclick","keydown"]),this.width){const[n,r]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[h,c]=this.getInitialTranslation();[h,c]=this.pageTranslationToScreen(h,c);const[u,d]=this.pageDimensions,[f,g]=this.pageTranslation;let p,m;switch(this.rotation){case 0:p=e+(o[0]-f)/u,m=s+this.height-(o[1]-g)/d;break;case 90:p=e+(o[0]-f)/u,m=s-(o[1]-g)/d,[h,c]=[c,-h];break;case 180:p=e-this.width+(o[0]-f)/u,m=s-(o[1]-g)/d,[h,c]=[-h,-c];break;case 270:p=e+(o[0]-f-this.height*d)/u,m=s+(o[1]-g-this.width*u)/d,[h,c]=[-c,h];break}this.setAt(p*n,m*r,h,c)}else this.setAt(e*n,s*r,this.width*n,this.height*r);w(this,re,_f).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,y;const s=e.clipboardData||window.clipboardData,{types:i}=s;if(i.length===1&&i[0]==="text/plain")return;e.preventDefault();const n=w(p=Ot,On,nm).call(p,s.getData("text")||"").replaceAll(Td,`
537
- `);if(!n)return;const r=window.getSelection();if(!r.rangeCount)return;this.editorDiv.normalize(),r.deleteFromDocument();const o=r.getRangeAt(0);if(!n.includes(`
538
- `)){o.insertNode(document.createTextNode(n)),this.editorDiv.normalize(),r.collapseToStart();return}const{startContainer:h,startOffset:c}=o,u=[],d=[];if(h.nodeType===Node.TEXT_NODE){const b=h.parentElement;if(d.push(h.nodeValue.slice(c).replaceAll(Td,"")),b!==this.editorDiv){let x=u;for(const C of this.editorDiv.childNodes){if(C===b){x=d;continue}x.push(w(m=Ot,On,yf).call(m,C))}}u.push(h.nodeValue.slice(0,c).replaceAll(Td,""))}else if(h===this.editorDiv){let b=u,x=0;for(const C of this.editorDiv.childNodes)x++===c&&(b=d),b.push(w(y=Ot,On,yf).call(y,C))}v(this,As,`${u.join(`
539
- `)}${n}${d.join(`
540
- `)}`),w(this,re,_f).call(this);const f=new Range;let g=u.reduce((b,x)=>b+x.length,0);for(const{firstChild:b}of this.editorDiv.childNodes)if(b.nodeType===Node.TEXT_NODE){const x=b.nodeValue.length;if(g<=x){f.setStart(b,g),f.setEnd(b,g);break}g-=x}r.removeAllRanges(),r.addRange(f)}get contentDiv(){return this.editorDiv}static async deserialize(e,s,i){var o;let n=null;if(e instanceof xb){const{data:{defaultAppearanceData:{fontSize:h,fontColor:c},rect:u,rotation:d,id:f,popupRef:g},textContent:p,textPosition:m,parent:{page:{pageNumber:y}}}=e;if(!p||p.length===0)return null;n=e={annotationType:at.FREETEXT,color:Array.from(c),fontSize:h,value:p.join(`
541
- `),position:m,pageIndex:y-1,rect:u.slice(0),rotation:d,id:f,deleted:!1,popupRef:g}}const r=await super.deserialize(e,s,i);return v(r,Ts,e.fontSize),v(r,di,q.makeHexColor(...e.color)),v(r,As,w(o=Ot,On,nm).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=Ot._internalPadding*this.parentScale,i=this.getRect(s,s),n=Vt._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:l(this,di)),r={annotationType:at.FREETEXT,color:n,fontSize:l(this,Ts),value:w(this,re,Gy).call(this),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?r:this.annotationElementId&&!w(this,re,Wy).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(${l(this,Ts)}px * var(--scale-factor))`,i.color=l(this,di),s.replaceChildren();for(const r of l(this,As).split(`
542
- `)){const o=document.createElement("div");o.append(r?document.createTextNode(r):document.createElement("br")),s.append(o)}const n=Ot._internalPadding*this.parentScale;return e.updateEdited({rect:this.getRect(n,n),popupContent:l(this,As)}),s}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}};di=new WeakMap,As=new WeakMap,kc=new WeakMap,Vo=new WeakMap,Ts=new WeakMap,re=new WeakSet,Hy=function(e){const s=n=>{this.editorDiv.style.fontSize=`calc(${n}px * var(--scale-factor))`,this.translate(0,-(n-l(this,Ts))*this.parentScale),v(this,Ts,n),w(this,re,bf).call(this)},i=l(this,Ts);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:gt.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},zy=function(e){const s=n=>{v(this,di,this.editorDiv.style.color=n)},i=l(this,di);this.addCommands({cmd:s.bind(this,e),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:gt.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Vy=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(w(i=Ot,On,yf).call(i,n)),s=n);return e.join(`
543
- `)},bf=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()},On=new WeakSet,yf=function(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(Td,"")},_f=function(){if(this.editorDiv.replaceChildren(),!!l(this,As))for(const e of l(this,As).split(`
544
- `)){const s=document.createElement("div");s.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(s)}},Gy=function(){return l(this,As).replaceAll(" "," ")},nm=function(e){return e.replaceAll(" "," ")},Wy=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},_(Ot,On),Q(Ot,"_freeTextDefaultContent",""),Q(Ot,"_internalPadding",0),Q(Ot,"_defaultColor",null),Q(Ot,"_defaultFontSize",10),Q(Ot,"_type","freetext"),Q(Ot,"_editorType",at.FREETEXT);let rp=Ot;class U{toSVGPath(){Pt("Abstract method `toSVGPath` must be implemented.")}get box(){Pt("Abstract getter `box` must be implemented.")}serialize(t,e){Pt("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||(r=new Float32Array(t.length));for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o]*i,r[o+1]=s+t[o+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||(r=new Float32Array(t.length));for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o+1]*i,r[o+1]=s+t[o]*n;return r}static _translate(t,e,s,i){i||(i=new Float32Array(t.length));for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}Q(U,"PRECISION",1e-4);const Dn=class Dn{constructor({x:t,y:e},s,i,n,r,o=0){_(this,de);_(this,Es);_(this,fi,[]);_(this,dh);_(this,fh);_(this,Hi,[]);_(this,ut,new Float32Array(18));_(this,Go);_(this,Wo);_(this,Pc);_(this,Mc);_(this,gh);_(this,ph);_(this,br,[]);v(this,Es,s),v(this,ph,n*i),v(this,fh,r),l(this,ut).set([NaN,NaN,NaN,NaN,t,e],6),v(this,dh,o),v(this,Mc,l(Dn,Oc)*i),v(this,Pc,l(Dn,Ud)*i),v(this,gh,i),l(this,br).push(t,e)}isEmpty(){return isNaN(l(this,ut)[8])}add({x:t,y:e}){var R;v(this,Go,t),v(this,Wo,e);const[s,i,n,r]=l(this,Es);let[o,h,c,u]=l(this,ut).subarray(8,12);const d=t-c,f=e-u,g=Math.hypot(d,f);if(g<l(this,Pc))return!1;const p=g-l(this,Mc),m=p/g,y=m*d,b=m*f;let x=o,C=h;o=c,h=u,c+=y,u+=b,(R=l(this,br))==null||R.push(t,e);const S=-b/p,T=y/p,P=S*l(this,ph),M=T*l(this,ph);return l(this,ut).set(l(this,ut).subarray(2,8),0),l(this,ut).set([c+P,u+M],4),l(this,ut).set(l(this,ut).subarray(14,18),12),l(this,ut).set([c-P,u-M],16),isNaN(l(this,ut)[6])?(l(this,Hi).length===0&&(l(this,ut).set([o+P,h+M],2),l(this,Hi).push(NaN,NaN,NaN,NaN,(o+P-s)/n,(h+M-i)/r),l(this,ut).set([o-P,h-M],14),l(this,fi).push(NaN,NaN,NaN,NaN,(o-P-s)/n,(h-M-i)/r)),l(this,ut).set([x,C,o,h,c,u],6),!this.isEmpty()):(l(this,ut).set([x,C,o,h,c,u],6),Math.abs(Math.atan2(C-h,x-o)-Math.atan2(b,y))<Math.PI/2?([o,h,c,u]=l(this,ut).subarray(2,6),l(this,Hi).push(NaN,NaN,NaN,NaN,((o+c)/2-s)/n,((h+u)/2-i)/r),[o,h,x,C]=l(this,ut).subarray(14,18),l(this,fi).push(NaN,NaN,NaN,NaN,((x+o)/2-s)/n,((C+h)/2-i)/r),!0):([x,C,o,h,c,u]=l(this,ut).subarray(0,6),l(this,Hi).push(((x+5*o)/6-s)/n,((C+5*h)/6-i)/r,((5*o+c)/6-s)/n,((5*h+u)/6-i)/r,((o+c)/2-s)/n,((h+u)/2-i)/r),[c,u,o,h,x,C]=l(this,ut).subarray(12,18),l(this,fi).push(((x+5*o)/6-s)/n,((C+5*h)/6-i)/r,((5*o+c)/6-s)/n,((5*h+u)/6-i)/r,((o+c)/2-s)/n,((h+u)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=l(this,Hi),e=l(this,fi);if(isNaN(l(this,ut)[6])&&!this.isEmpty())return w(this,de,Xy).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]}`);w(this,de,Yy).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 w(this,de,Uy).call(this,s),s.join(" ")}newFreeDrawOutline(t,e,s,i,n,r){return new Tb(t,e,s,i,n,r)}getOutlines(){var d;const t=l(this,Hi),e=l(this,fi),s=l(this,ut),[i,n,r,o]=l(this,Es),h=new Float32Array((((d=l(this,br))==null?void 0:d.length)??0)+2);for(let f=0,g=h.length-2;f<g;f+=2)h[f]=(l(this,br)[f]-i)/r,h[f+1]=(l(this,br)[f+1]-n)/o;if(h[h.length-2]=(l(this,Go)-i)/r,h[h.length-1]=(l(this,Wo)-n)/o,isNaN(s[6])&&!this.isEmpty())return w(this,de,$y).call(this,h);const c=new Float32Array(l(this,Hi).length+24+l(this,fi).length);let u=t.length;for(let f=0;f<u;f+=2){if(isNaN(t[f])){c[f]=c[f+1]=NaN;continue}c[f]=t[f],c[f+1]=t[f+1]}u=w(this,de,Ky).call(this,c,u);for(let f=e.length-6;f>=6;f-=6)for(let g=0;g<6;g+=2){if(isNaN(e[f+g])){c[u]=c[u+1]=NaN,u+=2;continue}c[u]=e[f+g],c[u+1]=e[f+g+1],u+=2}return w(this,de,qy).call(this,c,u),this.newFreeDrawOutline(c,h,l(this,Es),l(this,gh),l(this,dh),l(this,fh))}};Es=new WeakMap,fi=new WeakMap,dh=new WeakMap,fh=new WeakMap,Hi=new WeakMap,ut=new WeakMap,Go=new WeakMap,Wo=new WeakMap,Pc=new WeakMap,Mc=new WeakMap,gh=new WeakMap,ph=new WeakMap,br=new WeakMap,Oc=new WeakMap,Xd=new WeakMap,Ud=new WeakMap,de=new WeakSet,nu=function(){const t=l(this,ut).subarray(4,6),e=l(this,ut).subarray(16,18),[s,i,n,r]=l(this,Es);return[(l(this,Go)+(t[0]-e[0])/2-s)/n,(l(this,Wo)+(t[1]-e[1])/2-i)/r,(l(this,Go)+(e[0]-t[0])/2-s)/n,(l(this,Wo)+(e[1]-t[1])/2-i)/r]},Xy=function(){const[t,e,s,i]=l(this,Es),[n,r,o,h]=w(this,de,nu).call(this);return`M${(l(this,ut)[2]-t)/s} ${(l(this,ut)[3]-e)/i} L${(l(this,ut)[4]-t)/s} ${(l(this,ut)[5]-e)/i} L${n} ${r} L${o} ${h} L${(l(this,ut)[16]-t)/s} ${(l(this,ut)[17]-e)/i} L${(l(this,ut)[14]-t)/s} ${(l(this,ut)[15]-e)/i} Z`},Uy=function(t){const e=l(this,fi);t.push(`L${e[4]} ${e[5]} Z`)},Yy=function(t){const[e,s,i,n]=l(this,Es),r=l(this,ut).subarray(4,6),o=l(this,ut).subarray(16,18),[h,c,u,d]=w(this,de,nu).call(this);t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${c} L${u} ${d} L${(o[0]-e)/i} ${(o[1]-s)/n}`)},$y=function(t){const e=l(this,ut),[s,i,n,r]=l(this,Es),[o,h,c,u]=w(this,de,nu).call(this),d=new Float32Array(36);return d.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,c,u,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(d,t,l(this,Es),l(this,gh),l(this,dh),l(this,fh))},qy=function(t,e){const s=l(this,fi);return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6},Ky=function(t,e){const s=l(this,ut).subarray(4,6),i=l(this,ut).subarray(16,18),[n,r,o,h]=l(this,Es),[c,u,d,f]=w(this,de,nu).call(this);return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,d,f,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24},_(Dn,Oc,8),_(Dn,Xd,2),_(Dn,Ud,l(Dn,Oc)+l(Dn,Xd));let Ed=Dn;class Tb extends U{constructor(e,s,i,n,r,o){super();_(this,Yd);_(this,mh);_(this,Xo,new Float32Array(4));_(this,Rn);_(this,Dc);_(this,ks);_(this,Rc);_(this,Qt);v(this,Qt,e),v(this,ks,s),v(this,mh,i),v(this,Rc,n),v(this,Rn,r),v(this,Dc,o),this.lastPoint=[NaN,NaN],w(this,Yd,Jy).call(this,o);const[h,c,u,d]=l(this,Xo);for(let f=0,g=e.length;f<g;f+=2)e[f]=(e[f]-h)/u,e[f+1]=(e[f+1]-c)/d;for(let f=0,g=s.length;f<g;f+=2)s[f]=(s[f]-h)/u,s[f+1]=(s[f+1]-c)/d}toSVGPath(){const e=[`M${l(this,Qt)[4]} ${l(this,Qt)[5]}`];for(let s=6,i=l(this,Qt).length;s<i;s+=6){if(isNaN(l(this,Qt)[s])){e.push(`L${l(this,Qt)[s+4]} ${l(this,Qt)[s+5]}`);continue}e.push(`C${l(this,Qt)[s]} ${l(this,Qt)[s+1]} ${l(this,Qt)[s+2]} ${l(this,Qt)[s+3]} ${l(this,Qt)[s+4]} ${l(this,Qt)[s+5]}`)}return e.push("Z"),e.join(" ")}serialize([e,s,i,n],r){const o=i-e,h=n-s;let c,u;switch(r){case 0:c=U._rescale(l(this,Qt),e,n,o,-h),u=U._rescale(l(this,ks),e,n,o,-h);break;case 90:c=U._rescaleAndSwap(l(this,Qt),e,s,o,h),u=U._rescaleAndSwap(l(this,ks),e,s,o,h);break;case 180:c=U._rescale(l(this,Qt),i,s,-o,h),u=U._rescale(l(this,ks),i,s,-o,h);break;case 270:c=U._rescaleAndSwap(l(this,Qt),i,n,-o,-h),u=U._rescaleAndSwap(l(this,ks),i,n,-o,-h);break}return{outline:Array.from(c),points:[Array.from(u)]}}get box(){return l(this,Xo)}newOutliner(e,s,i,n,r,o=0){return new Ed(e,s,i,n,r,o)}getNewOutline(e,s){const[i,n,r,o]=l(this,Xo),[h,c,u,d]=l(this,mh),f=r*u,g=o*d,p=i*u+h,m=n*d+c,y=this.newOutliner({x:l(this,ks)[0]*f+p,y:l(this,ks)[1]*g+m},l(this,mh),l(this,Rc),e,l(this,Dc),s??l(this,Rn));for(let b=2;b<l(this,ks).length;b+=2)y.add({x:l(this,ks)[b]*f+p,y:l(this,ks)[b+1]*g+m});return y.getOutlines()}}mh=new WeakMap,Xo=new WeakMap,Rn=new WeakMap,Dc=new WeakMap,ks=new WeakMap,Rc=new WeakMap,Qt=new WeakMap,Yd=new WeakSet,Jy=function(e){const s=l(this,Qt);let i=s[4],n=s[5],r=i,o=n,h=i,c=n,u=i,d=n;const f=e?Math.max:Math.min;for(let p=6,m=s.length;p<m;p+=6){if(isNaN(s[p]))r=Math.min(r,s[p+4]),o=Math.min(o,s[p+5]),h=Math.max(h,s[p+4]),c=Math.max(c,s[p+5]),d<s[p+5]?(u=s[p+4],d=s[p+5]):d===s[p+5]&&(u=f(u,s[p+4]));else{const y=q.bezierBoundingBox(i,n,...s.slice(p,p+6));r=Math.min(r,y[0]),o=Math.min(o,y[1]),h=Math.max(h,y[2]),c=Math.max(c,y[3]),d<y[3]?(u=y[2],d=y[3]):d===y[3]&&(u=f(u,y[2]))}i=s[p+4],n=s[p+5]}const g=l(this,Xo);g[0]=r-l(this,Rn),g[1]=o-l(this,Rn),g[2]=h-r+2*l(this,Rn),g[3]=c-o+2*l(this,Rn),this.lastPoint=[u,d]};class op{constructor(t,e=0,s=0,i=!0){_(this,qe);_(this,Fc);_(this,Lc);_(this,yr,[]);_(this,gi,[]);let n=1/0,r=-1/0,o=1/0,h=-1/0;const c=10**-4;for(const{x:y,y:b,width:x,height:C}of t){const S=Math.floor((y-e)/c)*c,T=Math.ceil((y+x+e)/c)*c,P=Math.floor((b-e)/c)*c,M=Math.ceil((b+C+e)/c)*c,D=[S,P,M,!0],R=[T,P,M,!1];l(this,yr).push(D,R),n=Math.min(n,S),r=Math.max(r,T),o=Math.min(o,P),h=Math.max(h,M)}const u=r-n+2*s,d=h-o+2*s,f=n-s,g=o-s,p=l(this,yr).at(i?-1:-2),m=[p[0],p[2]];for(const y of l(this,yr)){const[b,x,C]=y;y[0]=(b-f)/u,y[1]=(x-g)/d,y[2]=(C-g)/d}v(this,Fc,new Float32Array([f,g,u,d])),v(this,Lc,m)}getOutlines(){l(this,yr).sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of l(this,yr))e[3]?(t.push(...w(this,qe,rm).call(this,e)),w(this,qe,Zy).call(this,e)):(w(this,qe,t_).call(this,e),t.push(...w(this,qe,rm).call(this,e)));return w(this,qe,Qy).call(this,t)}}Fc=new WeakMap,Lc=new WeakMap,yr=new WeakMap,gi=new WeakMap,qe=new WeakSet,Qy=function(t){const e=[],s=new Set;for(const r of t){const[o,h,c]=r;e.push([o,h,r],[o,c,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],c=e[r+1][2];h.push(c),c.push(h),s.add(h),s.add(c)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,c,u,d]=r;s.delete(r);let f=o,g=h;for(n=[o,c],i.push(n);;){let p;if(s.has(u))p=u;else if(s.has(d))p=d;else break;s.delete(p),[o,h,c,u,d]=p,f!==o&&(n.push(f,g,o,g===h?h:c),f=o),g=g===h?c:h}n.push(f,g)}return new nA(i,l(this,Fc),l(this,Lc))},wf=function(t){const e=l(this,gi);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},Zy=function([,t,e]){const s=w(this,qe,wf).call(this,t);l(this,gi).splice(s,0,[t,e])},t_=function([,t,e]){const s=w(this,qe,wf).call(this,t);for(let i=s;i<l(this,gi).length;i++){const[n,r]=l(this,gi)[i];if(n!==t)break;if(n===t&&r===e){l(this,gi).splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=l(this,gi)[i];if(n!==t)break;if(n===t&&r===e){l(this,gi).splice(i,1);return}}},rm=function(t){const[e,s,i]=t,n=[[e,s,i]],r=w(this,qe,wf).call(this,i);for(let o=0;o<r;o++){const[h,c]=l(this,gi)[o];for(let u=0,d=n.length;u<d;u++){const[,f,g]=n[u];if(!(c<=f||g<=h)){if(f>=h){if(g>c)n[u][1]=c;else{if(d===1)return[];n.splice(u,1),u--,d--}continue}n[u][2]=h,g>c&&n.push([e,c,g])}}}return n};class nA extends U{constructor(e,s,i){super();_(this,Ic);_(this,vh);v(this,vh,e),v(this,Ic,s),this.lastPoint=i}toSVGPath(){const e=[];for(const s of l(this,vh)){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,c=n-s;for(const u of l(this,vh)){const d=new Array(u.length);for(let f=0;f<u.length;f+=2)d[f]=e+u[f]*h,d[f+1]=n-u[f+1]*c;o.push(d)}return o}get box(){return l(this,Ic)}get classNamesForOutlining(){return["highlightOutline"]}}Ic=new WeakMap,vh=new WeakMap;class ap extends Ed{newFreeDrawOutline(t,e,s,i,n,r){return new rA(t,e,s,i,n,r)}}class rA extends Tb{newOutliner(t,e,s,i,n,r=0){return new ap(t,e,s,i,n,r)}}const us=class us{constructor({editor:t=null,uiManager:e=null}){_(this,Et);_(this,pi,null);_(this,Uo,null);_(this,bh);_(this,fe,null);_(this,jc,!1);_(this,yh,!1);_(this,Nc,null);_(this,Bc);_(this,_r,null);_(this,mi,null);_(this,_h);var s;t?(v(this,yh,!1),v(this,_h,gt.HIGHLIGHT_COLOR),v(this,Nc,t)):(v(this,yh,!0),v(this,_h,gt.HIGHLIGHT_DEFAULT_COLOR)),v(this,mi,(t==null?void 0:t._uiManager)||e),v(this,Bc,l(this,mi)._eventBus),v(this,bh,(t==null?void 0:t.color)||((s=l(this,mi))==null?void 0:s.highlightColors.values().next().value)||"#FFFF98"),l(us,Hc)||v(us,Hc,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 ct(this,"_keyboardManager",new pl([[["Escape","mac+Escape"],us.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],us.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],us.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],us.prototype._moveToPrevious],[["Home","mac+Home"],us.prototype._moveToBeginning],[["End","mac+End"],us.prototype._moveToEnd]]))}renderButton(){const t=v(this,pi,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=l(this,mi)._signal;t.addEventListener("click",w(this,Et,la).bind(this),{signal:e}),t.addEventListener("keydown",w(this,Et,hm).bind(this),{signal:e});const s=v(this,Uo,document.createElement("span"));return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=l(this,bh),t.append(s),t}renderMainDropdown(){const t=v(this,fe,w(this,Et,om).call(this));return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}_colorSelectFromKeyboard(t){if(t.target===l(this,pi)){w(this,Et,la).call(this,t);return}const e=t.target.getAttribute("data-color");e&&w(this,Et,am).call(this,e,t)}_moveToNext(t){var e,s;if(!l(this,Et,Or)){w(this,Et,la).call(this,t);return}if(t.target===l(this,pi)){(e=l(this,fe).firstChild)==null||e.focus();return}(s=t.target.nextSibling)==null||s.focus()}_moveToPrevious(t){var e,s;if(t.target===((e=l(this,fe))==null?void 0:e.firstChild)||t.target===l(this,pi)){l(this,Et,Or)&&this._hideDropdownFromKeyboard();return}l(this,Et,Or)||w(this,Et,la).call(this,t),(s=t.target.previousSibling)==null||s.focus()}_moveToBeginning(t){var e;if(!l(this,Et,Or)){w(this,Et,la).call(this,t);return}(e=l(this,fe).firstChild)==null||e.focus()}_moveToEnd(t){var e;if(!l(this,Et,Or)){w(this,Et,la).call(this,t);return}(e=l(this,fe).lastChild)==null||e.focus()}hideDropdown(){var t,e;(t=l(this,fe))==null||t.classList.add("hidden"),(e=l(this,_r))==null||e.abort(),v(this,_r,null)}_hideDropdownFromKeyboard(){var t;if(!l(this,yh)){if(!l(this,Et,Or)){(t=l(this,Nc))==null||t.unselect();return}this.hideDropdown(),l(this,pi).focus({preventScroll:!0,focusVisible:l(this,jc)})}}updateColor(t){if(l(this,Uo)&&(l(this,Uo).style.backgroundColor=t),!l(this,fe))return;const e=l(this,mi).highlightColors.values();for(const s of l(this,fe).children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){var t,e;(t=l(this,pi))==null||t.remove(),v(this,pi,null),v(this,Uo,null),(e=l(this,fe))==null||e.remove(),v(this,fe,null)}};pi=new WeakMap,Uo=new WeakMap,bh=new WeakMap,fe=new WeakMap,jc=new WeakMap,yh=new WeakMap,Nc=new WeakMap,Bc=new WeakMap,_r=new WeakMap,mi=new WeakMap,_h=new WeakMap,Hc=new WeakMap,Et=new WeakSet,om=function(){const t=document.createElement("div"),e=l(this,mi)._signal;t.addEventListener("contextmenu",ni,{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 l(this,mi).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",l(us,Hc)[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===l(this,bh)),n.addEventListener("click",w(this,Et,am).bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",w(this,Et,hm).bind(this),{signal:e}),t},am=function(t,e){e.stopPropagation(),l(this,Bc).dispatch("switchannotationeditorparams",{source:this,type:l(this,_h),value:t})},hm=function(t){us._keyboardManager.exec(this,t)},la=function(t){if(l(this,Et,Or)){this.hideDropdown();return}if(v(this,jc,t.detail===0),l(this,_r)||(v(this,_r,new AbortController),window.addEventListener("pointerdown",w(this,Et,e_).bind(this),{signal:l(this,mi).combinedSignal(l(this,_r))})),l(this,fe)){l(this,fe).classList.remove("hidden");return}const e=v(this,fe,w(this,Et,om).call(this));l(this,pi).append(e)},e_=function(t){var e;(e=l(this,fe))!=null&&e.contains(t.target)||this.hideDropdown()},Or=function(){return l(this,fe)&&!l(this,fe).classList.contains("hidden")},_(us,Hc,null);let kd=us;const yt=class yt extends Vt{constructor(e){super({...e,name:"highlightEditor"});_(this,ot);_(this,wh,null);_(this,zc,0);_(this,Fn);_(this,Yo,null);_(this,xh,null);_(this,ds,null);_(this,Vc,null);_(this,Gc,0);_(this,$o,null);_(this,Vs,null);_(this,Ps,null);_(this,xe,!1);_(this,Sh,null);_(this,Ln);_(this,Ie,null);_(this,Ch,"");_(this,Gs);_(this,Wc,"");this.color=e.color||yt._defaultColor,v(this,Gs,e.thickness||yt._defaultThickness),v(this,Ln,e.opacity||yt._defaultOpacity),v(this,Fn,e.boxes||null),v(this,Wc,e.methodOfCreation||""),v(this,Ch,e.text||""),this._isDraggable=!1,e.highlightId>-1?(v(this,xe,!0),w(this,ot,xf).call(this,e),w(this,ot,ca).call(this)):l(this,Fn)&&(v(this,wh,e.anchorNode),v(this,zc,e.anchorOffset),v(this,Vc,e.focusNode),v(this,Gc,e.focusOffset),w(this,ot,lm).call(this),w(this,ot,ca).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const e=yt.prototype;return ct(this,"_keyboardManager",new pl([[["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:l(this,xe)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:l(this,Gs),methodOfCreation:l(this,Wc)}}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;Vt.initialize(e,s),yt._defaultColor||(yt._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(e,s){switch(e){case gt.HIGHLIGHT_DEFAULT_COLOR:yt._defaultColor=s;break;case gt.HIGHLIGHT_THICKNESS:yt._defaultThickness=s;break}}translateInPage(e,s){}get toolbarPosition(){return l(this,Sh)}updateParams(e,s){switch(e){case gt.HIGHLIGHT_COLOR:w(this,ot,s_).call(this,s);break;case gt.HIGHLIGHT_THICKNESS:w(this,ot,i_).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[gt.HIGHLIGHT_DEFAULT_COLOR,yt._defaultColor],[gt.HIGHLIGHT_THICKNESS,yt._defaultThickness]]}get propertiesToUpdate(){return[[gt.HIGHLIGHT_COLOR,this.color||yt._defaultColor],[gt.HIGHLIGHT_THICKNESS,l(this,Gs)||yt._defaultThickness],[gt.HIGHLIGHT_FREE,l(this,xe)]]}async addEditToolbar(){const e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(v(this,xh,new kd({editor:this})),e.addColorPicker(l(this,xh))),e):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(w(this,ot,ru).call(this))}getBaseTranslation(){return[0,0]}getRect(e,s){return super.getRect(e,s,w(this,ot,ru).call(this))}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),e&&this.div.focus()}remove(){w(this,ot,cm).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(w(this,ot,ca).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?w(this,ot,cm).call(this):e&&(w(this,ot,ca).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;l(this,xe)?(e=(e-this.rotation+360)%360,i=w(n=yt,Ws,Gh).call(n,l(this,Vs).box,e)):i=w(r=yt,Ws,Gh).call(r,[this.x,this.y,this.width,this.height],e),s.updateProperties(l(this,Ps),{bbox:i,root:{"data-main-rotation":e}}),s.updateProperties(l(this,Ie),{bbox:w(o=yt,Ws,Gh).call(o,l(this,ds).box,e),root:{"data-main-rotation":e}})}render(){if(this.div)return this.div;const e=super.render();l(this,Ch)&&(e.setAttribute("aria-label",l(this,Ch)),e.setAttribute("role","mark")),l(this,xe)?e.classList.add("free"):this.div.addEventListener("keydown",w(this,ot,r_).bind(this),{signal:this._uiManager._signal});const s=v(this,$o,document.createElement("div"));e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=l(this,Yo);const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),bd(this,l(this,$o),["pointerover","pointerleave"]),this.enableEditing(),e}pointerover(){var e;this.isSelected||(e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{hovered:!0}})}pointerleave(){var e;this.isSelected||(e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{hovered:!1}})}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:w(this,ot,Sf).call(this,!0);break;case 1:case 3:w(this,ot,Sf).call(this,!1);break}}select(){var e;super.select(),l(this,Ie)&&((e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{hovered:!1,selected:!0}}))}unselect(){var e;super.unselect(),l(this,Ie)&&((e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{selected:!1}}),l(this,xe)||w(this,ot,Sf).call(this,!1))}get _mustFixPosition(){return!l(this,xe)}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.updateProperties(l(this,Ps),{rootClass:{hidden:!e}}),this.parent.drawLayer.updateProperties(l(this,Ie),{rootClass:{hidden:!e}}))}static startHighlighting(e,s,{target:i,x:n,y:r}){const{x:o,y:h,width:c,height:u}=i.getBoundingClientRect(),d=new AbortController,f=e.combinedSignal(d),g=p=>{d.abort(),w(this,Ws,l_).call(this,e,p)};window.addEventListener("blur",g,{signal:f}),window.addEventListener("pointerup",g,{signal:f}),window.addEventListener("pointerdown",bs,{capture:!0,passive:!1,signal:f}),window.addEventListener("contextmenu",ni,{signal:f}),i.addEventListener("pointermove",w(this,Ws,h_).bind(this,e),{signal:f}),this._freeHighlight=new ap({x:n,y:r},[o,h,c,u],e.scale,this._defaultThickness/2,s,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static async deserialize(e,s,i){var m,y,b,x;let n=null;if(e instanceof Cb){const{data:{quadPoints:C,rect:S,rotation:T,id:P,color:M,opacity:D,popupRef:R},parent:{page:{pageNumber:V}}}=e;n=e={annotationType:at.HIGHLIGHT,color:Array.from(M),opacity:D,quadPoints:C,boxes:null,pageIndex:V-1,rect:S.slice(0),rotation:T,id:P,deleted:!1,popupRef:R}}else if(e instanceof np){const{data:{inkLists:C,rect:S,rotation:T,id:P,color:M,borderStyle:{rawWidth:D},popupRef:R},parent:{page:{pageNumber:V}}}=e;n=e={annotationType:at.HIGHLIGHT,color:Array.from(M),thickness:D,inkLists:C,boxes:null,pageIndex:V-1,rect:S.slice(0),rotation:T,id:P,deleted:!1,popupRef:R}}const{color:r,quadPoints:o,inkLists:h,opacity:c}=e,u=await super.deserialize(e,s,i);u.color=q.makeHexColor(...r),v(u,Ln,c||1),h&&v(u,Gs,e.thickness),u.annotationElementId=e.id||null,u._initialData=n;const[d,f]=u.pageDimensions,[g,p]=u.pageTranslation;if(o){const C=v(u,Fn,[]);for(let S=0;S<o.length;S+=8)C.push({x:(o[S]-g)/d,y:1-(o[S+1]-p)/f,width:(o[S+2]-o[S])/d,height:(o[S+1]-o[S+5])/f});w(m=u,ot,lm).call(m),w(y=u,ot,ca).call(y),u.rotate(u.rotation)}else if(h){v(u,xe,!0);const C=h[0],S={x:C[0]-g,y:f-(C[1]-p)},T=new ap(S,[0,0,d,f],1,l(u,Gs)/2,!0,.001);for(let D=0,R=C.length;D<R;D+=2)S.x=C[D]-g,S.y=f-(C[D+1]-p),T.add(S);const{id:P,clipPathId:M}=s.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:u.color,"fill-opacity":u._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:T.toSVGPath()}},!0,!0);w(b=u,ot,xf).call(b,{highlightOutlines:T.getOutlines(),highlightId:P,clipPathId:M}),w(x=u,ot,ca).call(x)}return u}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();const s=this.getRect(0,0),i=Vt._colorManager.convert(this.color),n={annotationType:at.HIGHLIGHT,color:i,opacity:l(this,Ln),thickness:l(this,Gs),quadPoints:w(this,ot,o_).call(this),outlines:w(this,ot,a_).call(this,s),pageIndex:this.pageIndex,rect:s,rotation:w(this,ot,ru).call(this),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!w(this,ot,c_).call(this,n)?null:(n.id=this.annotationElementId,n)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}};wh=new WeakMap,zc=new WeakMap,Fn=new WeakMap,Yo=new WeakMap,xh=new WeakMap,ds=new WeakMap,Vc=new WeakMap,Gc=new WeakMap,$o=new WeakMap,Vs=new WeakMap,Ps=new WeakMap,xe=new WeakMap,Sh=new WeakMap,Ln=new WeakMap,Ie=new WeakMap,Ch=new WeakMap,Gs=new WeakMap,Wc=new WeakMap,ot=new WeakSet,lm=function(){const e=new op(l(this,Fn),.001);v(this,Vs,e.getOutlines()),[this.x,this.y,this.width,this.height]=l(this,Vs).box;const s=new op(l(this,Fn),.0025,.001,this._uiManager.direction==="ltr");v(this,ds,s.getOutlines());const{lastPoint:i}=l(this,ds);v(this,Sh,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height])},xf=function({highlightOutlines:e,highlightId:s,clipPathId:i}){var d,f;if(v(this,Vs,e),v(this,ds,e.getNewOutline(l(this,Gs)/2+1.5,.0025)),s>=0)v(this,Ps,s),v(this,Yo,i),this.parent.drawLayer.finalizeDraw(s,{bbox:e.box,path:{d:e.toSVGPath()}}),v(this,Ie,this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:l(this,ds).box,path:{d:l(this,ds).toSVGPath()}},!0));else if(this.parent){const g=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(l(this,Ps),{bbox:w(d=yt,Ws,Gh).call(d,l(this,Vs).box,(g-this.rotation+360)%360),path:{d:e.toSVGPath()}}),this.parent.drawLayer.updateProperties(l(this,Ie),{bbox:w(f=yt,Ws,Gh).call(f,l(this,ds).box,g),path:{d:l(this,ds).toSVGPath()}})}const[r,o,h,c]=e.box;switch(this.rotation){case 0:this.x=r,this.y=o,this.width=h,this.height=c;break;case 90:{const[g,p]=this.parentDimensions;this.x=o,this.y=1-r,this.width=h*p/g,this.height=c*g/p;break}case 180:this.x=1-r,this.y=1-o,this.width=h,this.height=c;break;case 270:{const[g,p]=this.parentDimensions;this.x=1-o,this.y=r,this.width=h*p/g,this.height=c*g/p;break}}const{lastPoint:u}=l(this,ds);v(this,Sh,[(u[0]-r)/h,(u[1]-o)/c])},s_=function(e){const s=(r,o)=>{var h,c;this.color=r,v(this,Ln,o),(h=this.parent)==null||h.drawLayer.updateProperties(l(this,Ps),{root:{fill:r,"fill-opacity":o}}),(c=l(this,xh))==null||c.updateColor(r)},i=this.color,n=l(this,Ln);this.addCommands({cmd:s.bind(this,e,yt._defaultOpacity),undo:s.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:gt.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(e)},!0)},i_=function(e){const s=l(this,Gs),i=n=>{v(this,Gs,n),w(this,ot,n_).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:gt.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:e},!0)},n_=function(e){if(!l(this,xe))return;w(this,ot,xf).call(this,{highlightOutlines:l(this,Vs).getNewOutline(e/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},cm=function(){l(this,Ps)===null||!this.parent||(this.parent.drawLayer.remove(l(this,Ps)),v(this,Ps,null),this.parent.drawLayer.remove(l(this,Ie)),v(this,Ie,null))},ca=function(e=this.parent){l(this,Ps)===null&&({id:es(this,Ps)._,clipPathId:es(this,Yo)._}=e.drawLayer.draw({bbox:l(this,Vs).box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":l(this,Ln)},rootClass:{highlight:!0,free:l(this,xe)},path:{d:l(this,Vs).toSVGPath()}},!1,!0),v(this,Ie,e.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:l(this,xe)},bbox:l(this,ds).box,path:{d:l(this,ds).toSVGPath()}},l(this,xe))),l(this,$o)&&(l(this,$o).style.clipPath=l(this,Yo)))},Ws=new WeakSet,Gh=function([e,s,i,n],r){switch(r){case 90:return[1-s-n,e,n,i];case 180:return[1-e-i,1-s-n,i,n];case 270:return[s,1-e-i,n,i]}return[e,s,i,n]},r_=function(e){yt._keyboardManager.exec(this,e)},Sf=function(e){if(!l(this,wh))return;const s=window.getSelection();e?s.setPosition(l(this,wh),l(this,zc)):s.setPosition(l(this,Vc),l(this,Gc))},ru=function(){return l(this,xe)?this.rotation:0},o_=function(){if(l(this,xe))return null;const[e,s]=this.pageDimensions,[i,n]=this.pageTranslation,r=l(this,Fn),o=new Float32Array(r.length*8);let h=0;for(const{x:c,y:u,width:d,height:f}of r){const g=c*e+i,p=(1-u)*s+n;o[h]=o[h+4]=g,o[h+1]=o[h+3]=p,o[h+2]=o[h+6]=g+d*e,o[h+5]=o[h+7]=p-f*s,h+=8}return o},a_=function(e){return l(this,Vs).serialize(e,w(this,ot,ru).call(this))},h_=function(e,s){this._freeHighlight.add(s)&&e.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})},l_=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=""},c_=function(e){const{color:s}=this._initialData;return e.color.some((i,n)=>i!==s[n])},_(yt,Ws),Q(yt,"_defaultColor",null),Q(yt,"_defaultOpacity",1),Q(yt,"_defaultThickness",12),Q(yt,"_type","highlight"),Q(yt,"_editorType",at.HIGHLIGHT),Q(yt,"_freeHighlightId",-1),Q(yt,"_freeHighlight",null),Q(yt,"_freeHighlightClipId","");let Pd=yt;class oA{constructor(){_(this,qo,Object.create(null))}updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){l(this,qo)[t]=e}toSVGProperties(){const t=l(this,qo);return v(this,qo,Object.create(null)),{root:t}}reset(){v(this,qo,Object.create(null))}updateAll(t=this){this.updateProperties(t)}clone(){Pt("Not implemented")}}qo=new WeakMap;const Y=class Y extends Vt{constructor(e){super(e);_(this,vt);_(this,Ms,null);_(this,Ah);Q(this,"_drawId",null);v(this,Ah,e.mustBeCommitted||!1),e.drawOutlines&&(w(this,vt,um).call(this,e),w(this,vt,ou).call(this))}static _mergeSVGProperties(e,s){const i=new Set(Object.keys(e));for(const[n,r]of Object.entries(s))i.has(n)?Object.assign(e[n],r):e[n]=r;return e}static getDefaultDrawingOptions(e){Pt("Not implemented")}static get typesMap(){Pt("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(e,s){const i=this.typesMap.get(e);i&&this._defaultDrawingOptions.updateProperty(i,s),this._currentParent&&(l(Y,ve).updateProperty(i,s),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(e,s){const i=this.constructor.typesMap.get(e);i&&this._updateProperty(e,i,s)}static get defaultPropertiesToUpdate(){const e=[],s=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)e.push([i,s[n]]);return e}get propertiesToUpdate(){const e=[],{_drawingOptions:s}=this;for(const[i,n]of this.constructor.typesMap)e.push([i,s[n]]);return e}_updateProperty(e,s,i){const n=this._drawingOptions,r=n[s],o=h=>{var u;n.updateProperty(s,h);const c=l(this,Ms).updateProperty(s,h);c&&w(this,vt,au).call(this,c),(u=this.parent)==null||u.drawLayer.updateProperties(this._drawId,n.toSVGProperties())};this.addCommands({cmd:o.bind(this,i),undo:o.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties(l(this,Ms).getPathResizingSVGProperties(w(this,vt,Cf).call(this)),{bbox:w(this,vt,Wh).call(this)}))}_onResized(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties(l(this,Ms).getPathResizedSVGProperties(w(this,vt,Cf).call(this)),{bbox:w(this,vt,Wh).call(this)}))}_onTranslating(e,s){var i;(i=this.parent)==null||i.drawLayer.updateProperties(this._drawId,{bbox:w(this,vt,Wh).call(this,e,s)})}_onTranslated(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties(l(this,Ms).getPathTranslatedSVGProperties(w(this,vt,Cf).call(this),this.parentDimensions),{bbox:w(this,vt,Wh).call(this)}))}_onStartDragging(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,l(this,Ah)&&(v(this,Ah,!1),this.commit(),this.parent.setSelected(this),e&&this.isOnScreen&&this.div.focus())}remove(){w(this,vt,fm).call(this),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(w(this,vt,ou).call(this),w(this,vt,au).call(this,l(this,Ms).box),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?(this._uiManager.removeShouldRescale(this),w(this,vt,fm).call(this)):e&&(this._uiManager.addShouldRescale(this),w(this,vt,ou).call(this,e),s=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(e),s&&this.select()}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties({bbox:w(this,vt,Wh).call(this)},l(this,Ms).updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&w(this,vt,au).call(this,l(this,Ms).updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const e=super.render();e.classList.add("draw");const s=document.createElement("div");e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal";const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),this._uiManager.addShouldRescale(this),this.disableEditing(),e}static createDrawerInstance(e,s,i,n,r){Pt("Not implemented")}static startDrawing(e,s,i,n){var y;const{target:r,offsetX:o,offsetY:h,pointerId:c,pointerType:u}=n;if(l(Y,xr)&&l(Y,xr)!==u)return;const{viewport:{rotation:d}}=e,{width:f,height:g}=r.getBoundingClientRect(),p=v(Y,Ko,new AbortController),m=e.combinedSignal(p);if(l(Y,wr)||v(Y,wr,c),l(Y,xr)??v(Y,xr,u),window.addEventListener("pointerup",b=>{var x;l(Y,wr)===b.pointerId?this._endDraw(b):(x=l(Y,Sr))==null||x.delete(b.pointerId)},{signal:m}),window.addEventListener("pointercancel",b=>{var x;l(Y,wr)===b.pointerId?this._currentParent.endDrawingSession():(x=l(Y,Sr))==null||x.delete(b.pointerId)},{signal:m}),window.addEventListener("pointerdown",b=>{l(Y,xr)===b.pointerType&&((l(Y,Sr)||v(Y,Sr,new Set)).add(b.pointerId),l(Y,ve).isCancellable()&&(l(Y,ve).removeLastElement(),l(Y,ve).isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",ni,{signal:m}),r.addEventListener("pointermove",this._drawMove.bind(this),{signal:m}),r.addEventListener("touchmove",b=>{b.timeStamp===l(Y,Qo)&&bs(b)},{signal:m}),e.toggleDrawing(),(y=s._editorUndoBar)==null||y.hide(),l(Y,ve)){e.drawLayer.updateProperties(this._currentDrawId,l(Y,ve).startNew(o,h,f,g,d));return}s.updateUIForDefaultProperties(this),v(Y,ve,this.createDrawerInstance(o,h,f,g,d)),v(Y,Jo,this.getDefaultDrawingOptions()),this._currentParent=e,{id:this._currentDrawId}=e.drawLayer.draw(this._mergeSVGProperties(l(Y,Jo).toSVGProperties(),l(Y,ve).defaultSVGProperties),!0,!1)}static _drawMove(e){var r;if(v(Y,Qo,-1),!l(Y,ve))return;const{offsetX:s,offsetY:i,pointerId:n}=e;if(l(Y,wr)===n){if(((r=l(Y,Sr))==null?void 0:r.size)>=1){this._endDraw(e);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,l(Y,ve).add(s,i)),v(Y,Qo,e.timeStamp),bs(e)}}static _cleanup(e){e&&(this._currentDrawId=-1,this._currentParent=null,v(Y,ve,null),v(Y,Jo,null),v(Y,xr,null),v(Y,Qo,NaN)),l(Y,Ko)&&(l(Y,Ko).abort(),v(Y,Ko,null),v(Y,wr,NaN),v(Y,Sr,null))}static _endDraw(e){const s=this._currentParent;if(s){if(s.toggleDrawing(!0),this._cleanup(!1),e&&s.drawLayer.updateProperties(this._currentDrawId,l(Y,ve).end(e.offsetX,e.offsetY)),this.supportMultipleDrawings){const i=l(Y,ve),n=this._currentDrawId,r=i.getLastElement();s.addCommands({cmd:()=>{s.drawLayer.updateProperties(n,i.setLastElement(r))},undo:()=>{s.drawLayer.updateProperties(n,i.removeLastElement())},mustExec:!1,type:gt.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(e){const s=this._currentParent;if(!s)return null;if(s.toggleDrawing(!0),s.cleanUndoStack(gt.DRAW_STEP),!l(Y,ve).isEmpty()){const{pageDimensions:[i,n],scale:r}=s,o=s.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:l(Y,ve).getOutlines(i*r,n*r,r,this._INNER_MARGIN),drawingOptions:l(Y,Jo),mustBeCommitted:!e});return this._cleanup(!0),o}return s.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,s,i,n,r,o){Pt("Not implemented")}static async deserialize(e,s,i){var d,f;const{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}=s.viewport,c=this.deserializeDraw(o,h,n,r,this._INNER_MARGIN,e),u=await super.deserialize(e,s,i);return u.createDrawingOptions(e),w(d=u,vt,um).call(d,{drawOutlines:c}),w(f=u,vt,ou).call(f),u.onScaleChanging(),u.rotate(),u}serializeDraw(e){const[s,i]=this.pageTranslation,[n,r]=this.pageDimensions;return l(this,Ms).serialize([s,i,n,r],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}};Ms=new WeakMap,Ah=new WeakMap,ve=new WeakMap,Ko=new WeakMap,Jo=new WeakMap,wr=new WeakMap,xr=new WeakMap,Sr=new WeakMap,Qo=new WeakMap,vt=new WeakSet,um=function({drawOutlines:e,drawId:s,drawingOptions:i}){v(this,Ms,e),this._drawingOptions||(this._drawingOptions=i),s>=0?(this._drawId=s,this.parent.drawLayer.finalizeDraw(s,e.defaultProperties)):this._drawId=w(this,vt,dm).call(this,e,this.parent),w(this,vt,au).call(this,e.box)},dm=function(e,s){const{id:i}=s.drawLayer.draw(Y._mergeSVGProperties(this._drawingOptions.toSVGProperties(),e.defaultSVGProperties),!1,!1);return i},fm=function(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())},ou=function(e=this.parent){if(!(this._drawId!==null&&this.parent===e)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,e.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=w(this,vt,dm).call(this,l(this,Ms),e)}},u_=function([e,s,i,n]){const{parentDimensions:[r,o],rotation:h}=this;switch(h){case 90:return[s,1-e,i*(o/r),n*(r/o)];case 180:return[1-e,1-s,i,n];case 270:return[1-s,e,i*(o/r),n*(r/o)];default:return[e,s,i,n]}},Cf=function(){const{x:e,y:s,width:i,height:n,parentDimensions:[r,o],rotation:h}=this;switch(h){case 90:return[1-s,e,i*(r/o),n*(o/r)];case 180:return[1-e,1-s,i,n];case 270:return[s,1-e,i*(r/o),n*(o/r)];default:return[e,s,i,n]}},au=function(e){if([this.x,this.y,this.width,this.height]=w(this,vt,u_).call(this,e),this.div){this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)}this._onResized()},Wh=function(){const{x:e,y:s,width:i,height:n,rotation:r,parentRotation:o,parentDimensions:[h,c]}=this;switch((r*4+o)/90){case 1:return[1-s-n,e,n,i];case 2:return[1-e-i,1-s-n,i,n];case 3:return[s,1-e-i,n,i];case 4:return[e,s-i*(h/c),n*(c/h),i*(h/c)];case 5:return[1-s,e,i*(h/c),n*(c/h)];case 6:return[1-e-n*(c/h),1-s,n*(c/h),i*(h/c)];case 7:return[s-i*(h/c),1-e-n*(c/h),i*(h/c),n*(c/h)];case 8:return[e-i,s-n,i,n];case 9:return[1-s,e-i,n,i];case 10:return[1-e,1-s,i,n];case 11:return[s-n,1-e,n,i];case 12:return[e-n*(c/h),s,n*(c/h),i*(h/c)];case 13:return[1-s-i*(h/c),e-n*(c/h),i*(h/c),n*(c/h)];case 14:return[1-e,1-s-i*(h/c),n*(c/h),i*(h/c)];case 15:return[s,1-e,i*(h/c),n*(c/h)];default:return[e,s,i,n]}},Q(Y,"_currentDrawId",-1),Q(Y,"_currentParent",null),_(Y,ve,null),_(Y,Ko,null),_(Y,Jo,null),_(Y,wr,NaN),_(Y,xr,null),_(Y,Sr,null),_(Y,Qo,NaN),Q(Y,"_INNER_MARGIN",3);let hp=Y;class aA{constructor(t,e,s,i,n,r){_(this,Eh);_(this,zi,new Float64Array(6));_(this,be);_(this,ye);_(this,Zo);_(this,Th);_(this,Ke);_(this,Se,"");_(this,Xs,0);_(this,ta,new Md);_(this,ea);_(this,sa);v(this,ea,s),v(this,sa,i),v(this,Zo,n),v(this,Th,r),[t,e]=w(this,Eh,Af).call(this,t,e);const o=v(this,be,[NaN,NaN,NaN,NaN,t,e]);v(this,Ke,[t,e]),v(this,ye,[{line:o,points:l(this,Ke)}]),l(this,zi).set(o,0)}updateProperty(t,e){t==="stroke-width"&&v(this,Th,e)}isEmpty(){return!l(this,ye)||l(this,ye).length===0}isCancellable(){return l(this,Ke).length<=10}add(t,e){[t,e]=w(this,Eh,Af).call(this,t,e);const[s,i,n,r]=l(this,zi).subarray(2,6),o=t-n,h=e-r;return Math.hypot(l(this,ea)*o,l(this,sa)*h)<=2?null:(l(this,Ke).push(t,e),isNaN(s)?(l(this,zi).set([n,r,t,e],2),l(this,be).push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(l(this,zi)[0])&&l(this,be).splice(6,6),l(this,zi).set([s,i,n,r,t,e],0),l(this,be).push(...U.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(l(this,Ke).length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){v(this,ea,s),v(this,sa,i),v(this,Zo,n),[t,e]=w(this,Eh,Af).call(this,t,e);const r=v(this,be,[NaN,NaN,NaN,NaN,t,e]);v(this,Ke,[t,e]);const o=l(this,ye).at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),l(this,ye).push({line:r,points:l(this,Ke)}),l(this,zi).set(r,0),v(this,Xs,0),this.toSVGPath(),null}getLastElement(){return l(this,ye).at(-1)}setLastElement(t){return l(this,ye)?(l(this,ye).push(t),v(this,be,t.line),v(this,Ke,t.points),v(this,Xs,0),{path:{d:this.toSVGPath()}}):l(this,ta).setLastElement(t)}removeLastElement(){if(!l(this,ye))return l(this,ta).removeLastElement();l(this,ye).pop(),v(this,Se,"");for(let t=0,e=l(this,ye).length;t<e;t++){const{line:s,points:i}=l(this,ye)[t];v(this,be,s),v(this,Ke,i),v(this,Xs,0),this.toSVGPath()}return{path:{d:l(this,Se)}}}toSVGPath(){const t=U.svgRound(l(this,be)[4]),e=U.svgRound(l(this,be)[5]);if(l(this,Ke).length===2)return v(this,Se,`${l(this,Se)} M ${t} ${e} Z`),l(this,Se);if(l(this,Ke).length<=6){const i=l(this,Se).lastIndexOf("M");v(this,Se,`${l(this,Se).slice(0,i)} M ${t} ${e}`),v(this,Xs,6)}if(l(this,Ke).length===4){const i=U.svgRound(l(this,be)[10]),n=U.svgRound(l(this,be)[11]);return v(this,Se,`${l(this,Se)} L ${i} ${n}`),v(this,Xs,12),l(this,Se)}const s=[];l(this,Xs)===0&&(s.push(`M ${t} ${e}`),v(this,Xs,6));for(let i=l(this,Xs),n=l(this,be).length;i<n;i+=6){const[r,o,h,c,u,d]=l(this,be).slice(i,i+6).map(U.svgRound);s.push(`C${r} ${o} ${h} ${c} ${u} ${d}`)}return v(this,Se,l(this,Se)+s.join(" ")),v(this,Xs,l(this,be).length),l(this,Se)}getOutlines(t,e,s,i){const n=l(this,ye).at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),l(this,ta).build(l(this,ye),t,e,s,l(this,Zo),l(this,Th),i),v(this,zi,null),v(this,be,null),v(this,ye,null),v(this,Se,null),l(this,ta)}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}zi=new WeakMap,be=new WeakMap,ye=new WeakMap,Zo=new WeakMap,Th=new WeakMap,Ke=new WeakMap,Se=new WeakMap,Xs=new WeakMap,ta=new WeakMap,ea=new WeakMap,sa=new WeakMap,Eh=new WeakSet,Af=function(t,e){return U._normalizePoint(t,e,l(this,ea),l(this,sa),l(this,Zo))};const yp=class yp extends U{constructor(){super(...arguments);_(this,Ce);_(this,Je);_(this,Xc,0);_(this,Uc);_(this,Os);_(this,Vi);_(this,Gi);_(this,kh);_(this,Ph);_(this,Mh)}build(e,s,i,n,r,o,h){v(this,Vi,s),v(this,Gi,i),v(this,kh,n),v(this,Ph,r),v(this,Mh,o),v(this,Uc,h??0),v(this,Os,e),w(this,Ce,f_).call(this)}setLastElement(e){return l(this,Os).push(e),{path:{d:this.toSVGPath()}}}removeLastElement(){return l(this,Os).pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const e=[];for(const{line:s}of l(this,Os)){if(e.push(`M${U.svgRound(s[4])} ${U.svgRound(s[5])}`),s.length===6){e.push("Z");continue}if(s.length===12){e.push(`L${U.svgRound(s[10])} ${U.svgRound(s[11])}`);continue}for(let i=6,n=s.length;i<n;i+=6){const[r,o,h,c,u,d]=s.subarray(i,i+6).map(U.svgRound);e.push(`C${r} ${o} ${h} ${c} ${u} ${d}`)}}return e.join("")}serialize([e,s,i,n],r){const o=[],h=[],[c,u,d,f]=w(this,Ce,d_).call(this);let g,p,m,y,b,x,C,S,T;switch(l(this,Ph)){case 0:T=U._rescale,g=e,p=s+n,m=i,y=-n,b=e+c*i,x=s+(1-u-f)*n,C=e+(c+d)*i,S=s+(1-u)*n;break;case 90:T=U._rescaleAndSwap,g=e,p=s,m=i,y=n,b=e+u*i,x=s+c*n,C=e+(u+f)*i,S=s+(c+d)*n;break;case 180:T=U._rescale,g=e+i,p=s,m=-i,y=n,b=e+(1-c-d)*i,x=s+u*n,C=e+(1-c)*i,S=s+(u+f)*n;break;case 270:T=U._rescaleAndSwap,g=e+i,p=s+n,m=-i,y=-n,b=e+(1-u-f)*i,x=s+(1-c-d)*n,C=e+(1-u)*i,S=s+(1-c)*n;break}for(const{line:P,points:M}of l(this,Os))o.push(T(P,g,p,m,y,r?new Array(P.length):null)),h.push(T(M,g,p,m,y,r?new Array(M.length):null));return{lines:o,points:h,rect:[b,x,C,S]}}static deserialize(e,s,i,n,r,{paths:{lines:o,points:h},rotation:c,thickness:u}){const d=[];let f,g,p,m,y;switch(c){case 0:y=U._rescale,f=-e/i,g=s/n+1,p=1/i,m=-1/n;break;case 90:y=U._rescaleAndSwap,f=-s/n,g=-e/i,p=1/n,m=1/i;break;case 180:y=U._rescale,f=e/i+1,g=-s/n,p=-1/i,m=1/n;break;case 270:y=U._rescaleAndSwap,f=s/n+1,g=e/i+1,p=-1/n,m=-1/i;break}if(!o){o=[];for(const x of h){const C=x.length;if(C===2){o.push(new Float32Array([NaN,NaN,NaN,NaN,x[0],x[1]]));continue}if(C===4){o.push(new Float32Array([NaN,NaN,NaN,NaN,x[0],x[1],NaN,NaN,NaN,NaN,x[2],x[3]]));continue}const S=new Float32Array(3*(C-2));o.push(S);let[T,P,M,D]=x.subarray(0,4);S.set([NaN,NaN,NaN,NaN,T,P],0);for(let R=4;R<C;R+=2){const V=x[R],H=x[R+1];S.set(U.createBezierPoints(T,P,M,D,V,H),(R-2)*3),[T,P,M,D]=[M,D,V,H]}}}for(let x=0,C=o.length;x<C;x++)d.push({line:y(o[x].map(S=>S??NaN),f,g,p,m),points:y(h[x].map(S=>S??NaN),f,g,p,m)});const b=new yp;return b.build(d,i,n,1,c,u,r),b}get box(){return l(this,Je)}updateProperty(e,s){return e==="stroke-width"?w(this,Ce,g_).call(this,s):null}updateParentDimensions([e,s],i){const[n,r]=w(this,Ce,zn).call(this);v(this,Vi,e),v(this,Gi,s),v(this,kh,i);const[o,h]=w(this,Ce,zn).call(this),c=o-n,u=h-r,d=l(this,Je);return d[0]-=c,d[1]-=u,d[2]+=2*c,d[3]+=2*u,d}updateRotation(e){return v(this,Xc,e),{path:{transform:this.rotationTransform}}}get viewBox(){return l(this,Je).map(U.svgRound).join(" ")}get defaultProperties(){const[e,s]=l(this,Je);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`}}}get rotationTransform(){const[,,e,s]=l(this,Je);let i=0,n=0,r=0,o=0,h=0,c=0;switch(l(this,Xc)){case 90:n=s/e,r=-e/s,h=e;break;case 180:i=-1,o=-1,h=e,c=s;break;case 270:n=-s/e,r=e/s,c=s;break;default:return""}return`matrix(${i} ${n} ${r} ${o} ${U.svgRound(h)} ${U.svgRound(c)})`}getPathResizingSVGProperties([e,s,i,n]){const[r,o]=w(this,Ce,zn).call(this),[h,c,u,d]=l(this,Je);if(Math.abs(u-r)<=U.PRECISION||Math.abs(d-o)<=U.PRECISION){const y=e+i/2-(h+u/2),b=s+n/2-(c+d/2);return{path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`,transform:`${this.rotationTransform} translate(${y} ${b})`}}}const f=(i-2*r)/(u-2*r),g=(n-2*o)/(d-2*o),p=u/i,m=d/n;return{path:{"transform-origin":`${U.svgRound(h)} ${U.svgRound(c)}`,transform:`${this.rotationTransform} scale(${p} ${m}) translate(${U.svgRound(r)} ${U.svgRound(o)}) scale(${f} ${g}) translate(${U.svgRound(-r)} ${U.svgRound(-o)})`}}}getPathResizedSVGProperties([e,s,i,n]){const[r,o]=w(this,Ce,zn).call(this),h=l(this,Je),[c,u,d,f]=h;if(h[0]=e,h[1]=s,h[2]=i,h[3]=n,Math.abs(d-r)<=U.PRECISION||Math.abs(f-o)<=U.PRECISION){const b=e+i/2-(c+d/2),x=s+n/2-(u+f/2);for(const{line:C,points:S}of l(this,Os))U._translate(C,b,x,C),U._translate(S,b,x,S);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const g=(i-2*r)/(d-2*r),p=(n-2*o)/(f-2*o),m=-g*(c+r)+e+r,y=-p*(u+o)+s+o;if(g!==1||p!==1||m!==0||y!==0)for(const{line:b,points:x}of l(this,Os))U._rescale(b,m,y,g,p,b),U._rescale(x,m,y,g,p,x);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([e,s],i){const[n,r]=i,o=l(this,Je),h=e-o[0],c=s-o[1];if(l(this,Vi)===n&&l(this,Gi)===r)for(const{line:u,points:d}of l(this,Os))U._translate(u,h,c,u),U._translate(d,h,c,d);else{const u=l(this,Vi)/n,d=l(this,Gi)/r;v(this,Vi,n),v(this,Gi,r);for(const{line:f,points:g}of l(this,Os))U._rescale(f,h,c,u,d,f),U._rescale(g,h,c,u,d,g);o[2]*=u,o[3]*=d}return o[0]=e,o[1]=s,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`}}}get defaultSVGProperties(){const e=l(this,Je);return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${U.svgRound(e[0])} ${U.svgRound(e[1])}`,transform:this.rotationTransform||null},bbox:e}}};Je=new WeakMap,Xc=new WeakMap,Uc=new WeakMap,Os=new WeakMap,Vi=new WeakMap,Gi=new WeakMap,kh=new WeakMap,Ph=new WeakMap,Mh=new WeakMap,Ce=new WeakSet,zn=function(e=l(this,Mh)){const s=l(this,Uc)+e/2*l(this,kh);return l(this,Ph)%180===0?[s/l(this,Vi),s/l(this,Gi)]:[s/l(this,Gi),s/l(this,Vi)]},d_=function(){const[e,s,i,n]=l(this,Je),[r,o]=w(this,Ce,zn).call(this,0);return[e+r,s+o,i-2*r,n-2*o]},f_=function(){const e=v(this,Je,new Float32Array([1/0,1/0,-1/0,-1/0]));for(const{line:n}of l(this,Os)){if(n.length<=12){for(let h=4,c=n.length;h<c;h+=6){const[u,d]=n.subarray(h,h+2);e[0]=Math.min(e[0],u),e[1]=Math.min(e[1],d),e[2]=Math.max(e[2],u),e[3]=Math.max(e[3],d)}continue}let r=n[4],o=n[5];for(let h=6,c=n.length;h<c;h+=6){const[u,d,f,g,p,m]=n.subarray(h,h+6);q.bezierBoundingBox(r,o,u,d,f,g,p,m,e),r=p,o=m}}const[s,i]=w(this,Ce,zn).call(this);e[0]=Math.min(1,Math.max(0,e[0]-s)),e[1]=Math.min(1,Math.max(0,e[1]-i)),e[2]=Math.min(1,Math.max(0,e[2]+s)),e[3]=Math.min(1,Math.max(0,e[3]+i)),e[2]-=e[0],e[3]-=e[1]},g_=function(e){const[s,i]=w(this,Ce,zn).call(this);v(this,Mh,e);const[n,r]=w(this,Ce,zn).call(this),[o,h]=[n-s,r-i],c=l(this,Je);return c[0]-=o,c[1]-=h,c[2]+=2*o,c[3]+=2*h,c};let Md=yp;const _p=class _p extends oA{constructor(e){super();_(this,Oh);v(this,Oh,e),super.updateProperties({fill:"none",stroke:Vt._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(e,s){e==="stroke-width"&&(s??(s=this["stroke-width"]),s*=l(this,Oh).realScale),super.updateSVGProperty(e,s)}clone(){const e=new _p(l(this,Oh));return e.updateAll(this),e}};Oh=new WeakMap;let lp=_p;const Dh=class Dh extends hp{constructor(e){super({...e,name:"inkEditor"});_(this,$d);this._willKeepAspectRatio=!0}static initialize(e,s){Vt.initialize(e,s),this._defaultDrawingOptions=new lp(s.viewParameters)}static getDefaultDrawingOptions(e){const s=this._defaultDrawingOptions.clone();return s.updateProperties(e),s}static get supportMultipleDrawings(){return!0}static get typesMap(){return ct(this,"typesMap",new Map([[gt.INK_THICKNESS,"stroke-width"],[gt.INK_COLOR,"stroke"],[gt.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(e,s,i,n,r){return new aA(e,s,i,n,r,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(e,s,i,n,r,o){return Md.deserialize(e,s,i,n,r,o)}static async deserialize(e,s,i){let n=null;if(e instanceof np){const{data:{inkLists:o,rect:h,rotation:c,id:u,color:d,opacity:f,borderStyle:{rawWidth:g},popupRef:p},parent:{page:{pageNumber:m}}}=e;n=e={annotationType:at.INK,color:Array.from(d),thickness:g,opacity:f,paths:{points:o},boxes:null,pageIndex:m-1,rect:h.slice(0),rotation:c,id:u,deleted:!1,popupRef:p}}const r=await super.deserialize(e,s,i);return r.annotationElementId=e.id||null,r._initialData=n,r}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:e,_drawingOptions:s,parent:i}=this;s.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(e,s.toSVGProperties())}static onScaleChangingWhenDrawing(){const e=this._currentParent;e&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),e.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:e,thickness:s,opacity:i}){this._drawingOptions=Dh.getDefaultDrawingOptions({stroke:q.makeHexColor(...e),"stroke-width":s,"stroke-opacity":i})}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:s,points:i,rect:n}=this.serializeDraw(e),{_drawingOptions:{stroke:r,"stroke-opacity":o,"stroke-width":h}}=this,c={annotationType:at.INK,color:Vt._colorManager.convert(r),opacity:o,thickness:h,paths:{lines:s,points:i},pageIndex:this.pageIndex,rect:n,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?c:this.annotationElementId&&!w(this,$d,p_).call(this,c)?null:(c.id=this.annotationElementId,c)}renderAnnotationElement(e){const{points:s,rect:i}=this.serializeDraw(!1);return e.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:s}),null}};$d=new WeakSet,p_=function(e){const{color:s,thickness:i,opacity:n,pageIndex:r}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||e.color.some((o,h)=>o!==s[h])||e.thickness!==i||e.opacity!==n||e.pageIndex!==r},Q(Dh,"_type","ink"),Q(Dh,"_editorType",at.INK),Q(Dh,"_defaultDrawingOptions",null);let cp=Dh;const Yc=class Yc extends Vt{constructor(e){super({...e,name:"stampEditor"});_(this,bt);_(this,Wt,null);_(this,Ae,null);_(this,Cr,null);_(this,In,null);_(this,Ar,null);_(this,Rh,"");_(this,Wi,null);_(this,Xi,null);_(this,Ds,!1);_(this,Fh,!1);v(this,In,e.bitmapUrl),v(this,Ar,e.bitmapFile)}static initialize(e,s){Vt.initialize(e,s)}static get supportedTypes(){return ct(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(s=>`image/${s}`))}static get supportedTypesStr(){return ct(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,s){s.pasteEditor(at.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 c=h.output;return await this.setGuessedAltText(c),s&&!this.hasAltTextData()&&(this.altTextData={alt:c,decorative:!1}),c}remove(){var e;l(this,Ae)&&(v(this,Wt,null),this._uiManager.imageManager.deleteId(l(this,Ae)),(e=l(this,Wi))==null||e.remove(),v(this,Wi,null),l(this,Xi)&&(clearTimeout(l(this,Xi)),v(this,Xi,null))),super.remove()}rebuild(){if(!this.parent){l(this,Ae)&&w(this,bt,Tf).call(this);return}super.rebuild(),this.div!==null&&(l(this,Ae)&&l(this,Wi)===null&&w(this,bt,Tf).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(e){this._isDraggable=!0,e&&this.div.focus()}isEmpty(){return!(l(this,Cr)||l(this,Wt)||l(this,In)||l(this,Ar)||l(this,Ae))}get isResizable(){return!0}render(){if(this.div)return this.div;let e,s;if(this.width&&(e=this.x,s=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),l(this,Wt)?w(this,bt,gm).call(this):w(this,bt,Tf).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._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;l(this,Xi)!==null&&clearTimeout(l(this,Xi)),v(this,Xi,setTimeout(()=>{v(this,Xi,null),w(this,bt,pm).call(this)},200))}copyCanvas(e,s,i=!1){var g;e||(e=224);const{width:n,height:r}=l(this,Wt),o=new Vg;let h=l(this,Wt),c=n,u=r,d=null;if(s){if(n>s||r>s){const D=Math.min(s/n,s/r);c=Math.floor(n*D),u=Math.floor(r*D)}d=document.createElement("canvas");const p=d.width=Math.ceil(c*o.sx),m=d.height=Math.ceil(u*o.sy);l(this,Ds)||(h=w(this,bt,Ef).call(this,p,m));const y=d.getContext("2d");y.filter=this._uiManager.hcmFilter;let b="white",x="#cfcfd8";this._uiManager.hcmFilter!=="none"?x="black":(g=window.matchMedia)!=null&&g.call(window,"(prefers-color-scheme: dark)").matches&&(b="#8f8f9d",x="#42414d");const C=15,S=C*o.sx,T=C*o.sy,P=new OffscreenCanvas(S*2,T*2),M=P.getContext("2d");M.fillStyle=b,M.fillRect(0,0,S*2,T*2),M.fillStyle=x,M.fillRect(0,0,S,T),M.fillRect(S,T,S,T),y.fillStyle=y.createPattern(P,"repeat"),y.fillRect(0,0,p,m),y.drawImage(h,0,0,h.width,h.height,0,0,p,m)}let f=null;if(i){let p,m;if(o.symmetric&&h.width<e&&h.height<e)p=h.width,m=h.height;else if(h=l(this,Wt),n>e||r>e){const x=Math.min(e/n,e/r);p=Math.floor(n*x),m=Math.floor(r*x),l(this,Ds)||(h=w(this,bt,Ef).call(this,p,m))}const b=new OffscreenCanvas(p,m).getContext("2d",{willReadFrequently:!0});b.drawImage(h,0,0,h.width,h.height,0,0,p,m),f={width:p,height:m,data:b.getImageData(0,0,p,m).data}}return{canvas:d,width:c,height:u,imageData:f}}getImageForAltText(){return l(this,Wi)}static async deserialize(e,s,i){var m;let n=null;if(e instanceof Ab){const{data:{rect:y,rotation:b,id:x,structParent:C,popupRef:S},container:T,parent:{page:{pageNumber:P}}}=e,M=T.querySelector("canvas"),D=i.imageManager.getFromCanvas(T.id,M);M.remove();const R=((m=await s._structTree.getAriaAttributes(`${jg}${x}`))==null?void 0:m.get("aria-label"))||"";n=e={annotationType:at.STAMP,bitmapId:D.id,bitmap:D.bitmap,pageIndex:P-1,rect:y.slice(0),rotation:b,id:x,deleted:!1,accessibilityData:{decorative:!1,altText:R},isSvg:!1,structParent:C,popupRef:S}}const r=await super.deserialize(e,s,i),{rect:o,bitmap:h,bitmapUrl:c,bitmapId:u,isSvg:d,accessibilityData:f}=e;u&&i.imageManager.isValidId(u)?(v(r,Ae,u),h&&v(r,Wt,h)):v(r,In,c),v(r,Ds,d);const[g,p]=r.pageDimensions;return r.width=(o[2]-o[0])/g,r.height=(o[3]-o[1])/p,r.annotationElementId=e.id||null,f&&(r.altTextData=f),r._initialData=n,v(r,Fh,!!n),r}serialize(e=!1,s=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:at.STAMP,bitmapId:l(this,Ae),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:l(this,Ds),structTreeParentId:this._structTreeParentId};if(e)return i.bitmapUrl=w(this,bt,kf).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=w(this,bt,m_).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=l(this,Ds)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(l(this,Ae)))s.stamps.set(l(this,Ae),{area:o,serialized:i}),i.bitmap=w(this,bt,kf).call(this,!1);else if(l(this,Ds)){const h=s.stamps.get(l(this,Ae));o>h.area&&(h.area=o,h.serialized.bitmap.close(),h.serialized.bitmap=w(this,bt,kf).call(this,!1))}return i}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}};Wt=new WeakMap,Ae=new WeakMap,Cr=new WeakMap,In=new WeakMap,Ar=new WeakMap,Rh=new WeakMap,Wi=new WeakMap,Xi=new WeakMap,Ds=new WeakMap,Fh=new WeakMap,bt=new WeakSet,hu=function(e,s=!1){if(!e){this.remove();return}v(this,Wt,e.bitmap),s||(v(this,Ae,e.id),v(this,Ds,e.isSvg)),e.file&&v(this,Rh,e.file.name),w(this,bt,gm).call(this)},lu=function(){if(v(this,Cr,null),this._uiManager.enableWaiting(!1),!!l(this,Wi)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&l(this,Wt)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&l(this,Wt)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},Tf=function(){if(l(this,Ae)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(l(this,Ae)).then(i=>w(this,bt,hu).call(this,i,!0)).finally(()=>w(this,bt,lu).call(this));return}if(l(this,In)){const i=l(this,In);v(this,In,null),this._uiManager.enableWaiting(!0),v(this,Cr,this._uiManager.imageManager.getFromUrl(i).then(n=>w(this,bt,hu).call(this,n)).finally(()=>w(this,bt,lu).call(this)));return}if(l(this,Ar)){const i=l(this,Ar);v(this,Ar,null),this._uiManager.enableWaiting(!0),v(this,Cr,this._uiManager.imageManager.getFromFile(i).then(n=>w(this,bt,hu).call(this,n)).finally(()=>w(this,bt,lu).call(this)));return}const e=document.createElement("input");e.type="file",e.accept=Yc.supportedTypesStr;const s=this._uiManager._signal;v(this,Cr,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}}),w(this,bt,hu).call(this,n)}i()},{signal:s}),e.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>w(this,bt,lu).call(this))),e.click()},gm=function(){var d;const{div:e}=this;let{width:s,height:i}=l(this,Wt);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 f=Math.min(o*n/s,o*r/i);s*=f,i*=f}const[h,c]=this.parentDimensions;this.setDims(s*h/n,i*c/r),this._uiManager.enableWaiting(!1);const u=v(this,Wi,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),this.width=s/n,this.height=i/r,(d=this._initialOptions)!=null&&d.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),w(this,bt,pm).call(this),l(this,Fh)||(this.parent.addUndoableEditor(this),v(this,Fh,!0)),this._reportTelemetry({action:"inserted_image"}),l(this,Rh)&&u.setAttribute("aria-label",l(this,Rh))},Ef=function(e,s){const{width:i,height:n}=l(this,Wt);let r=i,o=n,h=l(this,Wt);for(;r>2*e||o>2*s;){const c=r,u=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 d=new OffscreenCanvas(r,o);d.getContext("2d").drawImage(h,0,0,c,u,0,0,r,o),h=d.transferToImageBitmap()}return h},pm=function(){const[e,s]=this.parentDimensions,{width:i,height:n}=this,r=new Vg,o=Math.ceil(i*e*r.sx),h=Math.ceil(n*s*r.sy),c=l(this,Wi);if(!c||c.width===o&&c.height===h)return;c.width=o,c.height=h;const u=l(this,Ds)?l(this,Wt):w(this,bt,Ef).call(this,o,h),d=c.getContext("2d");d.filter=this._uiManager.hcmFilter,d.drawImage(u,0,0,u.width,u.height,0,0,o,h)},kf=function(e){if(e){if(l(this,Ds)){const n=this._uiManager.imageManager.getSvgUrl(l(this,Ae));if(n)return n}const s=document.createElement("canvas");return{width:s.width,height:s.height}=l(this,Wt),s.getContext("2d").drawImage(l(this,Wt),0,0),s.toDataURL()}if(l(this,Ds)){const[s,i]=this.pageDimensions,n=Math.round(this.width*s*Kn.PDF_TO_CSS_UNITS),r=Math.round(this.height*i*Kn.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(n,r);return o.getContext("2d").drawImage(l(this,Wt),0,0,l(this,Wt).width,l(this,Wt).height,0,0,n,r),o.transferToImageBitmap()}return structuredClone(l(this,Wt))},m_=function(e){var o;const{pageIndex:s,accessibilityData:{altText:i}}=this._initialData,n=e.pageIndex===s,r=(((o=e.accessibilityData)==null?void 0:o.alt)||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&n&&r,isSameAltText:r}},Q(Yc,"_type","stamp"),Q(Yc,"_editorType",at.STAMP);let up=Yc;const bi=class bi{constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:c,l10n:u}){_(this,Nt);_(this,ia);_(this,Lh,!1);_(this,Ui,null);_(this,Tr,null);_(this,jn,null);_(this,Us,new Map);_(this,Er,!1);_(this,Ih,!1);_(this,na,!1);_(this,vi,null);_(this,Nn,null);_(this,je,null);_(this,Bn,null);_(this,$);const d=[...l(bi,kr).values()];if(!bi._initialized){bi._initialized=!0;for(const f of d)f.initialize(u,t)}t.registerEditorTypes(d),v(this,$,t),this.pageIndex=e,this.div=s,v(this,ia,n),v(this,Ui,r),this.viewport=c,v(this,je,h),this.drawLayer=o,this._structTree=i,l(this,$).addLayer(this)}get isEmpty(){return l(this,Us).size===0}get isInvisible(){return this.isEmpty&&l(this,$).getMode()===at.NONE}updateToolbar(t){l(this,$).updateToolbar(t)}updateMode(t=l(this,$).getMode()){switch(w(this,Nt,Pf).call(this),t){case at.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case at.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case at.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 l(bi,kr).values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){var e;return t===((e=l(this,je))==null?void 0:e.div)}setEditingState(t){l(this,$).setEditingState(t)}addCommands(t){l(this,$).addCommands(t)}cleanUndoStack(t){l(this,$).cleanUndoStack(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=l(this,Ui))==null||e.div.classList.toggle("disabled",!t)}async enable(){v(this,na,!0),this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of l(this,Us).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(l(this,$).removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!l(this,Ui)){v(this,na,!1);return}const e=l(this,Ui).getEditableAnnotations();for(const s of e){if(s.hide(),l(this,$).isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}v(this,na,!1)}disable(){var i;v(this,Ih,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const n of l(this,Us).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(l(this,Ui)){const n=l(this,Ui).getEditableAnnotations();for(const r of n){const{id:o}=r.data;if(l(this,$).isDeletedAnnotationElement(o))continue;let h=e.get(o);if(h){h.resetAnnotationElement(r),h.show(!1),r.show();continue}h=t.get(o),h&&(l(this,$).addChangedExistingAnnotation(h),h.renderAnnotationElement(r)&&h.show(!1)),r.show()}}w(this,Nt,Pf).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const n of l(bi,kr).values())s.remove(`${n._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),v(this,Ih,!1)}getEditableAnnotation(t){var e;return((e=l(this,Ui))==null?void 0:e.getEditableAnnotation(t))||null}setActiveEditor(t){l(this,$).getActive()!==t&&l(this,$).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=l(this,je))!=null&&t.div&&!l(this,Bn)){v(this,Bn,new AbortController);const e=l(this,$).combinedSignal(l(this,Bn));l(this,je).div.addEventListener("pointerdown",w(this,Nt,v_).bind(this),{signal:e}),l(this,je).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=l(this,je))!=null&&t.div&&l(this,Bn)&&(l(this,Bn).abort(),v(this,Bn,null),l(this,je).div.classList.remove("highlighting"))}enableClick(){if(l(this,Tr))return;v(this,Tr,new AbortController);const t=l(this,$).combinedSignal(l(this,Tr));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){var t;(t=l(this,Tr))==null||t.abort(),v(this,Tr,null)}attach(t){l(this,Us).set(t.id,t);const{annotationElementId:e}=t;e&&l(this,$).isDeletedAnnotationElement(e)&&l(this,$).removeDeletedAnnotationElement(t)}detach(t){var e;l(this,Us).delete(t.id),(e=l(this,ia))==null||e.removePointerInTextLayer(t.contentDiv),!l(this,Ih)&&t.annotationElementId&&l(this,$).addDeletedAnnotationElement(t)}remove(t){this.detach(t),l(this,$).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){var e;t.parent!==this&&(t.parent&&t.annotationElementId&&(l(this,$).addDeletedAnnotationElement(t.annotationElementId),Vt.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),l(this,$).addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!l(this,na)),l(this,$).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var s;if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!l(this,jn)&&(t._focusEventsAllowed=!1,v(this,jn,setTimeout(()=>{v(this,jn,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:l(this,$)._signal}),e.focus())},0))),t._structTreeParentId=(s=l(this,ia))==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 l(this,$).getId()}combinedSignal(t){return l(this,$).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=l(this,Nt,$i))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,e){l(this,$).updateToolbar(t),l(this,$).updateMode(t);const{offsetX:s,offsetY:i}=w(this,Nt,vm).call(this),n=this.getNextId(),r=w(this,Nt,mm).call(this,{parent:this,id:n,x:s,y:i,uiManager:l(this,$),isCentered:!0,...e});r&&this.add(r)}async deserialize(t){var e;return await((e=l(bi,kr).get(t.annotationType??t.annotationEditorType))==null?void 0:e.deserialize(t,this,l(this,$)))||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=w(this,Nt,mm).call(this,{parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:l(this,$),isCentered:e,...s});return n&&this.add(n),n}addNewEditor(){this.createAndAddNewEditor(w(this,Nt,vm).call(this),!0)}setSelected(t){l(this,$).setSelected(t)}toggleSelected(t){l(this,$).toggleSelected(t)}unselect(t){l(this,$).unselect(t)}pointerup(t){var s;const{isMac:e}=Ue.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&l(this,Er)&&(v(this,Er,!1),!((s=l(this,Nt,$i))!=null&&s.isDrawer&&l(this,Nt,$i).supportMultipleDrawings))){if(!l(this,Lh)){v(this,Lh,!0);return}if(l(this,$).getMode()===at.STAMP){l(this,$).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){var i;if(l(this,$).getMode()===at.HIGHLIGHT&&this.enableTextSelection(),l(this,Er)){v(this,Er,!1);return}const{isMac:e}=Ue.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(v(this,Er,!0),(i=l(this,Nt,$i))!=null&&i.isDrawer){this.startDrawingSession(t);return}const s=l(this,$).getActive();v(this,Lh,!s||s.isEmpty())}startDrawingSession(t){if(this.div.focus(),l(this,vi)){l(this,Nt,$i).startDrawing(this,l(this,$),!1,t);return}l(this,$).setCurrentDrawingSession(this),v(this,vi,new AbortController);const e=l(this,$).combinedSignal(l(this,vi));this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(v(this,Nn,null),this.commitOrRemove())},{signal:e}),l(this,Nt,$i).startDrawing(this,l(this,$),!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&v(this,Nn,e);return}l(this,Nn)&&setTimeout(()=>{var e;(e=l(this,Nn))==null||e.focus(),v(this,Nn,null)},0)}endDrawingSession(t=!1){return l(this,vi)?(l(this,$).setCurrentDrawingSession(null),l(this,vi).abort(),v(this,vi,null),v(this,Nn,null),l(this,Nt,$i).endDrawing(t)):null}findNewParent(t,e,s){const i=l(this,$).findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return l(this,vi)?(this.endDrawingSession(),!0):!1}onScaleChanging(){l(this,vi)&&l(this,Nt,$i).onScaleChangingWhenDrawing(this)}destroy(){var t,e;this.commitOrRemove(),((t=l(this,$).getActive())==null?void 0:t.parent)===this&&(l(this,$).commitOrRemove(),l(this,$).setActiveEditor(null)),l(this,jn)&&(clearTimeout(l(this,jn)),v(this,jn,null));for(const s of l(this,Us).values())(e=l(this,ia))==null||e.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,l(this,Us).clear(),l(this,$).removeLayer(this)}render({viewport:t}){this.viewport=t,$r(this.div,t);for(const e of l(this,$).getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){l(this,$).commitOrRemove(),w(this,Nt,Pf).call(this);const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,$r(this.div,{rotation:s}),e!==s)for(const i of l(this,Us).values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return l(this,$).viewParameters.realScale}};ia=new WeakMap,Lh=new WeakMap,Ui=new WeakMap,Tr=new WeakMap,jn=new WeakMap,Us=new WeakMap,Er=new WeakMap,Ih=new WeakMap,na=new WeakMap,vi=new WeakMap,Nn=new WeakMap,je=new WeakMap,Bn=new WeakMap,$=new WeakMap,kr=new WeakMap,Nt=new WeakSet,v_=function(t){l(this,$).unselectAll();const{target:e}=t;if(e===l(this,je).div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&l(this,je).div.contains(e)){const{isMac:s}=Ue.platform;if(t.button!==0||t.ctrlKey&&s)return;l(this,$).showAllEditors("highlight",!0,!0),l(this,je).div.classList.add("free"),this.toggleDrawing(),Pd.startHighlighting(this,l(this,$).direction==="ltr",{target:l(this,je).div,x:t.x,y:t.y}),l(this,je).div.addEventListener("pointerup",()=>{l(this,je).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:l(this,$)._signal}),t.preventDefault()}},$i=function(){return l(bi,kr).get(l(this,$).getMode())},mm=function(t){const e=l(this,Nt,$i);return e?new e.prototype.constructor(t):null},vm=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),c=(n+o)/2-t,u=(r+h)/2-e,[d,f]=this.viewport.rotation%180===0?[c,u]:[u,c];return{offsetX:d,offsetY:f}},Pf=function(){for(const t of l(this,Us).values())t.isEmpty()&&t.remove()},Q(bi,"_initialized",!1),_(bi,kr,new Map([rp,cp,up,Pd].map(t=>[t._editorType,t])));let dp=bi;const Ne=class Ne{constructor({pageIndex:t}){_(this,Yi);_(this,yi,null);_(this,$c,0);_(this,Qe,new Map);_(this,ra,new Map);this.pageIndex=t}setParent(t){if(!l(this,yi)){v(this,yi,t);return}if(l(this,yi)!==t){if(l(this,Qe).size>0)for(const e of l(this,Qe).values())e.remove(),t.append(e);v(this,yi,t)}}static get _svgFactory(){return ct(this,"_svgFactory",new sp)}draw(t,e=!1,s=!1){const i=es(this,$c)._++,n=w(this,Yi,bm).call(this),r=Ne._svgFactory.createElement("defs");n.append(r);const o=Ne._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),e&&l(this,ra).set(i,o);const c=s?w(this,Yi,y_).call(this,r,h):null,u=Ne._svgFactory.createElement("use");return n.append(u),u.setAttribute("href",`#${h}`),this.updateProperties(n,t),l(this,Qe).set(i,n),{id:i,clipPathId:`url(#${c})`}}drawOutline(t,e){const s=es(this,$c)._++,i=w(this,Yi,bm).call(this),n=Ne._svgFactory.createElement("defs");i.append(n);const r=Ne._svgFactory.createElement("path");n.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke");let h;if(e){const d=Ne._svgFactory.createElement("mask");n.append(d),h=`mask_p${this.pageIndex}_${s}`,d.setAttribute("id",h),d.setAttribute("maskUnits","objectBoundingBox");const f=Ne._svgFactory.createElement("rect");d.append(f),f.setAttribute("width","1"),f.setAttribute("height","1"),f.setAttribute("fill","white");const g=Ne._svgFactory.createElement("use");d.append(g),g.setAttribute("href",`#${o}`),g.setAttribute("stroke","none"),g.setAttribute("fill","black"),g.setAttribute("fill-rule","nonzero"),g.classList.add("mask")}const c=Ne._svgFactory.createElement("use");i.append(c),c.setAttribute("href",`#${o}`),h&&c.setAttribute("mask",`url(#${h})`);const u=c.cloneNode();return i.append(u),c.classList.add("mainOutline"),u.classList.add("secondaryOutline"),this.updateProperties(i,t),l(this,Qe).set(s,i),s}finalizeDraw(t,e){l(this,ra).delete(t),this.updateProperties(t,e)}updateProperties(t,e){var h;if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,o=typeof t=="number"?l(this,Qe).get(t):t;if(o){if(s&&w(this,Yi,ym).call(this,o,s),i&&w(h=Ne,qd,b_).call(h,o,i),n){const{classList:c}=o;for(const[u,d]of Object.entries(n))c.toggle(u,d)}if(r){const u=o.firstChild.firstChild;w(this,Yi,ym).call(this,u,r)}}}updateParent(t,e){if(e===this)return;const s=l(this,Qe).get(t);s&&(l(e,yi).append(s),l(this,Qe).delete(t),l(e,Qe).set(t,s))}remove(t){l(this,ra).delete(t),l(this,yi)!==null&&(l(this,Qe).get(t).remove(),l(this,Qe).delete(t))}destroy(){v(this,yi,null);for(const t of l(this,Qe).values())t.remove();l(this,Qe).clear(),l(this,ra).clear()}};yi=new WeakMap,$c=new WeakMap,Qe=new WeakMap,ra=new WeakMap,qd=new WeakSet,b_=function(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`},Yi=new WeakSet,bm=function(){const t=Ne._svgFactory.create(1,1,!0);return l(this,yi).append(t),t.setAttribute("aria-hidden",!0),t},y_=function(t,e){const s=Ne._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=Ne._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i},ym=function(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)},_(Ne,qd);let fp=Ne;globalThis.pdfjsTestingUtils={HighlightOutliner:op},et.AbortException,et.AnnotationEditorLayer,et.AnnotationEditorParamsType,et.AnnotationEditorType,et.AnnotationEditorUIManager,et.AnnotationLayer,et.AnnotationMode,et.ColorPicker,et.DOMSVGFactory,et.DrawLayer,et.FeatureTest;var hA=et.GlobalWorkerOptions;et.ImageKind,et.InvalidPDFException,et.MissingPDFException,et.OPS,et.OutputScale,et.PDFDataRangeTransport,et.PDFDateString,et.PDFWorker,et.PasswordResponses,et.PermissionFlag,et.PixelsPerInch,et.RenderingCancelledException,et.TextLayer,et.TouchManager,et.UnexpectedResponseException,et.Util,et.VerbosityLevel,et.XfaLayer,et.build,et.createValidAbsoluteUrl,et.fetchData;var lA=et.getDocument;et.getFilenameFromUrl,et.getPdfFilenameFromUrl,et.getXfaPageViewport,et.isDataScheme,et.isPdfFile,et.noContextMenu,et.normalizeUnicode,et.setLayerDimensions,et.shadow,et.stopEvent,et.version;const cA={"pdfjs-dist":"4.10.38"};function uA(a){return new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>t(s.result)),s.addEventListener("error",e),s.readAsDataURL(a)})}const dA=cA["pdfjs-dist"].replace("^","");hA.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${dA}/pdf.worker.min.mjs`;async function fA(a){const t="data:application/pdf;base64,",e=await uA(a);if(typeof e=="string")return window.atob(e.slice(t.length))}function gA(a,t){return lA({data:a,password:t}).promise}const hs=new Map;function pA(a){const t=new bg(a);return hs.set(a,t),t}function mA(a,t){const e=Date.now();return{PDFId:`${a.name}-${e}`,name:a.name.replace(/.pdf/,""),updateDate:e,PDFBase64:t}}function vA(a,t){const e=a.getViewport({scale:t}),s=document.createElement("canvas"),i=s.getContext("2d"),n=rS()/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 bA({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await Yx(a),n=s.filter(o=>o!==null),r=lx.groupSVGElements(n,i);return n.forEach(o=>{o.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function yA(a,t){if(!hs.get(a))return;const s=1/3,i=TA(t,s);kb(a,i,s)}async function _A(a,t){const e=await aS(t),s=Date.now(),n={PDFId:`${t.name}${s}`,name:t.name.replace(/.png|.jpg|.jpeg/,""),updateDate:s,PDFBase64:e};return Eb(a,{url:e}),{...n,pages:1}}async function Eb(a,{url:t,scale:e=.5}){if(!hs.get(a))return;const i=await Me.fromURL(t);i.scale(e),kb(a,i,e)}function kb(a,t,e){const s=hs.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function wA(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 xA(a,t,e){!e||!a||(e.scale(1/t),wA(a,e))}function SA(a,t){if(!a)return;const e=a._cornerSize||6;a.borderScaleFactor=1/t,a.cornerSize=e*(1/t),a.touchCornerSize=e*4*(1/t),a.setCoords()}function CA(a){const t=hs.get(a);t&&(t.discardActiveObject(),t.renderAll())}function AA(a){const t=hs.get(a);t&&(t.clear(),hs.delete(a))}function TA(a,t){return new Me(a,{scaleX:t,scaleY:t})}function gp(a,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:o}=a,h=t.x*r*i,c=t.y*o*n;a.set({left:e-h,top:s-c})}function Pb(a,t,e){var n;const s=a.type,i={"application/pdf":EA,"image/png":Ob,"image/jpeg":Ob};return((n=i[s])==null?void 0:n.call(i,a,t,e))??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function EA(a,t,e){const s=await fA(a);if(!s)return;const i=mA(a,s);try{const n=await Mb({page:1,PDFBase64:s,scale:.8,password:t},e);return{...i,pages:n}}catch(n){return Promise.reject(n)}}async function Mb({page:a,PDFBase64:t,scale:e,password:s},i){try{const n=await gA(t,s),r=await n.getPage(a),{renderTask:o,canvas:h}=vA(r,e);return o.promise.then(()=>(i&&yA(i,h),n.numPages))}catch(n){return Promise.reject(n)}}async function Ob(a,t,e){if(e)return await _A(e,a)}async function kA(a,t){const e=hs.get(a);if(!e)return;const s=e==null?void 0:e.getActiveObject();if(!s)return;const i=await s.clone(k_);i instanceof Fs?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),gp(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function PA(a){const t=hs.get(a);if(!t)return;const e=t.getActiveObject();e&&(e instanceof Fs?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Db(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{},h=tt.useRef(null),c=tt.useRef(null),u=tt.useRef(1),d=tt.useRef({...E_});function f(){if(!t||hs.has(t))return;const F=pA(t);return F.on("selection:created",I=>{if(r==null||r(I),I.selected.length<=1)return;const j=F.getActiveObject();j&&(c.current=j,e!=null&&e.value&&c.current.set(e.value),c.current._cornerSize=c.current.cornerSize,T(u.current))}),F.on("selection:cleared",I=>{o==null||o(I),M(F)}),s&&F.on("mouse:down",s),i&&F.on("mouse:move",i),n&&F.on("mouse:up",n),F}function g(F,I){return Pb(F,I,t)}function p(F){return Mb(F,t)}function m({url:F,scale:I=.5}){return Eb(t,{url:F,scale:I})}async function y(F,I,j){const K=hs.get(t);if(!K)return;const L=await Me.fromURL(F,{},{...C_,...I});gp(L,j),K.add(L),x(K,L),K.setActiveObject(L)}function b(F,I,j){const K=hs.get(t);if(!K)return;const L=new Pe(F,{...A_,...I});gp(L,j),K.add(L),x(K,L),K.setActiveObject(L)}function x(F,I){I.on("selected",j=>C({canvas:F,target:j.target})),I.on("modified",j=>C({canvas:F,target:j.target})),I.on("scaling",()=>M(F)),I.on("moving",()=>M(F)),I.on("rotating",()=>M(F)),I._cornerSize=I._cornerSize??I.cornerSize}async function C({canvas:F,target:I,stroke:j=d.current.stroke,uuid:K=Date.now()}){var Z;if(F.getActiveObjects().length>1||((Z=h.current)==null?void 0:Z.stroke)===`${j}-${K}`)return;const z=await bA(d.current,K,j);M(F),h.current=z,c.current=I,S(F,I,K),T(u.current,!0),z&&F.add(z)}function S(F,I,j){h.current&&(h.current.on("selected",()=>{F.remove(I),M(F)}),h.current.on("mouseover",()=>{C({canvas:F,target:I,stroke:d.current.hoverStroke,uuid:j})}),h.current.on("mouseout",()=>{C({canvas:F,target:I,stroke:d.current.stroke,uuid:j})}))}function T(F,I=!1){const j=hs.get(t);u.current=F,j&&(SA(c.current,F),xA(c.current,F,h.current),!I&&j.renderAll())}function P(F){if(!F)return;d.current={...d.current,...F};const I=hs.get(t);!h||!c.current||!I||C({target:c.current,canvas:I})}function M(F){c.current=null,h.current&&(F.remove(h.current),h.current=null)}function D(){CA(t)}function R(){AA(t)}function V(){return kA(t,x)}function H(){PA(t)}return{createCanvas:f,loadFile:g,specifyPage:p,renderImage:m,addFabric:y,addTextFabric:b,clearActive:D,deleteCanvas:R,scaleFabric:T,setCloseSvgOptions:P,copyActiveFabric:V,deleteActiveFabric:H}}function MA(a){let t=0;const e=oS(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});tt.useEffect(()=>(window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)),[])}const OA=tt.forwardRef(DA);function DA({file:a,page:t=1,canvasId:e="PDF-canvas",fileZoom:s=1,fileScale:i=1,canvasScale:n=1,canvasClass:r="",isDrop:o=!1,password:h,dropTextOptions:c,dropImageOptions:u,closeSvgOptions:d,selectionOptions:f,manualReload:g,onLoaded:p,onReload:m,onPointerDown:y,onPointerMove:b,onPointerUp:x,onSelectionCreated:C,onSelectionCleared:S},T){const P=tt.useRef(null),M=`${e}-${t-1}`,D=tt.useMemo(()=>s*n,[s,n]),R=tt.useMemo(()=>({...T_,...f}),[f]),{createCanvas:V,specifyPage:H,addFabric:F,addTextFabric:I,renderImage:j,clearActive:K,deleteCanvas:L,scaleFabric:z,setCloseSvgOptions:Z,copyActiveFabric:Dt,deleteActiveFabric:Bt}=Db({id:M,selectionOptions:R,pointerDown:y,pointerMove:b,pointerUp:x,selectionCreated:C,selectionCleared:S});MA(Ze);async function Xt(){window.requestAnimationFrame(async()=>{if(V(),a.PDFBase64.startsWith("data:image")||a.canvas){const{canvas:it}=a,nt=it?7:3,Zt=it!=null&&it.length?it[t-1]:a.PDFBase64;j({url:Zt,scale:i/nt});return}await H({page:t,PDFBase64:a.PDFBase64,scale:i,password:h}),p==null||p()})}function Ft(it){if(it.preventDefault(),it.stopPropagation(),!o||!it.dataTransfer)return;const{dataTransfer:nt,nativeEvent:Zt}=it,{offsetX:Ys,offsetY:Te}=Zt,Kd=nt.getData("text/plain"),qc=nt.getData("text/uri-list"),Jd=nt.getData("custom/offset"),Pr=Jd?JSON.parse(Jd):null,oa={top:Te,left:Ys},Mr={x:(Pr==null?void 0:Pr.offsetX)??0,y:(Pr==null?void 0:Pr.offsetY)??0};qc?_t(qc,oa,Mr):Kd&&oe(Kd,oa,Mr)}function _t(it,nt,Zt){F(it,{...u,...nt},Zt)}function oe(it,nt,Zt){I(it,{...c,...nt},Zt)}function Ze(){g||Xt(),m==null||m()}return tt.useImperativeHandle(T,()=>({reload:Xt,addImage:_t,addText:oe,clearActive:K,deleteCanvas:L,copyActiveFabric:Dt,deleteActiveFabric:Bt,canvasRef:P})),tt.useEffect(()=>{Ze()},[i,t,a,h]),tt.useEffect(()=>{z(D)},[D]),tt.useEffect(()=>{Z(d)},[d]),tt.useEffect(()=>()=>L(),[]),Sm.jsx("div",{style:{transform:`scale(${D})`},onDragOver:it=>it.preventDefault(),onDragEnter:it=>it.preventDefault(),onDrop:Ft,children:Sm.jsx("canvas",{id:M,ref:P,className:r})})}dt.default=OA,dt.loadFile=Pb,dt.useFabric=Db,Object.defineProperties(dt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
533
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2],l=Math.max(n,r,a),h=(n+r+a)/3,c=2*Math.abs(l-h)/255*s;e[i]+=l!==n?(l-n)*c:0,e[i+1]+=l!==r?(l-r)*c:0,e[i+2]+=l!==a?(l-a)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}S(Xn,"type","Vibrance"),S(Xn,"defaults",{vibrance:0}),S(Xn,"uniformLocations",["uVibrance"]),I.setClass(Xn);let vh=null;function bf(){const o=document.createElement("div");o.style.width="1in",document.body.append(o);const t=o.offsetWidth;return o.remove(),t}function yf(){const o=vh??bf();return vh=o,o/72}function _f(o,t=500){if(typeof o!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,o.apply(this,s)},t)}}function wf(o){return new Promise((t,e)=>{const s=window.URL.createObjectURL(o),i=new Image;i.src=s,i.addEventListener("load",async()=>{window.URL.revokeObjectURL(s),t(await xf(i))}),i.addEventListener("error",n=>{window.URL.revokeObjectURL(s),e(n)})})}function xf(o){return new Promise(t=>{const e=document.createElement("canvas"),s=e.getContext("2d"),{naturalWidth:i,naturalHeight:n}=o;e.width=i,e.height=n,s?.drawImage(o,0,0,i,n),t(e.toDataURL("image/jpeg",.8))})}var Pi={};Pi.d=(o,t)=>{for(var e in t)Pi.o(t,e)&&!Pi.o(o,e)&&Object.defineProperty(o,e,{enumerable:!0,get:t[e]})},Pi.o=(o,t)=>Object.prototype.hasOwnProperty.call(o,t);var X=globalThis.pdfjsLib={};Pi.d(X,{AbortException:()=>cs,AnnotationEditorLayer:()=>ss,AnnotationEditorParamsType:()=>st,AnnotationEditorType:()=>J,AnnotationEditorUIManager:()=>us,AnnotationLayer:()=>vp,AnnotationMode:()=>ls,ColorPicker:()=>ye,DOMSVGFactory:()=>za,DrawLayer:()=>te,FeatureTest:()=>Qt,GlobalWorkerOptions:()=>Ni,ImageKind:()=>Un,InvalidPDFException:()=>wa,MissingPDFException:()=>Oi,OPS:()=>Me,OutputScale:()=>Pa,PDFDataRangeTransport:()=>Zh,PDFDateString:()=>Sh,PDFWorker:()=>ii,PasswordResponses:()=>Tf,PermissionFlag:()=>Af,PixelsPerInch:()=>ti,RenderingCancelledException:()=>Ta,TextLayer:()=>Zt,TouchManager:()=>er,UnexpectedResponseException:()=>Kn,Util:()=>z,VerbosityLevel:()=>Yn,XfaLayer:()=>ic,build:()=>Jg,createValidAbsoluteUrl:()=>Mf,fetchData:()=>Qn,getDocument:()=>Vg,getFilenameFromUrl:()=>Bf,getPdfFilenameFromUrl:()=>Hf,getXfaPageViewport:()=>zf,isDataScheme:()=>Zn,isPdfFile:()=>Ea,noContextMenu:()=>Oe,normalizeUnicode:()=>If,setLayerDimensions:()=>Ms,shadow:()=>tt,stopEvent:()=>ge,version:()=>Kg});const Gt=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),bh=[1,0,0,1,0,0],ba=[.001,0,0,.001,0,0],Sf=1e7,ya=1.35,fe={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},ls={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Cf="pdfjs_internal_editor_",J={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},st={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,DRAW_STEP:41},Af={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Wt={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Un={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Lt={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,WIDGET:20},Mi={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Yn={ERRORS:0,WARNINGS:1,INFOS:5},Me={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},Tf={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let $n=Yn.WARNINGS;function Ef(o){Number.isInteger(o)&&($n=o)}function kf(){return $n}function qn(o){$n>=Yn.INFOS&&console.log(`Info: ${o}`)}function Q(o){$n>=Yn.WARNINGS&&console.log(`Warning: ${o}`)}function ut(o){throw new Error(o)}function Mt(o,t){o||ut(t)}function Pf(o){switch(o?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Mf(o,t=null,e=null){if(!o)return null;try{if(e&&typeof o=="string"&&(e.addDefaultProtocol&&o.startsWith("www.")&&o.match(/\./g)?.length>=2&&(o=`http://${o}`),e.tryConvertEncoding))try{o=Lf(o)}catch{}const s=t?new URL(o,t):new URL(o);if(Pf(s))return s}catch{}return null}function tt(o,t,e,s=!1){return Object.defineProperty(o,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const hs=function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class yh extends hs{constructor(t,e){super(t,"PasswordException"),this.code=e}}class _a extends hs{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class wa extends hs{constructor(t){super(t,"InvalidPDFException")}}class Oi extends hs{constructor(t){super(t,"MissingPDFException")}}class Kn extends hs{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Of extends hs{constructor(t){super(t,"FormatError")}}class cs extends hs{constructor(t){super(t,"AbortException")}}function _h(o){(typeof o!="object"||o?.length===void 0)&&ut("Invalid argument for bytesToString");const t=o.length,e=8192;if(t<e)return String.fromCharCode.apply(null,o);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=o.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function Jn(o){typeof o!="string"&&ut("Invalid argument for stringToBytes");const t=o.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=o.charCodeAt(s)&255;return e}function Df(o){return String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,o&255)}function xa(o){const t=Object.create(null);for(const[e,s]of o)t[e]=s;return t}function Rf(){const o=new Uint8Array(4);return o[0]=1,new Uint32Array(o.buffer,0,1)[0]===1}function Ff(){try{return new Function(""),!0}catch{return!1}}class Qt{static get isLittleEndian(){return tt(this,"isLittleEndian",Rf())}static get isEvalSupported(){return tt(this,"isEvalSupported",Ff())}static get isOffscreenCanvasSupported(){return tt(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return tt(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?tt(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):tt(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return tt(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const Sa=Array.from(Array(256).keys(),o=>o.toString(16).padStart(2,"0"));class z{static makeHexColor(t,e,s){return`#${Sa[t]}${Sa[e]}${Sa[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],a=(s+r)/2,l=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,h=a+l||1,c=a-l||1;return[Math.sqrt(h),Math.sqrt(c)]}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#t(t,e,s,i,n,r,a,l,h,c){if(h<=0||h>=1)return;const u=1-h,d=h*h,f=d*h,g=u*(u*(u*t+3*h*e)+3*d*s)+f*i,p=u*(u*(u*n+3*h*r)+3*d*a)+f*l;c[0]=Math.min(c[0],g),c[1]=Math.min(c[1],p),c[2]=Math.max(c[2],g),c[3]=Math.max(c[3],p)}static#e(t,e,s,i,n,r,a,l,h,c,u,d){if(Math.abs(h)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,a,l,-u/c,d);return}const f=c**2-4*u*h;if(f<0)return;const g=Math.sqrt(f),p=2*h;this.#t(t,e,s,i,n,r,a,l,(-c+g)/p,d),this.#t(t,e,s,i,n,r,a,l,(-c-g)/p,d)}static bezierBoundingBox(t,e,s,i,n,r,a,l,h){return h?(h[0]=Math.min(h[0],t,a),h[1]=Math.min(h[1],e,l),h[2]=Math.max(h[2],t,a),h[3]=Math.max(h[3],e,l)):h=[Math.min(t,a),Math.min(e,l),Math.max(t,a),Math.max(e,l)],this.#e(t,s,n,a,e,i,r,l,3*(-t+3*(s-n)+a),6*(t-2*s+n),3*(s-t),h),this.#e(t,s,n,a,e,i,r,l,3*(-e+3*(i-r)+l),6*(e-2*i+r),3*(i-e),h),h}}function Lf(o){return decodeURIComponent(escape(o))}let Ca=null,wh=null;function If(o){return Ca||(Ca=/([\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,wh=new Map([["ſt","ſt"]])),o.replaceAll(Ca,(t,e,s)=>e?e.normalize("NFKC"):wh.get(s))}function jf(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const o=new Uint8Array(32);return crypto.getRandomValues(o),_h(o)}const Aa="pdfjs_internal_id_";function Nf(o){return Uint8Array.prototype.toBase64?o.toBase64():btoa(_h(o))}typeof Promise.try!="function"&&(Promise.try=function(o,...t){return new Promise(e=>{e(o(...t))})});const es="http://www.w3.org/2000/svg";class ti{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Qn(o,t="text"){if(Ri(o,document.baseURI)){const e=await fetch(o);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",o,!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 Di{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const l=(t[2]+t[0])/2,h=(t[3]+t[1])/2;let c,u,d,f;switch(i%=360,i<0&&(i+=360),i){case 180:c=-1,u=0,d=0,f=1;break;case 90:c=0,u=1,d=1,f=0;break;case 270:c=0,u=-1,d=-1,f=0;break;case 0:c=1,u=0,d=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,f=-f);let g,p,v,m;c===0?(g=Math.abs(h-t[1])*s+n,p=Math.abs(l-t[0])*s+r,v=(t[3]-t[1])*s,m=(t[2]-t[0])*s):(g=Math.abs(l-t[0])*s+n,p=Math.abs(h-t[1])*s+r,v=(t[2]-t[0])*s,m=(t[3]-t[1])*s),this.transform=[c*s,u*s,d*s,f*s,g-c*s*l-d*s*h,p-u*s*l-f*s*h],this.width=v,this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return tt(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new Di({viewBox:this.viewBox.slice(),userUnit:this.userUnit,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 Ta extends hs{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Zn(o){const t=o.length;let e=0;for(;e<t&&o[e].trim()==="";)e++;return o.substring(e,e+5).toLowerCase()==="data:"}function Ea(o){return typeof o=="string"&&/\.pdf$/i.test(o)}function Bf(o){return[o]=o.split(/[#?]/,1),o.substring(o.lastIndexOf("/")+1)}function Hf(o,t="document.pdf"){if(typeof o!="string")return t;if(Zn(o))return Q('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(o);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 xh{started=Object.create(null);times=[];time(t){t in this.started&&Q(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||Q(`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
534
+ `);return t.join("")}}function Ri(o,t){try{const{protocol:e}=t?new URL(o,t):new URL(o);return e==="http:"||e==="https:"}catch{return!1}}function Oe(o){o.preventDefault()}function ge(o){o.preventDefault(),o.stopPropagation()}class Sh{static#t;static toDateObject(t){if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.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 a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let l=parseInt(e[6],10);l=l>=0&&l<=59?l:0;const h=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let u=parseInt(e[9],10)||0;return u=u>=0&&u<=59?u:0,h==="-"?(r+=c,a+=u):h==="+"&&(r-=c,a-=u),new Date(Date.UTC(s,i,n,r,a,l))}}function zf(o,{scale:t=1,rotation:e=0}){const{width:s,height:i}=o.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new Di({viewBox:n,userUnit:1,scale:t,rotation:e})}function ka(o){if(o.startsWith("#")){const t=parseInt(o.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return o.startsWith("rgb(")?o.slice(4,-1).split(",").map(t=>parseInt(t)):o.startsWith("rgba(")?o.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(Q(`Not a valid color format: "${o}"`),[0,0,0])}function Vf(o){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of o.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;o.set(e,ka(s))}t.remove()}function mt(o){const{a:t,b:e,c:s,d:i,e:n,f:r}=o.getTransform();return[t,e,s,i,n,r]}function ze(o){const{a:t,b:e,c:s,d:i,e:n,f:r}=o.getTransform().invertSelf();return[t,e,s,i,n,r]}function Ms(o,t,e=!1,s=!0){if(t instanceof Di){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=o,a=Qt.isCSSRoundSupported,l=`var(--scale-factor) * ${i}px`,h=`var(--scale-factor) * ${n}px`,c=a?`round(down, ${l}, var(--scale-round-x, 1px))`:`calc(${l})`,u=a?`round(down, ${h}, var(--scale-round-y, 1px))`:`calc(${h})`;!e||t.rotation%180===0?(r.width=c,r.height=u):(r.width=u,r.height=c)}s&&o.setAttribute("data-main-rotation",t.rotation)}class Pa{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}}class Fi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,Fi.#n||=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=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:e}),t.addEventListener("pointerdown",Fi.#l,{signal:e});const s=this.#i=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,r=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#t}static#l(t){t.stopPropagation()}#o(t){this.#s._focusEventsAllowed=!1,ge(t)}#c(t){this.#s._focusEventsAllowed=!0,ge(t)}#h(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#o.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Oe,{signal:e})}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",Fi.#n[t]),this.#h(s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#u(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#h(e),this.#i.prepend(e,this.#u),this.#r=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#h(e),this.#i.prepend(e,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class Gf{#t=null;#e=null;#s;constructor(t){this.#s=t}#i(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",Oe,{signal:this.#s._signal});const e=this.#t=document.createElement("div");return e.className="buttons",t.append(e),this.#n(),t}#r(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const a=n.x+(e?n.width:0);if(r>s){i=a,s=r;continue}e?a>i&&(i=a):a<i&&(i=a)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#r(e,s),{style:r}=this.#e||=this.#i();t.append(this.#e),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#n(){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=this.#s._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function tr(o,t,e){for(const s of e)t.addEventListener(s,o[s].bind(o))}class Wf{#t=0;get id(){return`${Cf}${this.#t++}`}}class Ma{#t=jf();#e=0;#s=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 tt(this,"_isSVGFittingCanvas",n)}async#i(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Qn(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=Ma._isSVGFittingCanvas,r=new FileReader,a=new Image,l=new Promise((h,c)=>{a.onload=()=>{s.bitmap=a,s.isSvg=!0,h()},r.onload=async()=>{const u=s.svgUrl=r.result;a.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},a.onerror=r.onerror=c});r.readAsDataURL(i),await l}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){Q(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#i(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#i(t,t)}async getFromBlob(t,e){const s=await e;return this.#i(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.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){this.#s||=new Map;let s=this.#s.get(t);if(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_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class Xf{#t=[];#e=!1;#s;#i=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(i&&t(),this.#e)return;const l={cmd:t,undo:e,post:s,type:n};if(this.#i===-1){this.#t.length>0&&(this.#t.length=0),this.#i=0,this.#t.push(l);return}if(r&&this.#t[this.#i].type===n){a&&(l.undo=this.#t[this.#i].undo),this.#t[this.#i]=l;return}const h=this.#i+1;h===this.#s?this.#t.splice(0,1):(this.#i=h,h<this.#t.length&&this.#t.splice(h)),this.#t.push(l)}undo(){if(this.#i===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1,this.#i-=1}redo(){if(this.#i<this.#t.length-1){this.#i+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#i!==-1}hasSomethingToRedo(){return this.#i<this.#t.length-1}cleanType(t){if(this.#i!==-1){for(let e=this.#i;e>=0;e--)if(this.#t[e].type!==t){this.#t.splice(e+1,this.#i-e),this.#i=e;return}this.#t.length=0,this.#i=-1}}destroy(){this.#t=null}}class Li{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Qt.platform;for(const[s,i,n={}]of t)for(const r of s){const a=r.startsWith("mac+");e&&a?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!a&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}#t(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}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#t(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:a=null}}=s;a&&!a(t,e)||(i.bind(t,...r,e)(),n||ge(e))}}class Oa{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Vf(t),tt(this,"_colors",t)}convert(t){const e=ka(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 Oa._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}}class us{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#l=null;#o=new Xf;#c=null;#h=null;#d=0;#u=new Set;#f=null;#a=null;#g=new Set;_editorUndoBar=null;#m=!1;#p=!1;#v=!1;#_=null;#b=null;#w=null;#S=null;#A=!1;#E=null;#P=new Wf;#x=!1;#k=!1;#T=null;#O=null;#F=null;#I=null;#C=J.NONE;#y=new Set;#R=null;#z=null;#V=null;#G={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#j=[0,0];#L=null;#N=null;#W=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=us.prototype,e=r=>r.#N.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:a})=>{if(a instanceof HTMLInputElement){const{type:l}=a;return l!=="text"&&l!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return tt(this,"_keyboardManager",new Li([[["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:a})=>!(a instanceof HTMLButtonElement)&&r.#N.contains(a)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:a})=>!(a instanceof HTMLButtonElement)&&r.#N.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}]]))}constructor(t,e,s,i,n,r,a,l,h,c,u,d,f){const g=this._signal=this.#t.signal;this.#N=t,this.#W=e,this.#r=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",p=>this.updateParams(p.type,p.value),{signal:g}),this.#et(),this.#rt(),this.#$(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#z=r,this.#S=a||null,this.#m=l,this.#p=h,this.#v=c,this.#I=u||null,this.viewParameters={realScale:ti.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#D?.resolve(),this.#D=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#i.values())t.destroy();this.#i.clear(),this.#s.clear(),this.#g.clear(),this.#e=null,this.#y.clear(),this.#o.destroy(),this.#r?.destroy(),this.#E?.hide(),this.#E=null,this.#b&&(clearTimeout(this.#b),this.#b=null),this.#L&&(clearTimeout(this.#L),this.#L=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#I}get useNewAltTextFlow(){return this.#p}get useNewAltTextWhenAddingImage(){return this.#v}get hcmFilter(){return tt(this,"hcmFilter",this.#z?this.#_.addHCMFilter(this.#z.foreground,this.#z.background):"none")}get direction(){return tt(this,"direction",getComputedStyle(this.#N).direction)}get highlightColors(){return tt(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return tt(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#h=t}setMainHighlightColorPicker(t){this.#F=t}editAltText(t,e=!1){this.#r?.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":this.#v=e;break}}onPageChanging({pageNumber:t}){this.#d=t-1}focusMainContainer(){this.#N.focus()}findParent(t,e){for(const s of this.#i.values()){const{x:i,y:n,width:r,height:a}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+a)return s}return null}disableUserSelect(t=!1){this.#W.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#g.add(t)}removeShouldRescale(t){this.#g.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*ti.PDF_TO_CSS_UNITS;for(const e of this.#g)e.onScaleChanging();this.#h?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#B({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Y(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#i.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,a=e.toString(),h=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(h);if(!c)return;e.empty();const u=this.#Y(h),d=this.#C===J.NONE,f=()=>{u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:a}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(J.HIGHLIGHT,f);return}f()}#Z(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#B(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#E||=new Gf(this),this.#E.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#n&&!this.#n.has(t.id)&&this.#n.setValue(t.id,t)}#tt(){const t=document.getSelection();if(!t||t.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#M({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#R)return;const i=this.#B(t).closest(".textLayer");if(!i){this.#R&&(this.#E?.hide(),this.#R=null,this.#M({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=e,this.#M({hasSelectedText:!0}),!(this.#C!==J.HIGHLIGHT&&this.#C!==J.NONE)&&(this.#C===J.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===J.HIGHLIGHT?this.#Y(i):null;n?.toggleDrawing();const r=new AbortController,a=this.combinedSignal(r),l=h=>{h.type==="pointerup"&&h.button!==0||(r.abort(),n?.toggleDrawing(!0),h.type==="pointerup"&&this.#U("main_toolbar"))};window.addEventListener("pointerup",l,{signal:a}),window.addEventListener("blur",l,{signal:a})}}#U(t=""){this.#C===J.HIGHLIGHT?this.highlightSelection(t):this.#m&&this.#Z()}#et(){document.addEventListener("selectionchange",this.#tt.bind(this),{signal:this._signal})}#st(){if(this.#w)return;this.#w=new AbortController;const t=this.combinedSignal(this.#w);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#it(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#y)if(e.div.contains(t)){this.#O=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;const[t,e]=this.#O;this.#O=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#$(){if(this.#T)return;this.#T=new AbortController;const t=this.combinedSignal(this.#T);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#nt(){this.#T?.abort(),this.#T=null}#q(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);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})}#K(){this.#c?.abort(),this.#c=null}#rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#$(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#a)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#a)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#y){const i=s.serialize(!0);i&&e.push(i)}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 this.#a)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){Q(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const l of s){const h=await i.deserialize(l);if(!h)return;n.push(h)}const r=()=>{for(const l of n)this.#J(l);this.#Q(n)},a=()=>{for(const l of n)l.remove()};this.addCommands({cmd:r,undo:a,mustExec:!0})}catch(n){Q(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==J.NONE&&!this.isEditorHandlingKeyboard&&us._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("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}}#M(t){Object.entries(t).some(([s,i])=>this.#G[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#G,t)}),this.#C===J.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#H([[st.HIGHLIGHT_FREE,!0]]))}#H(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#M({isEditing:this.#C!==J.NONE,isEmpty:this.#X(),hasSomethingToUndo:this.#o.hasSomethingToUndo(),hasSomethingToRedo:this.#o.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#K(),this.#M({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#a){this.#a=t;for(const e of this.#a)this.#H(e.defaultPropertiesToUpdate)}}getId(){return this.#P.id}get currentLayer(){return this.#i.get(this.#d)}getLayer(t){return this.#i.get(t)}get currentPageIndex(){return this.#d}addLayer(t){this.#i.set(t.pageIndex,t),this.#x?t.enable():t.disable()}removeLayer(t){this.#i.delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(this.#C!==t&&!(this.#D&&(await this.#D.promise,!this.#D))){if(this.#D=Promise.withResolvers(),this.#C=t,t===J.NONE){this.setEditingState(!1),this.#ot(),this._editorUndoBar?.hide(),this.#D.resolve();return}this.setEditingState(!0),await this.#at(),this.unselectAll();for(const i of this.#i.values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#D.resolve();return}for(const i of this.#s.values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();this.#D.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#C&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#a){switch(t){case st.CREATE:this.currentLayer.addNewEditor();return;case st.HIGHLIGHT_DEFAULT_COLOR:this.#F?.updateColor(e);break;case st.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#V||=new Map).set(t,e),this.showAllEditors("highlight",e);break}for(const s of this.#y)s.updateParams(t,e);for(const s of this.#a)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#V?.get(st.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#H([[st.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#k!==t){this.#k=t;for(const e of this.#i.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#at(){if(!this.#x){this.#x=!0;const t=[];for(const e of this.#i.values())t.push(e.enable());await Promise.all(t);for(const e of this.#s.values())e.enable()}}#ot(){if(this.unselectAll(),this.#x){this.#x=!1;for(const t of this.#i.values())t.disable();for(const t of this.#s.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#s.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.focusMainContainer(),this.#b=null},0)),this.#s.delete(t.id),this.unselect(t),(!t.annotationElementId||!this.#u.has(t.annotationElementId))&&this.#n?.remove(t.id)}addDeletedAnnotationElement(t){this.#u.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#u.has(t)}removeDeletedAnnotationElement(t){this.#u.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#J(t){const e=this.#i.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#H(t.propertiesToUpdate))}get#lt(){let t=null;for(t of this.#y);return t}updateUI(t){this.#lt===t&&this.#H(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#H(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#M({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#M({hasSelectedEditor:!0})}setSelected(t){this.#h?.commitOrRemove();for(const e of this.#y)e!==t&&e.unselect();this.#y.clear(),this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#M({hasSelectedEditor:!0})}isSelected(t){return this.#y.has(t)}get firstSelectedEditor(){return this.#y.values().next().value}unselect(t){t.unselect(),this.#y.delete(t),this.#M({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#y.size!==0}get isEnterHandled(){return this.#y.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#o.undo(),this.#M({hasSomethingToUndo:this.#o.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#X()}),this._editorUndoBar?.hide()}redo(){this.#o.redo(),this.#M({hasSomethingToUndo:!0,hasSomethingToRedo:this.#o.hasSomethingToRedo(),isEmpty:this.#X()})}addCommands(t){this.#o.add(t),this.#M({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#X()})}cleanUndoStack(t){this.#o.cleanType(t)}#X(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#y],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#J(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Q(t){for(const e of this.#y)e.unselect();this.#y.clear();for(const e of t)e.isEmpty()||(this.#y.add(e),e.select());this.#M({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#y)t.commit();this.#Q(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==J.NONE))&&!this.#h?.commitOrRemove()&&this.hasSelection){for(const t of this.#y)t.unselect();this.#y.clear(),this.#M({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#j[0]+=t,this.#j[1]+=e;const[i,n]=this.#j,r=[...this.#y],a=1e3;this.#L&&clearTimeout(this.#L),this.#L=setTimeout(()=>{this.#L=null,this.#j[0]=this.#j[1]=0,this.addCommands({cmd:()=>{for(const l of r)this.#s.has(l.id)&&l.translateInPage(i,n)},undo:()=>{for(const l of r)this.#s.has(l.id)&&l.translateInPage(-i,-n)},mustExec:!1})},a);for(const l of r)l.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(const t of this.#y)this.#f.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);const t=this.#f;this.#f=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},a]of t)a.newX=i,a.newY=n,a.newPageIndex=r,e||=i!==a.savedX||n!==a.savedY||r!==a.savedPageIndex;if(!e)return!1;const s=(i,n,r,a)=>{if(this.#s.has(i.id)){const l=this.#i.get(a);l?i._setParentAndPosition(l,n,r):(i.pageIndex=a,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:a}]of t)s(i,n,r,a)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:a}]of t)s(i,n,r,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#f)for(const s of this.#f.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(){return this.getActive()?.shouldGetKeyboardEvents()||this.#y.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#C}get imageManager(){return tt(this,"imageManager",new Ma)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let h=0,c=e.rangeCount;h<c;h++)if(!t.contains(e.getRangeAt(h).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(h,c,u,d)=>({x:(c-i)/r,y:1-(h+u-s)/n,width:d/r,height:u/n});break;case"180":a=(h,c,u,d)=>({x:1-(h+u-s)/n,y:1-(c+d-i)/r,width:u/n,height:d/r});break;case"270":a=(h,c,u,d)=>({x:1-(c+d-i)/r,y:(h-s)/n,width:d/r,height:u/n});break;default:a=(h,c,u,d)=>({x:(h-s)/n,y:(c-i)/r,width:u/n,height:d/r});break}const l=[];for(let h=0,c=e.rangeCount;h<c;h++){const u=e.getRangeAt(h);if(!u.collapsed)for(const{x:d,y:f,width:g,height:p}of u.getClientRects())g===0||p===0||l.push(a(d,f,g,p))}return l.length===0?null:l}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#l||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#l?.delete(t)}renderAnnotationElement(t){const e=this.#l?.get(t.data.id);if(!e)return;const s=this.#n.getRawValue(e);s&&(this.#C===J.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Ve{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#l=!1;#o=null;#c=null;#h=null;#d=null;#u=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#u=t._uiManager.useNewAltTextFlow,Ve.#f||=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){Ve._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#i=document.createElement("span");t.append(e),this.#u?(t.classList.add("new"),t.setAttribute("data-l10n-id",Ve.#f.missing),e.setAttribute("data-l10n-id",Ve.#f["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=this.#c._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#u&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#a}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#l=!0,i(n))},{signal:s}),await this.#g(),t}get#a(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#l}),this.#l=!1)}isEmpty(){return this.#u?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#u?this.#t!==null||!!this.#h:this.isEmpty()}get guessedText(){return this.#h}async setGuessedText(t){this.#t===null&&(this.#h=t,this.#d=await Ve._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#u||this.#t){this.#o?.remove(),this.#o=null;return}if(!this.#o){const e=this.#o=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#o.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#h===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#h,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#h=s,this.#d=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#s&&(!t&&this.#n&&(clearTimeout(this.#n),this.#n=null),this.#s.disabled=!t)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#a}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#r=null,this.#o?.remove(),this.#o=null}async#g(){const t=this.#s;if(!t)return;if(this.#u){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",Ve.#f[this.#a]),this.#i?.setAttribute("data-l10n-id",Ve.#f[`${this.#a}-label`]),!this.#t){this.#r?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#r?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#r;if(!e){this.#r=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#c.id}`;const i=100,n=this.#c._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#n),this.#n=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#n=setTimeout(()=>{this.#n=null,this.#r.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#n&&(clearTimeout(this.#n),this.#n=null),this.#r?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#c.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class er{#t;#e=!1;#s=null;#i;#r;#n;#l;#o;#c=null;#h;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#t=t,this.#s=s,this.#i=e,this.#r=i,this.#n=n,this.#l=r,this.#h=new AbortController,this.#o=AbortSignal.any([a,this.#h.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#o})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return tt(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#u(t){if(this.#i?.()||t.touches.length<2)return;if(!this.#d){this.#d=new AbortController;const i=AbortSignal.any([this.#o,this.#d.signal]),n=this.#t,r={signal:i,passive:!1};n.addEventListener("touchmove",this.#f.bind(this),r),n.addEventListener("touchend",this.#a.bind(this),r),n.addEventListener("touchcancel",this.#a.bind(this),r),this.#r?.()}if(ge(t),t.touches.length!==2||this.#s?.()){this.#c=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#c={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:a}=s,l=this.#c,{touch0X:h,touch0Y:c,touch1X:u,touch1Y:d}=l,f=u-h,g=d-c,p=r-i,v=a-n,m=Math.hypot(p,v)||1,b=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(b-m)<=er.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(l.touch0X=i,l.touch0Y=n,l.touch1X=r,l.touch1Y=a,t.preventDefault(),!this.#e){this.#e=!0;return}const _=[(i+r)/2,(n+a)/2];this.#n?.(_,b,m)}#a(t){this.#d.abort(),this.#d=null,this.#l?.(),this.#c&&(t.preventDefault(),this.#c=null,this.#e=!1)}destroy(){this.#h?.abort(),this.#h=null}}class G{#t=null;#e=null;#s=null;#i=!1;#r=null;#n="";#l=!1;#o=null;#c=null;#h=null;#d=null;#u="";#f=!1;#a=null;#g=!1;#m=!1;#p=!1;#v=null;#_=0;#b=0;#w=null;#S=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#A=!1;#E=G._zIndex++;static _borderLineWidth=-1;static _colorManager=new Oa;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=G.prototype._resizeWithKeyboard,e=us.TRANSLATE_SMALL,s=us.TRANSLATE_BIG;return tt(this,"_resizerKeyboardManager",new Li([[["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"],G.prototype._stopResizingWithKeyboard]]))}constructor(t){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[a,l]=this.parentDimensions;this.x=t.x/a,this.y=t.y/l,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return tt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Uf({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(G._l10n??=t,G._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"}),G._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);G._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){ut("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#A}set _isDraggable(t){this.#A=t,this.div?.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=this.#E}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#B(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.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()}#P([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#P(this.parentDimensions,t,e)}translateInPage(t,e){this.#a||=[this.x,this.y,this.width,this.height],this.#P(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#a||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:u,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,u,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[l,h]=this.getBaseTranslation();r+=l,a+=h;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#a&&(this.#a[0]!==this.x||this.#a[1]!==this.y)}get _hasBeenResized(){return!!this.#a&&(this.#a[2]!==this.width||this.#a[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=G,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{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:a,height:l}=this;if(a*=s,l*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-a,n)),r=Math.max(0,Math.min(i-l,r));break;case 90:n=Math.max(0,Math.min(s-l,n)),r=Math.min(i,Math.max(a,r));break;case 180:n=Math.min(s,Math.max(a,n)),r=Math.min(i,Math.max(l,r));break;case 270:n=Math.min(s,Math.max(l,n)),r=Math.max(0,Math.min(i-a,r));break}this.x=n/=s,this.y=r/=i;const[h,c]=this.getBaseTranslation();n+=h,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#x(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return G.#x(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return G.#x(t,e,360-this.parentRotation)}#k(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]}}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,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,this.#l||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#l&&e.endsWith("%");if(i&&n)return;const[r,a]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#l&&!n&&(t.height=`${(100*parseFloat(e)/a).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#T(){if(this.#o)return;this.#o=document.createElement("div"),this.#o.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");this.#o.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#O.bind(this,s),{signal:e}),i.addEventListener("contextmenu",Oe,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#o)}#O(t,e){e.preventDefault();const{isMac:s}=Qt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#c=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#C.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",ge,{passive:!1,signal:r}),window.addEventListener("contextmenu",Oe,{signal:r}),this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,l=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const h=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=l,this.#I()};window.addEventListener("pointerup",h,{signal:r}),window.addEventListener("blur",h,{signal:r})}#F(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()}_onResized(){}#I(){if(!this.#h)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#h;this.#h=null;const n=this.x,r=this.y,a=this.width,l=this.height;n===t&&r===e&&a===s&&l===i||this.addCommands({cmd:this.#F.bind(this,n,r,a,l),undo:this.#F.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#C(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,a=this.width,l=this.height,h=G.MIN_SIZE/s,c=G.MIN_SIZE/i,u=this.#k(this.rotation),d=(M,L)=>[u[0]*M+u[2]*L,u[1]*M+u[3]*L],f=this.#k(360-this.rotation),g=(M,L)=>[f[0]*M+f[2]*L,f[1]*M+f[3]*L];let p,v,m=!1,b=!1;switch(t){case"topLeft":m=!0,p=(M,L)=>[0,0],v=(M,L)=>[M,L];break;case"topMiddle":p=(M,L)=>[M/2,0],v=(M,L)=>[M/2,L];break;case"topRight":m=!0,p=(M,L)=>[M,0],v=(M,L)=>[0,L];break;case"middleRight":b=!0,p=(M,L)=>[M,L/2],v=(M,L)=>[0,L/2];break;case"bottomRight":m=!0,p=(M,L)=>[M,L],v=(M,L)=>[0,0];break;case"bottomMiddle":p=(M,L)=>[M/2,L],v=(M,L)=>[M/2,0];break;case"bottomLeft":m=!0,p=(M,L)=>[0,L],v=(M,L)=>[M,0];break;case"middleLeft":b=!0,p=(M,L)=>[0,L/2],v=(M,L)=>[M,L/2];break}const _=p(a,l),w=v(a,l);let C=d(...w);const T=G._round(n+C[0]),E=G._round(r+C[1]);let k=1,O=1,H,N;if(e.fromKeyboard)({deltaX:H,deltaY:N}=e);else{const{screenX:M,screenY:L}=e,[Y,ft]=this.#c;[H,N]=this.screenToPageTranslation(M-Y,L-ft),this.#c[0]=M,this.#c[1]=L}if([H,N]=g(H/s,N/i),m){const M=Math.hypot(a,l);k=O=Math.max(Math.min(Math.hypot(w[0]-_[0]-H,w[1]-_[1]-N)/M,1/a,1/l),h/a,c/l)}else b?k=Math.max(h,Math.min(1,Math.abs(w[0]-_[0]-H)))/a:O=Math.max(c,Math.min(1,Math.abs(w[1]-_[1]-N)))/l;const P=G._round(a*k),R=G._round(l*O);C=d(...v(P,R));const F=T-C[0],V=E-C[1];this.#a||=[this.x,this.y,this.width,this.height],this.width=P,this.height=R,this.x=F,this.y=V,this.setDims(s*P,i*R),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new Fi(this),this.div.append(this._editToolbar.render()),this.#s&&await this._editToolbar.addAltText(this.#s),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#s?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#s||(Ve.initialize(G._l10n),this.#s=new Ve(this),this.#t&&(this.#s.data=this.#t,this.#t=null),await this.addEditToolbar())}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.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=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#j();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),tr(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new er({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#z.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#y(){this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#R(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#k(this.rotation),a=(T,E)=>[r[0]*T+r[2]*E,r[1]*T+r[3]*E],[l,h]=this.parentDimensions,c=this.x,u=this.y,d=this.width,f=this.height,g=G.MIN_SIZE/l,p=G.MIN_SIZE/h;n=Math.max(Math.min(n,1/d,1/f),g/d,p/f);const v=G._round(d*n),m=G._round(f*n);if(v===d&&m===f)return;this.#a||=[c,u,d,f];const b=a(d/2,f/2),_=G._round(c+b[0]),w=G._round(u+b[1]),C=a(v/2,m/2);this.x=_-C[0],this.y=w-C[1],this.width=v,this.height=m,this.setDims(l*v,h*m),this.fixAndSetPosition(),this._onResizing()}#z(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=Qt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#G(t);return}this.#V(t)}get isSelected(){return this._uiManager.isSelected(this)}#V(t){const{isMac:e}=Qt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#G(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},a=h=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#V(h),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#b=t.clientY,this.#r=t.pointerId,this.#n=t.pointerType,window.addEventListener("pointermove",h=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:u,pointerId:d}=h;if(d!==this.#r){ge(h);return}const[f,g]=this.screenToPageTranslation(c-this.#_,u-this.#b);this.#_=c,this.#b=u,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",ge,r),window.addEventListener("pointerdown",h=>{h.pointerType===this.#n&&(this.#S||h.isPrimary)&&a(h),ge(h)},r));const l=h=>{if(!this.#r||this.#r===h.pointerId){a(h);return}ge(h)};window.addEventListener("pointerup",l,{signal:n}),window.addEventListener("blur",l,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.#v=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[a,l]=this.pageTranslation,h=t/i,c=e/i,u=this.x*n,d=this.y*r,f=this.width*n,g=this.height*r;switch(s){case 0:return[u+h+a,r-d-c-g+l,u+h+f+a,r-d-c+l];case 90:return[u+c+a,r-d+h+l,u+c+g+a,r-d+h+f+l];case 180:return[u-h-f+a,r-d+c+l,u-h+a,r-d+c+g+l];case 270:return[u-c-g+a,r-d-h-f+l,u-c+a,r-d-h+l];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,a=n-s,l=r-i;switch(this.rotation){case 0:return[s,e-r,a,l];case 90:return[s,e-i,l,a];case 180:return[n,e-i,a,l];case 270:return[n,e-r,l,a];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#m=!0}disableEditMode(){this.#m=!1}isInEditMode(){return this.#m}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#j(){if(this.#d||!this.div)return;this.#d=new AbortController;const t=this._uiManager.combinedSignal(this.#d);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#j()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){ut("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,i.#t=t.accessibilityData;const[n,r]=i.pageDimensions,[a,l,h,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=a/n,i.y=l/r,i.width=h/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#d?.abort(),this.#d=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#v&&(clearTimeout(this.#v),this.#v=null),this.#B(),this.removeEditToolbar(),this.#w){for(const t of this.#w.values())clearTimeout(t);this.#w=null}this.parent=null,this.#S?.destroy(),this.#S=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#T(),this.#o.classList.remove("hidden"),tr(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),this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#o.children;if(!this.#e){this.#e=Array.from(e);const r=this.#L.bind(this),a=this.#N.bind(this),l=this._uiManager._signal;for(const h of this.#e){const c=h.getAttribute("data-resizer-name");h.setAttribute("role","spinbutton"),h.addEventListener("keydown",r,{signal:l}),h.addEventListener("blur",a,{signal:l}),h.addEventListener("focus",this.#W.bind(this,c),{signal:l}),h.setAttribute("data-l10n-id",G._l10nResizer[c])}}const s=this.#e[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let a=0;a<i-n;a++)this.#o.append(this.#o.firstChild);else if(n>i)for(let a=0;a<n-i;a++)this.#o.firstChild.before(this.#o.lastChild);let r=0;for(const a of e){const h=this.#e[r++].getAttribute("data-resizer-name");a.setAttribute("data-l10n-id",G._l10nResizer[h])}}this.#D(0),this.#p=!0,this.#o.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#L(t){G._resizerKeyboardManager.exec(this,t)}#N(t){this.#p&&t.relatedTarget?.parentNode!==this.#o&&this.#B()}#W(t){this.#u=this.#p?t:""}#D(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#p&&this.#C(this.#u,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#p=!1,this.#D(-1),this.#I()}_stopResizingWithKeyboard(){this.#B(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#s?.toggleAltTextBadge(!1)}unselect(){this.#o?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(t){this.#g=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#l=!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){this.#w||=new Map;const{action:s}=t;let i=this.#w.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#w.delete(s),this.#w.size===0&&(this.#w=null)},G._telemetryTimeout),this.#w.set(s,i);return}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),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class Uf extends G{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Ch=3285377520,be=4294901760,Ge=65535;class Ah{constructor(t){this.h1=t?t&4294967295:Ch,this.h2=t?t&4294967295:Ch}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,v=t.length;p<v;p++){const m=t.charCodeAt(p);m<=255?e[s++]=m:(e[s++]=m>>>8,e[s++]=m&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 a=0,l=0,h=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&Ge,g=d&Ge;for(let p=0;p<i;p++)p&1?(a=r[p],a=a*u&be|a*f&Ge,a=a<<15|a>>>17,a=a*d&be|a*g&Ge,h^=a,h=h<<13|h>>>19,h=h*5+3864292196):(l=r[p],l=l*u&be|l*f&Ge,l=l<<15|l>>>17,l=l*d&be|l*g&Ge,c^=l,c=c<<13|c>>>19,c=c*5+3864292196);switch(a=0,n){case 3:a^=e[i*4+2]<<16;case 2:a^=e[i*4+1]<<8;case 1:a^=e[i*4],a=a*u&be|a*f&Ge,a=a<<15|a>>>17,a=a*d&be|a*g&Ge,i&1?h^=a:c^=a}this.h1=h,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&be|t*36045&Ge,e=e*4283543511&be|((e<<16|t>>>16)*2950163797&be)>>>16,t^=e>>>1,t=t*444984403&be|t*60499&Ge,e=e*3301882366&be|((e<<16|t>>>16)*3120437893&be)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Da=Object.freeze({map:null,hash:"",transfer:void 0});class Ra{#t=!1;#e=null;#s=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#s.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#s.get(t)}remove(t){if(this.#s.delete(t),this.#s.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of this.#s.values())if(e instanceof G)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#s.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,this.#s.set(t,e);i&&this.#i(),e instanceof G&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?xa(this.#s):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#s.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Th(this)}get serializable(){if(this.#s.size===0)return Da;const t=new Map,e=new Ah,s=[],i=Object.create(null);let n=!1;for(const[r,a]of this.#s){const l=a instanceof G?a.serialize(!1,i):a;l&&(t.set(r,l),e.update(`${r}:${JSON.stringify(l)}`),n||=!!l.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}:Da}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof G))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const r=t[n]||=new Map;for(const[a,l]of Object.entries(i)){if(a==="type")continue;let h=r.get(a);h||(h=new Map,r.set(a,h));const c=h.get(l)??0;h.set(l,c+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#s.values())!(e instanceof G)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Th extends Ra{#t;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#t={map:n,hash:s,transfer:i}}get print(){ut("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return tt(this,"modifiedIds",{ids:new Set,hash:""})}}class Yf{#t=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){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(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#t.has(t.loadedName))){if(Mt(!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(),this.#t.add(s),e?.(t)}catch{Q(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}ut("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 Q(`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(){const t=!!this._document?.fonts;return tt(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Gt||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),tt(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(Mt(!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 tt(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(w,C){return w.charCodeAt(C)<<24|w.charCodeAt(C+1)<<16|w.charCodeAt(C+2)<<8|w.charCodeAt(C+3)&255}function i(w,C,T,E){const k=w.substring(0,C),O=w.substring(C+T);return k+E+O}let n,r;const a=this._document.createElement("canvas");a.width=1,a.height=1;const l=a.getContext("2d");let h=0;function c(w,C){if(++h>30){Q("Load test font never loaded."),C();return}if(l.font="30px "+w,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(c.bind(null,w,C))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const g=16,p=1482184792;let v=s(d,g);for(n=0,r=u.length-3;n<r;n+=4)v=v-p+s(u,n)|0;n<u.length&&(v=v-p+s(u+"XXX",n)|0),d=i(d,g,4,Df(v));const m=`url(data:font/opentype;base64,${btoa(d)});`,b=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(b);const _=this._document.createElement("div");_.style.visibility="hidden",_.style.width=_.style.height="10px",_.style.position="absolute",_.style.top=_.style.left="0px";for(const w of[t.loadedName,u]){const C=this._document.createElement("span");C.textContent="Hi",C.style.fontFamily=w,_.append(C)}this._document.body.append(_),c(u,()=>{_.remove(),e.complete()})}}class $f{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Nf(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){Q(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const sr={DATA:1,ERROR:2},Ot={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Eh(){}function re(o){if(o instanceof cs||o instanceof wa||o instanceof Oi||o instanceof yh||o instanceof Kn||o instanceof _a)return o;switch(o instanceof Error||typeof o=="object"&&o!==null||ut('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),o.name){case"AbortException":return new cs(o.message);case"InvalidPDFException":return new wa(o.message);case"MissingPDFException":return new Oi(o.message);case"PasswordException":return new yh(o.message,o.code);case"UnexpectedResponseException":return new Kn(o.message,o.status);case"UnknownErrorException":return new _a(o.message,o.details)}return new _a(o.message,o.toString())}class Ii{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#i(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===sr.DATA)i.resolve(t.data);else if(t.callback===sr.ERROR)i.reject(re(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;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:sr.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:sr.ERROR,callbackId:t.callbackId,reason:re(r)})});return}if(t.streamId){this.#s(t);return}e(t.data)}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,a=this.targetName,l=this.comObj;return new ReadableStream({start:h=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:h,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},l.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:h.desiredSize},i),c.promise},pull:h=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,l.postMessage({sourceName:r,targetName:a,stream:Ot.PULL,streamId:n,desiredSize:h.desiredSize}),c.promise},cancel:h=>{Mt(h instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,l.postMessage({sourceName:r,targetName:a,stream:Ot.CANCEL,streamId:n,reason:re(h)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],l={enqueue(h,c=1,u){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=c,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:Ot.ENQUEUE,streamId:e,chunk:h},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ot.CLOSE,streamId:e}),delete r.streamSinks[e])},error(h){Mt(h instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ot.ERROR,streamId:e,reason:re(h)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};l.sinkCapability.resolve(),l.ready=l.sinkCapability.promise,this.streamSinks[e]=l,Promise.try(a,t.data,l).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ot.START_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Ot.START_COMPLETE,streamId:e,reason:re(h)})})}#i(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case Ot.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(re(t.reason));break;case Ot.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(re(t.reason));break;case Ot.PULL:if(!a){n.postMessage({sourceName:s,targetName:i,stream:Ot.PULL_COMPLETE,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||Eh).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ot.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Ot.PULL_COMPLETE,streamId:e,reason:re(h)})});break;case Ot.ENQUEUE:if(Mt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Ot.CLOSE:if(Mt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case Ot.ERROR:Mt(r,"error should have stream controller"),r.controller.error(re(t.reason)),this.#r(r,e);break;case Ot.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(re(t.reason)),this.#r(r,e);break;case Ot.CANCEL:if(!a)break;const l=re(t.reason);Promise.try(a.onCancel||Eh,l).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ot.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Ot.CANCEL_COMPLETE,streamId:e,reason:re(h)})}),a.sinkCapability.reject(l),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#r(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class kh{#t=!1;constructor({enableHWA:t=!1}){this.#t=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:!this.#t})}}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){ut("Abstract method `_createCanvas` called.")}}class qf extends kh{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 Ph{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){ut("Abstract method `_fetch` called.")}}class Mh extends Ph{async _fetch(t){const e=await Qn(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):Jn(e)}}class Oh{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 Kf extends Oh{#t;#e;#s;#i;#r;#n;#l=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#o(){return this.#e||=new Map}get#c(){return this.#n||=new Map}get#h(){if(!this.#s){const t=this.#r.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#r.createElementNS(es,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(es,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#d(t){if(t.length===1){const l=t[0],h=new Array(256);for(let u=0;u<256;u++)h[u]=l[u]/255;const c=h.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),a=new Array(256);for(let l=0;l<256;l++)n[l]=e[l]/255,r[l]=s[l]/255,a[l]=i[l]/255;return[n.join(","),r.join(","),a.join(",")]}#u(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Zn(e)?Q('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=e.split("#",1)[0])}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#o.get(t);if(e)return e;const[s,i,n]=this.#d(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#o.get(r),e)return this.#o.set(t,e),e;const a=`g_${this.#i}_transfer_map_${this.#l++}`,l=this.#u(a);this.#o.set(t,l),this.#o.set(r,l);const h=this.#g(a);return this.#p(s,i,n,h),l}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#c.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#c.set(i,n)),!t||!e))return n.url;const r=this.#_(t);t=z.makeHexColor(...r);const a=this.#_(e);if(e=z.makeHexColor(...a),this.#h.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const l=new Array(256);for(let f=0;f<=255;f++){const g=f/255;l[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const h=l.join(","),c=`g_${this.#i}_hcm_filter`,u=n.filter=this.#g(c);this.#p(h,h,h,u),this.#a(u);const d=(f,g)=>{const p=r[f]/255,v=a[f]/255,m=new Array(g+1);for(let b=0;b<=g;b++)m[b]=p+b/g*(v-p);return m.join(",")};return this.#p(d(0,5),d(1,5),d(2,5),u),n.url=this.#u(c),n.url}addAlphaFilter(t){let e=this.#o.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#o.get(i),e)return this.#o.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#l++}`,r=this.#u(n);this.#o.set(t,r),this.#o.set(i,r);const a=this.#g(n);return this.#v(s,a),r}addLuminosityFilter(t){let e=this.#o.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#o.get(i),e)return this.#o.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#l++}`,r=this.#u(n);this.#o.set(t,r),this.#o.set(i,r);const a=this.#g(n);return this.#f(a),t&&this.#v(s,a),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let a=this.#c.get(t);if(a?.key===r||(a?(a.filter?.remove(),a.key=r,a.url="none",a.filter=null):(a={key:r,url:"none",filter:null},this.#c.set(t,a)),!e||!s))return a.url;const[l,h]=[e,s].map(this.#_.bind(this));let c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),u=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),[d,f]=[i,n].map(this.#_.bind(this));u<c&&([c,u,d,f]=[u,c,f,d]),this.#h.style.color="";const g=(m,b,_)=>{const w=new Array(256),C=(u-c)/_,T=m/255,E=(b-m)/(255*_);let k=0;for(let O=0;O<=_;O++){const H=Math.round(c+O*C),N=T+O*E;for(let P=k;P<=H;P++)w[P]=N;k=H+1}for(let O=k;O<256;O++)w[O]=w[k-1];return w.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,v=a.filter=this.#g(p);return this.#a(v),this.#p(g(d[0],f[0],5),g(d[1],f[1],5),g(d[2],f[2],5),v),a.url=this.#u(p),a.url}destroy(t=!1){t&&this.#n?.size||(this.#s?.parentNode.parentNode.remove(),this.#s=null,this.#e?.clear(),this.#e=null,this.#n?.clear(),this.#n=null,this.#l=0)}#f(t){const e=this.#r.createElementNS(es,"feColorMatrix");e.setAttribute("type","matrix"),e.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"),t.append(e)}#a(t){const e=this.#r.createElementNS(es,"feColorMatrix");e.setAttribute("type","matrix"),e.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"),t.append(e)}#g(t){const e=this.#r.createElementNS(es,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#h.append(e),e}#m(t,e,s){const i=this.#r.createElementNS(es,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(es,"feComponentTransfer");i.append(n),this.#m(n,"feFuncR",t),this.#m(n,"feFuncG",e),this.#m(n,"feFuncB",s)}#v(t,e){const s=this.#r.createElementNS(es,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#h.style.color=t,ka(getComputedStyle(this.#h).getPropertyValue("color"))}}class Dh{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){ut("Abstract method `_fetch` called.")}}class Rh extends Dh{async _fetch(t){const e=await Qn(t,"arraybuffer");return new Uint8Array(e)}}Gt&&Q("Please use the `legacy` build in Node.js environments.");async function Fh(o){const e=await process.getBuiltinModule("fs").promises.readFile(o);return new Uint8Array(e)}class Jf extends Oh{}class Qf extends kh{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:jt&&jt.tagName.toUpperCase()==="SCRIPT"&&jt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class Zf extends Ph{async _fetch(t){return Fh(t)}}class tg extends Dh{async _fetch(t){return Fh(t)}}const Xt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Fa(o,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),o.clip(i)}class La{getPattern(){ut("Abstract method `getPattern` called.")}}class eg extends La{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===Xt.STROKE||i===Xt.FILL){const r=e.current.getClippedPathBoundingBox(i,mt(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,l=Math.ceil(r[3]-r[1])||1,h=e.cachedCanvases.getCanvas("pattern",a,l),c=h.context;c.clearRect(0,0,c.canvas.width,c.canvas.height),c.beginPath(),c.rect(0,0,c.canvas.width,c.canvas.height),c.translate(-r[0],-r[1]),s=z.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),Fa(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(h.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else Fa(t,this._bbox),n=this._createGradient(t);return n}}function Ia(o,t,e,s,i,n,r,a){const l=t.coords,h=t.colors,c=o.data,u=o.width*4;let d;l[e+1]>l[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d),l[s+1]>l[i+1]&&(d=s,s=i,i=d,d=r,r=a,a=d),l[e+1]>l[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d);const f=(l[e]+t.offsetX)*t.scaleX,g=(l[e+1]+t.offsetY)*t.scaleY,p=(l[s]+t.offsetX)*t.scaleX,v=(l[s+1]+t.offsetY)*t.scaleY,m=(l[i]+t.offsetX)*t.scaleX,b=(l[i+1]+t.offsetY)*t.scaleY;if(g>=b)return;const _=h[n],w=h[n+1],C=h[n+2],T=h[r],E=h[r+1],k=h[r+2],O=h[a],H=h[a+1],N=h[a+2],P=Math.round(g),R=Math.round(b);let F,V,M,L,Y,ft,bt,_t;for(let gt=P;gt<=R;gt++){if(gt<v){const $=gt<g?0:(g-gt)/(g-v);F=f-(f-p)*$,V=_-(_-T)*$,M=w-(w-E)*$,L=C-(C-k)*$}else{let $;gt>b?$=1:v===b?$=0:$=(v-gt)/(v-b),F=p-(p-m)*$,V=T-(T-O)*$,M=E-(E-H)*$,L=k-(k-N)*$}let rt;gt<g?rt=0:gt>b?rt=1:rt=(g-gt)/(g-b),Y=f-(f-m)*rt,ft=_-(_-O)*rt,bt=w-(w-H)*rt,_t=C-(C-N)*rt;const Dt=Math.round(Math.min(F,Y)),ee=Math.round(Math.max(F,Y));let K=u*gt+Dt*4;for(let $=Dt;$<=ee;$++)rt=(F-$)/(F-Y),rt<0?rt=0:rt>1&&(rt=1),c[K++]=V-(V-ft)*rt|0,c[K++]=M-(M-bt)*rt|0,c[K++]=L-(L-_t)*rt|0,c[K++]=255}}function sg(o,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const a=t.verticesPerRow,l=Math.floor(s.length/a)-1,h=a-1;for(n=0;n<l;n++){let c=n*a;for(let u=0;u<h;u++,c++)Ia(o,e,s[c],s[c+1],s[c+a],i[c],i[c+1],i[c+a]),Ia(o,e,s[c+a+1],s[c+1],s[c+a],i[c+a+1],i[c+1],i[c+a])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)Ia(o,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 ig extends La{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 a=Math.floor(this._bounds[0]),l=Math.floor(this._bounds[1]),h=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-l,u=Math.min(Math.ceil(Math.abs(h*t[0]*1.1)),3e3),d=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=h/u,g=c/d,p={coords:this._coords,colors:this._colors,offsetX:-a,offsetY:-l,scaleX:1/f,scaleY:1/g},v=u+2*2,m=d+2*2,b=s.getCanvas("mesh",v,m),_=b.context,w=_.createImageData(u,d);if(e){const T=w.data;for(let E=0,k=T.length;E<k;E+=4)T[E]=e[0],T[E+1]=e[1],T[E+2]=e[2],T[E+3]=255}for(const T of this._figures)sg(w,T,p);return _.putImageData(w,2,2),{canvas:b.canvas,offsetX:a-2*f,offsetY:l-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){Fa(t,this._bbox);let n;if(i===Xt.SHADING)n=z.singularValueDecompose2dScale(mt(t));else if(n=z.singularValueDecompose2dScale(e.baseTransform),this.matrix){const a=z.singularValueDecompose2dScale(this.matrix);n=[n[0]*a[0],n[1]*a[1]]}const r=this._createMeshCanvas(n,i===Xt.SHADING?null:this._background,e.cachedCanvases);return i!==Xt.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 ng extends La{getPattern(){return"hotpink"}}function rg(o){switch(o[0]){case"RadialAxial":return new eg(o);case"Mesh":return new ig(o);case"Dummy":return new ng}throw new Error(`Unknown IR type: ${o[0]}`)}const Lh={COLORED:1,UNCOLORED:2};class ja{static MAX_PATTERN_SIZE=3e3;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:a}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),qn("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,v=z.singularValueDecompose2dScale(this.matrix),m=z.singularValueDecompose2dScale(this.baseTransform),b=v[0]*m[0],_=v[1]*m[1];let w=g,C=p,T=!1,E=!1;const k=Math.ceil(l*b),O=Math.ceil(h*_),H=Math.ceil(g*b),N=Math.ceil(p*_);k>=H?w=l:T=!0,O>=N?C=h:E=!0;const P=this.getSizeAndScale(w,this.ctx.canvas.width,b),R=this.getSizeAndScale(C,this.ctx.canvas.height,_),F=t.cachedCanvases.getCanvas("pattern",P.size,R.size),V=F.context,M=a.createCanvasGraphics(V);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,i,r),V.translate(-P.scale*c,-R.scale*u),M.transform(P.scale,0,0,R.scale,0,0),V.save(),this.clipBbox(M,c,u,d,f),M.baseTransform=mt(M.ctx),M.executeOperatorList(s),M.endDrawing(),V.restore(),T||E){const L=F.canvas;T&&(w=l),E&&(C=h);const Y=this.getSizeAndScale(w,this.ctx.canvas.width,b),ft=this.getSizeAndScale(C,this.ctx.canvas.height,_),bt=Y.size,_t=ft.size,gt=t.cachedCanvases.getCanvas("pattern-workaround",bt,_t),rt=gt.context,Dt=T?Math.floor(g/l):0,ee=E?Math.floor(p/h):0;for(let K=0;K<=Dt;K++)for(let $=0;$<=ee;$++)rt.drawImage(L,bt*K,_t*$,bt,_t,0,0,bt,_t);return{canvas:gt.canvas,scaleX:Y.scale,scaleY:ft.scale,offsetX:c,offsetY:u}}return{canvas:F.canvas,scaleX:P.scale,scaleY:R.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(ja.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,a=n-s;t.ctx.rect(e,s,r,a),t.current.updateRectMinMax(mt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case Lh.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case Lh.UNCOLORED:const a=z.makeHexColor(s[0],s[1],s[2]);i.fillStyle=a,i.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new Of(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Xt.SHADING&&(n=z.transform(n,e.baseTransform),this.matrix&&(n=z.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let a=new DOMMatrix(n);a=a.translate(r.offsetX,r.offsetY),a=a.scale(1/r.scaleX,1/r.scaleY);const l=t.createPattern(r.canvas,"repeat");return l.setTransform(a),l}}function ag({src:o,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const a=Qt.isLittleEndian?4278190080:255,[l,h]=r?[n,a]:[a,n],c=s>>3,u=s&7,d=o.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const v=t+c;t<v;t++){const m=t<d?o[t]:255;e[f++]=m&128?h:l,e[f++]=m&64?h:l,e[f++]=m&32?h:l,e[f++]=m&16?h:l,e[f++]=m&8?h:l,e[f++]=m&4?h:l,e[f++]=m&2?h:l,e[f++]=m&1?h:l}if(u===0)continue;const p=t<d?o[t++]:255;for(let v=0;v<u;v++)e[f++]=p&1<<7-v?h:l}return{srcPos:t,destPos:f}}const Ih=16,jh=100,og=15,Nh=10,Bh=1e3,ae=16;function lg(o,t){if(o._removeMirroring)throw new Error("Context is already forwarding operations.");o.__originalSave=o.save,o.__originalRestore=o.restore,o.__originalRotate=o.rotate,o.__originalScale=o.scale,o.__originalTranslate=o.translate,o.__originalTransform=o.transform,o.__originalSetTransform=o.setTransform,o.__originalResetTransform=o.resetTransform,o.__originalClip=o.clip,o.__originalMoveTo=o.moveTo,o.__originalLineTo=o.lineTo,o.__originalBezierCurveTo=o.bezierCurveTo,o.__originalRect=o.rect,o.__originalClosePath=o.closePath,o.__originalBeginPath=o.beginPath,o._removeMirroring=()=>{o.save=o.__originalSave,o.restore=o.__originalRestore,o.rotate=o.__originalRotate,o.scale=o.__originalScale,o.translate=o.__originalTranslate,o.transform=o.__originalTransform,o.setTransform=o.__originalSetTransform,o.resetTransform=o.__originalResetTransform,o.clip=o.__originalClip,o.moveTo=o.__originalMoveTo,o.lineTo=o.__originalLineTo,o.bezierCurveTo=o.__originalBezierCurveTo,o.rect=o.__originalRect,o.closePath=o.__originalClosePath,o.beginPath=o.__originalBeginPath,delete o._removeMirroring},o.save=function(){t.save(),this.__originalSave()},o.restore=function(){t.restore(),this.__originalRestore()},o.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},o.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},o.transform=function(s,i,n,r,a,l){t.transform(s,i,n,r,a,l),this.__originalTransform(s,i,n,r,a,l)},o.setTransform=function(s,i,n,r,a,l){t.setTransform(s,i,n,r,a,l),this.__originalSetTransform(s,i,n,r,a,l)},o.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},o.rotate=function(s){t.rotate(s),this.__originalRotate(s)},o.clip=function(s){t.clip(s),this.__originalClip(s)},o.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},o.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},o.bezierCurveTo=function(e,s,i,n,r,a){t.bezierCurveTo(e,s,i,n,r,a),this.__originalBezierCurveTo(e,s,i,n,r,a)},o.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},o.closePath=function(){t.closePath(),this.__originalClosePath()},o.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class hg{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 ir(o,t,e,s,i,n,r,a,l,h){const[c,u,d,f,g,p]=mt(o);if(u===0&&d===0){const b=r*c+g,_=Math.round(b),w=a*f+p,C=Math.round(w),T=(r+l)*c+g,E=Math.abs(Math.round(T)-_)||1,k=(a+h)*f+p,O=Math.abs(Math.round(k)-C)||1;return o.setTransform(Math.sign(c),0,0,Math.sign(f),_,C),o.drawImage(t,e,s,i,n,0,0,E,O),o.setTransform(c,u,d,f,g,p),[E,O]}if(c===0&&f===0){const b=a*d+g,_=Math.round(b),w=r*u+p,C=Math.round(w),T=(a+h)*d+g,E=Math.abs(Math.round(T)-_)||1,k=(r+l)*u+p,O=Math.abs(Math.round(k)-C)||1;return o.setTransform(0,Math.sign(u),Math.sign(d),0,_,C),o.drawImage(t,e,s,i,n,0,0,O,E),o.setTransform(c,u,d,f,g,p),[O,E]}o.drawImage(t,e,s,i,n,r,a,l,h);const v=Math.hypot(c,u),m=Math.hypot(d,f);return[v*l,m*h]}function cg(o){const{width:t,height:e}=o;if(t>Bh||e>Bh)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)),a,l,h;const c=t+7&-8;let u=new Uint8Array(c*e),d=0;for(const m of o.data){let b=128;for(;b>0;)u[d++]=m&b?0:255,b>>=1}let f=0;for(d=0,u[d]!==0&&(r[0]=1,++f),l=1;l<t;l++)u[d]!==u[d+1]&&(r[l]=u[d]?2:1,++f),d++;for(u[d]!==0&&(r[l]=2,++f),a=1;a<e;a++){d=a*c,h=a*n,u[d-c]!==u[d]&&(r[h]=u[d]?1:8,++f);let m=(u[d]?4:0)+(u[d-c]?8:0);for(l=1;l<t;l++)m=(m>>2)+(u[d+1]?4:0)+(u[d-c+1]?8:0),i[m]&&(r[h+l]=i[m],++f),d++;if(u[d-c]!==u[d]&&(r[h+l]=u[d]?2:4,++f),f>s)return null}for(d=c*(e-1),h=a*n,u[d]!==0&&(r[h]=8,++f),l=1;l<t;l++)u[d]!==u[d+1]&&(r[h+l]=u[d]?4:8,++f),d++;if(u[d]!==0&&(r[h+l]=4,++f),f>s)return null;const g=new Int32Array([0,n,-1,0,-n,0,0,0,1]),p=new Path2D;for(a=0;f&&a<=e;a++){let m=a*n;const b=m+t;for(;m<b&&!r[m];)m++;if(m===b)continue;p.moveTo(m%n,a);const _=m;let w=r[m];do{const C=g[w];do m+=C;while(!r[m]);const T=r[m];T!==5&&T!==10?(w=T,r[m]=0):(w=T&51*w>>4,r[m]&=w>>2|w<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(_!==m);--a}return u=null,r=null,function(m){m.save(),m.scale(1/t,-1/e),m.translate(0,-e),m.fill(p),m.beginPath(),m.restore()}}class Hh{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=bh,this.textMatrixScale=1,this.fontMatrix=ba,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=Wt.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!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,a,l,h,c){const u=z.bezierBoundingBox(e,s,i,n,r,a,l,h,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Xt.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Xt.STROKE){e||ut("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=Xt.FILL,e=null){return z.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function zh(o,t){if(t instanceof ImageData){o.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%ae,n=(e-i)/ae,r=i===0?n:n+1,a=o.createImageData(s,ae);let l=0,h;const c=t.data,u=a.data;let d,f,g,p;if(t.kind===Un.GRAYSCALE_1BPP){const v=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),b=m.length,_=s+7>>3,w=4294967295,C=Qt.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?ae:i,h=0,f=0;f<g;f++){const T=v-l;let E=0;const k=T>_?s:T*8-7,O=k&-8;let H=0,N=0;for(;E<O;E+=8)N=c[l++],m[h++]=N&128?w:C,m[h++]=N&64?w:C,m[h++]=N&32?w:C,m[h++]=N&16?w:C,m[h++]=N&8?w:C,m[h++]=N&4?w:C,m[h++]=N&2?w:C,m[h++]=N&1?w:C;for(;E<k;E++)H===0&&(N=c[l++],H=128),m[h++]=N&H?w:C,H>>=1}for(;h<b;)m[h++]=0;o.putImageData(a,0,d*ae)}}else if(t.kind===Un.RGBA_32BPP){for(f=0,p=s*ae*4,d=0;d<n;d++)u.set(c.subarray(l,l+p)),l+=p,o.putImageData(a,0,f),f+=ae;d<r&&(p=s*i*4,u.set(c.subarray(l,l+p)),o.putImageData(a,0,f))}else if(t.kind===Un.RGB_24BPP)for(g=ae,p=s*g,d=0;d<r;d++){for(d>=n&&(g=i,p=s*g),h=0,f=p;f--;)u[h++]=c[l++],u[h++]=c[l++],u[h++]=c[l++],u[h++]=255;o.putImageData(a,0,d*ae)}else throw new Error(`bad image kind: ${t.kind}`)}function Vh(o,t){if(t.bitmap){o.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%ae,n=(e-i)/ae,r=i===0?n:n+1,a=o.createImageData(s,ae);let l=0;const h=t.data,c=a.data;for(let u=0;u<r;u++){const d=u<n?ae:i;({srcPos:l}=ag({src:h,srcPos:l,dest:c,width:s,height:d,nonBlackColor:0})),o.putImageData(a,0,u*ae)}}function ji(o,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)o[s]!==void 0&&(t[s]=o[s]);o.setLineDash!==void 0&&(t.setLineDash(o.getLineDash()),t.lineDashOffset=o.lineDashOffset)}function nr(o){if(o.strokeStyle=o.fillStyle="#000000",o.fillRule="nonzero",o.globalAlpha=1,o.lineWidth=1,o.lineCap="butt",o.lineJoin="miter",o.miterLimit=10,o.globalCompositeOperation="source-over",o.font="10px sans-serif",o.setLineDash!==void 0&&(o.setLineDash([]),o.lineDashOffset=0),!Gt){const{filter:t}=o;t!=="none"&&t!==""&&(o.filter="none")}}function Gh(o,t){if(t)return!0;const e=z.singularValueDecompose2dScale(o);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*ti.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const ug=["butt","round","square"],dg=["miter","round","bevel"],fg={},Wh={};class ei{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:a=null},l,h){this.ctx=t,this.current=new Hh(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=a||[],this.optionalContentConfig=r,this.cachedCanvases=new hg(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=l,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=h,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,a=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=a,s){const l=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=l.canvas,this.ctx=l.context,this.ctx.save(),this.ctx.transform(...mt(this.compositeCtx))}this.ctx.save(),nr(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=mt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let a=e||0;const l=n.length;if(l===a)return a;const h=l-a>Nh&&typeof s=="function",c=h?Date.now()+og:0;let u=0;const d=this.commonObjs,f=this.objs;let g;for(;;){if(i!==void 0&&a===i.nextBreakPoint)return i.breakIt(a,s),a;if(g=r[a],g!==Me.dependency)this[g].apply(this,n[a]);else for(const p of n[a]){const v=p.startsWith("g_")?d:f;if(!v.has(p))return v.get(p,s),a}if(a++,a===l)return a;if(h&&++u>Nh){if(Date.now()>c)return s(),a;u=0}}}#t(){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)}endDrawing(){this.#t(),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(),this.#e()}#e(){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}}}_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),a=s,l=i,h="prescale1",c,u;for(;n>2&&a>1||r>2&&l>1;){let d=a,f=l;n>2&&a>1&&(d=a>=16384?Math.floor(a/2)-1||1:Math.ceil(a/2),n/=a/d),r>2&&l>1&&(f=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l)/2,r/=l/f),c=this.cachedCanvases.getCanvas(h,d,f),u=c.context,u.clearRect(0,0,d,f),u.drawImage(t,0,0,a,l,0,0,d,f),t=c.canvas,a=d,l=f,h=h==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:a,paintHeight:l}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,a=mt(e);let l,h,c,u;if((t.bitmap||t.data)&&t.count>1){const k=t.bitmap||t.data.buffer;h=JSON.stringify(r?a:[a.slice(0,4),n]),l=this._cachedBitmapsMap.get(k),l||(l=new Map,this._cachedBitmapsMap.set(k,l));const O=l.get(h);if(O&&!r){const H=Math.round(Math.min(a[0],a[2])+a[4]),N=Math.round(Math.min(a[1],a[3])+a[5]);return{canvas:O,offsetX:H,offsetY:N}}c=O}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),Vh(u.context,t));let d=z.transform(a,[1/s,0,0,-1/i,0,0]);d=z.transform(d,[1,0,0,1,0,-i]);const[f,g,p,v]=z.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,b=Math.round(v-g)||1,_=this.cachedCanvases.getCanvas("fillCanvas",m,b),w=_.context,C=f,T=g;w.translate(-C,-T),w.transform(...d),c||(c=this._scaleImage(u.canvas,ze(w)),c=c.img,l&&r&&l.set(h,c)),w.imageSmoothingEnabled=Gh(mt(w),t.interpolate),ir(w,c,0,0,c.width,c.height,0,0,s,i),w.globalCompositeOperation="source-in";const E=z.transform(ze(w),[1,0,0,1,-C,-T]);return w.fillStyle=r?n.getPattern(e,this,E,Xt.FILL):n,w.fillRect(0,0,s,i),l&&!r&&(this.cachedCanvases.delete("fillCanvas"),l.set(h,_.canvas)),{canvas:_.canvas,offsetX:Math.round(C),offsetY:Math.round(T)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=ug[t]}setLineJoin(t){this.ctx.lineJoin=dg[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(...mt(this.suspendedCtx)),ji(this.suspendedCtx,n),lg(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(),ji(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],a=i[2]-n,l=i[3]-r;a===0||l===0||(this.genericComposeSMask(e.context,s,a,l,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,a,l,h,c,u){let d=t.canvas,f=l-c,g=h-u;if(r){const v=z.makeHexColor(...r);if(f<0||g<0||f+s>d.width||g+i>d.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),b=m.context;b.drawImage(d,-f,-g),b.globalCompositeOperation="destination-atop",b.fillStyle=v,b.fillRect(0,0,s,i),b.globalCompositeOperation="source-over",d=m.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const m=new Path2D;m.rect(f,g,s,i),t.clip(m),t.globalCompositeOperation="destination-atop",t.fillStyle=v,t.fillRect(f,g,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&a?e.filter=this.filterFactory.addAlphaFilter(a):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(a));const p=new Path2D;p.rect(l,h,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(d,f,g,s,i,l,h,s,i),e.restore()}save(){this.inSMaskMode?(ji(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(),ji(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,a=n.y,l,h;const c=mt(i),u=c[0]===0&&c[3]===0||c[1]===0&&c[2]===0,d=u?s.slice(0):null;for(let f=0,g=0,p=t.length;f<p;f++)switch(t[f]|0){case Me.rectangle:r=e[g++],a=e[g++];const v=e[g++],m=e[g++],b=r+v,_=a+m;i.moveTo(r,a),v===0||m===0?i.lineTo(b,_):(i.lineTo(b,a),i.lineTo(b,_),i.lineTo(r,_)),u||n.updateRectMinMax(c,[r,a,b,_]),i.closePath();break;case Me.moveTo:r=e[g++],a=e[g++],i.moveTo(r,a),u||n.updatePathMinMax(c,r,a);break;case Me.lineTo:r=e[g++],a=e[g++],i.lineTo(r,a),u||n.updatePathMinMax(c,r,a);break;case Me.curveTo:l=r,h=a,r=e[g+4],a=e[g+5],i.bezierCurveTo(e[g],e[g+1],e[g+2],e[g+3],r,a),n.updateCurvePathMinMax(c,l,h,e[g],e[g+1],e[g+2],e[g+3],r,a,d),g+=6;break;case Me.curveTo2:l=r,h=a,i.bezierCurveTo(r,a,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,l,h,r,a,e[g],e[g+1],e[g+2],e[g+3],d),r=e[g+2],a=e[g+3],g+=4;break;case Me.curveTo3:l=r,h=a,r=e[g+2],a=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,a,r,a),n.updateCurvePathMinMax(c,l,h,e[g],e[g+1],r,a,r,a,d),g+=4;break;case Me.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(c,d),n.setCurrentPoint(r,a)}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?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,ze(e),Xt.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,ze(e),Xt.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=fg}eoClip(){this.pendingClip=Wh}beginText(){this.current.textMatrix=bh,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}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:a,fontSize:l,path:h}of t)s.addPath(h,new DOMMatrix(n).preMultiplySelf(i).translate(r,a).scale(l,-l));e.clip(s),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){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||ba,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&Q("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=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`;let a="normal";s.black?a="900":s.bold&&(a="bold");const l=s.italic?"italic":"normal";let h=e;e<Ih?h=Ih:e>jh&&(h=jh),this.current.fontSizeScale=e/h,this.ctx.font=`${l} ${a} ${h}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)}#s(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n){const r=this.ctx,a=this.current,l=a.font,h=a.textRenderingMode,c=a.fontSize/a.fontSizeScale,u=h&Wt.FILL_STROKE_MASK,d=!!(h&Wt.ADD_TO_PATH_FLAG),f=a.patternFill&&!l.missingFile,g=a.patternStroke&&!l.missingFile;let p;if((l.disableFontFace||d||f||g)&&(p=l.getPathGenerator(this.commonObjs,t)),l.disableFontFace||f||g){if(r.save(),r.translate(e,s),r.scale(c,-c),u===Wt.FILL||u===Wt.FILL_STROKE)if(i){const v=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,v,i))}else r.fill(p);if(u===Wt.STROKE||u===Wt.FILL_STROKE)if(n){const v=r.getTransform();r.setTransform(...n),r.stroke(this.#s(p,v,n))}else r.lineWidth/=c,r.stroke(p);r.restore()}else(u===Wt.FILL||u===Wt.FILL_STROKE)&&r.fillText(t,e,s),(u===Wt.STROKE||u===Wt.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:mt(r),x:e,y:s,fontSize:c,path:p})}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 tt(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,a=e.charSpacing,l=e.wordSpacing,h=e.fontDirection,c=e.textHScale*h,u=t.length,d=s.vertical,f=d?1:-1,g=s.defaultVMetrics,p=i*e.fontMatrix[0],v=e.textRenderingMode===Wt.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),h>0?n.scale(c,-1):n.scale(c,1);let m,b;if(e.patternFill){n.save();const E=e.fillColor.getPattern(n,this,ze(n),Xt.FILL);m=mt(n),n.restore(),n.fillStyle=E}if(e.patternStroke){n.save();const E=e.strokeColor.getPattern(n,this,ze(n),Xt.STROKE);b=mt(n),n.restore(),n.strokeStyle=E}let _=e.lineWidth;const w=e.textMatrixScale;if(w===0||_===0){const E=e.textRenderingMode&Wt.FILL_STROKE_MASK;(E===Wt.STROKE||E===Wt.FILL_STROKE)&&(_=this.getSinglePixelWidth())}else _/=w;if(r!==1&&(n.scale(r,r),_/=r),n.lineWidth=_,s.isInvalidPDFjsFont){const E=[];let k=0;for(const O of t)E.push(O.unicode),k+=O.width;n.fillText(E.join(""),0,0),e.x+=k*p*c,n.restore(),this.compose();return}let C=0,T;for(T=0;T<u;++T){const E=t[T];if(typeof E=="number"){C+=f*E*i/1e3;continue}let k=!1;const O=(E.isSpace?l:0)+a,H=E.fontChar,N=E.accent;let P,R,F=E.width;if(d){const M=E.vmetric||g,L=-(E.vmetric?M[1]:F*.5)*p,Y=M[2]*p;F=M?-M[0]:F,P=L/r,R=(C+Y)/r}else P=C/r,R=0;if(s.remeasure&&F>0){const M=n.measureText(H).width*1e3/i*r;if(F<M&&this.isFontSubpixelAAEnabled){const L=F/M;k=!0,n.save(),n.scale(L,1),P/=L}else F!==M&&(P+=(F-M)/2e3*i/r)}if(this.contentVisible&&(E.isInFont||s.missingFile)){if(v&&!N)n.fillText(H,P,R);else if(this.paintChar(H,P,R,m,b),N){const M=P+i*N.offset.x/r,L=R-i*N.offset.y/r;this.paintChar(N.fontChar,M,L,m,b)}}const V=d?F*p-O*h:F*p+O*h;C+=V,k&&n.restore()}d?e.y-=C:e.x+=C*c,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,a=i.vertical?1:-1,l=s.charSpacing,h=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||ba,d=t.length,f=s.textRenderingMode===Wt.INVISIBLE;let g,p,v,m;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(c,r),g=0;g<d;++g){if(p=t[g],typeof p=="number"){m=a*p*n/1e3,this.ctx.translate(m,0),s.x+=m*c;continue}const b=(p.isSpace?h:0)+l,_=i.charProcOperatorList[p.operatorListId];if(!_){Q(`Type3 character "${p.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=p,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(_),this.restore()),v=z.applyTransform([p.width,0],u)[0]*n+b,e.translate(v,0),s.x+=v*c}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||mt(this.ctx),n={createCanvasGraphics:r=>new ei(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new ja(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}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),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}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=rg(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,ze(e),Xt.SHADING);const i=ze(e);if(i){const{width:n,height:r}=e.canvas,[a,l,h,c]=z.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(a,l,h-a,c-l)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){ut("Should not call beginInlineImage")}beginImageData(){ut("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=mt(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(mt(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||qn("TODO: Support non-isolated groups."),t.knockout&&Q("Knockout groups not supported.");const s=mt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=z.getAxialAlignedBoundingBox(t.bbox,mt(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]),a=Math.floor(i[1]),l=Math.max(Math.ceil(i[2])-r,1),h=Math.max(Math.ceil(i[3])-a,1);this.current.startNewPathAndClipBox([0,0,l,h]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,l,h),d=u.context;d.translate(-r,-a),d.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:r,offsetY:a,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,a),e.save()),ji(e,d),this.ctx=d,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=mt(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(this.#t(),nr(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],a=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]=a;const[l,h]=z.singularValueDecompose2dScale(mt(this.ctx)),{viewportScale:c}=this,u=Math.ceil(r*this.outputScaleX*c),d=Math.ceil(a*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(l,0,0,-h,0,a*h),nr(this.ctx)}else nr(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new Hh(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),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=cg(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 a=this.ctx;a.save();const l=mt(a);a.transform(e,s,i,n,0,0);const h=this._createMaskCanvas(t);a.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]);for(let c=0,u=r.length;c<u;c+=2){const d=z.transform(l,[e,s,i,n,r[c],r[c+1]]),[f,g]=z.applyTransform([0,0],d);a.drawImage(h.canvas,f,g)}a.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:a,height:l,transform:h}=n,c=this.cachedCanvases.getCanvas("maskCanvas",a,l),u=c.context;u.save();const d=this.getObject(r,n);Vh(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,ze(e),Xt.FILL):s,u.fillRect(0,0,a,l),u.restore(),e.save(),e.transform(...h),e.scale(1,-1),ir(e,c.canvas,0,0,a,l,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){Q("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){Q("Dependent image isn't ready yet");return}const r=n.width,a=n.height,l=[];for(let h=0,c=i.length;h<c;h+=2)l.push({transform:[e,0,0,s,i[h],i[h+1]],x:0,y:0,w:r,h:a});this.paintInlineImageXObjectGroup(n,l)}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(),!Gt){const{filter:a}=i;a!=="none"&&a!==""&&(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 l=this.cachedCanvases.getCanvas("inlineImage",e,s).context;zh(l,t),n=this.applyTransferMapsToCanvas(l)}const r=this._scaleImage(n,ze(i));i.imageSmoothingEnabled=Gh(mt(i),t.interpolate),ir(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,l=this.cachedCanvases.getCanvas("inlineImage",n,r).context;zh(l,t),i=this.applyTransferMapsToCanvas(l)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),ir(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===Wh?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=mt(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,a;if(s===0&&i===0){const l=Math.abs(e),h=Math.abs(n);if(l===h)if(t===0)r=a=1/l;else{const c=l*t;r=a=c<1?1/c:1}else if(t===0)r=1/l,a=1/h;else{const c=l*t,u=h*t;r=c<1?1/c:1,a=u<1?1/u:1}}else{const l=Math.abs(e*n-s*i),h=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/l,a=h/l;else{const u=t*l;r=c>u?c/u:1,a=h>u?h/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}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 a=Math.max(i,n);e.setLineDash(r.map(l=>l/a)),e.lineDashOffset/=a}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}}for(const o in Me)ei.prototype[o]!==void 0&&(ei.prototype[Me[o]]=ei.prototype[o]);class Ni{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}class gg{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}getAll(){return xa(this.#t)}has(t){return this.#t.has(t)}}const si=Symbol("INTERNAL");class pg{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&fe.DISPLAY),this.#e=!!(t&fe.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#i;if(!this.#i)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==si&&ut("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class mg{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=fe.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,this.#i=t.order;for(const s of t.groups)this.#e.set(s.id,new pg(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(si,!1);for(const s of t.on)this.#e.get(s)._setVisible(si,!0);for(const s of t.off)this.#e.get(s)._setVisible(si,!1);this.#s=this.getHash()}}#r(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=this.#r(n);else if(this.#e.has(n))r=this.#e.get(n).visible;else return Q(`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"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return qn("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(Q(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#r(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return Q(`Unknown optional content policy ${t.policy}.`),!0}return Q(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){Q(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const r of n)r!==t&&this.#e.get(r)?._setVisible(si,!1,!0);i._setVisible(si,!!e,!0),this.#t=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=this.#e.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}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#i?this.#i.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?xa(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Ah;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class vg{constructor(t,{disableRange:e=!1,disableStream:s=!1}){Mt(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:a}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=a,n?.length>0){const l=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(l)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((l,h)=>{this._onReceiveData({begin:l,chunk:h})}),t.addProgressListener((l,h)=>{this._onProgress({loaded:l,total:h})}),t.addProgressiveReadListener(l=>{this._onReceiveData({chunk:l})}),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)});Mt(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){Mt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new bg(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new yg(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class bg{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Ea(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 yg{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 _g(o){let t=!0,e=s("filename\\*","i").exec(o);if(e){e=e[1];let c=a(e);return c=unescape(c),c=l(c),c=h(c),n(c)}if(e=r(o),e){const c=h(e);return n(c)}if(e=s("filename","i").exec(o),e){e=e[1];let c=a(e);return c=h(c),n(c)}function s(c,u){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(c,u){if(c){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const d=new TextDecoder(c,{fatal:!0}),f=Jn(u);u=d.decode(f),t=!1}catch{}}return u}function n(c){return t&&/[\x80-\xff]/.test(c)&&(c=i("utf-8",c),t&&(c=i("iso-8859-1",c))),c}function r(c){const u=[];let d;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=f.exec(c))!==null;){let[,p,v,m]=d;if(p=parseInt(p,10),p in u){if(p===0)break;continue}u[p]=[v,m]}const g=[];for(let p=0;p<u.length&&p in u;++p){let[v,m]=u[p];m=a(m),v&&(m=unescape(m),p===0&&(m=l(m))),g.push(m)}return g.join("")}function a(c){if(c.startsWith('"')){const u=c.slice(1).split('\\"');for(let d=0;d<u.length;++d){const f=u[d].indexOf('"');f!==-1&&(u[d]=u[d].slice(0,f),u.length=d+1),u[d]=u[d].replaceAll(/\\(.)/g,"$1")}c=u.join('"')}return c}function l(c){const u=c.indexOf("'");if(u===-1)return c;const d=c.slice(0,u),g=c.slice(u+1).replace(/^[^']*'/,"");return i(d,g)}function h(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(u,d,f,g){if(f==="q"||f==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,v){return String.fromCharCode(parseInt(v,16))}),i(d,g);try{g=atob(g)}catch{}return i(d,g)})}return""}function Xh(o,t){const e=new Headers;if(!o||!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 rr(o){try{return new URL(o).origin}catch{}return null}function Uh({responseHeaders:o,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(o.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||o.get("Accept-Ranges")!=="bytes"||(o.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function Yh(o){const t=o.get("Content-Disposition");if(t){let e=_g(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Ea(e))return e}return null}function ar(o,t){return o===404||o===0&&t.startsWith("file:")?new Oi('Missing PDF "'+t+'".'):new Kn(`Unexpected server response (${o}) while retrieving PDF "${t}".`,o)}function $h(o){return o===200||o===206}function qh(o,t,e){return{method:"GET",headers:o,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function Kh(o){return o instanceof Uint8Array?o.buffer:o instanceof ArrayBuffer?o:(Q(`getArrayBuffer - unexpected data format: ${o}`),new Uint8Array(o).buffer)}class Jh{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=Xh(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return Mt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new wg(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new xg(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class wg{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,qh(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=rr(n.url),!$h(n.status))throw ar(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:a,suggestedLength:l}=Uh({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=a,this._contentLength=l||this._contentLength,this._filename=Yh(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new cs("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(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Kh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class xg{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,qh(n,this._withCredentials,this._abortController)).then(a=>{const l=rr(a.url);if(l!==t._responseOrigin)throw new Error(`Expected range response-origin "${l}" to match "${t._responseOrigin}".`);if(!$h(a.status))throw ar(a.status,r);this._readCapability.resolve(),this._reader=a.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Kh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const Na=200,Ba=206;function Sg(o){const t=o.response;return typeof t!="string"?t:Jn(t).buffer}class Cg{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Xh(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}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=Ba):i.expectedStatus=Na,e.responseType="arraybuffer",Mt(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{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){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){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){s.onError(i.status);return}const n=i.status||Na;if(!(n===Na&&s.expectedStatus===Ba)&&n!==s.expectedStatus){s.onError(i.status);return}const a=Sg(i);if(n===Ba){const l=i.getResponseHeader("Content-Range"),h=/bytes (\d+)-(\d+)\/(\d+)/.exec(l);h?s.onDone({begin:parseInt(h[1],10),chunk:a}):(Q('Missing or invalid "Content-Range" header.'),s.onError(0))}else a?s.onDone({begin:0,chunk:a}):s.onError(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 Ag{constructor(t){this._source=t,this._manager=new Cg(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 Mt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Tg(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Eg(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Tg{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),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);this._manager._responseOrigin=rr(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(a=>{const[l,...h]=a.split(": ");return[l,h.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=Uh({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=Yh(i),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=ar(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){this.onProgress?.({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(await this._headersCapability.promise,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 Eg{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=rr(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(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??=ar(t,this._url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({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 kg=/^[a-z][a-z0-9\-+.]+:/i;function Pg(o){if(kg.test(o))return new URL(o);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(o))}class Mg{constructor(t){this.source=t,this.url=Pg(t.url),Mt(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return Mt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Og(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Dg(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Og{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();const s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new Oi(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}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(){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,this.onProgress?.({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 cs("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Dg{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){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,this.onProgress?.({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)}}const Rg=1e5,oe=30,Fg=.8;class Zt{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#l=0;#o=0;#c=null;#h=null;#d=0;#u=0;#f=Object.create(null);#a=[];#g=null;#m=[];#p=new WeakMap;#v=null;static#_=new Map;static#b=new Map;static#w=new WeakMap;static#S=null;static#A=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#g=t;else if(typeof t=="object")this.#g=new ReadableStream({start(l){l.enqueue(t),l.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#h=e,this.#u=s.scale*(globalThis.devicePixelRatio||1),this.#d=s.rotation,this.#n={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:r,pageY:a}=s.rawDims;this.#v=[1,0,0,-1,-r,a+n],this.#o=i,this.#l=n,Zt.#O(),Ms(e,s),this.#t.promise.finally(()=>{Zt.#A.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Qt.platform;return tt(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#c.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#r??=e.lang,Object.assign(this.#f,e.styles),this.#E(e.items),t()},this.#t.reject)};return this.#c=this.#g.getReader(),Zt.#A.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,Ms(this.#h,{rotation:i})),s!==this.#u){e?.(),this.#u=s;const n={div:null,properties:null,ctx:Zt.#k(this.#r)};for(const r of this.#m)n.properties=this.#p.get(r),n.div=r,this.#x(n)}}cancel(){const t=new cs("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#a}#E(t){if(this.#s)return;this.#n.ctx??=Zt.#k(this.#r);const e=this.#m,s=this.#a;for(const i of t){if(e.length>Rg){Q("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id!==null&&this.#e.setAttribute("id",`${i.id}`),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#P(i)}}#P(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#m.push(e);const i=z.transform(this.#v,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#i&&r.fontSubstitution||r.fontFamily;a=Zt.fontFamilyMap.get(a)||a;const l=Math.hypot(i[2],i[3]),h=l*Zt.#F(a,this.#r);let c,u;n===0?(c=i[4],u=i[5]-h):(c=i[4]+h*Math.sin(n),u=i[5]-h*Math.cos(n));const d="calc(var(--scale-factor)*",f=e.style;this.#e===this.#h?(f.left=`${(100*c/this.#o).toFixed(2)}%`,f.top=`${(100*u/this.#l).toFixed(2)}%`):(f.left=`${d}${c.toFixed(2)}px)`,f.top=`${d}${u.toFixed(2)}px)`),f.fontSize=`${d}${(Zt.#S*l).toFixed(2)}px)`,f.fontFamily=a,s.fontSize=l,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#i&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const p=Math.abs(t.transform[0]),v=Math.abs(t.transform[3]);p!==v&&Math.max(p,v)/Math.min(p,v)>1.5&&(g=!0)}if(g&&(s.canvasWidth=r.vertical?t.height:t.width),this.#p.set(e,s),this.#n.div=e,this.#n.properties=s,this.#x(this.#n),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#x(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(Zt.#S>1&&(r=`scale(${1/Zt.#S})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:a}=n,{canvasWidth:l,fontSize:h}=s;Zt.#T(i,h*this.#u,a);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${l*this.#u/c}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#A.size>0)){this.#_.clear();for(const{canvas:t}of this.#b.values())t.remove();this.#b.clear()}}static#k(t=null){let e=this.#b.get(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}),this.#b.set(t,e),this.#w.set(e,{size:0,family:""})}return e}static#T(t,e,s){const i=this.#w.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#O(){if(this.#S!==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),this.#S=t.getBoundingClientRect().height,t.remove()}static#F(t,e){const s=this.#_.get(t);if(s)return s;const i=this.#k(e);i.canvas.width=i.canvas.height=oe,this.#T(i,oe,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,a=Math.abs(n.fontBoundingBoxDescent);if(r){const c=r/(r+a);return this.#_.set(t,c),i.canvas.width=i.canvas.height=0,c}i.strokeStyle="red",i.clearRect(0,0,oe,oe),i.strokeText("g",0,0);let l=i.getImageData(0,0,oe,oe).data;a=0;for(let c=l.length-1-3;c>=0;c-=4)if(l[c]>0){a=Math.ceil(c/4/oe);break}i.clearRect(0,0,oe,oe),i.strokeText("A",0,oe),l=i.getImageData(0,0,oe,oe).data,r=0;for(let c=0,u=l.length;c<u;c+=4)if(l[c]>0){r=oe-Math.floor(c/4/oe);break}i.canvas.width=i.canvas.height=0;const h=r?r/(r+a):Fg;return this.#_.set(t,h),h}}class Bi{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const a=n.name;if(a==="#text")r=n.value;else if(Bi.shouldBuildText(a))n?.attributes?.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 Lg=65536,Ig=100,jg=5e3,Ng=Gt?Qf:qf,Bg=Gt?Zf:Mh,Hg=Gt?Jf:Kf,zg=Gt?tg:Rh;function Vg(o={}){typeof o=="string"||o instanceof URL?o={url:o}:(o instanceof ArrayBuffer||ArrayBuffer.isView(o))&&(o={data:o});const t=new Ha,{docId:e}=t,s=o.url?Gg(o.url):null,i=o.data?Wg(o.data):null,n=o.httpHeaders||null,r=o.withCredentials===!0,a=o.password??null,l=o.range instanceof Zh?o.range:null,h=Number.isInteger(o.rangeChunkSize)&&o.rangeChunkSize>0?o.rangeChunkSize:Lg;let c=o.worker instanceof ii?o.worker:null;const u=o.verbosity,d=typeof o.docBaseUrl=="string"&&!Zn(o.docBaseUrl)?o.docBaseUrl:null,f=typeof o.cMapUrl=="string"?o.cMapUrl:null,g=o.cMapPacked!==!1,p=o.CMapReaderFactory||Bg,v=typeof o.standardFontDataUrl=="string"?o.standardFontDataUrl:null,m=o.StandardFontDataFactory||zg,b=o.stopAtErrors!==!0,_=Number.isInteger(o.maxImageSize)&&o.maxImageSize>-1?o.maxImageSize:-1,w=o.isEvalSupported!==!1,C=typeof o.isOffscreenCanvasSupported=="boolean"?o.isOffscreenCanvasSupported:!Gt,T=typeof o.isImageDecoderSupported=="boolean"?o.isImageDecoderSupported:!Gt&&(Qt.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(o.canvasMaxAreaInBytes)?o.canvasMaxAreaInBytes:-1,k=typeof o.disableFontFace=="boolean"?o.disableFontFace:Gt,O=o.fontExtraProperties===!0,H=o.enableXfa===!0,N=o.ownerDocument||globalThis.document,P=o.disableRange===!0,R=o.disableStream===!0,F=o.disableAutoFetch===!0,V=o.pdfBug===!0,M=o.CanvasFactory||Ng,L=o.FilterFactory||Hg,Y=o.enableHWA===!0,ft=l?l.length:o.length??NaN,bt=typeof o.useSystemFonts=="boolean"?o.useSystemFonts:!Gt&&!k,_t=typeof o.useWorkerFetch=="boolean"?o.useWorkerFetch:p===Mh&&m===Rh&&f&&v&&Ri(f,document.baseURI)&&Ri(v,document.baseURI),gt=null;Ef(u);const rt={canvasFactory:new M({ownerDocument:N,enableHWA:Y}),filterFactory:new L({docId:e,ownerDocument:N}),cMapReaderFactory:_t?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:_t?null:new m({baseUrl:v})};if(!c){const K={verbosity:u,port:Ni.workerPort};c=K.port?ii.fromPort(K):new ii(K),t._worker=c}const Dt={docId:e,apiVersion:"4.10.38",data:i,password:a,disableAutoFetch:F,rangeChunkSize:h,length:ft,docBaseUrl:d,enableXfa:H,evaluatorOptions:{maxImageSize:_,disableFontFace:k,ignoreErrors:b,isEvalSupported:w,isOffscreenCanvasSupported:C,isImageDecoderSupported:T,canvasMaxAreaInBytes:E,fontExtraProperties:O,useSystemFonts:bt,cMapUrl:_t?f:null,standardFontDataUrl:_t?v:null}},ee={disableFontFace:k,fontExtraProperties:O,ownerDocument:N,pdfBug:V,styleElement:gt,loadingParams:{disableAutoFetch:F,enableXfa:H}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const K=c.messageHandler.sendWithPromise("GetDocRequest",Dt,i?[i.buffer]:null);let $;if(l)$=new vg(l,{disableRange:P,disableStream:R});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Tt;if(Gt)if(Ri(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");Tt=Jh}else Tt=Mg;else Tt=Ri(s)?Jh:Ag;$=new Tt({url:s,length:ft,httpHeaders:n,withCredentials:r,rangeChunkSize:h,disableRange:P,disableStream:R})}return K.then(Tt=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const _e=new Ii(e,Tt,c.port),Nt=new $g(_e,t,$,ee,rt);t._transport=Nt,_e.send("Ready",null)})}).catch(t._capability.reject),t}function Gg(o){if(o instanceof URL)return o.href;try{return new URL(o,window.location).href}catch{if(Gt&&typeof o=="string")return o}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Wg(o){if(Gt&&typeof Buffer<"u"&&o instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(o instanceof Uint8Array&&o.byteLength===o.buffer.byteLength)return o;if(typeof o=="string")return Jn(o);if(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="object"&&!isNaN(o?.length))return new Uint8Array(o);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function Qh(o){return typeof o=="object"&&Number.isInteger(o?.num)&&o.num>=0&&Number.isInteger(o?.gen)&&o.gen>=0}class Ha{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Ha.#t++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}}class Zh{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){ut("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Xg{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 tt(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 Ug{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new xh:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new tc,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 Di({viewBox:this.view,userUnit:this.userUnit,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 tt(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=ls.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:a=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:c=null,isEditing:u=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(s,i,c,u),{renderingIntent:f,cacheKey:g}=d;this.#e=!1,this.#i(),a||=this._transport.getOptionalContentConfig(f);let p=this._intentStates.get(g);p||(p=Object.create(null),this._intentStates.set(g,p)),p.streamReaderCancelTimeout&&(clearTimeout(p.streamReaderCancelTimeout),p.streamReaderCancelTimeout=null);const v=!!(f&fe.PRINT);p.displayReadyCapability||(p.displayReadyCapability=Promise.withResolvers(),p.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const m=w=>{p.renderTasks.delete(b),(this._maybeCleanupAfterRender||v)&&(this.#e=!0),this.#s(!v),w?(b.capability.reject(w),this._abortOperatorList({intentState:p,reason:w instanceof Error?w:new Error(w)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new ni({callback:m,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:p.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:h});(p.renderTasks||=new Set).add(b);const _=b.task;return Promise.all([p.displayReadyCapability.promise,a]).then(([w,C])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(C.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:w,optionalContentConfig:C}),b.operatorListChanged()}).catch(m),_}getOperatorList({intent:t="display",annotationMode:e=ls.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(l))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let a=this._intentStates.get(r.cacheKey);a||(a=Object.create(null),this._intentStates.set(r.cacheKey,a));let l;return a.opListReadCapability||(l=Object.create(null),l.operatorListChanged=n,a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(l),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),a.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=>Bi.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:l,done:h}){if(h){s(a);return}a.lang??=l.lang,Object.assign(a.styles,l.styles),a.items.push(...l.items),n()},i)}const r=e.getReader(),a={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(),this.#e=!1,this.#i(),Promise.all(t)}cleanup(t=!1){this.#e=!0;const e=this.#s(!1);return t&&e&&(this._stats&&=new xh),e}#s(t=!1){if(this.#i(),!this.#e||this.destroyed)return!1;if(t)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},jg),!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(),this.#e=!1,!0}#i(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.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&&this.#s(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,l=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),h=this._intentStates.get(e);h.streamReader=l;const c=()=>{l.read().then(({value:u,done:d})=>{if(d){h.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,h),c())},u=>{if(h.streamReader=null,!this._transport.destroyed){if(h.operatorList){h.operatorList.lastChunk=!0;for(const d of h.renderTasks)d.operatorListChanged();this.#s(!0)}if(h.displayReadyCapability)h.displayReadyCapability.reject(u);else if(h.opListReadCapability)h.opListReadCapability.reject(u);else throw u}})};c()}_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 Ta){let i=Ig;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 cs(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}}class Yg{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){Q("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}const vt=class vt{constructor({name:t=null,port:e=null,verbosity:s=kf()}={}){hi(this,ri);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(De(vt,Ls)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(De(vt,Ls)||Wi(vt,Ls,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new Ii("main","worker",t),this._messageHandler.on("ready",function(){}),gr(this,ri,mr).call(this)}_initialize(){if(De(vt,Fs)||De(vt,ai,vr)){this._setupFakeWorker();return}let{workerSrc:t}=vt;try{vt._isSameOrigin(window.location.href,t)||(t=vt._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new Ii("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",a=>{if(n.abort(),this.destroyed||!a){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,gr(this,ri,mr).call(this)}),s.on("ready",a=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const a=new Uint8Array;s.send("test",a,[a.buffer])};r();return}catch{qn("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){De(vt,Fs)||(Q("Setting up fake worker."),Wi(vt,Fs,!0)),vt._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Yg;this._port=e;const s=`fake${Dc(vt,hr)._++}`,i=new Ii(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new Ii(s,s+"_worker",e),gr(this,ri,mr).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,De(vt,Ls)?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=De(this,Ls)?.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 vt(t)}static get workerSrc(){if(Ni.workerSrc)return Ni.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return tt(this,"_setupFakeWorkerGlobal",(async()=>De(this,ai,vr)?De(this,ai,vr):(await import(this.workerSrc)).WorkerMessageHandler)())}};hr=new WeakMap,Fs=new WeakMap,Ls=new WeakMap,ri=new WeakSet,mr=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},ai=new WeakSet,vr=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},hi(vt,ai),hi(vt,hr,0),hi(vt,Fs,!1),hi(vt,Ls),Gt&&(Wi(vt,Fs,!0),Ni.workerSrc||="./pdf.worker.mjs"),vt._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},vt._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let ii=vt;class $g{#t=new Map;#e=new Map;#s=new Map;#i=new Map;#r=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new tc,this.fontLoader=new Yf({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()}#n(t,e=null){const s=this.#t.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#t.set(t,i),i}get annotationStorage(){return tt(this,"annotationStorage",new Ra)}getRenderingIntent(t,e=ls.ENABLE,s=null,i=!1,n=!1){let r=fe.DISPLAY,a=Da;switch(t){case"any":r=fe.ANY;break;case"display":break;case"print":r=fe.PRINT;break;default:Q(`getRenderingIntent - invalid intent: ${t}`)}const l=r&fe.PRINT&&s instanceof Th?s:this.annotationStorage;switch(e){case ls.DISABLE:r+=fe.ANNOTATIONS_DISABLE;break;case ls.ENABLE:break;case ls.ENABLE_FORMS:r+=fe.ANNOTATIONS_FORMS;break;case ls.ENABLE_STORAGE:r+=fe.ANNOTATIONS_STORAGE,a=l.serializable;break;default:Q(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=fe.IS_EDITING),n&&(r+=fe.OPLIST);const{ids:h,hash:c}=l.modifiedIds,u=[r,a.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:a,modifiedIds:h}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#e.values())t.push(s._destroy());this.#e.clear(),this.#s.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Zt.cleanup(),this._networkStream?.cancelAllRequests(new cs("Worker was terminated.")),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)=>{Mt(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}Mt(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=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=a=>{e.onProgress?.({loaded:a.loaded,total:a.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{Mt(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:a}){if(a){i.close();return}Mt(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(a=>{if(!this.destroyed)throw a})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new Xg(s,this))}),t.on("DocException",s=>{e._capability.reject(re(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw re(s);const i=n=>{n instanceof Error?this.#r.reject(n):this.#r.resolve({password:n})};e.onPassword(i,s.code)}catch(i){this.#r.reject(i)}return this.#r.promise}),t.on("DataLoaded",s=>{e.onProgress?.({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#e.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:r,fontExtraProperties:a,pdfBug:l}=this._params;if("error"in n){const d=n.error;Q(`Error during font loading: ${d}`),this.commonObjs.resolve(s,d);break}const h=l&&globalThis.FontInspector?.enabled?(d,f)=>globalThis.FontInspector.fontAdded(d,f):null,c=new $f(n,{disableFontFace:r,fontExtraProperties:a,inspectFont:h});this.fontLoader.bind(c).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!a&&c.data&&(c.data=null),this.commonObjs.resolve(s,c)});break;case"CopyLocalImage":const{imageRef:u}=n;Mt(u,"The imageRef must be defined.");for(const d of this.#e.values())for(const[,f]of d.objs)if(f?.ref===u)return f.dataLen?(this.commonObjs.resolve(s,structuredClone(f)),f.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])=>{if(this.destroyed)return;const a=this.#e.get(i);if(!a.objs.has(s)){if(a._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":a.objs.resolve(s,r),r?.dataLen>Sf&&(a._maybeCleanupAfterRender=!0);break;case"Pattern":a.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||e.onProgress?.({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(){this.annotationStorage.size<=0&&Q("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:this._fullReader?.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=this.#s.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&&this.#i.set(n.refStr,t);const r=new Ug(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return Qh(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 this.#n("GetFieldObjects")}hasJSActions(){return this.#n("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 this.#n("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 this.#n("GetOptionalContentConfig").then(e=>new mg(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#t.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>({info:i[0],metadata:i[1]?new gg(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.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 this.#e.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Zt.cleanup()}}cachedPageNumber(t){if(!Qh(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const Hi=Symbol("INITIAL_DATA");class tc{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:Hi}}get(t,e=null){if(e){const i=this.#e(t);return i.promise.then(()=>e(i.data)),null}const s=this.#t[t];if(!s||s.data===Hi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t[t];return!!e&&e.data!==Hi}delete(t){const e=this.#t[t];return!e||e.data===Hi?!1:(delete this.#t[t],!0)}resolve(t,e=null){const s=this.#e(t);s.data=e,s.resolve()}clear(){for(const t in this.#t){const{data:e}=this.#t[t];e?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const t in this.#t){const{data:e}=this.#t[t];e!==Hi&&(yield[t,e])}}}class qg{#t=null;constructor(t){this.#t=t,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(t=0){this.#t.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#t.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#t;return t.form||t.canvas&&e?.size>0}}class ni{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:a,canvasFactory:l,filterFactory:h,useRequestAnimationFrame:c=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=l,this.filterFactory=h,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=c===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new qg(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}){if(this.cancelled)return;if(this._canvas){if(ni.#e.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.");ni.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.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 ei(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,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),ni.#e.delete(this._canvas),this.callback(t||new Ta(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.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?this.#t=window.requestAnimationFrame(()=>{this.#t=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(),ni.#e.delete(this._canvas),this.callback())))}}const Kg="4.10.38",Jg="f9bea397f";function ec(o){return Math.floor(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0")}function zi(o){return Math.max(0,Math.min(255,255*o))}class sc{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=zi(t),[t,t,t]}static G_HTML([t]){const e=ec(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(zi)}static RGB_HTML(t){return`#${t.map(ec).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[zi(1-Math.min(1,t+i)),zi(1-Math.min(1,s+i)),zi(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,a=Math.min(i,n,r);return["CMYK",i,n,r,a]}}class Qg{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){ut("Abstract method `_createSVG` called.")}}class za extends Qg{_createSVG(t){return document.createElementNS(es,t)}}class ic{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",a=>{i.setValue(e,{value:a.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",a=>{i.setValue(e,{value:a.target.checked?a.target.getAttribute("xfaOn"):a.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",a=>{i.setValue(e,{value:a.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const a of s.children)a.attributes.value===r.value?a.attributes.selected=!0:a.attributes.hasOwnProperty("selected")&&delete a.attributes.selected}t.addEventListener("input",a=>{const l=a.target.options,h=l.selectedIndex===-1?"":l[l.selectedIndex].value;i.setValue(e,{value:h})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[l,h]of Object.entries(r))if(h!=null)switch(l){case"class":h.length&&t.setAttribute(l,h.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",h);break;case"style":Object.assign(t.style,h);break;case"textContent":t.textContent=h;break;default:(!a||l!=="href"&&l!=="newWindow")&&t.setAttribute(l,h)}a&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){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 a=n!=="richText",l=t.div;if(l.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;l.style.transform=u}a&&l.setAttribute("class","xfaLayer xfaFont");const h=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),a&&Bi.shouldBuildText(i.name)&&h.push(u)}return{textDivs:h}}const c=[[i,-1,r]];for(;c.length>0;){const[u,d,f]=c.at(-1);if(d+1===u.children.length){c.pop();continue}const g=u.children[++c.at(-1)[1]];if(g===null)continue;const{name:p}=g;if(p==="#text"){const m=document.createTextNode(g.value);h.push(m),f.append(m);continue}const v=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(v),g.attributes&&this.setAttributes({html:v,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,v]);else if(g.value){const m=document.createTextNode(g.value);a&&Bi.shouldBuildText(p)&&h.push(m),v.append(m)}}for(const u of l.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))u.setAttribute("readOnly",!0);return{textDivs:h}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const Vi=1e3,Zg=9,Os=new WeakSet;function ds(o){return{width:o[2]-o[0],height:o[3]-o[1]}}class tp{static create(t){switch(t.data.annotationType){case Lt.LINK:return new nc(t);case Lt.TEXT:return new ep(t);case Lt.WIDGET:switch(t.data.fieldType){case"Tx":return new sp(t);case"Btn":return t.data.radioButton?new rc(t):t.data.checkBox?new np(t):new rp(t);case"Ch":return new ap(t);case"Sig":return new ip(t)}return new Ds(t);case Lt.POPUP:return new Va(t);case Lt.FREETEXT:return new ac(t);case Lt.LINE:return new lp(t);case Lt.SQUARE:return new hp(t);case Lt.CIRCLE:return new cp(t);case Lt.POLYLINE:return new oc(t);case Lt.CARET:return new dp(t);case Lt.INK:return new Ga(t);case Lt.POLYGON:return new up(t);case Lt.HIGHLIGHT:return new lc(t);case Lt.UNDERLINE:return new fp(t);case Lt.SQUIGGLY:return new gp(t);case Lt.STRIKEOUT:return new pp(t);case Lt.STAMP:return new hc(t);case Lt.FILEATTACHMENT:return new mp(t);default:return new Ct(t)}}}class Ct{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){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?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ct._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#t||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#i(e),this.#s?.popup.updateEdited(t)}resetEdited(){this.#t&&(this.#i(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:l}}}}=this;s?.splice(0,4,...t);const{width:h,height:c}=ds(t);e.left=`${100*(t[0]-a)/n}%`,e.top=`${100*(r-t[3]+l)/r}%`,i===0?(e.width=`${100*h/n}%`,e.height=`${100*c/r}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Ds||(n.tabIndex=Vi);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 Va){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:a,height:l}=ds(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,v=e.borderStyle.verticalCornerRadius;if(p>0||v>0){const b=`calc(${p}px * var(--scale-factor)) / calc(${v}px * var(--scale-factor))`;r.borderRadius=b}else if(this instanceof rc){const b=`calc(${a}px * var(--scale-factor)) / calc(${l}px * var(--scale-factor))`;r.borderRadius=b}switch(e.borderStyle.style){case Mi.SOLID:r.borderStyle="solid";break;case Mi.DASHED:r.borderStyle="dashed";break;case Mi.BEVELED:Q("Unimplemented border style: beveled");break;case Mi.INSET:Q("Unimplemented border style: inset");break;case Mi.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=z.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const h=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:c,pageHeight:u,pageX:d,pageY:f}=i.rawDims;r.left=`${100*(h[0]-d)/c}%`,r.top=`${100*(h[1]-f)/u}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*a/c}%`,r.height=`${100*l/u}%`):this.setRotation(g,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}=ds(this.data.rect);let a,l;t%180===0?(a=100*n/s,l=100*r/i):(a=100*r/s,l=100*n/i),e.style.width=`${a}%`,e.style.height=`${l}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],a=n.slice(1);i.target.style[s]=sc[`${r}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[s]:sc[`${r}_rgb`](a)})};return tt(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))(t[i]||s[i])?.(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 a={detail:{[i]:n},target:t};r(a),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(p=>Math.fround(p));if(t.length===8){const[p,v,m,b]=t.subarray(2,6);if(i===p&&n===v&&e===m&&s===b)return}const{style:r}=this.container;let a;if(this.#e){const{borderColor:p,borderWidth:v}=r;r.borderWidth=0,a=["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="${p}" stroke-width="${v}">`],this.container.classList.add("hasBorder")}const l=i-e,h=n-s,{svgFactory:c}=this,u=c.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const d=c.createElement("defs");u.append(d);const f=c.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),d.append(f);for(let p=2,v=t.length;p<v;p+=8){const m=t[p],b=t[p+1],_=t[p+2],w=t[p+3],C=c.createElement("rect"),T=(_-e)/l,E=(n-b)/h,k=(m-_)/l,O=(b-w)/h;C.setAttribute("x",T),C.setAttribute("y",E),C.setAttribute("width",k),C.setAttribute("height",O),f.append(C),a?.push(`<rect vector-effect="non-scaling-stroke" x="${T}" y="${E}" width="${k}" height="${O}"/>`)}this.#e&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(u),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,e=this.#s=new Va({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(){ut("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:a}of i){if(n===-1||r===e)continue;const l=typeof a=="string"?a:null,h=document.querySelector(`[data-element-id="${r}"]`);if(h&&!Os.has(h)){Q(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:l,domElement:h})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&Os.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.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",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class nc extends Ct{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#e(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#t()}#e(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#s(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){Q('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:r}=e,a=[];if(i.length!==0||n.length!==0){const c=new Set(n);for(const u of i){const d=this._fieldObjects[u]||[];for(const{id:f}of d)c.add(f)}for(const u of Object.values(this._fieldObjects))for(const d of u)c.has(d.id)===r&&a.push(d)}else for(const c of Object.values(this._fieldObjects))a.push(...c);const l=this.annotationStorage,h=[];for(const c of a){const{id:u}=c;switch(h.push(u),c.type){case"text":{const f=c.defaultValue||"";l.setValue(u,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;l.setValue(u,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";l.setValue(u,{value:f});break}default:continue}const d=document.querySelector(`[data-element-id="${u}"]`);if(d){if(!Os.has(d)){Q(`_bindResetFormAction - element not allowed: ${u}`);continue}}else continue;d.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:h,name:"ResetForm"}}),!1}}}class ep extends Ct{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 Ds extends Ct{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Qt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{this.linkService.eventBus?.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=>{if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)(r==="Action"||this.data.actions?.[r])&&((r==="Focus"||r==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,r,i),r==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):r==="Blur"&&!this.data.actions?.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||Zg,n=t.style;let r;const a=2,l=h=>Math.round(10*h)/10;if(this.data.multiLine){const h=Math.abs(this.data.rect[3]-this.data.rect[1]-a),c=Math.round(h/(ya*i))||1,u=h/c;r=Math.min(i,l(u/ya))}else{const h=Math.abs(this.data.rect[3]-this.data.rect[1]-a);r=Math.min(i,l(h/ya))}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 sp extends Ds{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(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let a=i.formattedValue||this.data.textContent?.join(`
535
+ `)||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const l={userValue:n,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=a??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",a??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),Os.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=Vi,this._setRequired(s,this.data.required),r&&(s.maxLength=r),s.addEventListener("input",c=>{t.setValue(e,{value:c.target.value}),this.setPropertyOnSiblings(s,"value",c.target.value,"value"),l.formattedValue=null}),s.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue??"";s.value=l.userValue=u,l.formattedValue=null});let h=c=>{const{formattedValue:u}=l;u!=null&&(c.target.value=u),c.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",u=>{if(l.focused)return;const{target:d}=u;l.userValue&&(d.value=l.userValue),l.lastCommittedValue=d.value,l.commitKey=1,this.data.actions?.Focus||(l.focused=!0)}),s.addEventListener("updatefromsandbox",u=>{this.showElementAndHideCanvas(u.target);const d={value(f){l.userValue=f.detail.value??"",t.setValue(e,{value:l.userValue.toString()}),f.target.value=l.userValue},formattedValue(f){const{formattedValue:g}=f.detail;l.formattedValue=g,g!=null&&f.target!==document.activeElement&&(f.target.value=g),t.setValue(e,{formattedValue:g})},selRange(f){f.target.setSelectionRange(...f.detail.selRange)},charLimit:f=>{const{charLimit:g}=f.detail,{target:p}=f;if(g===0){p.removeAttribute("maxLength");return}p.setAttribute("maxLength",g);let v=l.userValue;!v||v.length<=g||(v=v.slice(0,g),p.value=l.userValue=v,t.setValue(e,{value:v}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:v,willCommit:!0,commitKey:1,selStart:p.selectionStart,selEnd:p.selectionEnd}}))}};this._dispatchEventFromSandbox(d,u)}),s.addEventListener("keydown",u=>{l.commitKey=1;let d=-1;if(u.key==="Escape"?d=0:u.key==="Enter"&&!this.data.multiLine?d=2:u.key==="Tab"&&(l.commitKey=3),d===-1)return;const{value:f}=u.target;l.lastCommittedValue!==f&&(l.lastCommittedValue=f,l.userValue=f,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:f,willCommit:!0,commitKey:d,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}))});const c=h;h=null,s.addEventListener("blur",u=>{if(!l.focused||!u.relatedTarget)return;this.data.actions?.Blur||(l.focused=!1);const{value:d}=u.target;l.userValue=d,l.lastCommittedValue!==d&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:d,willCommit:!0,commitKey:l.commitKey,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}),c(u)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",u=>{l.lastCommittedValue=null;const{data:d,target:f}=u,{value:g,selectionStart:p,selectionEnd:v}=f;let m=p,b=v;switch(u.inputType){case"deleteWordBackward":{const _=g.substring(0,p).match(/\w*[^\w]*$/);_&&(m-=_[0].length);break}case"deleteWordForward":{const _=g.substring(p).match(/^[^\w]*\w*/);_&&(b+=_[0].length);break}case"deleteContentBackward":p===v&&(m-=1);break;case"deleteContentForward":p===v&&(b+=1);break}u.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:g,change:d||"",willCommit:!1,selStart:m,selEnd:b}})}),this._setEventListeners(s,l,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],u=>u.target.value)}if(h&&s.addEventListener("blur",h),this.data.comb){const u=(this.data.rect[2]-this.data.rect[0])/r;s.classList.add("comb"),s.style.letterSpacing=`calc(${u}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 ip extends Ds{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class np extends Ds{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 Os.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=Vi,n.addEventListener("change",r=>{const{name:a,checked:l}=r.target;for(const h of this._getElementsByName(a,s)){const c=l&&h.exportValue===e.exportValue;h.domElement&&(h.domElement.checked=c),t.setValue(h.id,{value:c})}t.setValue(s,{value:l})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue||"Off";r.target.checked=a===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const a={value(l){l.target.checked=l.detail.value!=="Off",t.setValue(s,{value:l.target.checked})}};this._dispatchEventFromSandbox(a,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 rc extends Ds{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(Os.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=Vi,n.addEventListener("change",r=>{const{name:a,checked:l}=r.target;for(const h of this._getElementsByName(a,s))t.setValue(h.id,{value:!1});t.setValue(s,{value:l})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue;r.target.checked=a!=null&&a===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",a=>{const l={value:h=>{const c=r===h.detail.value;for(const u of this._getElementsByName(h.target.name)){const d=c&&u.id===s;u.domElement&&(u.domElement.checked=d),t.setValue(u.id,{value:d})}}};this._dispatchEventFromSandbox(l,a)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class rp extends nc{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 ap extends Ds{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");Os.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=Vi;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",c=>{const u=this.data.defaultFieldValue;for(const d of i.options)d.selected=d.value===u});for(const c of this.data.options){const u=document.createElement("option");u.textContent=c.displayValue,u.value=c.exportValue,s.value.includes(c.exportValue)&&(u.setAttribute("selected",!0),n=!1),i.append(u)}let r=null;if(n){const c=document.createElement("option");c.value=" ",c.setAttribute("hidden",!0),c.setAttribute("selected",!0),i.prepend(c),r=()=>{c.remove(),i.removeEventListener("input",r),r=null},i.addEventListener("input",r)}const a=c=>{const u=c?"value":"textContent",{options:d,multiple:f}=i;return f?Array.prototype.filter.call(d,g=>g.selected).map(g=>g[u]):d.selectedIndex===-1?null:d[d.selectedIndex][u]};let l=a(!1);const h=c=>{const u=c.target.options;return Array.prototype.map.call(u,d=>({displayValue:d.textContent,exportValue:d.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",c=>{const u={value(d){r?.();const f=d.detail.value,g=new Set(Array.isArray(f)?f:[f]);for(const p of i.options)p.selected=g.has(p.value);t.setValue(e,{value:a(!0)}),l=a(!1)},multipleSelection(d){i.multiple=!0},remove(d){const f=i.options,g=d.detail.remove;f[g].selected=!1,i.remove(g),f.length>0&&Array.prototype.findIndex.call(f,v=>v.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:a(!0),items:h(d)}),l=a(!1)},clear(d){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),l=a(!1)},insert(d){const{index:f,displayValue:g,exportValue:p}=d.detail.insert,v=i.children[f],m=document.createElement("option");m.textContent=g,m.value=p,v?v.before(m):i.append(m),t.setValue(e,{value:a(!0),items:h(d)}),l=a(!1)},items(d){const{items:f}=d.detail;for(;i.length!==0;)i.remove(0);for(const g of f){const{displayValue:p,exportValue:v}=g,m=document.createElement("option");m.textContent=p,m.value=v,i.append(m)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:a(!0),items:h(d)}),l=a(!1)},indices(d){const f=new Set(d.detail.indices);for(const g of d.target.options)g.selected=f.has(g.index);t.setValue(e,{value:a(!0)}),l=a(!1)},editable(d){d.target.disabled=!d.detail.editable}};this._dispatchEventFromSandbox(u,c)}),i.addEventListener("input",c=>{const u=a(!0),d=a(!1);t.setValue(e,{value:u}),c.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:l,change:d,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"]],c=>c.target.value)):i.addEventListener("input",function(c){t.setValue(e,{value:a(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Va extends Ct{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Ct._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new op({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=>`${Aa}${s}`).join(",")),this.container}}class op{#t=this.#E.bind(this);#e=this.#T.bind(this);#s=this.#k.bind(this);#i=this.#x.bind(this);#r=null;#n=null;#l=null;#o=null;#c=null;#h=null;#d=null;#u=!1;#f=null;#a=null;#g=null;#m=null;#p=null;#v=null;#_=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:a,parent:l,rect:h,parentRect:c,open:u}){this.#n=t,this.#p=i,this.#l=r,this.#m=a,this.#h=l,this.#r=e,this.#g=h,this.#d=c,this.#c=s,this.#o=Sh.toDateObject(n),this.trigger=s.flatMap(d=>d.getElementsToTriggerPopup());for(const d of this.trigger)d.addEventListener("click",this.#i),d.addEventListener("mouseenter",this.#s),d.addEventListener("mouseleave",this.#e),d.classList.add("popupTriggerArea");for(const d of s)d.container?.addEventListener("keydown",this.#t);this.#n.hidden=!0,u&&this.#x()}render(){if(this.#f)return;const t=this.#f=document.createElement("div");if(t.className="popup",this.#r){const n=t.style.outlineColor=z.makeHexColor(...this.#r);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(...this.#r.map(a=>Math.floor(.7*(255-a)+a)))}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),{dir:s.dir,str:s.textContent}=this.#p,t.append(e),this.#o){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:this.#o.valueOf()})),e.append(n)}const i=this.#b;if(i)ic.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(this.#l);t.append(n)}this.#n.append(t)}get#b(){const t=this.#m,e=this.#l;return t?.str&&(!e?.str||e.str===t.str)&&this.#m.html||null}get#w(){return this.#b?.attributes?.style?.fontSize||0}get#S(){return this.#b?.attributes?.style?.color||null}#A(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#S,fontSize:this.#w?`calc(${this.#w}px * var(--scale-factor))`:""}};for(const n of t.split(`
536
+ `))e.push({name:"span",value:n,attributes:i});return s}_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 a=i[n];s.append(document.createTextNode(a)),n<r-1&&s.append(document.createElement("br"))}return s}#E(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#u)&&this.#x()}updateEdited({rect:t,popupContent:e}){this.#v||={contentsObj:this.#l,richText:this.#m},t&&(this.#a=null),e&&(this.#m=this.#A(e),this.#l=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#v&&({contentsObj:this.#l,richText:this.#m}=this.#v,this.#v=null,this.#f?.remove(),this.#f=null,this.#a=null)}#P(){if(this.#a!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#h;let r=!!this.#d,a=r?this.#d:this.#g;for(const g of this.#c)if(!a||z.intersect(g.data.rect,a)!==null){a=g.data.rect,r=!0;break}const l=z.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),c=r?a[2]-a[0]+5:0,u=l[0]+c,d=l[1];this.#a=[100*(u-i)/e,100*(d-n)/s];const{style:f}=this.#n;f.left=`${this.#a[0]}%`,f.top=`${this.#a[1]}%`}#x(){this.#u=!this.#u,this.#u?(this.#k(),this.#n.addEventListener("click",this.#i),this.#n.addEventListener("keydown",this.#t)):(this.#T(),this.#n.removeEventListener("click",this.#i),this.#n.removeEventListener("keydown",this.#t))}#k(){this.#f||this.render(),this.isVisible?this.#u&&this.#n.classList.add("focused"):(this.#P(),this.#n.hidden=!1,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)+1e3)}#T(){this.#n.classList.remove("focused"),!(this.#u||!this.isVisible)&&(this.#n.hidden=!0,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)-1e3)}forceHide(){this.#_=this.isVisible,this.#_&&(this.#n.hidden=!0)}maybeShow(){this.#_&&(this.#f||this.#k(),this.#_=!1,this.#n.hidden=!1)}get isVisible(){return this.#n.hidden===!1}}class ac extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=J.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 lp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=ds(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#t=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class hp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=ds(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",n/2),r.setAttribute("y",n/2),r.setAttribute("width",e-n),r.setAttribute("height",s-n),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class cp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=ds(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",s/2),r.setAttribute("rx",e/2-n/2),r.setAttribute("ry",s/2-n/2),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class oc extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i}}=this;if(!e)return this.container;const{width:n,height:r}=ds(t),a=this.svgFactory.create(n,r,!0);let l=[];for(let c=0,u=e.length;c<u;c+=2){const d=e[c]-t[0],f=t[3]-e[c+1];l.push(`${d},${f}`)}l=l.join(" ");const h=this.#t=this.svgFactory.createElement(this.svgElementName);return h.setAttribute("points",l),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),a.append(h),this.container.append(a),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class up extends oc{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class dp extends Ct{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 Ga extends Ct{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?J.HIGHLIGHT:J.INK}#s(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:a,height:l}=this.#s(e,t),h=this.svgFactory.create(a,l,!0),c=this.#t=this.svgFactory.createElement("svg:g");h.append(c),c.setAttribute("stroke-width",i.width||1),c.setAttribute("stroke-linecap","round"),c.setAttribute("stroke-linejoin","round"),c.setAttribute("stroke-miterlimit",10),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),c.setAttribute("transform",r);for(let u=0,d=s.length;u<d;u++){const f=this.svgFactory.createElement(this.svgElementName);this.#e.push(f),f.setAttribute("points",s[u].join(",")),c.append(f)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(h),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#t;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,a=this.#e.length;r<a;r++)this.#e[r].setAttribute("points",s[r].join(","));if(i){const{transform:r,width:a,height:l}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${a} ${l}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class lc extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=J.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class fp extends Ct{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 gp extends Ct{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 pp extends Ct{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 hc extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=J.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 mp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||e.fillAlpha===0?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)),s.addEventListener("dblclick",this.#e.bind(this)),this.#t=s;const{isMac:i}=Qt.platform;return t.addEventListener("keydown",n=>{n.key==="Enter"&&(i?n.metaKey:n.ctrlKey)&&this.#e()}),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class vp{#t=null;#e=null;#s=new Map;#i=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:a}){this.div=t,this.#t=e,this.#e=s,this.#i=a||null,this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return this.#s.size>0}async#r(t,e){const s=t.firstChild||t,i=s.id=`${Aa}${e}`,n=await this.#i?.getAriaAttributes(i);if(n)for(const[r,a]of n)s.setAttribute(r,a);this.div.append(t),this.#t?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;Ms(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 za,annotationStorage:t.annotationStorage||new Ra,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const r of e){if(r.noHTML)continue;const a=r.annotationType===Lt.POPUP;if(a){const c=i.get(r.id);if(!c)continue;n.elements=c}else{const{width:c,height:u}=ds(r.rect);if(c<=0||u<=0)continue}n.data=r;const l=tp.create(n);if(!l.isRenderable)continue;if(!a&&r.popupRef){const c=i.get(r.popupRef);c?c.push(l):i.set(r.popupRef,[l])}const h=l.render();r.hidden&&(h.style.visibility="hidden"),await this.#r(h,r.id),l._isEditable&&(this.#s.set(l.data.id,l),this._annotationEditorUIManager?.renderAnnotationElement(l))}this.#n()}update({viewport:t}){const e=this.div;this.viewport=t,Ms(e,{rotation:t.rotation}),this.#n(),e.hidden=!1}#n(){if(!this.#e)return;const t=this.div;for(const[e,s]of this.#e){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)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(t){return this.#s.get(t)}}const or=/\r\n?|\n/g;class It extends G{#t;#e="";#s=`${this.id}-editor`;#i=null;#r;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=It.prototype,e=n=>n.isEmpty(),s=us.TRANSLATE_SMALL,i=us.TRANSLATE_BIG;return tt(this,"_keyboardManager",new Li([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=J.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||It._defaultColor||G._defaultLineColor,this.#r=t.fontSize||It._defaultFontSize}static initialize(t,e){G.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case st.FREETEXT_SIZE:It._defaultFontSize=e;break;case st.FREETEXT_COLOR:It._defaultColor=e;break}}updateParams(t,e){switch(t){case st.FREETEXT_SIZE:this.#n(e);break;case st.FREETEXT_COLOR:this.#l(e);break}}static get defaultPropertiesToUpdate(){return[[st.FREETEXT_SIZE,It._defaultFontSize],[st.FREETEXT_COLOR,It._defaultColor||G._defaultLineColor]]}get propertiesToUpdate(){return[[st.FREETEXT_SIZE,this.#r],[st.FREETEXT_COLOR,this.#t]]}#n(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-this.#r)*this.parentScale),this.#r=i,this.#c()},s=this.#r;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#l(t){const e=i=>{this.#t=this.editorDiv.style.color=i},s=this.#t;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-It._internalPadding*t,-(It._internalPadding+this.#r)*t]}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(J.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#i=new AbortController;const t=this._uiManager.combinedSignal(this.#i);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#s),this._isDraggable=!0,this.#i?.abort(),this.#i=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.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()}#o(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&s.nodeName==="BR"||(t.push(It.#h(s)),e=s);return t.join(`
537
+ `)}#c(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:i,div:n}=this,r=n.style.display,a=n.classList.contains("hidden");n.classList.remove("hidden"),n.style.display="hidden",i.div.append(this.div),s=n.getBoundingClientRect(),n.remove(),n.style.display=r,n.classList.toggle("hidden",a)}this.rotation%180===this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#e,e=this.#e=this.#o().trimEnd();if(t===e)return;const s=i=>{if(this.#e=i,!i){this.remove();return}this.#d(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#c()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){It._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){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 t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#s),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:s}=this.editorDiv;if(s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),tr(this,this.div,["dblclick","keydown"]),this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:r}=this._initialData;let[a,l]=this.getInitialTranslation();[a,l]=this.pageTranslationToScreen(a,l);const[h,c]=this.pageDimensions,[u,d]=this.pageTranslation;let f,g;switch(this.rotation){case 0:f=t+(r[0]-u)/h,g=e+this.height-(r[1]-d)/c;break;case 90:f=t+(r[0]-u)/h,g=e-(r[1]-d)/c,[a,l]=[l,-a];break;case 180:f=t-this.width+(r[0]-u)/h,g=e-(r[1]-d)/c,[a,l]=[-a,-l];break;case 270:f=t+(r[0]-u-this.height*c)/h,g=e+(r[1]-d-this.width*h)/c,[a,l]=[-l,a];break}this.setAt(f*i,g*n,a,l)}else this.setAt(t*i,e*n,this.width*i,this.height*n);this.#d(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#h(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(or,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=It.#f(e.getData("text")||"").replaceAll(or,`
538
+ `);if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes(`
539
+ `)){r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:a,startOffset:l}=r,h=[],c=[];if(a.nodeType===Node.TEXT_NODE){const f=a.parentElement;if(c.push(a.nodeValue.slice(l).replaceAll(or,"")),f!==this.editorDiv){let g=h;for(const p of this.editorDiv.childNodes){if(p===f){g=c;continue}g.push(It.#h(p))}}h.push(a.nodeValue.slice(0,l).replaceAll(or,""))}else if(a===this.editorDiv){let f=h,g=0;for(const p of this.editorDiv.childNodes)g++===l&&(f=c),f.push(It.#h(p))}this.#e=`${h.join(`
540
+ `)}${i}${c.join(`
541
+ `)}`,this.#d();const u=new Range;let d=h.reduce((f,g)=>f+g.length,0);for(const{firstChild:f}of this.editorDiv.childNodes)if(f.nodeType===Node.TEXT_NODE){const g=f.nodeValue.length;if(d<=g){u.setStart(f,d),u.setEnd(f,d);break}d-=g}n.removeAllRanges(),n.addRange(u)}#d(){if(this.editorDiv.replaceChildren(),!!this.#e)for(const t of this.#e.split(`
542
+ `)){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#u(){return this.#e.replaceAll(" "," ")}static#f(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,s){let i=null;if(t instanceof ac){const{data:{defaultAppearanceData:{fontSize:r,fontColor:a},rect:l,rotation:h,id:c,popupRef:u},textContent:d,textPosition:f,parent:{page:{pageNumber:g}}}=t;if(!d||d.length===0)return null;i=t={annotationType:J.FREETEXT,color:Array.from(a),fontSize:r,value:d.join(`
543
+ `),position:f,pageIndex:g-1,rect:l.slice(0),rotation:h,id:c,deleted:!1,popupRef:u}}const n=await super.deserialize(t,e,s);return n.#r=t.fontSize,n.#t=z.makeHexColor(...t.color),n.#e=It.#f(t.value),n.annotationElementId=t.id||null,n._initialData=i,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=It._internalPadding*this.parentScale,s=this.getRect(e,e),i=G._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#t),n={annotationType:J.FREETEXT,color:i,fontSize:this.#r,value:this.#u(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#a(n)?null:(n.id=this.annotationElementId,n)}#a(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((r,a)=>r!==i[a])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,e.replaceChildren();for(const n of this.#e.split(`
544
+ `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=It._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class B{static PRECISION=1e-4;toSVGPath(){ut("Abstract method `toSVGPath` must be implemented.")}get box(){ut("Abstract getter `box` must be implemented.")}serialize(t,e){ut("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,l=t.length;a<l;a+=2)r[a]=e+t[a]*i,r[a+1]=s+t[a+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,l=t.length;a<l;a+=2)r[a]=e+t[a+1]*i,r[a+1]=s+t[a]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class Rs{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#l;#o;#c;#h;#d;#u;#f=[];static#a=8;static#g=2;static#m=Rs.#a+Rs.#g;constructor({x:t,y:e},s,i,n,r,a=0){this.#t=s,this.#u=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=a,this.#h=Rs.#a*i,this.#c=Rs.#m*i,this.#d=i,this.#f.push(t,e)}isEmpty(){return isNaN(this.#n[8])}#p(){const t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#l+(t[0]-e[0])/2-s)/n,(this.#o+(t[1]-e[1])/2-i)/r,(this.#l+(e[0]-t[0])/2-s)/n,(this.#o+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#l=t,this.#o=e;const[s,i,n,r]=this.#t;let[a,l,h,c]=this.#n.subarray(8,12);const u=t-h,d=e-c,f=Math.hypot(u,d);if(f<this.#c)return!1;const g=f-this.#h,p=g/f,v=p*u,m=p*d;let b=a,_=l;a=h,l=c,h+=v,c+=m,this.#f?.push(t,e);const w=-m/g,C=v/g,T=w*this.#u,E=C*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([h+T,c+E],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([h-T,c-E],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([a+T,l+E],2),this.#r.push(NaN,NaN,NaN,NaN,(a+T-s)/n,(l+E-i)/r),this.#n.set([a-T,l-E],14),this.#e.push(NaN,NaN,NaN,NaN,(a-T-s)/n,(l-E-i)/r)),this.#n.set([b,_,a,l,h,c],6),!this.isEmpty()):(this.#n.set([b,_,a,l,h,c],6),Math.abs(Math.atan2(_-l,b-a)-Math.atan2(m,v))<Math.PI/2?([a,l,h,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((a+h)/2-s)/n,((l+c)/2-i)/r),[a,l,b,_]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((b+a)/2-s)/n,((_+l)/2-i)/r),!0):([b,_,a,l,h,c]=this.#n.subarray(0,6),this.#r.push(((b+5*a)/6-s)/n,((_+5*l)/6-i)/r,((5*a+h)/6-s)/n,((5*l+c)/6-i)/r,((a+h)/2-s)/n,((l+c)/2-i)/r),[h,c,a,l,b,_]=this.#n.subarray(12,18),this.#e.push(((b+5*a)/6-s)/n,((_+5*l)/6-i)/r,((5*a+h)/6-s)/n,((5*l+c)/6-i)/r,((a+h)/2-s)/n,((l+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#v();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]}`);this.#b(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 this.#_(s),s.join(" ")}#v(){const[t,e,s,i]=this.#t,[n,r,a,l]=this.#p();return`M${(this.#n[2]-t)/s} ${(this.#n[3]-e)/i} L${(this.#n[4]-t)/s} ${(this.#n[5]-e)/i} L${n} ${r} L${a} ${l} L${(this.#n[16]-t)/s} ${(this.#n[17]-e)/i} L${(this.#n[14]-t)/s} ${(this.#n[15]-e)/i} Z`}#_(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#b(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),a=this.#n.subarray(16,18),[l,h,c,u]=this.#p();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${l} ${h} L${c} ${u} L${(a[0]-e)/i} ${(a[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new cc(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,a]=this.#t,l=new Float32Array((this.#f?.length??0)+2);for(let u=0,d=l.length-2;u<d;u+=2)l[u]=(this.#f[u]-i)/r,l[u+1]=(this.#f[u+1]-n)/a;if(l[l.length-2]=(this.#l-i)/r,l[l.length-1]=(this.#o-n)/a,isNaN(s[6])&&!this.isEmpty())return this.#w(l);const h=new Float32Array(this.#r.length+24+this.#e.length);let c=t.length;for(let u=0;u<c;u+=2){if(isNaN(t[u])){h[u]=h[u+1]=NaN;continue}h[u]=t[u],h[u+1]=t[u+1]}c=this.#A(h,c);for(let u=e.length-6;u>=6;u-=6)for(let d=0;d<6;d+=2){if(isNaN(e[u+d])){h[c]=h[c+1]=NaN,c+=2;continue}h[c]=e[u+d],h[c+1]=e[u+d+1],c+=2}return this.#S(h,c),this.newFreeDrawOutline(h,l,this.#t,this.#d,this.#s,this.#i)}#w(t){const e=this.#n,[s,i,n,r]=this.#t,[a,l,h,c]=this.#p(),u=new Float32Array(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,a,l,NaN,NaN,NaN,NaN,h,c,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,this.#t,this.#d,this.#s,this.#i)}#S(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#A(t,e){const s=this.#n.subarray(4,6),i=this.#n.subarray(16,18),[n,r,a,l]=this.#t,[h,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/l,NaN,NaN,NaN,NaN,h,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/l],e),e+=24}}class cc extends B{#t;#e=new Float32Array(4);#s;#i;#r;#n;#l;constructor(t,e,s,i,n,r){super(),this.#l=t,this.#r=e,this.#t=s,this.#n=i,this.#s=n,this.#i=r,this.lastPoint=[NaN,NaN],this.#o(r);const[a,l,h,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-a)/h,t[u+1]=(t[u+1]-l)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-a)/h,e[u+1]=(e[u+1]-l)/c}toSVGPath(){const t=[`M${this.#l[4]} ${this.#l[5]}`];for(let e=6,s=this.#l.length;e<s;e+=6){if(isNaN(this.#l[e])){t.push(`L${this.#l[e+4]} ${this.#l[e+5]}`);continue}t.push(`C${this.#l[e]} ${this.#l[e+1]} ${this.#l[e+2]} ${this.#l[e+3]} ${this.#l[e+4]} ${this.#l[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,a=i-e;let l,h;switch(n){case 0:l=B._rescale(this.#l,t,i,r,-a),h=B._rescale(this.#r,t,i,r,-a);break;case 90:l=B._rescaleAndSwap(this.#l,t,e,r,a),h=B._rescaleAndSwap(this.#r,t,e,r,a);break;case 180:l=B._rescale(this.#l,s,e,-r,a),h=B._rescale(this.#r,s,e,-r,a);break;case 270:l=B._rescaleAndSwap(this.#l,s,i,-r,-a),h=B._rescaleAndSwap(this.#r,s,i,-r,-a);break}return{outline:Array.from(l),points:[Array.from(h)]}}#o(t){const e=this.#l;let s=e[4],i=e[5],n=s,r=i,a=s,l=i,h=s,c=i;const u=t?Math.max:Math.min;for(let f=6,g=e.length;f<g;f+=6){if(isNaN(e[f]))n=Math.min(n,e[f+4]),r=Math.min(r,e[f+5]),a=Math.max(a,e[f+4]),l=Math.max(l,e[f+5]),c<e[f+5]?(h=e[f+4],c=e[f+5]):c===e[f+5]&&(h=u(h,e[f+4]));else{const p=z.bezierBoundingBox(s,i,...e.slice(f,f+6));n=Math.min(n,p[0]),r=Math.min(r,p[1]),a=Math.max(a,p[2]),l=Math.max(l,p[3]),c<p[3]?(h=p[2],c=p[3]):c===p[3]&&(h=u(h,p[2]))}s=e[f+4],i=e[f+5]}const d=this.#e;d[0]=n-this.#s,d[1]=r-this.#s,d[2]=a-n+2*this.#s,d[3]=l-r+2*this.#s,this.lastPoint=[h,c]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new Rs(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[a,l,h,c]=this.#t,u=n*h,d=r*c,f=s*h+a,g=i*c+l,p=this.newOutliner({x:this.#r[0]*u+f,y:this.#r[1]*d+g},this.#t,this.#n,t,this.#i,e??this.#s);for(let v=2;v<this.#r.length;v+=2)p.add({x:this.#r[v]*u+f,y:this.#r[v+1]*d+g});return p.getOutlines()}}class Wa{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,a=1/0,l=-1/0;const h=10**-4;for(const{x:v,y:m,width:b,height:_}of t){const w=Math.floor((v-e)/h)*h,C=Math.ceil((v+b+e)/h)*h,T=Math.floor((m-e)/h)*h,E=Math.ceil((m+_+e)/h)*h,k=[w,T,E,!0],O=[C,T,E,!1];this.#s.push(k,O),n=Math.min(n,w),r=Math.max(r,C),a=Math.min(a,T),l=Math.max(l,E)}const c=r-n+2*s,u=l-a+2*s,d=n-s,f=a-s,g=this.#s.at(i?-1:-2),p=[g[0],g[2]];for(const v of this.#s){const[m,b,_]=v;v[0]=(m-d)/c,v[1]=(b-f)/u,v[2]=(_-f)/u}this.#t=new Float32Array([d,f,c,u]),this.#e=p}getOutlines(){this.#s.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#s)e[3]?(t.push(...this.#c(e)),this.#l(e)):(this.#o(e),t.push(...this.#c(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[a,l,h]=r;e.push([a,l,r],[a,h,r])}e.sort((r,a)=>r[1]-a[1]||r[0]-a[0]);for(let r=0,a=e.length;r<a;r+=2){const l=e[r][2],h=e[r+1][2];l.push(h),h.push(l),s.add(l),s.add(h)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[a,l,h,c,u]=r;s.delete(r);let d=a,f=l;for(n=[a,h],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[a,l,h,c,u]=g,d!==a&&(n.push(d,f,a,f===l?l:h),d=a),f=f===l?h:l}n.push(d,f)}return new bp(i,this.#t,this.#e)}#n(t){const e=this.#i;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}#l([,t,e]){const s=this.#n(t);this.#i.splice(s,0,[t,e])}#o([,t,e]){const s=this.#n(t);for(let i=s;i<this.#i.length;i++){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}}#c(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#n(i);for(let a=0;a<r;a++){const[l,h]=this.#i[a];for(let c=0,u=n.length;c<u;c++){const[,d,f]=n[c];if(!(h<=d||f<=l)){if(d>=l){if(f>h)n[c][1]=h;else{if(u===1)return[];n.splice(c,1),c--,u--}continue}n[c][2]=l,f>h&&n.push([e,h,f])}}}return n}}class bp extends B{#t;#e;constructor(t,e,s){super(),this.#e=t,this.#t=e,this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],a=e[n+1];r===s?(t.push(`V${a}`),i=a):a===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],a=s-t,l=i-e;for(const h of this.#e){const c=new Array(h.length);for(let u=0;u<h.length;u+=2)c[u]=t+h[u]*a,c[u+1]=i-h[u+1]*l;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class Xa extends Rs{newFreeDrawOutline(t,e,s,i,n,r){return new yp(t,e,s,i,n,r)}}class yp extends cc{newOutliner(t,e,s,i,n,r=0){return new Xa(t,e,s,i,n,r)}}class ye{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#l=null;#o;#c=null;#h=null;#d;static#u=null;static get _keyboardManager(){return tt(this,"_keyboardManager",new Li([[["Escape","mac+Escape"],ye.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ye.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ye.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ye.prototype._moveToPrevious],[["Home","mac+Home"],ye.prototype._moveToBeginning],[["End","mac+End"],ye.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=st.HIGHLIGHT_COLOR,this.#l=t):(this.#n=!0,this.#d=st.HIGHLIGHT_DEFAULT_COLOR),this.#h=t?._uiManager||e,this.#o=this.#h._eventBus,this.#s=t?.color||this.#h?.highlightColors.values().next().value||"#FFFF98",ye.#u||=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"})}renderButton(){const t=this.#t=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=this.#h._signal;t.addEventListener("click",this.#m.bind(this),{signal:e}),t.addEventListener("keydown",this.#g.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#f();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#f(){const t=document.createElement("div"),e=this.#h._signal;t.addEventListener("contextmenu",Oe,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#h.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",ye.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#s),n.addEventListener("click",this.#a.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#g.bind(this),{signal:e}),t}#a(t,e){e.stopPropagation(),this.#o.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#m(t);return}const e=t.target.getAttribute("data-color");e&&this.#a(e,t)}_moveToNext(t){if(!this.#v){this.#m(t);return}if(t.target===this.#t){this.#i.firstChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#i?.firstChild||t.target===this.#t){this.#v&&this._hideDropdownFromKeyboard();return}this.#v||this.#m(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#v){this.#m(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#v){this.#m(t);return}this.#i.lastChild?.focus()}#g(t){ye._keyboardManager.exec(this,t)}#m(t){if(this.#v){this.hideDropdown();return}if(this.#r=t.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#h.combinedSignal(this.#c)})),this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#f();this.#t.append(e)}#p(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#c?.abort(),this.#c=null}get#v(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#v){this.#l?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#r})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#i)return;const e=this.#h.highlightColors.values();for(const s of this.#i.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class At extends G{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#l=null;#o=0;#c=null;#h=null;#d=null;#u=!1;#f=null;#a;#g=null;#m="";#p;#v="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=J.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=At.prototype;return tt(this,"_keyboardManager",new Li([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||At._defaultColor,this.#p=t.thickness||At._defaultThickness,this.#a=t.opacity||At._defaultOpacity,this.#s=t.boxes||null,this.#v=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#u=!0,this.#b(t),this.#P()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#l=t.focusNode,this.#o=t.focusOffset,this.#_(),this.#P(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#p,methodOfCreation:this.#v}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_(){const t=new Wa(this.#s,.001);this.#h=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#h.box;const e=new Wa(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#n=e.getOutlines();const{lastPoint:s}=this.#n;this.#f=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#b({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#h=t;const i=1.5;if(this.#n=t.getNewOutline(this.#p/2+i,.0025),e>=0)this.#d=e,this.#i=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},!0);else if(this.parent){const c=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#d,{bbox:At.#x(this.#h.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:At.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,a,l]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=a,this.height=l;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=a*u/c,this.height=l*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=a,this.height=l;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=a*u/c,this.height=l*c/u;break}}const{lastPoint:h}=this.#n;this.#f=[(h[0]-n)/a,(h[1]-r)/l]}static initialize(t,e){G.initialize(t,e),At._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case st.HIGHLIGHT_DEFAULT_COLOR:At._defaultColor=e;break;case st.HIGHLIGHT_THICKNESS:At._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case st.HIGHLIGHT_COLOR:this.#w(e);break;case st.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[st.HIGHLIGHT_DEFAULT_COLOR,At._defaultColor],[st.HIGHLIGHT_THICKNESS,At._defaultThickness]]}get propertiesToUpdate(){return[[st.HIGHLIGHT_COLOR,this.color||At._defaultColor],[st.HIGHLIGHT_THICKNESS,this.#p||At._defaultThickness],[st.HIGHLIGHT_FREE,this.#u]]}#w(t){const e=(n,r)=>{this.color=n,this.#a=r,this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#a;this.addCommands({cmd:e.bind(this,t,At._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#S(t){const e=this.#p,s=i=>{this.#p=i,this.#A(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#r=new ye({editor:this}),t.addColorPicker(this.#r)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#O())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#E(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#P(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#P(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#A(t){if(!this.#u)return;this.#b({highlightOutlines:this.#h.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#E(){this.#d===null||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#P(t=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#h.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#a},rootClass:{highlight:!0,free:this.#u},path:{d:this.#h.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#u},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#u),this.#c&&(this.#c.style.clipPath=this.#i))}static#x([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#u?(t=(t-this.rotation+360)%360,s=At.#x(this.#h.box,t)):s=At.#x([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#d,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:At.#x(this.#n.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#m&&(t.setAttribute("aria-label",this.#m),t.setAttribute("role","mark")),this.#u?t.classList.add("free"):this.div.addEventListener("keydown",this.#k.bind(this),{signal:this._uiManager._signal});const e=this.#c=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#i;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),tr(this,this.#c,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#k(t){At._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1);break}}#T(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#l,this.#o)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#d,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#O(){return this.#u?this.rotation:0}#F(){if(this.#u)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let a=0;for(const{x:l,y:h,width:c,height:u}of n){const d=l*t+s,f=(1-h)*e+i;r[a]=r[a+4]=d,r[a+1]=r[a+3]=f,r[a+2]=r[a+6]=d+c*t,r[a+5]=r[a+7]=f-u*e,a+=8}return r}#I(t){return this.#h.serialize(t,this.#O())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:a,width:l,height:h}=s.getBoundingClientRect(),c=new AbortController,u=t.combinedSignal(c),d=f=>{c.abort(),this.#y(t,f)};window.addEventListener("blur",d,{signal:u}),window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("pointerdown",ge,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",Oe,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new Xa({x:i,y:n},[r,a,l,h],t.scale,this._defaultThickness/2,e,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#C(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#y(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof lc){const{data:{quadPoints:g,rect:p,rotation:v,id:m,color:b,opacity:_,popupRef:w},parent:{page:{pageNumber:C}}}=t;i=t={annotationType:J.HIGHLIGHT,color:Array.from(b),opacity:_,quadPoints:g,boxes:null,pageIndex:C-1,rect:p.slice(0),rotation:v,id:m,deleted:!1,popupRef:w}}else if(t instanceof Ga){const{data:{inkLists:g,rect:p,rotation:v,id:m,color:b,borderStyle:{rawWidth:_},popupRef:w},parent:{page:{pageNumber:C}}}=t;i=t={annotationType:J.HIGHLIGHT,color:Array.from(b),thickness:_,inkLists:g,boxes:null,pageIndex:C-1,rect:p.slice(0),rotation:v,id:m,deleted:!1,popupRef:w}}const{color:n,quadPoints:r,inkLists:a,opacity:l}=t,h=await super.deserialize(t,e,s);h.color=z.makeHexColor(...n),h.#a=l||1,a&&(h.#p=t.thickness),h.annotationElementId=t.id||null,h._initialData=i;const[c,u]=h.pageDimensions,[d,f]=h.pageTranslation;if(r){const g=h.#s=[];for(let p=0;p<r.length;p+=8)g.push({x:(r[p]-d)/c,y:1-(r[p+1]-f)/u,width:(r[p+2]-r[p])/c,height:(r[p+1]-r[p+5])/u});h.#_(),h.#P(),h.rotate(h.rotation)}else if(a){h.#u=!0;const g=a[0],p={x:g[0]-d,y:u-(g[1]-f)},v=new Xa(p,[0,0,c,u],1,h.#p/2,!0,.001);for(let _=0,w=g.length;_<w;_+=2)p.x=g[_]-d,p.y=u-(g[_+1]-f),v.add(p);const{id:m,clipPathId:b}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:h.color,"fill-opacity":h._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:v.toSVGPath()}},!0,!0);h.#b({highlightOutlines:v.getOutlines(),highlightId:m,clipPathId:b}),h.#P()}return h}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=G._colorManager.convert(this.color),i={annotationType:J.HIGHLIGHT,color:s,opacity:this.#a,thickness:this.#p,quadPoints:this.#F(),outlines:this.#I(e),pageIndex:this.pageIndex,rect:e,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#R(i)?null:(i.id=this.annotationElementId,i)}#R(t){const{color:e}=this._initialData;return t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class _p{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){const t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){ut("Not implemented")}}class W extends G{#t=null;#e;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#l=null;static#o=null;static#c=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,t.drawOutlines&&(this.#h(t),this.#f())}#h({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#d(t,this.parent),this.#m(t.box)}#d(t,e){const{id:s}=e.drawLayer.draw(W._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){ut("Not implemented")}static get typesMap(){ut("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(W.#s.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=a=>{i.updateProperty(e,a);const l=this.#t.updateProperty(e,a);l&&this.#m(l),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties())};this.addCommands({cmd:r.bind(this,s),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#g()),{bbox:this.#p()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#p(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#p()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#u(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#m(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#u()):t&&(this._uiManager.addShouldRescale(this),this.#f(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#u(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#d(this.#t,t)}}#a([t,e,s,i]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#g(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#m(t){if([this.x,this.y,this.width,this.height]=this.#a(t),this.div){this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}this._onResized()}#p(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[a,l]}=this;switch((n*4+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(a/l),i*(l/a),s*(a/l)];case 5:return[1-e,t,s*(a/l),i*(l/a)];case 6:return[1-t-i*(l/a),1-e,i*(l/a),s*(a/l)];case 7:return[e-s*(a/l),1-t-i*(l/a),s*(a/l),i*(l/a)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(l/a),e,i*(l/a),s*(a/l)];case 13:return[1-e-s*(a/l),t-i*(l/a),s*(a/l),i*(l/a)];case 14:return[1-t,1-e-s*(a/l),i*(l/a),s*(a/l)];case 15:return[e,1-t,s*(a/l),i*(l/a)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties({bbox:this.#p()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#m(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal";const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),this._uiManager.addShouldRescale(this),this.disableEditing(),t}static createDrawerInstance(t,e,s,i,n){ut("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:a,pointerId:l,pointerType:h}=i;if(W.#l&&W.#l!==h)return;const{viewport:{rotation:c}}=t,{width:u,height:d}=n.getBoundingClientRect(),f=W.#i=new AbortController,g=t.combinedSignal(f);if(W.#n||=l,W.#l??=h,window.addEventListener("pointerup",p=>{W.#n===p.pointerId?this._endDraw(p):W.#o?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{W.#n===p.pointerId?this._currentParent.endDrawingSession():W.#o?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{W.#l===p.pointerType&&((W.#o||=new Set).add(p.pointerId),W.#s.isCancellable()&&(W.#s.removeLastElement(),W.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",Oe,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===W.#c&&ge(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),W.#s){t.drawLayer.updateProperties(this._currentDrawId,W.#s.startNew(r,a,u,d,c));return}e.updateUIForDefaultProperties(this),W.#s=this.createDrawerInstance(r,a,u,d,c),W.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(W.#r.toSVGProperties(),W.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(W.#c=-1,!W.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(W.#n===i){if(W.#o?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,W.#s.add(e,s)),W.#c=t.timeStamp,ge(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,W.#s=null,W.#r=null,W.#l=null,W.#c=NaN),W.#i&&(W.#i.abort(),W.#i=null,W.#n=NaN,W.#o=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t&&e.drawLayer.updateProperties(this._currentDrawId,W.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=W.#s,i=this._currentDrawId,n=s.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,s.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,s.removeLastElement())},mustExec:!1,type:st.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(st.DRAW_STEP),!W.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:W.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:W.#r,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){ut("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:a}}=e.viewport,l=this.deserializeDraw(r,a,i,n,this._INNER_MARGIN,t),h=await super.deserialize(t,e,s);return h.createDrawingOptions(t),h.#h({drawOutlines:l}),h.#f(),h.onScaleChanging(),h.rotate(),h}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#t.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class wp{#t=new Float64Array(6);#e;#s;#i;#r;#n;#l="";#o=0;#c=new lr;#h;#d;constructor(t,e,s,i,n,r){this.#h=s,this.#d=i,this.#i=n,this.#r=r,[t,e]=this.#u(t,e);const a=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#s=[{line:a,points:this.#n}],this.#t.set(a,0)}updateProperty(t,e){t==="stroke-width"&&(this.#r=e)}#u(t,e){return B._normalizePoint(t,e,this.#h,this.#d,this.#i)}isEmpty(){return!this.#s||this.#s.length===0}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#u(t,e);const[s,i,n,r]=this.#t.subarray(2,6),a=t-n,l=e-r;return Math.hypot(this.#h*a,this.#d*l)<=2?null:(this.#n.push(t,e),isNaN(s)?(this.#t.set([n,r,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([s,i,n,r,t,e],0),this.#e.push(...B.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(this.#n.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#h=s,this.#d=i,this.#i=n,[t,e]=this.#u(t,e);const r=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e];const a=this.#s.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#s.push({line:r,points:this.#n}),this.#t.set(r,0),this.#o=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(t){return this.#s?(this.#s.push(t),this.#e=t.line,this.#n=t.points,this.#o=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#c.removeLastElement();this.#s.pop(),this.#l="";for(let t=0,e=this.#s.length;t<e;t++){const{line:s,points:i}=this.#s[t];this.#e=s,this.#n=i,this.#o=0,this.toSVGPath()}return{path:{d:this.#l}}}toSVGPath(){const t=B.svgRound(this.#e[4]),e=B.svgRound(this.#e[5]);if(this.#n.length===2)return this.#l=`${this.#l} M ${t} ${e} Z`,this.#l;if(this.#n.length<=6){const i=this.#l.lastIndexOf("M");this.#l=`${this.#l.slice(0,i)} M ${t} ${e}`,this.#o=6}if(this.#n.length===4){const i=B.svgRound(this.#e[10]),n=B.svgRound(this.#e[11]);return this.#l=`${this.#l} L ${i} ${n}`,this.#o=12,this.#l}const s=[];this.#o===0&&(s.push(`M ${t} ${e}`),this.#o=6);for(let i=this.#o,n=this.#e.length;i<n;i+=6){const[r,a,l,h,c,u]=this.#e.slice(i,i+6).map(B.svgRound);s.push(`C${r} ${a} ${l} ${h} ${c} ${u}`)}return this.#l+=s.join(" "),this.#o=this.#e.length,this.#l}getOutlines(t,e,s,i){const n=this.#s.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#c.build(this.#s,t,e,s,this.#i,this.#r,i),this.#t=null,this.#e=null,this.#s=null,this.#l=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class lr extends B{#t;#e=0;#s;#i;#r;#n;#l;#o;#c;build(t,e,s,i,n,r,a){this.#r=e,this.#n=s,this.#l=i,this.#o=n,this.#c=r,this.#s=a??0,this.#i=t,this.#u()}setLastElement(t){return this.#i.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#i.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#i){if(t.push(`M${B.svgRound(e[4])} ${B.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${B.svgRound(e[10])} ${B.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,a,l,h,c]=e.subarray(s,s+6).map(B.svgRound);t.push(`C${n} ${r} ${a} ${l} ${h} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],a=[],[l,h,c,u]=this.#d();let d,f,g,p,v,m,b,_,w;switch(this.#o){case 0:w=B._rescale,d=t,f=e+i,g=s,p=-i,v=t+l*s,m=e+(1-h-u)*i,b=t+(l+c)*s,_=e+(1-h)*i;break;case 90:w=B._rescaleAndSwap,d=t,f=e,g=s,p=i,v=t+h*s,m=e+l*i,b=t+(h+u)*s,_=e+(l+c)*i;break;case 180:w=B._rescale,d=t+s,f=e,g=-s,p=i,v=t+(1-l-c)*s,m=e+h*i,b=t+(1-l)*s,_=e+(h+u)*i;break;case 270:w=B._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,v=t+(1-h-u)*s,m=e+(1-l-c)*i,b=t+(1-h)*s,_=e+(1-l)*i;break}for(const{line:C,points:T}of this.#i)r.push(w(C,d,f,g,p,n?new Array(C.length):null)),a.push(w(T,d,f,g,p,n?new Array(T.length):null));return{lines:r,points:a,rect:[v,m,b,_]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:a},rotation:l,thickness:h}){const c=[];let u,d,f,g,p;switch(l){case 0:p=B._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=B._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=B._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=B._rescaleAndSwap,u=e/i+1,d=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of a){const b=m.length;if(b===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(b===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1],NaN,NaN,NaN,NaN,m[2],m[3]]));continue}const _=new Float32Array(3*(b-2));r.push(_);let[w,C,T,E]=m.subarray(0,4);_.set([NaN,NaN,NaN,NaN,w,C],0);for(let k=4;k<b;k+=2){const O=m[k],H=m[k+1];_.set(B.createBezierPoints(w,C,T,E,O,H),(k-2)*3),[w,C,T,E]=[T,E,O,H]}}}for(let m=0,b=r.length;m<b;m++)c.push({line:p(r[m].map(_=>_??NaN),u,d,f,g),points:p(a[m].map(_=>_??NaN),u,d,f,g)});const v=new lr;return v.build(c,s,i,1,l,h,n),v}#h(t=this.#c){const e=this.#s+t/2*this.#l;return this.#o%180===0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#d(){const[t,e,s,i]=this.#t,[n,r]=this.#h(0);return[t+n,e+r,s-2*n,i-2*r]}#u(){const t=this.#t=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:i}of this.#i){if(i.length<=12){for(let a=4,l=i.length;a<l;a+=6){const[h,c]=i.subarray(a,a+2);t[0]=Math.min(t[0],h),t[1]=Math.min(t[1],c),t[2]=Math.max(t[2],h),t[3]=Math.max(t[3],c)}continue}let n=i[4],r=i[5];for(let a=6,l=i.length;a<l;a+=6){const[h,c,u,d,f,g]=i.subarray(a,a+6);z.bezierBoundingBox(n,r,h,c,u,d,f,g,t),n=f,r=g}}const[e,s]=this.#h();t[0]=Math.min(1,Math.max(0,t[0]-e)),t[1]=Math.min(1,Math.max(0,t[1]-s)),t[2]=Math.min(1,Math.max(0,t[2]+e)),t[3]=Math.min(1,Math.max(0,t[3]+s)),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return t==="stroke-width"?this.#f(e):null}#f(t){const[e,s]=this.#h();this.#c=t;const[i,n]=this.#h(),[r,a]=[i-e,n-s],l=this.#t;return l[0]-=r,l[1]-=a,l[2]+=2*r,l[3]+=2*a,l}updateParentDimensions([t,e],s){const[i,n]=this.#h();this.#r=t,this.#n=e,this.#l=s;const[r,a]=this.#h(),l=r-i,h=a-n,c=this.#t;return c[0]-=l,c[1]-=h,c[2]+=2*l,c[3]+=2*h,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(B.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,a=0,l=0;switch(this.#e){case 90:i=e/t,n=-t/e,a=t;break;case 180:s=-1,r=-1,a=t,l=e;break;case 270:i=-e/t,n=t/e,l=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${B.svgRound(a)} ${B.svgRound(l)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#h(),[a,l,h,c]=this.#t;if(Math.abs(h-n)<=B.PRECISION||Math.abs(c-r)<=B.PRECISION){const p=t+s/2-(a+h/2),v=e+i/2-(l+c/2);return{path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${v})`}}}const u=(s-2*n)/(h-2*n),d=(i-2*r)/(c-2*r),f=h/s,g=c/i;return{path:{"transform-origin":`${B.svgRound(a)} ${B.svgRound(l)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${B.svgRound(n)} ${B.svgRound(r)}) scale(${u} ${d}) translate(${B.svgRound(-n)} ${B.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#h(),a=this.#t,[l,h,c,u]=a;if(a[0]=t,a[1]=e,a[2]=s,a[3]=i,Math.abs(c-n)<=B.PRECISION||Math.abs(u-r)<=B.PRECISION){const v=t+s/2-(l+c/2),m=e+i/2-(h+u/2);for(const{line:b,points:_}of this.#i)B._translate(b,v,m,b),B._translate(_,v,m,_);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(c-2*n),f=(i-2*r)/(u-2*r),g=-d*(l+n)+t+n,p=-f*(h+r)+e+r;if(d!==1||f!==1||g!==0||p!==0)for(const{line:v,points:m}of this.#i)B._rescale(v,g,p,d,f,v),B._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,a=t-r[0],l=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:h,points:c}of this.#i)B._translate(h,a,l,h),B._translate(c,a,l,c);else{const h=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:u,points:d}of this.#i)B._rescale(u,a,l,h,c,u),B._rescale(d,a,l,h,c,d);r[2]*=h,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${B.svgRound(t[0])} ${B.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Ua extends _p{#t;constructor(t){super(),this.#t=t,super.updateProperties({fill:"none",stroke:G._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){t==="stroke-width"&&(e??=this["stroke-width"],e*=this.#t.realScale),super.updateSVGProperty(t,e)}clone(){const t=new Ua(this.#t);return t.updateAll(this),t}}class Ya extends W{static _type="ink";static _editorType=J.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){G.initialize(t,e),this._defaultDrawingOptions=new Ua(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return tt(this,"typesMap",new Map([[st.INK_THICKNESS,"stroke-width"],[st.INK_COLOR,"stroke"],[st.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new wp(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return lr.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof Ga){const{data:{inkLists:r,rect:a,rotation:l,id:h,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:J.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:a.slice(0),rotation:l,id:h,deleted:!1,popupRef:f}}const n=await super.deserialize(t,e,s);return n.annotationElementId=t.id||null,n._initialData=i,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=Ya.getDefaultDrawingOptions({stroke:z.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s,rect:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":r,"stroke-width":a}}=this,l={annotationType:J.INK,color:G._colorManager.convert(n),opacity:r,thickness:a,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?l:this.annotationElementId&&!this.#t(l)?null:(l.id=this.annotationElementId,l)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some((r,a)=>r!==e[a])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class $a extends G{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#l=null;#o=null;#c=!1;#h=!1;static _type="stamp";static _editorType=J.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile}static initialize(t,e){G.initialize(t,e)}static get supportedTypes(){return tt(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return tt(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(J.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#d(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#c=t.isSvg),t.file&&(this.#n=t.file.name),this.#a()}#u(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#l){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const l=a.output;return await this.setGuessedAltText(l),e&&!this.hasAltTextData()&&(this.altTextData={alt:l,decorative:!1}),l}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#d(s,!0)).finally(()=>this.#u());return}if(this.#i){const s=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#d(i)).finally(()=>this.#u());return}if(this.#r){const s=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#d(i)).finally(()=>this.#u());return}const t=document.createElement("input");t.type="file",t.accept=$a.supportedTypesStr;const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#l?.remove(),this.#l=null,this.#o&&(clearTimeout(this.#o),this.#o=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#f();return}super.rebuild(),this.div!==null&&(this.#e&&this.#l===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#i||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#t?this.#a():this.#f(),this.width&&!this.annotationElementId){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#o!==null&&clearTimeout(this.#o);const t=200;this.#o=setTimeout(()=>{this.#o=null,this.#m()},t)}#a(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const c=Math.min(r*i/e,r*n/s);e*=c,s*=c}const[a,l]=this.parentDimensions;this.setDims(e*a/i,s*l/n),this._uiManager.enableWaiting(!1);const h=this.#l=document.createElement("canvas");h.setAttribute("role","img"),this.addContainer(h),this.width=e/i,this.height=s/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#m(),this.#h||(this.parent.addUndoableEditor(this),this.#h=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&h.setAttribute("aria-label",this.#n)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new Pa;let a=this.#t,l=i,h=n,c=null;if(e){if(i>e||n>e){const T=Math.min(e/i,e/n);l=Math.floor(i*T),h=Math.floor(n*T)}c=document.createElement("canvas");const d=c.width=Math.ceil(l*r.sx),f=c.height=Math.ceil(h*r.sy);this.#c||(a=this.#g(d,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",v="#cfcfd8";this._uiManager.hcmFilter!=="none"?v="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",v="#42414d");const m=15,b=m*r.sx,_=m*r.sy,w=new OffscreenCanvas(b*2,_*2),C=w.getContext("2d");C.fillStyle=p,C.fillRect(0,0,b*2,_*2),C.fillStyle=v,C.fillRect(0,0,b,_),C.fillRect(b,_,b,_),g.fillStyle=g.createPattern(w,"repeat"),g.fillRect(0,0,d,f),g.drawImage(a,0,0,a.width,a.height,0,0,d,f)}let u=null;if(s){let d,f;if(r.symmetric&&a.width<t&&a.height<t)d=a.width,f=a.height;else if(a=this.#t,i>t||n>t){const v=Math.min(t/i,t/n);d=Math.floor(i*v),f=Math.floor(n*v),this.#c||(a=this.#g(d,f))}const p=new OffscreenCanvas(d,f).getContext("2d",{willReadFrequently:!0});p.drawImage(a,0,0,a.width,a.height,0,0,d,f),u={width:d,height:f,data:p.getImageData(0,0,d,f).data}}return{canvas:c,width:l,height:h,imageData:u}}#g(t,e){const{width:s,height:i}=this.#t;let n=s,r=i,a=this.#t;for(;n>2*t||r>2*e;){const l=n,h=r;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const c=new OffscreenCanvas(n,r);c.getContext("2d").drawImage(a,0,0,l,h,0,0,n,r),a=c.transferToImageBitmap()}return a}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new Pa,r=Math.ceil(s*t*n.sx),a=Math.ceil(i*e*n.sy),l=this.#l;if(!l||l.width===r&&l.height===a)return;l.width=r,l.height=a;const h=this.#c?this.#t:this.#g(r,a),c=l.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(h,0,0,h.width,h.height,0,0,r,a)}getImageForAltText(){return this.#l}#p(t){if(t){if(this.#c){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#c){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*ti.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*ti.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,n);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,s){let i=null;if(t instanceof hc){const{data:{rect:g,rotation:p,id:v,structParent:m,popupRef:b},container:_,parent:{page:{pageNumber:w}}}=t,C=_.querySelector("canvas"),T=s.imageManager.getFromCanvas(_.id,C);C.remove();const E=(await e._structTree.getAriaAttributes(`${Aa}${v}`))?.get("aria-label")||"";i=t={annotationType:J.STAMP,bitmapId:T.id,bitmap:T.bitmap,pageIndex:w-1,rect:g.slice(0),rotation:p,id:v,deleted:!1,accessibilityData:{decorative:!1,altText:E},isSvg:!1,structParent:m,popupRef:b}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:a,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:u}=t;h&&s.imageManager.isValidId(h)?(n.#e=h,a&&(n.#t=a)):n.#i=l,n.#c=c;const[d,f]=n.pageDimensions;return n.width=(r[2]-r[0])/d,n.height=(r[3]-r[1])/f,n.annotationElementId=t.id||null,u&&(n.altTextData=u),n._initialData=i,n.#h=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:J.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#p(!0),s.accessibilityData=this.serializeAltText(!0),s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const a=this.#v(s);if(a.isSame)return null;a.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}if(s.id=this.annotationElementId,e===null)return s;e.stamps||=new Map;const r=this.#c?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:r,serialized:s}),s.bitmap=this.#p(!1);else if(this.#c){const a=e.stamps.get(this.#e);r>a.area&&(a.area=r,a.serialized.bitmap.close(),a.serialized.bitmap=this.#p(!1))}return s}#v(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class ss{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#l=!1;#o=!1;#c=!1;#h=null;#d=null;#u=null;#f=null;#a;static _initialized=!1;static#g=new Map([It,Ya,$a,At].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:a,textLayer:l,viewport:h,l10n:c}){const u=[...ss.#g.values()];if(!ss._initialized){ss._initialized=!0;for(const d of u)d.initialize(c,t)}t.registerEditorTypes(u),this.#a=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=h,this.#u=l,this.drawLayer=a,this._structTree=i,this.#a.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#a.getMode()===J.NONE}updateToolbar(t){this.#a.updateToolbar(t)}updateMode(t=this.#a.getMode()){switch(this.#b(),t){case J.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case J.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case J.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 ss.#g.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#u?.div}setEditingState(t){this.#a.setEditingState(t)}addCommands(t){this.#a.addCommands(t)}cleanUndoStack(t){this.#a.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of this.#n.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#a.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s){this.#c=!1;return}const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#a.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#c=!1}disable(){this.#o=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#n.values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#s){const i=this.#s.getEditableAnnotations();for(const n of i){const{id:r}=n.data;if(this.#a.isDeletedAnnotationElement(r))continue;let a=e.get(r);if(a){a.resetAnnotationElement(n),a.show(!1),n.show();continue}a=t.get(r),a&&(this.#a.addChangedExistingAnnotation(a),a.renderAnnotationElement(n)&&a.show(!1)),n.show()}}this.#b(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of ss.#g.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#o=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#a.getActive()!==t&&this.#a.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#u?.div&&!this.#f){this.#f=new AbortController;const t=this.#a.combinedSignal(this.#f);this.#u.div.addEventListener("pointerdown",this.#m.bind(this),{signal:t}),this.#u.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#u.div.classList.remove("highlighting"))}#m(t){this.#a.unselectAll();const{target:e}=t;if(e===this.#u.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#u.div.contains(e)){const{isMac:s}=Qt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#a.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),At.startHighlighting(this,this.#a.direction==="ltr",{target:this.#u.div,x:t.x,y:t.y}),this.#u.div.addEventListener("pointerup",()=>{this.#u.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#a._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#a.combinedSignal(this.#i);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#i?.abort(),this.#i=null}attach(t){this.#n.set(t.id,t);const{annotationElementId:e}=t;e&&this.#a.isDeletedAnnotationElement(e)&&this.#a.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#o&&t.annotationElementId&&this.#a.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#a.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#a.addDeletedAnnotationElement(t.annotationElementId),G.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.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),this.#a.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#c),this.#a.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#r&&(t._focusEventsAllowed=!1,this.#r=setTimeout(()=>{this.#r=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#a._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(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 this.#a.getId()}get#p(){return ss.#g.get(this.#a.getMode())}combinedSignal(t){return this.#a.combinedSignal(t)}#v(t){const e=this.#p;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#a.updateToolbar(t),this.#a.updateMode(t);const{offsetX:s,offsetY:i}=this.#_(),n=this.getNextId(),r=this.#v({parent:this,id:n,x:s,y:i,uiManager:this.#a,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await ss.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#a)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#v({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#a,isCentered:e,...s});return n&&this.add(n),n}#_(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),a=Math.min(window.innerWidth,t+s),l=Math.min(window.innerHeight,e+i),h=(n+a)/2-t,c=(r+l)/2-e,[u,d]=this.viewport.rotation%180===0?[h,c]:[c,h];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#_(),!0)}setSelected(t){this.#a.setSelected(t)}toggleSelected(t){this.#a.toggleSelected(t)}unselect(t){this.#a.unselect(t)}pointerup(t){const{isMac:e}=Qt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#l&&(this.#l=!1,!(this.#p?.isDrawer&&this.#p.supportMultipleDrawings))){if(!this.#e){this.#e=!0;return}if(this.#a.getMode()===J.STAMP){this.#a.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#a.getMode()===J.HIGHLIGHT&&this.enableTextSelection(),this.#l){this.#l=!1;return}const{isMac:e}=Qt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#l=!0,this.#p?.isDrawer){this.startDrawingSession(t);return}const s=this.#a.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus(),this.#h){this.#p.startDrawing(this,this.#a,!1,t);return}this.#a.setCurrentDrawingSession(this),this.#h=new AbortController;const e=this.#a.combinedSignal(this.#h);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#d=null,this.commitOrRemove())},{signal:e}),this.#p.startDrawing(this,this.#a,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#d=e);return}this.#d&&setTimeout(()=>{this.#d?.focus(),this.#d=null},0)}endDrawingSession(t=!1){return this.#h?(this.#a.setCurrentDrawingSession(null),this.#h.abort(),this.#h=null,this.#d=null,this.#p.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#a.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#h?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#h&&this.#p.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#a.getActive()?.parent===this&&(this.#a.commitOrRemove(),this.#a.setActiveEditor(null)),this.#r&&(clearTimeout(this.#r),this.#r=null);for(const t of this.#n.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#n.clear(),this.#a.removeLayer(this)}#b(){for(const t of this.#n.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,Ms(this.div,t);for(const e of this.#a.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#a.commitOrRemove(),this.#b();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,Ms(this.div,{rotation:s}),e!==s)for(const i of this.#n.values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#a.viewParameters.realScale}}class te{#t=null;#e=0;#s=new Map;#i=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#s.size>0)for(const e of this.#s.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return tt(this,"_svgFactory",new za)}static#r(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`}#n(){const t=te._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#l(t,e){const s=te._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=te._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#o(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=!1,s=!1){const i=this.#e++,n=this.#n(),r=te._svgFactory.createElement("defs");n.append(r);const a=te._svgFactory.createElement("path");r.append(a);const l=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",l),a.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,a);const h=s?this.#l(r,l):null,c=te._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${l}`),this.updateProperties(n,t),this.#s.set(i,n),{id:i,clipPathId:`url(#${h})`}}drawOutline(t,e){const s=this.#e++,i=this.#n(),n=te._svgFactory.createElement("defs");i.append(n);const r=te._svgFactory.createElement("path");n.append(r);const a=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",a),r.setAttribute("vector-effect","non-scaling-stroke");let l;if(e){const u=te._svgFactory.createElement("mask");n.append(u),l=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",l),u.setAttribute("maskUnits","objectBoundingBox");const d=te._svgFactory.createElement("rect");u.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const f=te._svgFactory.createElement("use");u.append(f),f.setAttribute("href",`#${a}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const h=te._svgFactory.createElement("use");i.append(h),h.setAttribute("href",`#${a}`),l&&h.setAttribute("mask",`url(#${l})`);const c=h.cloneNode();return i.append(c),h.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#s.set(s,i),s}finalizeDraw(t,e){this.#i.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,a=typeof t=="number"?this.#s.get(t):t;if(a){if(s&&this.#o(a,s),i&&te.#r(a,i),n){const{classList:l}=a;for(const[h,c]of Object.entries(n))l.toggle(h,c)}if(r){const h=a.firstChild.firstChild;this.#o(h,r)}}}updateParent(t,e){if(e===this)return;const s=this.#s.get(t);s&&(e.#t.append(s),this.#s.delete(t),e.#s.set(t,s))}remove(t){this.#i.delete(t),this.#t!==null&&(this.#s.get(t).remove(),this.#s.delete(t))}destroy(){this.#t=null;for(const t of this.#s.values())t.remove();this.#s.clear(),this.#i.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner:Wa},X.AbortException,X.AnnotationEditorLayer,X.AnnotationEditorParamsType,X.AnnotationEditorType,X.AnnotationEditorUIManager,X.AnnotationLayer,X.AnnotationMode,X.ColorPicker,X.DOMSVGFactory,X.DrawLayer,X.FeatureTest;var xp=X.GlobalWorkerOptions;X.ImageKind,X.InvalidPDFException,X.MissingPDFException,X.OPS,X.OutputScale,X.PDFDataRangeTransport,X.PDFDateString,X.PDFWorker,X.PasswordResponses,X.PermissionFlag,X.PixelsPerInch,X.RenderingCancelledException,X.TextLayer,X.TouchManager,X.UnexpectedResponseException,X.Util,X.VerbosityLevel,X.XfaLayer,X.build,X.createValidAbsoluteUrl,X.fetchData;var Sp=X.getDocument;X.getFilenameFromUrl,X.getPdfFilenameFromUrl,X.getXfaPageViewport,X.isDataScheme,X.isPdfFile,X.noContextMenu,X.normalizeUnicode,X.setLayerDimensions,X.shadow,X.stopEvent,X.version;const Cp={"pdfjs-dist":"4.10.38"};function Ap(o){return new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>t(s.result)),s.addEventListener("error",e),s.readAsDataURL(o)})}const Tp=Cp["pdfjs-dist"].replace("^","");xp.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Tp}/pdf.worker.min.mjs`;async function Ep(o){const t="data:application/pdf;base64,",e=await Ap(o);if(typeof e=="string")return window.atob(e.slice(t.length))}function kp(o,t){return Sp({data:o,password:t}).promise}const le=new Map;function Pp(o){const t=new aa(o);return le.set(o,t),t}function Mp(o,t){const e=Date.now();return{PDFId:`${o.name}-${e}`,name:o.name.replace(/.pdf/,""),updateDate:e,PDFBase64:t}}function Op(o,t){const e=o.getViewport({scale:t}),s=document.createElement("canvas"),i=s.getContext("2d"),n=yf()/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]},a=o.render(r);return{canvas:s,renderTask:a}}async function Dp({src:o},t,e){if(!o||!e)return null;const{objects:s,options:i}=await of(o),n=s.filter(a=>a!==null),r=xd.groupSVGElements(n,i);return n.forEach(a=>{a.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function Rp(o,t){if(!le.get(o))return;const s=1/3,i=Hp(t,s);dc(o,i,s)}async function Fp(o,t){const e=await wf(t),s=Date.now(),n={PDFId:`${t.name}${s}`,name:t.name.replace(/.png|.jpg|.jpeg/,""),updateDate:s,PDFBase64:e};return uc(o,{url:e}),{...n,pages:1}}async function uc(o,{url:t,scale:e=.5}){if(!le.get(o))return;const i=await Vt.fromURL(t);i.scale(e),dc(o,i,e)}function dc(o,t,e){const s=le.get(o);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function Lp(o,t){if(!t)return;const{oCoords:e}=o;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:a,scaleX:l}=t;t.top=i-n*a/2,t.left=s-r*l/2,t.setCoords()}function Ip(o,t,e){!e||!o||(e.scale(1/t),Lp(o,e))}function jp(o,t){if(!o)return;const e=o._cornerSize||6;o.borderScaleFactor=1/t,o.cornerSize=e*(1/t),o.touchCornerSize=e*4*(1/t),o.setCoords()}function Np(o){const t=le.get(o);t&&(t.discardActiveObject(),t.renderAll())}function Bp(o){const t=le.get(o);t&&(t.clear(),le.delete(o))}function Hp(o,t){return new Vt(o,{scaleX:t,scaleY:t})}function qa(o,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:a}=o,l=t.x*r*i,h=t.y*a*n;o.set({left:e-l,top:s-h})}function fc(o,t,e){const s=o.type;return{"application/pdf":zp,"image/png":pc,"image/jpeg":pc}[s]?.(o,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function zp(o,t,e){const s=await Ep(o);if(!s)return;const i=Mp(o,s);try{const n=await gc({page:1,PDFBase64:s,scale:.8,password:t},e);return{...i,pages:n}}catch(n){return Promise.reject(n)}}async function gc({page:o,PDFBase64:t,scale:e,password:s},i){try{const n=await kp(t,s),r=await n.getPage(o),{renderTask:a,canvas:l}=Op(r,e);return a.promise.then(()=>(i&&Rp(i,l),n.numPages))}catch(n){return Promise.reject(n)}}async function pc(o,t,e){if(e)return await Fp(e,o)}async function Vp(o,t){const e=le.get(o);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(zc);i instanceof me?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),qa(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function Gp(o){const t=le.get(o);if(!t)return;const e=t.getActiveObject();e&&(e instanceof me?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function mc(o){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:a}=o||{},l=Z.useRef(null),h=Z.useRef(null),c=Z.useRef(1),u=Z.useRef({...Hc});function d(){if(!t||le.has(t))return;const P=Pp(t);return P.on("selection:created",R=>{if(r?.(R),R.selected.length<=1)return;const F=P.getActiveObject();F&&(h.current=F,e?.value&&h.current.set(e.value),h.current._cornerSize=h.current.cornerSize,C(c.current))}),P.on("selection:cleared",R=>{a?.(R),E(P)}),s&&P.on("mouse:down",s),i&&P.on("mouse:move",i),n&&P.on("mouse:up",n),P}function f(P,R){return fc(P,R,t)}function g(P){return gc(P,t)}function p({url:P,scale:R=.5}){return uc(t,{url:P,scale:R})}async function v(P,R,F){const V=le.get(t);if(!V)return;const M=await Vt.fromURL(P,{},{...jc,...R});qa(M,F),V.add(M),b(V,M),V.setActiveObject(M)}function m(P,R,F){const V=le.get(t);if(!V)return;const M=new zt(P,{...Nc,...R});qa(M,F),V.add(M),b(V,M),V.setActiveObject(M)}function b(P,R){R.on("selected",F=>_({canvas:P,target:F.target})),R.on("modified",F=>_({canvas:P,target:F.target})),R.on("scaling",()=>E(P)),R.on("moving",()=>E(P)),R.on("rotating",()=>E(P)),R._cornerSize=R._cornerSize??R.cornerSize}async function _({canvas:P,target:R,stroke:F=u.current.stroke,uuid:V=Date.now()}){if(P.getActiveObjects().length>1||l.current?.stroke===`${F}-${V}`)return;const L=await Dp(u.current,V,F);E(P),l.current=L,h.current=R,w(P,R,V),C(c.current,!0),L&&P.add(L)}function w(P,R,F){l.current&&(l.current.on("selected",()=>{P.remove(R),E(P)}),l.current.on("mouseover",()=>{_({canvas:P,target:R,stroke:u.current.hoverStroke,uuid:F})}),l.current.on("mouseout",()=>{_({canvas:P,target:R,stroke:u.current.stroke,uuid:F})}))}function C(P,R=!1){const F=le.get(t);c.current=P,F&&(jp(h.current,P),Ip(h.current,P,l.current),!R&&F.renderAll())}function T(P){if(!P)return;u.current={...u.current,...P};const R=le.get(t);!l||!h.current||!R||_({target:h.current,canvas:R})}function E(P){h.current=null,l.current&&(P.remove(l.current),l.current=null)}function k(){Np(t)}function O(){Bp(t)}function H(){return Vp(t,b)}function N(){Gp(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:v,addTextFabric:m,clearActive:k,deleteCanvas:O,scaleFabric:C,setCloseSvgOptions:T,copyActiveFabric:H,deleteActiveFabric:N}}function Wp(o){let t=0;const e=_f(()=>{t!==window.innerWidth&&(t=window.innerWidth,o())});Z.useEffect(()=>(window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)),[])}const Xp=Z.forwardRef(Up);function Up({file:o,page:t=1,canvasId:e="PDF-canvas",fileZoom:s=1,fileScale:i=1,canvasScale:n=1,canvasClass:r="",isDrop:a=!1,password:l,dropTextOptions:h,dropImageOptions:c,closeSvgOptions:u,selectionOptions:d,manualReload:f,onLoaded:g,onReload:p,onPointerDown:v,onPointerMove:m,onPointerUp:b,onSelectionCreated:_,onSelectionCleared:w},C){const T=Z.useRef(null),E=`${e}-${t-1}`,k=Z.useMemo(()=>s*n,[s,n]),O=Z.useMemo(()=>({...Bc,...d}),[d]),{createCanvas:H,specifyPage:N,addFabric:P,addTextFabric:R,renderImage:F,clearActive:V,deleteCanvas:M,scaleFabric:L,setCloseSvgOptions:Y,copyActiveFabric:ft,deleteActiveFabric:bt}=mc({id:E,selectionOptions:O,pointerDown:v,pointerMove:m,pointerUp:b,selectionCreated:_,selectionCleared:w});Wp(ee);async function _t(){window.requestAnimationFrame(async()=>{if(H(),o.PDFBase64.startsWith("data:image")||o.canvas){const{canvas:K}=o,$=K?7:3,Tt=K?.length?K[t-1]:o.PDFBase64;F({url:Tt,scale:i/$});return}await N({page:t,PDFBase64:o.PDFBase64,scale:i,password:l}),g?.()})}function gt(K){if(K.preventDefault(),K.stopPropagation(),!a||!K.dataTransfer)return;const{dataTransfer:$,nativeEvent:Tt}=K,{offsetX:_e,offsetY:Nt}=Tt,cr=$.getData("text/plain"),Gi=$.getData("text/uri-list"),ur=$.getData("custom/offset"),dr=ur?JSON.parse(ur):null,Is={top:Nt,left:_e},fs={x:dr?.offsetX??0,y:dr?.offsetY??0};Gi?rt(Gi,Is,fs):cr&&Dt(cr,Is,fs)}function rt(K,$,Tt){P(K,{...c,...$},Tt)}function Dt(K,$,Tt){R(K,{...h,...$},Tt)}function ee(){f||_t(),p?.()}return Z.useImperativeHandle(C,()=>({reload:_t,addImage:rt,addText:Dt,clearActive:V,deleteCanvas:M,copyActiveFabric:ft,deleteActiveFabric:bt,canvasRef:T})),Z.useEffect(()=>{ee()},[i,t,o,l]),Z.useEffect(()=>{L(k)},[k]),Z.useEffect(()=>{Y(u)},[u]),Z.useEffect(()=>()=>M(),[]),ro.jsx("div",{style:{transform:`scale(${k})`},onDragOver:K=>K.preventDefault(),onDragEnter:K=>K.preventDefault(),onDrop:gt,children:ro.jsx("canvas",{id:E,ref:T,className:r})})}at.default=Xp,at.loadFile=fc,at.useFabric=mc,Object.defineProperties(at,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});