@component-hook/pdf-canvas 1.4.4 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,82 +1,39 @@
1
- (function(et,K){typeof exports=="object"&&typeof module<"u"?K(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],K):(et=typeof globalThis<"u"?globalThis:et||self,K(et["pdf-canvas"]={},et.React))})(this,(function(et,K){"use strict";var Nh=et=>{throw TypeError(et)};var Mo=(et,K,pt)=>K.has(et)||Nh("Cannot "+pt);var _e=(et,K,pt)=>(Mo(et,K,"read from private field"),pt?pt.call(et):K.get(et)),Ws=(et,K,pt)=>K.has(et)?Nh("Cannot add the same private member more than once"):K instanceof WeakSet?K.add(et):K.set(et,pt),Ai=(et,K,pt,Me)=>(Mo(et,K,"write to private field"),Me?Me.call(et,pt):K.set(et,pt),pt),Vn=(et,K,pt)=>(Mo(et,K,"access private method"),pt);var Bh=(et,K,pt,Me)=>({set _(Ze){Ai(et,K,Ze,pt)},get _(){return _e(et,K,Me)}});var Wn,_s,ws,zs,Un,Gs,Yn;var pt=typeof document<"u"?document.currentScript:null,Me={exports:{}},Ze={};var Po;function $h(){if(Po)return Ze;Po=1;var a=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,i,n){var r=null;if(n!==void 0&&(r=""+n),i.key!==void 0&&(r=""+i.key),"key"in i){n={};for(var o in i)o!=="key"&&(n[o]=i[o])}else n=i;return i=n.ref,{$$typeof:a,type:s,key:r,ref:i!==void 0?i:null,props:n}}return Ze.Fragment=t,Ze.jsx=e,Ze.jsxs=e,Ze}var Vs={};var Oo;function Hh(){return Oo||(Oo=1,process.env.NODE_ENV!=="production"&&(function(){function a(E){if(E==null)return null;if(typeof E=="function")return E.$$typeof===R?null:E.displayName||E.name||null;if(typeof E=="string")return E;switch(E){case b:return"Fragment";case v:return"Profiler";case m:return"StrictMode";case C:return"Suspense";case A:return"SuspenseList";case L:return"Activity"}if(typeof E=="object")switch(typeof E.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),E.$$typeof){case p:return"Portal";case y:return E.displayName||"Context";case _:return(E._context.displayName||"Context")+".Consumer";case w:var B=E.render;return E=E.displayName,E||(E=B.displayName||B.name||"",E=E!==""?"ForwardRef("+E+")":"ForwardRef"),E;case T:return B=E.displayName||null,B!==null?B:a(E.type)||"Memo";case k:B=E._payload,E=E._init;try{return a(E(B))}catch{}}return null}function t(E){return""+E}function e(E){try{t(E);var B=!1}catch{B=!0}if(B){B=console;var z=B.error,J=typeof Symbol=="function"&&Symbol.toStringTag&&E[Symbol.toStringTag]||E.constructor.name||"Object";return z.call(B,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),t(E)}}function s(E){if(E===b)return"<>";if(typeof E=="object"&&E!==null&&E.$$typeof===k)return"<...>";try{var B=a(E);return B?"<"+B+">":"<...>"}catch{return"<...>"}}function i(){var E=F.A;return E===null?null:E.getOwner()}function n(){return Error("react-stack-top-frame")}function r(E){if(P.call(E,"key")){var B=Object.getOwnPropertyDescriptor(E,"key").get;if(B&&B.isReactWarning)return!1}return E.key!==void 0}function o(E,B){function z(){M||(M=!0,console.error("%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://react.dev/link/special-props)",B))}z.isReactWarning=!0,Object.defineProperty(E,"key",{get:z,configurable:!0})}function l(){var E=a(this.type);return D[E]||(D[E]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),E=this.props.ref,E!==void 0?E:null}function h(E,B,z,J,Et,nt){var j=z.ref;return E={$$typeof:g,type:E,key:B,props:z,_owner:J},(j!==void 0?j:null)!==null?Object.defineProperty(E,"ref",{enumerable:!1,get:l}):Object.defineProperty(E,"ref",{enumerable:!1,value:null}),E._store={},Object.defineProperty(E._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(E,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(E,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:Et}),Object.defineProperty(E,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:nt}),Object.freeze&&(Object.freeze(E.props),Object.freeze(E)),E}function c(E,B,z,J,Et,nt){var j=B.children;if(j!==void 0)if(J)if(O(j)){for(J=0;J<j.length;J++)u(j[J]);Object.freeze&&Object.freeze(j)}else console.error("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 u(j);if(P.call(B,"key")){j=a(E);var dt=Object.keys(B).filter(function(Qt){return Qt!=="key"});J=0<dt.length?"{key: someKey, "+dt.join(": ..., ")+": ...}":"{key: someKey}",ut[j+J]||(dt=0<dt.length?"{"+dt.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
- let props = %s;
3
- <%s {...props} />
4
- React keys must be passed directly to JSX without using spread:
5
- let props = %s;
6
- <%s key={someKey} {...props} />`,J,j,dt,j),ut[j+J]=!0)}if(j=null,z!==void 0&&(e(z),j=""+z),r(B)&&(e(B.key),j=""+B.key),"key"in B){z={};for(var Tt in B)Tt!=="key"&&(z[Tt]=B[Tt])}else z=B;return j&&o(z,typeof E=="function"?E.displayName||E.name||"Unknown":E),h(E,j,z,i(),Et,nt)}function u(E){d(E)?E._store&&(E._store.validated=1):typeof E=="object"&&E!==null&&E.$$typeof===k&&(E._payload.status==="fulfilled"?d(E._payload.value)&&E._payload.value._store&&(E._payload.value._store.validated=1):E._store&&(E._store.validated=1))}function d(E){return typeof E=="object"&&E!==null&&E.$$typeof===g}var f=K,g=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),b=Symbol.for("react.fragment"),m=Symbol.for("react.strict_mode"),v=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),y=Symbol.for("react.context"),w=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),A=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),k=Symbol.for("react.lazy"),L=Symbol.for("react.activity"),R=Symbol.for("react.client.reference"),F=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,P=Object.prototype.hasOwnProperty,O=Array.isArray,$=console.createTask?console.createTask:function(){return null};f={react_stack_bottom_frame:function(E){return E()}};var M,D={},V=f.react_stack_bottom_frame.bind(f,n)(),lt=$(s(n)),ut={};Vs.Fragment=b,Vs.jsx=function(E,B,z){var J=1e4>F.recentlyCreatedOwnerStacks++;return c(E,B,z,!1,J?Error("react-stack-top-frame"):V,J?$(s(E)):lt)},Vs.jsxs=function(E,B,z){var J=1e4>F.recentlyCreatedOwnerStacks++;return c(E,B,z,!0,J?Error("react-stack-top-frame"):V,J?$(s(E)):lt)}})()),Vs}var Do;function zh(){return Do||(Do=1,process.env.NODE_ENV==="production"?Me.exports=$h():Me.exports=Hh()),Me.exports}var Ro=zh();const Gh="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",Wh={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Vh={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Xh={borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Uh={stroke:"#000",hoverStroke:"#B7EC5D",src:Gh},Yh=["borderColor","cornerStrokeColor","cornerSize","_cornerSize","selectionBackgroundColor"];function x(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 l=o.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 a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}class Lo{constructor(){x(this,"browserShadowBlurConstant",1),x(this,"DPI",96),x(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),x(this,"perfLimitSizeTotal",2097152),x(this,"maxCacheSideLimit",4096),x(this,"minCacheSideLimit",256),x(this,"disableStyleCopyPaste",!1),x(this,"enableGLFiltering",!0),x(this,"textureSize",4096),x(this,"forceGLPutImageData",!1),x(this,"cachesBoundsOfCurve",!1),x(this,"fontPaths",{}),x(this,"NUM_FRACTION_DIGITS",4)}}const it=new class extends Lo{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={...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 Lo,e=a?.reduce((s,i)=>(s[i]=t[i],s),{})||t;this.configure(e)}},Pe=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 le extends Error{constructor(t,e){super(`fabric: ${t}`,e)}}class Fo extends le{constructor(t){super(`${t} 'options.signal' is in 'aborted' state`)}}class qh{}class Kh extends qh{testPrecision(t,e){const s=`precision ${e} float;
7
- 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(),Pe("log",`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Qh={};let Io;const we=()=>Io||(Io={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Kh,dispose(){},copyPasteData:Qh}),xs=()=>we().document,Xs=()=>we().window,jo=()=>{var a;return Math.max((a=it.devicePixelRatio)!==null&&a!==void 0?a:Xs().devicePixelRatio,1)},Us=new class{constructor(){x(this,"boundsOfCurveCache",{}),this.charWidthsCache=new Map}getFontCache(a){let{fontFamily:t,fontStyle:e,fontWeight:s}=a;t=t.toLowerCase();const i=this.charWidthsCache;i.has(t)||i.set(t,new Map);const n=i.get(t),r=`${e.toLowerCase()}_${(s+"").toLowerCase()}`;return n.has(r)||n.set(r,new Map),n.get(r)}clearFontCache(a){a?this.charWidthsCache.delete((a||"").toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(a){const{perfLimitSizeTotal:t}=it,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},qn="7.2.0";function Ti(){}const Ge=Math.PI/2,Jh=Math.PI/4,he=2*Math.PI,Kn=Math.PI/180,Lt=Object.freeze([1,0,0,1,0,0]),Qn=16,We=.4477152502,U="center",st="left",Wt="top",Jn="bottom",mt="right",Ft="none",Zn=/\r?\n/,No="moving",Ei="scaling",Bo="rotating",tr="rotate",$o="skewing",Ys="resizing",Zh="modifyPoly",tc="modifyPath",ki="changed",Mi="scale",It="scaleX",Jt="scaleY",Ss="skewX",Cs="skewY",xt="fill",Vt="stroke",Pi="modified",ts="ltr",Oe="rtl",er="normal",As="json",sr="svg",I=new class{constructor(){this[As]=new Map,this[sr]=new Map}has(a){return this[As].has(a)}getClass(a){const t=this[As].get(a);if(!t)throw new le(`No class registered for ${a}`);return t}setClass(a,t){t?this[As].set(t,a):(this[As].set(a.type,a),this[As].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[sr].get(a)}setSVGClass(a,t){this[sr].set(t??a.type.toLowerCase(),a)}},Oi=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 ec{constructor(){x(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 es=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},ce=a=>{if(a===0)return 1;switch(Math.abs(a)/Ge){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ue=a=>{if(a===0)return 0;const t=a/Ge,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class S{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 S(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new S(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new S(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new S(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new S(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new S(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new S(this.x/t.x,this.y/t.y)}scalarDivide(t){return new S(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 S(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 S(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new S(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return`${this.x},${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 S(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ir;const s=ue(t),i=ce(t),n=this.subtract(e);return new S(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 S(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 ir=new S(0,0),Di=a=>!!a&&Array.isArray(a._objects);function Ho(a){class t extends a{constructor(){super(...arguments),x(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(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])&&(es(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(es(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 es(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 es(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(es(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:l=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const h=[],c=new S(i,n),u=c.add(new S(r,o));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 zo extends ec{_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 qs(a){return Xs().requestAnimationFrame(a)}function Go(a){return Xs().cancelAnimationFrame(a)}let sc=0;const Ve=()=>sc++,xe=()=>{const a=xs().createElement("canvas");if(!a||a.getContext===void 0)throw new le("Failed to create `canvas` element");return a},Wo=()=>xs().createElement("img"),Zt=a=>{const t=xe();return t.width=a.width,t.height=a.height,t},nr=(a,t,e)=>a.toDataURL(`image/${t}`,e),rr=(a,t,e)=>new Promise((s,i)=>{a.toBlob(s,`image/${t}`,e)}),gt=a=>a*Kn,De=a=>a/Kn,Vo=a=>a.every((t,e)=>t===Lt[e]),kt=(a,t,e)=>new S(a).transform(t,e),Xt=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 S(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},bt=(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]],Ri=(a,t)=>a.reduceRight((e,s)=>s&&e?bt(s,e,t):s||e,void 0)||Lt.concat(),Xo=a=>{let[t,e]=a;return Math.atan2(e,t)},ss=a=>{const t=Xo(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:De(t),scaleX:s,scaleY:i,skewX:De(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},Ts=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function is(){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=gt(a),i=ce(s),n=ue(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const Li=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},Uo=a=>Math.tan(gt(a)),or=a=>[1,0,Uo(a),1,0,0],ar=a=>[1,Uo(a),0,1,0,0],Ks=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=Li(s?-t:t,i?-e:e);return n&&(o=bt(o,or(n),!0)),r&&(o=bt(o,ar(r),!0)),o},Yo=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=Ts(t,e);s&&(i=bt(i,is({angle:s})));const n=Ks(a);return Vo(n)||(i=bt(i,n)),i},Qs=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 Fo("loadImage"));const n=Wo();let r;t&&(r=function(l){n.src="",i(l)},t.addEventListener("abort",r,{once:!0}));const o=function(){n.onload=n.onerror=null,r&&t?.removeEventListener("abort",r),s(n)};a?(n.onload=o,n.onerror=function(){r&&t?.removeEventListener("abort",r),i(new le(`Error loading ${n.src}`))},e&&(n.crossOrigin=e),n.src=a):o()})},Es=function(a){let{signal:t,reviver:e=Ti}=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=>I.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)})})},Js=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&&I.has(o.type)?Es([o],{signal:t}).then(l=>{let[h]=l;return i.push(h),h}):o),r=Object.keys(a);Promise.all(n).then(o=>o.reduce((l,h,c)=>(l[r[c]]=h,l),{})).then(e).catch(o=>{i.forEach(l=>{l.dispose&&l.dispose()}),s(o)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},ns=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in a&&(t[e]=a[e]),t),{})},lr=(a,t)=>Object.keys(a).reduce((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e),{}),rt=(a,t)=>parseFloat(Number(a).toFixed(t)),ks=a=>"matrix("+a.map(t=>rt(t,it.NUM_FRACTION_DIGITS)).join(" ")+")",ne=a=>!!a&&a.toLive!==void 0,qo=a=>!!a&&typeof a.toObject=="function",Ko=a=>!!a&&a.offsetX!==void 0&&"source"in a,rs=a=>!!a&&"multiSelectionStacking"in a;function Qo(a){const t=a&&de(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 de=a=>a.ownerDocument||null,Jo=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},Zo=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))},hr=(a,t)=>{let{width:e,height:s}=t;e&&(a.style.width=typeof e=="number"?`${e}px`:e),s&&(a.style.height=typeof s=="number"?`${s}px`:s)};function ta(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=Ft,a}class ea{constructor(t){x(this,"_originalCanvasStyle",void 0),x(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&&xs().getElementById(t)||xe();var s;if(e.hasAttribute("data-fabric"))throw new le("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",`${e}`),i.setAttribute("height",`${s}`),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;Zo(s,i,t,e)}setCSSDimensions(t){hr(this.lower.el,t)}calcOffset(){return(function(t){var e;const s=t&&de(t),i={left:0,top:0};if(!s)return i;const n=((e=Jo(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 l=Qo(t);return{left:r.left+l.left-(o.clientLeft||0)+i.left,top:r.top+l.top-(o.clientTop||0)+i.top}})(this.lower.el)}dispose(){we().dispose(this.lower.el),delete this.lower}}const ic={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...Lt],patternQuality:"best"},Z=a=>a.toString().replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let Zs;const Fi=a=>{if(Zs||Zs||(Zs="Intl"in Xs()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),Zs){const t=Zs.segment(a);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return nc(a)},nc=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=rc(a,s))!==!1&&t.push(e);return t},rc=(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 oc=Object.freeze({__proto__:null,capitalize:function(a){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return`${a.charAt(0).toUpperCase()}${t?a.slice(1):a.slice(1).toLowerCase()}`},escapeXml:Z,graphemeSplit:Fi});class ti extends Ho(zo){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 ti.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 ea(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&&(Pe("warn",`Canvas is trying to add an object that belongs to a different canvas.
8
- 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?jo():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const i={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=kt(t,Xt(i));i[0]=e,i[3]=e;const r=kt(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new S(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 S(-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=qs(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Xt(this.viewportTransform),i=kt({x:0,y:0},s),n=kt({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new S(o.x,r.y),bl:new S(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(Go(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=this.patternQuality,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[`${e}Color`],i=this[`${e}Image`],n=this.viewportTransform,r=this[`${e}Vpt`];if(!s&&!i)return;const o=ne(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 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")}getCenterPoint(){return new S(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new S(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new S(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 S(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new S(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return kt(this.getCenterPoint(),Xt(this.viewportTransform))}_centerObject(t,e){t.setXY(e,U,U),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{version:qn,...ns(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 ne(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),ne(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=[];var i;return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push(`<g clip-path="url(#${Z((i=this.clipPath.clipPathId)!==null&&i!==void 0?i:"")})" >
9
- `),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
10
- `),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" ?>
11
- `,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
12
- `)}_setSVGHeader(t,e){const s=e.width||`${this.width}`,i=e.height||`${this.height}`,n=it.NUM_FRACTION_DIGITS,r=e.viewBox;let o;if(r)o=`viewBox="${r.x} ${r.y} ${r.width} ${r.height}" `;else if(this.svgViewportTransformation){const l=this.viewportTransform;o=`viewBox="${rt(-l[4]/l[0],n)} ${rt(-l[5]/l[3],n)} ${rt(this.width/l[0],n)} ${rt(this.height/l[3],n)}" `}else o=`viewBox="0 0 ${this.width} ${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">
13
- `,"<desc>Created with Fabric.js ",qn,`</desc>
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("react"),require("react/jsx-runtime")):typeof define==`function`&&define.amd?define([`exports`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pdf-canvas`]={},e.React,e.react_jsx_runtime))})(this,function(e,t,n){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var r=`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`,i={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)`},o={borderColor:`black`,cornerStrokeColor:`black`,cornerSize:8,selectionBackgroundColor:`rgba(245, 245, 245, 0.8)`},s={stroke:`#000`,hoverStroke:`#B7EC5D`,src:r},c=[`borderColor`,`cornerStrokeColor`,`cornerSize`,`_cornerSize`,`selectionBackgroundColor`],l=Object.defineProperty,u=(e,t)=>{let n={};for(var r in e)l(n,r,{get:e[r],enumerable:!0});return t||l(n,Symbol.toStringTag,{value:`Module`}),n};function d(e){return d=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},d(e)}function f(e){var t=function(e,t){if(d(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(d(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}(e,`string`);return d(t)==`symbol`?t:t+``}function p(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var m=class{constructor(){p(this,`browserShadowBlurConstant`,1),p(this,`DPI`,96),p(this,`devicePixelRatio`,typeof window<`u`?window.devicePixelRatio:1),p(this,`perfLimitSizeTotal`,2097152),p(this,`maxCacheSideLimit`,4096),p(this,`minCacheSideLimit`,256),p(this,`disableStyleCopyPaste`,!1),p(this,`enableGLFiltering`,!0),p(this,`textureSize`,4096),p(this,`forceGLPutImageData`,!1),p(this,`cachesBoundsOfCurve`,!1),p(this,`fontPaths`,{}),p(this,`NUM_FRACTION_DIGITS`,4)}},h=new class extends m{constructor(e){super(),this.configure(e)}configure(e={}){Object.assign(this,e)}addFonts(e={}){this.fontPaths={...this.fontPaths,...e}}removeFonts(e=[]){e.forEach(e=>{delete this.fontPaths[e]})}clearFonts(){this.fontPaths={}}restoreDefaults(e){let t=new m,n=e?.reduce((e,n)=>(e[n]=t[n],e),{})||t;this.configure(n)}},g=(e,...t)=>console[e](`fabric`,...t),_=class extends Error{constructor(e,t){super(`fabric: ${e}`,t)}},v=class extends _{constructor(e){super(`${e} 'options.signal' is in 'aborted' state`)}},y=class{},b=class extends y{testPrecision(e,t){let n=`precision ${t} float;\nvoid main(){}`,r=e.createShader(e.FRAGMENT_SHADER);return!!r&&(e.shaderSource(r,n),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS))}queryWebGL(e){let t=e.getContext(`webgl`);t&&(this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.GLPrecision=[`highp`,`mediump`,`lowp`].find(e=>this.testPrecision(t,e)),t.getExtension(`WEBGL_lose_context`).loseContext(),g(`log`,`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(e){return!!this.maxTextureSize&&this.maxTextureSize>=e}},x={},S,C=()=>S||={document,window,isTouchSupported:`ontouchstart`in window||`ontouchstart`in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new b,dispose(){},copyPasteData:x},w=()=>C().document,T=()=>C().window,E=()=>Math.max(h.devicePixelRatio??T().devicePixelRatio,1),D=new class{constructor(){p(this,`boundsOfCurveCache`,{}),this.charWidthsCache=new Map}getFontCache({fontFamily:e,fontStyle:t,fontWeight:n}){e=e.toLowerCase();let r=this.charWidthsCache;r.has(e)||r.set(e,new Map);let i=r.get(e),a=`${t.toLowerCase()}_${(n+``).toLowerCase()}`;return i.has(a)||i.set(a,new Map),i.get(a)}clearFontCache(e){e?this.charWidthsCache.delete((e||``).toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(e){let{perfLimitSizeTotal:t}=h,n=Math.sqrt(t*e);return[Math.floor(n),Math.floor(t/n)]}},O=`7.4.0`;function k(){}var A=Math.PI/2,j=Math.PI/4,M=2*Math.PI,ee=Math.PI/180,N=Object.freeze([1,0,0,1,0,0]),P=`center`,F=`left`,I=`bottom`,te=`right`,ne=`none`,re=/\r?\n/,ie=`moving`,ae=`scaling`,oe=`rotating`,se=`rotate`,ce=`skewing`,le=`resizing`,ue=`modifyPoly`,de=`changed`,fe=`scale`,pe=`scaleX`,me=`scaleY`,he=`skewX`,ge=`skewY`,_e=`fill`,ve=`stroke`,ye=`modified`,be=`normal`,xe=`json`,L=new class{constructor(){this[xe]=new Map,this.svg=new Map}has(e){return this[xe].has(e)}getClass(e){let t=this[xe].get(e);if(!t)throw new _(`No class registered for ${e}`);return t}setClass(e,t){t?this[xe].set(t,e):(this[xe].set(e.type,e),this[xe].set(e.type.toLowerCase(),e))}getSVGClass(e){return this.svg.get(e)}setSVGClass(e,t){this.svg.set(t??e.type.toLowerCase(),e)}},Se=new class extends Array{remove(e){let t=this.indexOf(e);t>-1&&this.splice(t,1)}cancelAll(){let e=this.splice(0);return e.forEach(e=>e.abort()),e}cancelByCanvas(e){if(!e)return[];let t=this.filter(t=>t.target===e||typeof t.target==`object`&&t.target?.canvas===e);return t.forEach(e=>e.abort()),t}cancelByTarget(e){if(!e)return[];let t=this.filter(t=>t.target===e);return t.forEach(e=>e.abort()),t}},Ce=class{constructor(){p(this,`__eventListeners`,{})}on(e,t){if(this.__eventListeners||={},typeof e==`object`)return Object.entries(e).forEach(([e,t])=>{this.on(e,t)}),()=>this.off(e);if(t){let n=e;return this.__eventListeners[n]||(this.__eventListeners[n]=[]),this.__eventListeners[n].push(t),()=>this.off(n,t)}return()=>!1}once(e,t){if(typeof e==`object`){let t=[];return Object.entries(e).forEach(([e,n])=>{t.push(this.once(e,n))}),()=>t.forEach(e=>e())}if(t){let n=this.on(e,function(...e){t.call(this,...e),n()});return n}return()=>!1}_removeEventListener(e,t){if(this.__eventListeners[e]){if(t){let n=this.__eventListeners[e],r=n.indexOf(t);r>-1&&n.splice(r,1)}else this.__eventListeners[e]=[]}}off(e,t){if(this.__eventListeners){if(e===void 0)for(let e in this.__eventListeners)this._removeEventListener(e);else typeof e==`object`?Object.entries(e).forEach(([e,t])=>{this._removeEventListener(e,t)}):this._removeEventListener(e,t)}}fire(e,t){if(!this.__eventListeners)return;let n=this.__eventListeners[e]?.concat();if(n)for(let e=0;e<n.length;e++)n[e].call(this,t||{})}},we=(e,t)=>{let n=e.indexOf(t);return n!==-1&&e.splice(n,1),e},Te=e=>{if(e===0)return 1;switch(Math.abs(e)/A){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},Ee=e=>{if(e===0)return 0;let t=e/A,n=Math.sign(e);switch(t){case 1:return n;case 2:return 0;case 3:return-n}return Math.sin(e)},R=class e{constructor(e=0,t=0){typeof e==`object`?(this.x=e.x,this.y=e.y):(this.x=e,this.y=t)}add(t){return new e(this.x+t.x,this.y+t.y)}addEquals(e){return this.x+=e.x,this.y+=e.y,this}scalarAdd(t){return new e(this.x+t,this.y+t)}scalarAddEquals(e){return this.x+=e,this.y+=e,this}subtract(t){return new e(this.x-t.x,this.y-t.y)}subtractEquals(e){return this.x-=e.x,this.y-=e.y,this}scalarSubtract(t){return new e(this.x-t,this.y-t)}scalarSubtractEquals(e){return this.x-=e,this.y-=e,this}multiply(t){return new e(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new e(this.x*t,this.y*t)}scalarMultiplyEquals(e){return this.x*=e,this.y*=e,this}divide(t){return new e(this.x/t.x,this.y/t.y)}scalarDivide(t){return new e(this.x/t,this.y/t)}scalarDivideEquals(e){return this.x/=e,this.y/=e,this}eq(e){return this.x===e.x&&this.y===e.y}lt(e){return this.x<e.x&&this.y<e.y}lte(e){return this.x<=e.x&&this.y<=e.y}gt(e){return this.x>e.x&&this.y>e.y}gte(e){return this.x>=e.x&&this.y>=e.y}lerp(t,n=.5){return n=Math.max(Math.min(1,n),0),new e(this.x+(t.x-this.x)*n,this.y+(t.y-this.y)*n)}distanceFrom(e){let t=this.x-e.x,n=this.y-e.y;return Math.sqrt(t*t+n*n)}midPointFrom(e){return this.lerp(e)}min(t){return new e(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new e(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return`${this.x},${this.y}`}setXY(e,t){return this.x=e,this.y=t,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setFromPoint(e){return this.x=e.x,this.y=e.y,this}swap(e){let t=this.x,n=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=n}clone(){return new e(this.x,this.y)}rotate(t,n=De){let r=Ee(t),i=Te(t),a=this.subtract(n);return new e(a.x*i-a.y*r,a.x*r+a.y*i).add(n)}transform(t,n=!1){return new e(t[0]*this.x+t[2]*this.y+(n?0:t[4]),t[1]*this.x+t[3]*this.y+(n?0:t[5]))}},De=new R(0,0),Oe=e=>!!e&&Array.isArray(e._objects);function ke(e){class t extends e{constructor(...e){super(...e),p(this,`_objects`,[])}_onObjectAdded(e){}_onObjectRemoved(e){}_onStackOrderChanged(e){}add(...e){let t=this._objects.push(...e);return e.forEach(e=>this._onObjectAdded(e)),t}insertAt(e,...t){return this._objects.splice(e,0,...t),t.forEach(e=>this._onObjectAdded(e)),this._objects.length}remove(...e){let t=this._objects,n=[];return e.forEach(e=>{let r=t.indexOf(e);r!==-1&&(t.splice(r,1),n.push(e),this._onObjectRemoved(e))}),n}forEachObject(e){this.getObjects().forEach((t,n,r)=>e(t,n,r))}getObjects(...e){return e.length===0?[...this._objects]:this._objects.filter(t=>t.isType(...e))}item(e){return this._objects[e]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(e,n){return!!this._objects.includes(e)||!!n&&this._objects.some(n=>n instanceof t&&n.contains(e,!0))}complexity(){return this._objects.reduce((e,t)=>e+=t.complexity?t.complexity():0,0)}sendObjectToBack(e){return!(!e||e===this._objects[0])&&(we(this._objects,e),this._objects.unshift(e),this._onStackOrderChanged(e),!0)}bringObjectToFront(e){return!(!e||e===this._objects[this._objects.length-1])&&(we(this._objects,e),this._objects.push(e),this._onStackOrderChanged(e),!0)}sendObjectBackwards(e,t){if(!e)return!1;let n=this._objects.indexOf(e);if(n!==0){let r=this.findNewLowerIndex(e,n,t);return we(this._objects,e),this._objects.splice(r,0,e),this._onStackOrderChanged(e),!0}return!1}bringObjectForward(e,t){if(!e)return!1;let n=this._objects.indexOf(e);if(n!==this._objects.length-1){let r=this.findNewUpperIndex(e,n,t);return we(this._objects,e),this._objects.splice(r,0,e),this._onStackOrderChanged(e),!0}return!1}moveObjectTo(e,t){return e!==this._objects[t]&&(we(this._objects,e),this._objects.splice(t,0,e),this._onStackOrderChanged(e),!0)}findNewLowerIndex(e,t,n){let r;if(n){r=t;for(let n=t-1;n>=0;--n)if(e.isOverlapping(this._objects[n])){r=n;break}}else r=t-1;return r}findNewUpperIndex(e,t,n){let r;if(n){r=t;for(let n=t+1;n<this._objects.length;++n)if(e.isOverlapping(this._objects[n])){r=n;break}}else r=t+1;return r}collectObjects({left:e,top:t,width:n,height:r},{includeIntersecting:i=!0}={}){let a=[],o=new R(e,t),s=o.add(new R(n,r));for(let e=this._objects.length-1;e>=0;e--){let t=this._objects[e];t.selectable&&t.visible&&(i&&t.intersectsWithRect(o,s)||t.isContainedWithinRect(o,s)||i&&t.containsPoint(o)||i&&t.containsPoint(s))&&a.push(t)}return a}}return t}var Ae=class extends Ce{_setOptions(e={}){for(let t in e)this.set(t,e[t])}_setObject(e){for(let t in e)this._set(t,e[t])}set(e,t){return typeof e==`object`?this._setObject(e):this._set(e,t),this}_set(e,t){this[e]=t}toggle(e){let t=this.get(e);return typeof t==`boolean`&&this.set(e,!t),this}get(e){return this[e]}};function je(e){return T().requestAnimationFrame(e)}function Me(e){return T().cancelAnimationFrame(e)}var Ne=0,Pe=()=>Ne++,Fe=()=>{let e=w().createElement(`canvas`);if(!e||e.getContext===void 0)throw new _("Failed to create `canvas` element");return e},Ie=()=>w().createElement(`img`),Le=e=>{var t;let n=Re(e);return(t=n.getContext(`2d`))==null||t.drawImage(e,0,0),n},Re=e=>{let t=Fe();return t.width=e.width,t.height=e.height,t},ze=(e,t,n)=>e.toDataURL(`image/${t}`,n),Be=(e,t,n)=>new Promise((r,i)=>{e.toBlob(r,`image/${t}`,n)}),z=e=>e*ee,Ve=e=>e/ee,He=e=>e.every((e,t)=>e===N[t]),Ue=(e,t,n)=>new R(e).transform(t,n),We=e=>{let t=1/(e[0]*e[3]-e[1]*e[2]),n=[t*e[3],-t*e[1],-t*e[2],t*e[0],0,0],{x:r,y:i}=new R(e[4],e[5]).transform(n,!0);return n[4]=-r,n[5]=-i,n},B=(e,t,n)=>[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],n?0:e[0]*t[4]+e[2]*t[5]+e[4],n?0:e[1]*t[4]+e[3]*t[5]+e[5]],Ge=(e,t)=>e.reduceRight((e,n)=>n&&e?B(n,e,t):n||e,void 0)||N.concat(),Ke=([e,t])=>Math.atan2(t,e),qe=([e,t])=>Math.sqrt(e*e+t*t),Je=([,,e,t])=>Math.sqrt(e*e+t*t),Ye=e=>{let t=Ke(e),n=e[0]**2+e[1]**2,r=Math.sqrt(n),i=(e[0]*e[3]-e[2]*e[1])/r,a=Math.atan2(e[0]*e[2]+e[1]*e[3],n);return{angle:Ve(t),scaleX:r,scaleY:i,skewX:Ve(a),skewY:0,translateX:e[4]||0,translateY:e[5]||0}},Xe=(e,t=0)=>[1,0,0,1,e,t];function Ze({angle:e=0}={},{x:t=0,y:n=0}={}){let r=z(e),i=Te(r),a=Ee(r);return[i,a,-a,i,t?t-(i*t-a*n):0,n?n-(a*t+i*n):0]}var Qe=(e,t=e)=>[e,0,0,t,0,0],$e=e=>Math.tan(z(e)),et=e=>[1,0,$e(e),1,0,0],tt=e=>[1,$e(e),0,1,0,0],nt=({scaleX:e=1,scaleY:t=1,flipX:n=!1,flipY:r=!1,skewX:i=0,skewY:a=0})=>{let o=Qe(n?-e:e,r?-t:t);return i&&(o=B(o,et(i),!0)),a&&(o=B(o,tt(a),!0)),o},rt=e=>{let{translateX:t=0,translateY:n=0,angle:r=0}=e,i=Xe(t,n);r&&(i=B(i,Ze({angle:r})));let a=nt(e);return He(a)||(i=B(i,a)),i},it=(e,{signal:t,crossOrigin:n=null}={})=>new Promise(function(r,i){if(t&&t.aborted)return i(new v(`loadImage`));let a=Ie(),o;t&&(o=function(e){a.src=``,i(e)},t.addEventListener(`abort`,o,{once:!0}));let s=function(){a.onload=a.onerror=null,o&&t?.removeEventListener(`abort`,o),r(a)};e?(a.onload=s,a.onerror=function(){o&&t?.removeEventListener(`abort`,o),i(new _(`Error loading ${a.src}`))},n&&(a.crossOrigin=n),a.src=e):s()}),at=(e,{signal:t,reviver:n=k}={})=>new Promise((r,i)=>{let a=[];t&&t.addEventListener(`abort`,i,{once:!0}),Promise.allSettled(e.map(e=>L.getClass(e.type).fromObject(e,{signal:t}))).then(async t=>{for(let[r,i]of t.entries())if(i.status===`fulfilled`&&(await n(e[r],i.value),a.push(i.value)),i.status===`rejected`){let t=await n(e[r],void 0,i.reason);t&&a.push(t)}r(a)}).catch(e=>{a.forEach(e=>{e.dispose&&e.dispose()}),i(e)}).finally(()=>{t&&t.removeEventListener(`abort`,i)})}),ot=(e,{signal:t}={})=>new Promise((n,r)=>{let i=[];t&&t.addEventListener(`abort`,r,{once:!0});let a=Object.values(e).map(e=>e&&e.type&&L.has(e.type)?at([e],{signal:t}).then(([e])=>(i.push(e),e)):e),o=Object.keys(e);Promise.all(a).then(e=>e.reduce((e,t,n)=>(e[o[n]]=t,e),{})).then(n).catch(e=>{i.forEach(e=>{e.dispose&&e.dispose()}),r(e)}).finally(()=>{t&&t.removeEventListener(`abort`,r)})}),st=(e,t=[])=>t.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{}),ct=(e,t)=>Object.keys(e).reduce((n,r)=>(t(e[r],r,e)&&(n[r]=e[r]),n),{}),V=(e,t)=>parseFloat(Number(e).toFixed(t)),lt=e=>`matrix(`+e.map(e=>V(e,h.NUM_FRACTION_DIGITS)).join(` `)+`)`,ut=e=>!!e&&e.toLive!==void 0,dt=e=>!!e&&typeof e.toObject==`function`,ft=e=>!!e&&e.offsetX!==void 0&&`source`in e,pt=e=>!!e&&`multiSelectionStacking`in e;function mt(e){let t=e&&ht(e),n=0,r=0;if(!e||!t)return{left:n,top:r};let i=e,a=t.documentElement,o=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(n=o.scrollLeft||a.scrollLeft||0,r=o.scrollTop||a.scrollTop||0):(n+=i.scrollLeft||0,r+=i.scrollTop||0),i.nodeType!==1||i.style.position!==`fixed`););return{left:n,top:r}}var ht=e=>e.ownerDocument||null,gt=e=>e.ownerDocument?.defaultView||null,_t=(e,t,{width:n,height:r},i=1)=>{e.width=n,e.height=r,i>1&&(e.setAttribute(`width`,(n*i).toString()),e.setAttribute(`height`,(r*i).toString()),t.scale(i,i))},vt=(e,{width:t,height:n})=>{t&&(e.style.width=typeof t==`number`?`${t}px`:t),n&&(e.style.height=typeof n==`number`?`${n}px`:n)};function yt(e){return e.onselectstart!==void 0&&(e.onselectstart=()=>!1),e.style.userSelect=ne,e}var bt=class{constructor(e){p(this,`_originalCanvasStyle`,void 0),p(this,`lower`,void 0);let t=this.createLowerCanvas(e);this.lower={el:t,ctx:t.getContext(`2d`)}}createLowerCanvas(e){let t=(n=e)&&n.getContext!==void 0?e:e&&w().getElementById(e)||Fe();var n;if(t.hasAttribute(`data-fabric`))throw new _(`Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?`);return this._originalCanvasStyle=t.style.cssText,t.setAttribute(`data-fabric`,`main`),t.classList.add(`lower-canvas`),t}cleanupDOM({width:e,height:t}){let{el:n}=this.lower;n.classList.remove(`lower-canvas`),n.removeAttribute(`data-fabric`),n.setAttribute(`width`,`${e}`),n.setAttribute(`height`,`${t}`),n.style.cssText=this._originalCanvasStyle||``,this._originalCanvasStyle=void 0}setDimensions(e,t){let{el:n,ctx:r}=this.lower;_t(n,r,e,t)}setCSSDimensions(e){vt(this.lower.el,e)}calcOffset(){return function(e){let t=e&&ht(e),n={left:0,top:0};if(!t)return n;let r=gt(e)?.getComputedStyle(e,null)||{};n.left+=parseInt(r.borderLeftWidth,10)||0,n.top+=parseInt(r.borderTopWidth,10)||0,n.left+=parseInt(r.paddingLeft,10)||0,n.top+=parseInt(r.paddingTop,10)||0;let i={left:0,top:0},a=t.documentElement;e.getBoundingClientRect!==void 0&&(i=e.getBoundingClientRect());let o=mt(e);return{left:i.left+o.left-(a.clientLeft||0)+n.left,top:i.top+o.top-(a.clientTop||0)+n.top}}(this.lower.el)}dispose(){C().dispose(this.lower.el),delete this.lower}},xt={backgroundVpt:!0,backgroundColor:``,overlayVpt:!0,overlayColor:``,includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...N],patternQuality:`best`},St=u({capitalize:()=>Ct,escapeXml:()=>H,graphemeSplit:()=>Tt}),Ct=(e,t=!1)=>`${e.charAt(0).toUpperCase()}${t?e.slice(1):e.slice(1).toLowerCase()}`,H=e=>e.toString().replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/'/g,`&apos;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),wt,Tt=e=>{if(wt||wt||(wt=`Intl`in T()&&`Segmenter`in Intl&&new Intl.Segmenter(void 0,{granularity:`grapheme`})),wt){let t=wt.segment(e);return Array.from(t).map(({segment:e})=>e)}return Et(e)},Et=e=>{let t=[];for(let n,r=0;r<e.length;r++)!1!==(n=Dt(e,r))&&t.push(n);return t},Dt=(e,t)=>{let n=e.charCodeAt(t);if(isNaN(n))return``;if(n<55296||n>57343)return e.charAt(t);if(55296<=n&&n<=56319){if(e.length<=t+1)throw`High surrogate without following low surrogate`;let n=e.charCodeAt(t+1);if(56320>n||n>57343)throw`High surrogate without following low surrogate`;return e.charAt(t)+e.charAt(t+1)}if(t===0)throw`Low surrogate without preceding high surrogate`;let r=e.charCodeAt(t-1);if(55296>r||r>56319)throw`Low surrogate without preceding high surrogate`;return!1},Ot=class e extends ke(Ae){get lowerCanvasEl(){return this.elements.lower?.el}get contextContainer(){return this.elements.lower?.ctx}static getDefaults(){return e.ownDefaults}constructor(e,t={}){super(),Object.assign(this,this.constructor.getDefaults()),this.set(t),this.initElements(e),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(e){this.elements=new bt(e)}add(...e){let t=super.add(...e);return e.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(e,...t){let n=super.insertAt(e,...t);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(...e){let t=super.remove(...e);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(e){e.canvas&&e.canvas!==this&&(g(`warn`,`Canvas is trying to add an object that belongs to a different canvas.
2
+ Resulting to default behavior: removing object from previous canvas and adding to new canvas`),e.canvas.remove(e)),e._set(`canvas`,this),e.setCoords(),this.fire(`object:added`,{target:e}),e.fire(`added`,{target:this})}_onObjectRemoved(e){e._set(`canvas`,void 0),this.fire(`object:removed`,{target:e}),e.fire(`removed`,{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?E():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(e,{cssOnly:t=!1,backstoreOnly:n=!1}={}){if(!t){let t={width:this.width,height:this.height,...e};this.elements.setDimensions(t,this.getRetinaScaling()),this.hasLostContext=!0,this.width=t.width,this.height=t.height}n||this.elements.setCSSDimensions(e),this.calcOffset()}setDimensions(e,t){this._setDimensionsImpl(e,t),t&&t.cssOnly||this.requestRenderAll()}getZoom(){return qe(this.viewportTransform)}setViewportTransform(e){this.viewportTransform=e,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(e,t){let n=e,r=[...this.viewportTransform],i=Ue(e,We(r));r[0]=t,r[3]=t;let a=Ue(i,r);r[4]+=n.x-a.x,r[5]+=n.y-a.y,this.setViewportTransform(r)}setZoom(e){this.zoomToPoint(new R(0,0),e)}absolutePan(e){let t=[...this.viewportTransform];return t[4]=-e.x,t[5]=-e.y,this.setViewportTransform(t)}relativePan(e){return this.absolutePan(new R(-e.x-this.viewportTransform[4],-e.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(e){e.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=je(()=>this.renderAndReset()))}calcViewportBoundaries(){let e=this.width,t=this.height,n=We(this.viewportTransform),r=Ue({x:0,y:0},n),i=Ue({x:e,y:t},n),a=r.min(i),o=r.max(i);return this.vptCoords={tl:a,tr:new R(o.x,a.y),bl:new R(a.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&=(Me(this.nextRenderHandle),0)}drawControls(e){}renderCanvas(e,t){if(this.destroyed)return;let n=this.viewportTransform,r=this.clipPath;this.calcViewportBoundaries(),this.clearContext(e),e.imageSmoothingEnabled=this.imageSmoothingEnabled,e.patternQuality=this.patternQuality,this.fire(`before:render`,{ctx:e}),this._renderBackground(e),e.save(),e.transform(n[0],n[1],n[2],n[3],n[4],n[5]),this._renderObjects(e,t),e.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(e),r&&(r._set(`canvas`,this),r.shouldCache(),r._transformDone=!0,r.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(e,r)),this._renderOverlay(e),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(e),this.fire(`after:render`,{ctx:e}),this.__cleanupTask&&=(this.__cleanupTask(),void 0)}drawClipPathOnCanvas(e,t){let n=this.viewportTransform;e.save(),e.transform(...n),e.globalCompositeOperation=`destination-in`,t.transform(e),e.scale(1/t.zoomX,1/t.zoomY),e.drawImage(t._cacheCanvas,-t.cacheTranslationX,-t.cacheTranslationY),e.restore()}_renderObjects(e,t){for(let n=0,r=t.length;n<r;++n)t[n]&&t[n].render(e)}_renderBackgroundOrOverlay(e,t){let n=this[`${t}Color`],r=this[`${t}Image`],i=this.viewportTransform,a=this[`${t}Vpt`];if(!n&&!r)return;let o=ut(n);if(n){if(e.save(),e.beginPath(),e.moveTo(0,0),e.lineTo(this.width,0),e.lineTo(this.width,this.height),e.lineTo(0,this.height),e.closePath(),e.fillStyle=o?n.toLive(e):n,a&&e.transform(...i),o){e.transform(1,0,0,1,n.offsetX||0,n.offsetY||0);let t=n.gradientTransform||n.patternTransform;t&&e.transform(...t)}e.fill(),e.restore()}if(r){e.save();let{skipOffscreen:t}=this;this.skipOffscreen=a,a&&e.transform(...i),r.render(e),this.skipOffscreen=t,e.restore()}}_renderBackground(e){this._renderBackgroundOrOverlay(e,`background`)}_renderOverlay(e){this._renderBackgroundOrOverlay(e,`overlay`)}getCenterPoint(){return new R(this.width/2,this.height/2)}centerObjectH(e){return this._centerObject(e,new R(this.getCenterPoint().x,e.getCenterPoint().y))}centerObjectV(e){return this._centerObject(e,new R(e.getCenterPoint().x,this.getCenterPoint().y))}centerObject(e){return this._centerObject(e,this.getCenterPoint())}viewportCenterObject(e){return this._centerObject(e,this.getVpCenter())}viewportCenterObjectH(e){return this._centerObject(e,new R(this.getVpCenter().x,e.getCenterPoint().y))}viewportCenterObjectV(e){return this._centerObject(e,new R(e.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Ue(this.getCenterPoint(),We(this.viewportTransform))}_centerObject(e,t){e.setXY(t,P,P),e.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(e){return this.toDatalessObject(e)}toObject(e){return this._toObjectMethod(`toObject`,e)}toJSON(){return this.toObject()}toDatalessObject(e){return this._toObjectMethod(`toDatalessObject`,e)}_toObjectMethod(e,t){let n=this.clipPath,r=n&&!n.excludeFromExport?this._toObject(n,e,t):null;return{version:O,...st(this,t),objects:this._objects.filter(e=>!e.excludeFromExport).map(n=>this._toObject(n,e,t)),...this.__serializeBgOverlay(e,t),...r?{clipPath:r}:null}}_toObject(e,t,n){let r;this.includeDefaultValues||(r=e.includeDefaultValues,e.includeDefaultValues=!1);let i=e[t](n);return this.includeDefaultValues||(e.includeDefaultValues=!!r),i}__serializeBgOverlay(e,t){let n={},r=this.backgroundImage,i=this.overlayImage,a=this.backgroundColor,o=this.overlayColor;return ut(a)?a.excludeFromExport||(n.background=a.toObject(t)):a&&(n.background=a),ut(o)?o.excludeFromExport||(n.overlay=o.toObject(t)):o&&(n.overlay=o),r&&!r.excludeFromExport&&(n.backgroundImage=this._toObject(r,e,t)),i&&!i.excludeFromExport&&(n.overlayImage=this._toObject(i,e,t)),n}toSVG(e={},t){e.reviver=t;let n=[];return this._setSVGPreamble(n,e),this._setSVGHeader(n,e),this.clipPath&&n.push(`<g clip-path="url(#${H(this.clipPath.clipPathId??``)})" >\n`),this._setSVGBgOverlayColor(n,`background`),this._setSVGBgOverlayImage(n,`backgroundImage`,t),this._setSVGObjects(n,t),this.clipPath&&n.push(`</g>
3
+ `),this._setSVGBgOverlayColor(n,`overlay`),this._setSVGBgOverlayImage(n,`overlayImage`,t),n.push(`</svg>`),n.join(``)}_setSVGPreamble(e,t){t.suppressPreamble||e.push(`<?xml version="1.0" encoding="`,t.encoding||`UTF-8`,`" standalone="no" ?>
4
+ `,`<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" `,`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
5
+ `)}_setSVGHeader(e,t){let n=t.width||`${this.width}`,r=t.height||`${this.height}`,i=h.NUM_FRACTION_DIGITS,a=t.viewBox,o;if(a)o=`viewBox="${a.x} ${a.y} ${a.width} ${a.height}" `;else if(this.svgViewportTransformation){let e=this.viewportTransform;o=`viewBox="${V(-e[4]/e[0],i)} ${V(-e[5]/e[3],i)} ${V(this.width/e[0],i)} ${V(this.height/e[3],i)}" `}else o=`viewBox="0 0 ${this.width} ${this.height}" `;e.push(`<svg `,`xmlns="http://www.w3.org/2000/svg" `,`xmlns:xlink="http://www.w3.org/1999/xlink" `,`version="1.1" `,`width="`,n,`" `,`height="`,r,`" `,o,`xml:space="preserve">
6
+ `,`<desc>Created with Fabric.js `,O,`</desc>
14
7
  `,`<defs>
15
- `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
16
- `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId=`CLIPPATH_${Ve()}`,`<clipPath id="${e.clipPathId}" >
17
- ${e.toClipPathSVG(t.reviver)}</clipPath>
18
- `):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this[`${t}Color`];if(ne(e)){const s=this[`${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?ks(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=it.fontPaths;this._objects.forEach(function n(r){t.push(r),Di(r)&&r._objects.forEach(n)}),t.forEach(n=>{if(!(r=n)||typeof r._renderText!="function")return;var r;const{styles:o,fontFamily:l}=n;!e[l]&&s[l]&&(e[l]=!0,o&&Object.values(o).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 {
19
- font-family: '${n}';
20
- src: url('${s[n]}');
21
- }
22
- `).join("");return i?` <style type="text/css"><![CDATA[
23
- ${i}]]></style>
24
- `:""}_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[`${e}Color`];if(s)if(ne(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this[`${e}Vpt`]?ks(Xt(this.viewportTransform)):"";t.push(`<rect transform="${o} translate(${n/2},${r/2})" x="${s.offsetX-n/2}" y="${s.offsetY-r/2}" width="${i!=="repeat-y"&&i!=="no-repeat"||!Ko(s)?n:s.source.width}" height="${i!=="repeat-x"&&i!=="no-repeat"||!Ko(s)?r:s.source.height}" fill="url(#SVGID_${s.id})"></rect>
25
- `)}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',s,'"',`></rect>
26
- `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new le("`json` is undefined"));const{objects:i=[],...n}=typeof t=="string"?JSON.parse(t):t,{backgroundImage:r,background:o,overlayImage:l,overlay:h,clipPath:c}=n,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Es(i,{reviver:e,signal:s}),Js({backgroundImage:r,backgroundColor:o,overlayImage:l,overlayColor:h,clipPath:c},{signal:s})]).then(d=>{let[f,g]=d;return this.clear(),this.add(...f),this.set(n),this.set(g),this.renderOnAddRemove=u,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=Zt(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 nr(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 rr(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,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],b=this.enableRetinaScaling,m=Zt({width:o,height:l}),v=r?this._objects.filter(_=>r(_)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=o,this.height=l,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),v),this.viewportTransform=g,this.width=c,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=b,this.skipControlsDrawing=d,m}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Oi.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 (${this.complexity()}): { objects: ${this._objects.length} }>`}}x(ti,"ownDefaults",ic);const ac=["touchstart","touchmove","touchend"],sa=a=>{const t=Qo(a.target),e=(function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s})(a);return new S(e.clientX+t.left,e.clientY+t.top)},Ii=a=>ac.includes(a.type)||a.pointerType==="touch",ia=a=>{a.preventDefault(),a.stopPropagation()},Se=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:l}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(l>i||!n)&&(i=l),(l<e||!n)&&(e=l)}return{left:t,top:e,width:s-t,height:i-e}},na=(a,t)=>Ms(a,bt(t,a.calcOwnMatrix())),Ms=(a,t)=>{const{translateX:e,translateY:s,scaleX:i,scaleY:n,...r}=ss(t),o=new S(e,s);a.flipX=!1,a.flipY=!1,Object.assign(a,r),a.set({scaleX:i,scaleY:n}),a.setPositionByOrigin(o,U,U)},ra=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},cr=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}),ji=(a,t,e)=>{const s=a/2,i=t/2,n=[new S(-s,-i),new S(s,-i),new S(-s,i),new S(s,i)].map(o=>o.transform(e)),r=Se(n);return new S(r.width,r.height)},ei=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Lt;return bt(Xt(arguments.length>1&&arguments[1]!==void 0?arguments[1]:Lt),a)},os=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Lt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Lt;return a.transform(ei(t,e))},oa=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Lt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Lt;return a.transform(ei(t,e),!0)},ur=(a,t,e)=>{const s=ei(t,e);return Ms(a,bt(s,a.calcOwnMatrix())),s},lc={left:-.5,top:-.5,center:0,bottom:.5,right:.5},jt=a=>typeof a=="string"?lc[a]:a-.5,hc=new S(1,0),aa=new S,dr=(a,t)=>a.rotate(t),si=(a,t)=>new S(t).subtract(a),Ni=a=>a.distanceFrom(aa),Bi=(a,t)=>Math.atan2(Ps(a,t),la(a,t)),fr=a=>Bi(hc,a),$i=a=>a.eq(aa)?a:a.scalarDivide(Ni(a)),gr=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return $i(new S(-a.y,a.x).scalarMultiply(t?1:-1))},Ps=(a,t)=>a.x*t.y-a.y*t.x,la=(a,t)=>a.x*t.x+a.y*t.y,pr=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=Ps(t,e),i=Ps(t,a),n=Ps(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},Hi="not-allowed";function ha(a){return jt(a.originX)===jt(U)&&jt(a.originY)===jt(U)}function ca(a){return .5-jt(a)}const fe=(a,t)=>a[t],ua=(a,t,e,s)=>({e:a,transform:t,pointer:new S(e,s)});function da(a,t,e){const s=e,i=os(a.getCenterPoint(),a.canvas.viewportTransform,void 0),n=fr(si(i,s))+he;return Math.round(n%he/Jh)}function mr(a,t,e,s,i){var n;let{target:r,corner:o}=a;const l=r.controls[o],h=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,c=r.padding/h,u=(function(d,f,g,p){const b=d.getRelativeCenterPoint(),m=g!==void 0&&p!==void 0?d.translateToGivenOrigin(b,U,U,g,p):new S(d.left,d.top);return(d.angle?f.rotate(-gt(d.angle),b):f).subtract(m)})(r,new S(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 zi=a=>a.replace(/\s+/g," "),fa={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"},br=(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),ga=(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 l=(i+n)/2;if(i===n)r=o=0;else{const h=i-n;switch(o=l>.5?h/(2-i-n):h/(i+n),i){case a:r=(t-e)/h+(t<e?6:0);break;case t:r=(e-a)/h+2;break;case e:r=(a-t)/h+4}r/=6}return[Math.round(360*r),Math.round(100*o),Math.round(100*l),s]},pa=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},Gi=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),ma=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class ot{constructor(t){if(x(this,"isUnrecognised",!1),t)if(t instanceof ot)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 fa&&(t=fa[t]),t==="transparent"?[255,255,255,0]:ot.sourceFromHex(t)||ot.sourceFromRgb(t)||ot.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(${t},${e},${s})`}toRgba(){return`rgba(${this.getSource().join(",")})`}toHsl(){const[t,e,s]=ga(...this.getSource());return`hsl(${t},${e}%,${s}%)`}toHsla(){const[t,e,s,i]=ga(...this.getSource());return`hsla(${t},${e}%,${s}%,${i})`}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return`${Gi(t)}${Gi(e)}${Gi(s)}${Gi(Math.round(255*i))}`}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(ma(this.getSource())),this}toBlackWhite(t){const[e,,,s]=ma(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof ot||(t=new ot(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map((o,l)=>Math.round(.5*o+.5*s[l]));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return ot.fromRgba(t)}static fromRgba(t){return new ot(ot.sourceFromRgb(t))}static sourceFromRgb(t){const e=zi(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,pa(e[4])]}}static fromHsl(t){return ot.fromHsla(t)}static fromHsla(t){return new ot(ot.sourceFromHsl(t))}static sourceFromHsl(t){const e=zi(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=(ot.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,o,l;if(i===0)r=o=l=n;else{const h=n<=.5?n*(i+1):n+i-n*i,c=2*n-h;r=br(c,h,s+1/3),o=br(c,h,s),l=br(c,h,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*l),pa(e[4])]}static fromHex(t){return new ot(ot.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,o=255]=s.map(l=>parseInt(l,16));return[i,n,r,o/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?De(s):e.includes("turn")?360*s:s}}const Nt=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qn;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=it.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}},vr=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==Ft?[n.slice(1,4),n.slice(5,8)]:n===Ft?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},ii=function(a,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e=`url(#SVGID_${Z(t.id)})`;else{const n=new ot(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?`${a}: ${e}; ${s?`${a}-opacity: ${s}; `:""}`:`${a}="${e}" ${s?`${a}-opacity="${s}" `:""}`};class ba{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):Ft,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=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=ii(xt,this.fill);return[ii(Vt,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",l,"; ",d,"fill-rule: ",e,"; ","opacity: ",h,";",u,c].map(f=>Z(f)).join("")}getSvgFilter(){return this.shadow?`filter: url(#SVGID_${Z(this.shadow.id)});`:""}getSvgCommons(){return[this.id?`id="${Z(String(this.id))}" `:"",this.clipPath?`clip-path="url(#${this.clipPath.clipPathId})" `:""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix();return`${`transform="${ks(s)}`}${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="${this.getSvgStyles()}" `,o=i?`style="${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 b;l&&(l.clipPathId=`CLIPPATH_${Ve()}`,b=`<clipPath id="${l.clipPathId}" >
27
- ${l.toClipPathSVG(s)}</clipPath>
28
- `),c&&g.push("<g ",o,this.getSvgCommons(),` >
29
- `),g.push("<g ",this.getSvgTransform(!1),c?"":o+this.getSvgCommons(),` >
30
- `);const m=[r,h,e?"":this.addPaintOrder()," ",n?`transform="${n}" `:""].join("");return t[p]=m,ne(d)&&g.push(d.toSVG(this)),ne(u)&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(b),g.push(t.join("")),g.push(`</g>
31
- `),c&&g.push(`</g>
32
- `),s?s(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==xt?` paint-order="${Z(this.paintFirst)}" `:""}}function Wi(a){return new RegExp("^("+a.join("|")+")\\b","i")}const as="textDecorationThickness",va=["fontSize","fontWeight","fontFamily","fontStyle"],ya=["underline","overline","linethrough"],_a=[...va,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],wa=[..._a,...ya,"textBackgroundColor","direction",as],cc=[...va,...ya,Vt,"strokeWidth",xt,"deltaY","textBackgroundColor",as],uc={_reNewline:Zn,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:er,fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:st,fontStyle:er,lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:st,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:ts,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,[as]:66.667},Ce="justify",Vi="justify-left",ni="justify-right",ri="justify-center",ge=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,yr=String.raw`(?:\s*,?\s+|\s*,\s*)`,_r="http://www.w3.org/2000/svg",dc=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+ge+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+ge+"))?\\s+(.*)"),fc={cx:st,x:st,r:"radius",cy:Wt,y:Wt,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":as},wr="font-size",xr="clip-path",gc=Wi(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),pc=Wi(["symbol","image","marker","pattern","view","svg"]),xa=Wi(["symbol","g","a","svg","clipPath","defs"]),Sa=new RegExp(String.raw`^\s*(${ge})${yr}(${ge})${yr}(${ge})${yr}(${ge})\s*$`),Ca="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Aa=new RegExp("(?:\\s|^)"+Ca+Ca+"("+ge+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Re{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=typeof t=="string"?Re.parseShadow(t):t;Object.assign(this,Re.ownDefaults,e),this.id=Ve()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Aa.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(Aa,"")||"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=dr(new S(this.offsetX,this.offsetY),gt(-t.angle)),s=it.NUM_FRACTION_DIGITS,i=new ot(this.color);let n=40,r=40;return t.width&&t.height&&(n=100*rt((Math.abs(e.x)+this.blur)/t.width,s)+20,r=100*rt((Math.abs(e.y)+this.blur)/t.height,s)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),`<filter id="SVGID_${Z(this.id)}" y="-${r}%" height="${100+2*r}%" x="-${n}%" width="${100+2*n}%" >
33
- <feGaussianBlur in="SourceAlpha" stdDeviation="${rt(this.blur?this.blur/2:0,s)}"></feGaussianBlur>
34
- <feOffset dx="${rt(e.x,s)}" dy="${rt(e.y,s)}" result="oBlur" ></feOffset>
35
- <feFlood flood-color="${i.toRgb()}" flood-opacity="${i.getAlpha()}"/>
36
- <feComposite in2="oBlur" operator="in" />
37
- <feMerge>
38
- <feMergeNode></feMergeNode>
39
- <feMergeNode in="SourceGraphic"></feMergeNode>
40
- </feMerge>
41
- </filter>
42
- `}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=Re.ownDefaults;return this.includeDefaultValues?t:lr(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}x(Re,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),x(Re,"type","shadow"),I.setClass(Re,"shadow");const ls=(a,t,e)=>Math.max(a,Math.min(t,e)),mc=[Wt,st,It,Jt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Ss,Cs],Le=[xt,Vt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],bc={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:U,originY:U,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:xt,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},Sr=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/he*Math.asin(1):e/he*Math.asin(t/a),{a,c:t,p:e,s}),Ta=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*he/e),Ea=(a,t,e,s)=>-e*Math.cos(a/s*Ge)+e+t,Cr=(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,ka=(a,t,e,s)=>e-Cr(s-a,0,e,s)+t;var vc=Object.freeze({__proto__:null,defaultEasing:Ea,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:ka,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:l}=Sr(i,e,n,1.70158);return-Ta(r,o,l,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*ka(2*a,0,e,s)+t:.5*Cr(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:l,c:h}=Sr(i,e,n,1.70158);return a<1?-.5*Ta(r,o,l,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*he/l)*.5+h+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*Ge)+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:Cr,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:l,c:h}=Sr(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*he/l)+h+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*Ge)+t});const yc=()=>!1;class Ar{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Ea,onStart:o=Ti,onChange:l=Ti,onComplete:h=Ti,abort:c=yc,target:u}=t;x(this,"_state","pending"),x(this,"durationProgress",0),x(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=o,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(()=>qs(t),this.delay):qs(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),qs(this.tick)))}register(){Oi.push(this)}unregister(){Oi.remove(this)}abort(){this._state="aborted",this.unregister()}}class _c extends Ar{constructor(t){let{startValue:e=0,endValue:s=100,...i}=t;super({...i,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)}}}class wc extends Ar{constructor(t){let{startValue:e=[0],endValue:s=[100],...i}=t;super({...i,startValue:e,byValue:s.map((n,r)=>n-e[r])})}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 xc=(a,t,e,s)=>t+e*(1-Math.cos(a/s*Ge)),Tr=a=>a&&((t,e,s)=>a(new ot(t).toRgba(),e,s));class Sc extends Ar{constructor(t){let{startValue:e,endValue:s,easing:i=xc,onChange:n,onComplete:r,abort:o,...l}=t;const h=new ot(e).getSource(),c=new ot(s).getSource();super({...l,startValue:h,byValue:c.map((u,d)=>u-h[d]),easing:i,onChange:Tr(n),onComplete:Tr(r),abort:Tr(o)})}calculate(t){const[e,s,i,n]=this.startValue.map((o,l)=>this.easing(t,o,this.byValue[l],this.duration,l)),r=[...[e,s,i].map(Math.round),ls(0,n,1)];return{value:r,valueProgress:r.map((o,l)=>this.byValue[l]!==0?Math.abs((o-this.startValue[l])/this.byValue[l]):0).find(o=>o!==0)||0}}}function Er(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new wc(a):new _c(a);return t.start(),t}function Ma(a){const t=new Sc(a);return t.start(),t}class ft{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=si(e,s),r=si(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 S(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,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=o*d-l*u,p=c*o-h*l;if(p!==0){const b=f/p,m=g/p;return(n||0<=b&&b<=1)&&(r||0<=m&&m<=1)?new ft("Intersection").append(new S(t.x+b*o,t.y+b*l)):new ft}if(f===0||g===0){const b=n||r||ft.isPointContained(t,s,i)||ft.isPointContained(e,s,i)||ft.isPointContained(s,t,e)||ft.isPointContained(i,t,e);return new ft(b?"Coincident":void 0)}return new ft("Parallel")}static intersectSegmentLine(t,e,s,i){return ft.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return ft.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 ft,r=s.length;for(let o,l,h,c=0;c<r;c++){if(o=s[c],l=s[(c+1)%r],h=ft.intersectLineLine(t,e,o,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 ft.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new ft,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],l=t[(r+1)%i],h=ft.intersectSegmentPolygon(o,l,e);h.status==="Coincident"?(n.push(h),s.append(o,l)):s.append(...h.points)}return n.length>0&&n.length===t.length?new ft("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 S(n.x,i.y),o=new S(i.x,n.y);return ft.intersectPolygonPolygon(t,[i,r,n,o])}}class Cc extends zo{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?kt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=kt(t,Xt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new S(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=>kt(o,r))}return n}intersectsWithRect(t,e){return ft.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=ft.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 ft.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 Se(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(It,t),this._set(Jt,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?De(Xo(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||Lt.concat()}calcACoords(){const t=is({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=Ts(e,s),n=bt(i,t),r=this._getTransformedDimensions(),o=r.x/2,l=r.y/2;return{tl:kt({x:-o,y:-l},n),tr:kt({x:o,y:-l},n),bl:kt({x:-o,y:l},n),br:kt({x:o,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,jt(this.originX),jt(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),i=this.matrixCache;return i&&i.key.every((n,r)=>n===s[r])?i.value:(this.group&&(e=bt(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.every((r,o)=>r===t[o]))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=Yo(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new S(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={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 l;return l=e.skewX===0&&e.skewY===0?new S(r*e.scaleX,o*e.scaleY):ji(r,o,Ks(e)),l.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const l=jt(i)-jt(e),h=jt(n)-jt(s);if(l||h){const c=this._getTransformedDimensions();r+=l*c.x,o+=h*c.y}return new S(r,o)}translateToCenterPoint(t,e,s){if(e===U&&s===U)return t;const i=this.translateToGivenOrigin(t,e,s,U,U);return this.angle?i.rotate(gt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,U,U,e,s);return this.angle?i.rotate(gt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?kt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new S(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.getPositionByOrigin(t,e)}getPositionByOrigin(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.getPositionByOrigin(st,Wt)}positionByLeftTop(t){return this.setPositionByOrigin(t,st,Wt)}}let Fe=class Xn extends Cc{static getDefaults(){return Xn.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){Pe("warn","Setting type has no effect",t)}constructor(t){super(),x(this,"_cacheContext",null),Object.assign(this,Xn.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=xe(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=it.maxCacheSideLimit,n=it.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=it.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,l]=Us.limitDimsByArea(r),h=ls(n,o,i),c=ls(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:o,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=o/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 S(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=ss(this.calcTransformMatrix());return new S(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!==It&&t!==Jt||(e=this._constrainScale(e)),t===It&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Re||(e=new Re(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===Vt&&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.fire("before:render",{ctx:t}),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=Zt(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=Xt(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,ne(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&&(ne(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||Lt,o=n*i,l=r*i,h=e.nonScaling?new S(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*it.browserShadowBlurConstant*(o+l)*(h.x+h.y)/4,t.shadowOffsetX=e.offsetX*o*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(!ne(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===Vt?(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,l=Zt({width:Math.ceil(r),height:Math.ceil(o)}),h=l.getContext("2d");h&&(h.beginPath(),h.moveTo(0,0),h.lineTo(r,0),h.lineTo(r,o),h.lineTo(0,o),h.closePath(),h.translate(r/2,o/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 S(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=cr(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?jo():1,o=(t.multiplier||1)*r,l=t.canvasProvider||(v=>new ti(v,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&ra(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&ur(this,this.getViewportTransform()),this.setCoords();const h=xe(),c=this.getBoundingRect(),u=this.shadow,d=new S;if(u){const v=u.blur,_=u.nonScaling?new S(1,1):this.getObjectScaling();d.x=2*Math.round(n(u.offsetX)+v)*n(_.x),d.y=2*Math.round(n(u.offsetY)+v)*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 S(p.width/2,p.height/2),U,U);const b=this.canvas;p._objects=[this],this.set("canvas",p),this.setCoords();const m=p.toCanvasElement(o||1,t);return this.set("canvas",b),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 nr(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return rr(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=U,this.originY=U,this.left=n,this.top=r}if(this.set("angle",t),e){const{x:n,y:r}=this.getPositionByOrigin(s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Oi.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&we().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:l,onComplete:h}=s,c={...s,target:this,startValue:o??i.reduce((u,d)=>u[d],this),endValue:e,abort:r?.bind(this),onChange:(u,d,f)=>{i.reduce((g,p,b)=>(b===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?Ma(c):Er(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),o=s._objects.indexOf(n);return r>-1&&r>o}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Xn.customProperties,this.constructor.customProperties||[]);let e;const s=it.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:l,left:h,top:c,originX:u,originY:d,width:f,height:g,strokeWidth:p,strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:_,strokeMiterLimit:y,scaleX:w,scaleY:C,angle:A,flipX:T,flipY:k,opacity:L,visible:R,backgroundColor:F,fillRule:P,paintFirst:O,globalCompositeOperation:$,skewX:M,skewY:D}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const V=ut=>rt(ut,s),lt={...ns(this,t),type:this.constructor.type,version:qn,originX:u,originY:d,left:V(h),top:V(c),width:V(f),height:V(g),fill:qo(n)?n.toObject():n,stroke:qo(r)?r.toObject():r,strokeWidth:V(p),strokeDashArray:l&&l.concat(),strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:_,strokeMiterLimit:V(y),scaleX:V(w),scaleY:V(C),angle:V(A),flipX:T,flipY:k,opacity:V(L),shadow:o&&o.toObject(),visible:R,backgroundColor:F,fillRule:P,paintFirst:O,globalCompositeOperation:$,skewX:V(M),skewY:V(D),...e?{clipPath:e}:null};return this.includeDefaultValues?lt:this._removeDefaultValues(lt)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return lr(t,(i,n)=>{if(n===st||n===Wt||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`#<${this.constructor.type}>`}static _fromObject(t){let{type:e,...s}=t,{extraParam:i,...n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Js(s,n).then(r=>i?(delete r[i],new this(s[i],r)):new this(r))}static fromObject(t,e){return this._fromObject(t,e)}};x(Fe,"stateProperties",mc),x(Fe,"cacheProperties",Le),x(Fe,"ownDefaults",bc),x(Fe,"type","FabricObject"),x(Fe,"colorProperties",[xt,Vt,"backgroundColor"]),x(Fe,"customProperties",[]),I.setClass(Fe),I.setClass(Fe,"object");const Pa=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire(`object:${a}`,{...t,target:s}),s.fire(a,t)},Os=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Pa(a,{...ua(s,i,n,r),...e}),o};function Ds(a){return(t,e,s,i)=>{const{target:n,originX:r,originY:o}=e,l=n.getPositionByOrigin(r,o),h=a(t,e,s,i);return n.setPositionByOrigin(l,e.originX,e.originY),h}}const Ac=(a,t,e,s)=>(i,n,r,o)=>{const l=mr(n,n.originX,n.originY,r,o)[e],h=jt(n[t]);if(h===0||h>0&&l<0||h<0&&l>0){const{target:c}=n,u=c.strokeWidth/(c.strokeUniform?c[s]:1),d=ha(n)?2:1,f=c[a],g=Math.abs(l*d/c[s])-u;return c.set(a,Math.max(g,1)),f!==c[a]}return!1},Tc=Ac("width","originX","x","scaleX"),Oa=Os(Ys,Ds(Tc));function Ec(a,t,e,s,i){a.save();const{stroke:n,xSize:r,ySize:o,opName:l}=this.commonRenderProps(a,t,e,i,s);let h=r;r>o?a.scale(1,o/r):o>r&&(h=o,a.scale(r/o,1)),a.beginPath(),a.arc(0,0,h/2,0,he,!1),a[l](),n&&a.stroke(),a.restore()}function kc(a,t,e,s,i){a.save();const{stroke:n,xSize:r,ySize:o,opName:l}=this.commonRenderProps(a,t,e,i,s),h=r/2,c=o/2;a[`${l}Rect`](-h,-c,r,o),n&&a.strokeRect(-h,-c,r,o),a.restore()}class pe{constructor(t){x(this,"visible",!0),x(this,"actionName",Mi),x(this,"angle",0),x(this,"x",0),x(this,"y",0),x(this,"offsetX",0),x(this,"offsetY",0),x(this,"sizeX",0),x(this,"sizeY",0),x(this,"touchSizeX",0),x(this,"touchSizeY",0),x(this,"cursorStyle","crosshair"),x(this,"withConnection",!1),Object.assign(this,t)}getTransformAnchorPoint(){var t;return(t=this.transformAnchorPoint)!==null&&t!==void 0?t:new S(.5-this.x,.5-this.y)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:l,bl:h}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&ft.isPointInPolygon(s,[r,o,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,i){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 S(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=Ri([Ts(s,i),is({angle:t}),Li((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new S(-.5,-.5).transform(o),tr:new S(.5,-.5).transform(o),br:new S(.5,.5).transform(o),bl:new S(-.5,.5).transform(o)}}commonRenderProps(t,e,s,i){let n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const{cornerSize:r,cornerColor:o,transparentCorners:l,cornerStrokeColor:h}=n,c=r||i.cornerSize,u=this.sizeX||c,d=this.sizeY||c,f=l!==void 0?l:i.transparentCorners,g=f?Vt:xt,p=h||i.cornerStrokeColor,b=!f&&!!p;return t.fillStyle=o||i.cornerColor||"",t.strokeStyle=p||"",t.translate(e,s),t.rotate(gt(i.getTotalAngle())),{stroke:b,xSize:u,ySize:d,transparentCorners:f,opName:g}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?Ec.call(this,t,e,s,i,n):kc.call(this,t,e,s,i,n)}}const Mc=(a,t,e)=>e.lockRotation?Hi:t.cursorStyle,Pc=Os(Bo,Ds((a,t,e,s)=>{let{target:i,ex:n,ey:r,theta:o,originX:l,originY:h}=t;const c=i.getPositionByOrigin(l,h);if(fe(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=De(d-u+o);if(i.snapAngle&&i.snapAngle>0){const p=i.snapAngle,b=i.snapThreshold||p,m=Math.ceil(f/p)*p,v=Math.floor(f/p)*p;Math.abs(f-v)<b?f=v:Math.abs(f-m)<b&&(f=m)}f<0&&(f=360+f),f%=360;const g=i.angle!==f;return i.angle=f,g}));function Da(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Ra(a,t,e){const s=fe(a,"lockScalingX"),i=fe(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 Oc=["e","se","s","sw","w","nw","n","ne","e"],oi=(a,t,e,s)=>{const i=Da(a,e);if(Ra(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",i))return Hi;const n=da(e,0,s);return`${Oc[n]}-resize`};function kr(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Da(a,n);let l,h,c,u,d,f;if(Ra(n,r,o))return!1;if(t.gestureScale)h=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(l=mr(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),fe(n,"lockScalingFlip")&&(t.signX!==d||t.signY!==f))return!1;if(u=n._getTransformedDimensions(),o&&!r){const b=Math.abs(l.x)+Math.abs(l.y),{original:m}=t,v=b/(Math.abs(u.x*m.scaleX/n.scaleX)+Math.abs(u.y*m.scaleY/n.scaleY));h=m.scaleX*v,c=m.scaleY*v}else h=Math.abs(l.x*n.scaleX/u.x),c=Math.abs(l.y*n.scaleY/u.y);ha(t)&&(h*=2,c*=2),t.signX!==d&&r!=="y"&&(t.originX=ca(t.originX),h*=-1,t.signX=d),t.signY!==f&&r!=="x"&&(t.originY=ca(t.originY),c*=-1,t.signY=f)}const g=n.scaleX,p=n.scaleY;return r?(r==="x"&&n.set(It,h),r==="y"&&n.set(Jt,c)):(!fe(n,"lockScalingX")&&n.set(It,h),!fe(n,"lockScalingY")&&n.set(Jt,c)),g!==n.scaleX||p!==n.scaleY}const Xi=Os(Ei,Ds((a,t,e,s)=>kr(a,t,e,s))),Dc=Os(Ei,Ds((a,t,e,s)=>kr(a,t,e,s,{by:"x"}))),Rc=Os(Ei,Ds((a,t,e,s)=>kr(a,t,e,s,{by:"y"}))),Mr={x:{counterAxis:"y",scale:It,skew:Ss,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Jt,skew:Cs,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Lc=["ns","nesw","ew","nwse"],Fc=(a,t,e,s)=>{if(t.x!==0&&fe(e,"lockSkewingY")||t.y!==0&&fe(e,"lockSkewingX"))return Hi;const i=da(e,0,s)%4;return`${Lc[i]}-resize`};function La(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:l,skew:h,flip:c}=Mr[a];if(fe(n,l))return!1;const{origin:u,flip:d}=Mr[r],f=jt(e[u])*(n[d]?-1:1),g=-Math.sign(f)*(n[c]?-1:1),p=.5*-((n[h]===0&&mr(e,U,U,s,i)[a]>0||n[h]>0?1:-1)*g)+.5;return Os($o,Ds((m,v,_,y)=>(function(w,C,A){let{target:T,ex:k,ey:L,skewingSide:R,...F}=C;const{skew:P}=Mr[w],O=A.subtract(new S(k,L)).divide(new S(T.scaleX,T.scaleY))[w],$=T[P],M=F[P],D=Math.tan(gt(M)),V=w==="y"?T._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:T._getTransformedDimensions({scaleX:1,scaleY:1}).y,lt=2*O*R/Math.max(V,1)+D,ut=De(Math.atan(lt));T.set(P,ut);const E=$!==T[P];if(E&&w==="y"){const{skewX:B,scaleX:z}=T,J=T._getTransformedDimensions({skewY:$}),Et=T._getTransformedDimensions(),nt=B!==0?J.x/Et.x:1;nt!==1&&T.set(It,nt*z)}return E})(a,v,new S(_,y))))(t,{...e,[o]:p,skewingSide:g},s,i)}const Ic=(a,t,e,s)=>La("x",a,t,e,s),jc=(a,t,e,s)=>La("y",a,t,e,s);function Ui(a,t){return a[t.canvas.altActionKey]}const Yi=(a,t,e)=>{const s=Ui(a,e);return t.x===0?s?Ss:Jt:t.y===0?s?Cs:It:""},Rs=(a,t,e,s)=>Ui(a,e)?Fc(0,t,e,s):oi(a,t,e,s),Fa=(a,t,e,s)=>Ui(a,t.target)?jc(a,t,e,s):Dc(a,t,e,s),Ia=(a,t,e,s)=>Ui(a,t.target)?Ic(a,t,e,s):Rc(a,t,e,s),ja=()=>({ml:new pe({x:-.5,y:0,cursorStyleHandler:Rs,actionHandler:Fa,getActionName:Yi}),mr:new pe({x:.5,y:0,cursorStyleHandler:Rs,actionHandler:Fa,getActionName:Yi}),mb:new pe({x:0,y:.5,cursorStyleHandler:Rs,actionHandler:Ia,getActionName:Yi}),mt:new pe({x:0,y:-.5,cursorStyleHandler:Rs,actionHandler:Ia,getActionName:Yi}),tl:new pe({x:-.5,y:-.5,cursorStyleHandler:oi,actionHandler:Xi}),tr:new pe({x:.5,y:-.5,cursorStyleHandler:oi,actionHandler:Xi}),bl:new pe({x:-.5,y:.5,cursorStyleHandler:oi,actionHandler:Xi}),br:new pe({x:.5,y:.5,cursorStyleHandler:oi,actionHandler:Xi}),mtr:new pe({x:0,y:-.5,actionHandler:Pc,cursorStyleHandler:Mc,offsetY:-40,withConnection:!0,actionName:tr})}),Nc=()=>({mr:new pe({x:.5,y:0,actionHandler:Oa,cursorStyleHandler:Rs,actionName:Ys}),ml:new pe({x:-.5,y:0,actionHandler:Oa,cursorStyleHandler:Rs,actionName:Ys})}),Bc=()=>({...ja(),...Nc()});class ai extends Fe{static getDefaults(){return{...super.getDefaults(),...ai.ownDefaults}}constructor(t){super(),Object.assign(this,this.constructor.createControls(),ai.ownDefaults),this.setOptions(t)}static createControls(){return{controls:ja()}}_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(Mi))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=Ts(e.x,e.y),i=is({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=bt(s,i),r=bt(t,n),o=bt(r,[1/t[0],0,0,1/t[3],0,0]),l=this.group?ss(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,o,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(gt(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={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={hasBorders:s,hasControls:i,...e},r=this.getViewportTransform(),o=n.hasBorders,l=n.hasControls,h=bt(r,this.calcTransformMatrix()),c=ss(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(gt(this.group?c.angle:this.angle)),o&&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=ji(this.width,this.height,Ks(e)),r=this.isStrokeAccountedForInDimensions()?ir:(this.strokeUniform?new S().scalarAdd(this.canvas?this.canvas.getZoom():1):new S(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={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((l,h)=>{if(l.getVisibility(this,h)){const c=this.oCoords[h];l.render(t,c.x,c.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 Na(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}x(ai,"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 Mt extends ai{}Na(Mt,[ba]),I.setClass(Mt),I.setClass(Mt,"object");const Ba=(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 $a{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new S(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new S(1/this.options.scaleX,1/this.options.scaleY):new S(1,1)}createSideVector(t,e){const s=si(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 S(t);return e.y+=e.x*Math.tan(gt(this.options.skewY)),e.x+=e.y*Math.tan(gt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const $c=new S;class Ls extends $a{static getOrthogonalRotationFactor(t,e){const s=e?Bi(t,e):fr(t);return Math.abs(s)<Ge?-1:1}constructor(t,e,s,i){super(i),x(this,"AB",void 0),x(this,"AC",void 0),x(this,"alpha",void 0),x(this,"bisector",void 0),this.A=new S(t),this.B=new S(e),this.C=new S(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Bi(this.AB,this.AC),this.bisector=$i(dr(this.AB.eq($c)?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=Ls.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%he===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?Ni(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Ni(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new S(Ls.getOrthogonalRotationFactor(this.bisector),Ls.getOrthogonalRotationFactor(new S(this.bisector.y,this.bisector.x)));return[new S(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new S(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{pr(n,t,e)&&s.push(this.A.add(n))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:o,strokeUniform:l}=this.options,h=new S(Math.tan(gt(i)),Math.tan(gt(n))),c=this.strokeProjectionMagnitude,u=l?c/o/Math.sqrt(1/o**2+1/r**2*h.y**2):c/Math.sqrt(1+h.y**2),d=new S(Math.sqrt(Math.max(c**2-u**2,0)),u),f=l?c/Math.sqrt(1+h.x**2*(1/o)**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 S(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=>{pr(p,t,e)&&s.push(this.applySkew(this.A).add(p))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%he===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=Ps(i,r)>0,l=o?i:n,h=o?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 Ha extends $a{constructor(t,e,s){super(s),this.A=new S(t),this.T=new S(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 S(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 Ls(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new S(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($i(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 za=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 S(r)),n),[new S(a[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((o,l)=>{for(let h=o.length-1;h>=0;h--)if(l(o[h],h,o))return h;return-1})(i,o=>!o.eq(n));i.splice(r+1)}return i.forEach((n,r,o)=>{let l,h;r===0?(h=o[1],l=e?n:o[o.length-1]):r===o.length-1?(l=o[r-1],h=e?n:o[0]):(l=o[r-1],h=o[r+1]),e&&o.length===1?s.push(...new Ha(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Ls(n,l,h,t).project()):s.push(...new Ha(n,r===0?h:l,t).project())}),s},Pr=a=>{const t={};return Object.keys(a).forEach(e=>{t[e]={},Object.keys(a[e]).forEach(s=>{t[e][s]={...a[e][s]}})}),t},qi=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)},Ga=(a,t)=>{const e=t.split(`
43
- `),s=[];let i=-1,n={};a=Pr(a);for(let r=0;r<e.length;r++){const o=Fi(e[r]);if(a[r])for(let l=0;l<o.length;l++){i++;const h=a[r][l];h&&Object.keys(h).length>0&&(qi(n,h,!0)?s.push({start:i,end:i+1,style:h}):s[s.length-1].end++),n=h||{}}else i+=o.length,n={}}return s},Wa=(a,t)=>{if(!Array.isArray(a))return Pr(a);const e=t.split(Zn),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=Fi(e[r]);for(let l=0;l<o.length;l++)i++,a[n]&&a[n].start<=i&&i<a[n].end&&(s[r]=s[r]||{},s[r][l]={...a[n].style},i===a[n].end-1&&n++)}return s},Xe=["display","transform",xt,"fill-opacity","fill-rule","opacity",Vt,"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 Va(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 l=o.length;l--;)r=new RegExp("\\."+o[l]+n,"i"),t=t.replace(r,"")}return t.length===0}function Hc(a,t){let e=!0;const s=Va(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=Va(i=i.parentElement,r);return n.length===0})(a,t)),s&&e&&t.length===0}function zc(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},e={};for(const s in t)Hc(a,s.split(" "))&&(e={...e,...t[s]});return e}const Gc=a=>{var t;return(t=fc[a])!==null&&t!==void 0?t:a},Wc=new RegExp(`(${ge})`,"gi"),Bt=`(${ge})`,Vc=String.raw`(skewX)\(${Bt}\)`,Xc=String.raw`(skewY)\(${Bt}\)`,Uc=String.raw`(rotate)\(${Bt}(?: ${Bt} ${Bt})?\)`,Yc=String.raw`(scale)\(${Bt}(?: ${Bt})?\)`,qc=String.raw`(translate)\(${Bt}(?: ${Bt})?\)`,Or=`(?:${String.raw`(matrix)\(${Bt} ${Bt} ${Bt} ${Bt} ${Bt} ${Bt}\)`}|${qc}|${Uc}|${Yc}|${Vc}|${Xc})`,Kc=`(?:${Or}*)`,Qc=String.raw`^\s*(?:${Kc}?)\s*$`,Jc=new RegExp(Qc),Zc=new RegExp(Or),tu=new RegExp(Or,"g");function Ki(a){const t=[];if(!(a=(e=>zi(e.replace(Wc," $1 ").replace(/,/gi," ")))(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!Jc.test(a))return[...Lt];for(const e of a.matchAll(tu)){const s=Zc.exec(e[0]);if(!s)continue;let i=Lt;const n=s.filter(g=>!!g),[,r,...o]=n,[l,h,c,u,d,f]=o.map(g=>parseFloat(g));switch(r){case"translate":i=Ts(l,h);break;case tr:i=is({angle:l},{x:h,y:c});break;case Mi:i=Li(l,h);break;case Ss:i=or(l);break;case Cs:i=ar(l);break;case"matrix":i=[l,h,c,u,d,f]}t.push(i)}return Ri(t)}function eu(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==xt&&a!==Vt||t!==Ft){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===Ft?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?bt(e.transformMatrix,Ki(t)):Ki(t);else if(a==="visible")r=t!==Ft&&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"?st:t==="end"?mt:U;else if(a==="charSpacing"||a===as)n=Nt(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(xt),l=t.indexOf(Vt);r=xt,(o>-1&&l>-1&&l<o||o===-1&&l>-1)&&(r=Vt)}else{if(a==="href"||a==="xlink:href"||a==="font"||a==="id")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(Nt):Nt(t,s)}}else r="";return!i&&isNaN(n)?r:n}function Dr(a,t){a.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function su(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?Dr(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 iu={stroke:"strokeOpacity",fill:"fillOpacity"};function Ie(a,t,e){if(!a)return{};let s,i={},n=Qn;a.parentNode&&xa.test(a.parentNode.nodeName)&&(i=Ie(a.parentElement,t,e),i.fontSize&&(s=n=Nt(i.fontSize)));const r={...t.reduce((h,c)=>{const u=a.getAttribute(c);return u&&(h[c]=u),h},{}),...zc(a,e),...su(a)};r[xr]&&a.setAttribute(xr,r[xr]),r[wr]&&(s=Nt(r[wr],n),r[wr]=`${s}`);const o={};for(const h in r){const c=Gc(h),u=eu(c,r[h],i,s);o[c]=u}o&&o.font&&(function(h,c){const u=h.match(dc);if(!u)return;const d=u[1],f=u[3],g=u[4],p=u[5],b=u[6];d&&(c.fontStyle=d),f&&(c.fontWeight=isNaN(parseFloat(f))?f:parseFloat(f)),g&&(c.fontSize=Nt(g)),b&&(c.fontFamily=b),p&&(c.lineHeight=p===er?1:p)})(o.font,o);const l={...i,...o};return xa.test(a.nodeName)?l:(function(h){const c=Mt.getDefaults();return Object.entries(iu).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 ot(h[d]);h[d]=g.setAlpha(rt(g.getAlpha()*h[f],2)).toRgba()}),h})(l)}const Xa=["rx","ry"];class Ae extends Mt{static getDefaults(){return{...super.getDefaults(),...Ae.ownDefaults}}constructor(t){super(),Object.assign(this,Ae.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,l=r!==0||o!==0;t.beginPath(),t.moveTo(i+r,n),t.lineTo(i+e-r,n),l&&t.bezierCurveTo(i+e-We*r,n,i+e,n+We*o,i+e,n+o),t.lineTo(i+e,n+s-o),l&&t.bezierCurveTo(i+e,n+s-We*o,i+e-We*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),l&&t.bezierCurveTo(i+We*r,n+s,i,n+s-We*o,i,n+s-o),t.lineTo(i,n+o),l&&t.bezierCurveTo(i,n+We*o,i+We*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([...Xa,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:i}=this;return["<rect ","COMMON_PARTS",`x="${-t/2}" y="${-e/2}" rx="${Z(s)}" ry="${Z(i)}" width="${Z(t)}" height="${Z(e)}" />
44
- `]}static async fromElement(t,e,s){const{left:i=0,top:n=0,width:r=0,height:o=0,visible:l=!0,...h}=Ie(t,this.ATTRIBUTE_NAMES,s);return new this({...e,...h,left:i,top:n,width:r,height:o,visible:!!(l&&r&&o)})}}x(Ae,"type","Rect"),x(Ae,"cacheProperties",[...Le,...Xa]),x(Ae,"ownDefaults",{rx:0,ry:0}),x(Ae,"ATTRIBUTE_NAMES",[...Xe,"x","y","rx","ry","width","height"]),I.setClass(Ae),I.setSVGClass(Ae);const je="initialization",Qi="added",Rr="removed",Ji="imperative",Ua=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?ei(r.calcTransformMatrix(),a.calcTransformMatrix()):null,l=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),h=!t.isStrokeAccountedForInDimensions(),c=e&&h?oa(new S(s,s),void 0,a.calcTransformMatrix()):ir,u=!e&&h?s:0,d=ji(i+u,n+u,Ri([o,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[l.subtract(d),l.add(d)]};class Zi{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===Ji||!!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===Ji&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:l}=Se(t.map(u=>Ua(i,u)).reduce((u,d)=>u.concat(d),[])),h=new S(o,l),c=new S(n,r).add(h.scalarDivide(2));if(s===je){const u=this.getInitialSize(e,{size:h,center:c});return{center:c,relativeCorrection:new S(0,0),size:u}}return{center:c.transform(i.calcOwnMatrix()),size:h}}}x(Zi,"type","strategy");class Lr extends Zi{shouldPerformLayout(t){return!0}}x(Lr,"type","fit-content"),I.setClass(Lr);const Ya="layoutManager";class li{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Lr;x(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const 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[Pi,No,Ys,Bo,Ei,$o,ki,Zh,tc].map(i=>t.on(i,n=>this.performLayout(i===Pi?{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===Qi?this.subscribeTargets(t):s===Rr&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Ji&&t.deep){const{strategy:n,...r}=t;e.forEachObject(o=>o.layoutManager&&o.layoutManager.performLayout({...r,bubbles:!1,target:o}))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===je?new S:e.getRelativeCenterPoint(),{center:o,correction:l=new S,relativeCorrection:h=new S}=n,c=r.subtract(o).add(l).transform(i===je?Lt:Xt(e.calcOwnMatrix()),!0).add(h);return{result:n,prevCenter:r,nextCenter:o,offset:c}}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===je?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*jt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*jt(s.originY)}):(s.setPositionByOrigin(n,U,U),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,...o}=t,{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&&((o.path||(o.path=[])).push(s),h.layoutManager.performLayout({...o,target:h})),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Ya,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}I.setClass(li,Ya);class nu extends li{performLayout(){}}class te extends Ho(Mt){static getDefaults(){return{...super.getDefaults(),...te.ownDefaults}}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),x(this,"_activeObjects",[]),x(this,"__objectSelectionTracker",void 0),x(this,"__objectSelectionDisposer",void 0),Object.assign(this,te.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 li,this.layoutManager.performLayout({type:je,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(Pe("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(Pe("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(Qi,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(Qi,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Rr,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&&Ms(t,bt(Xt(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||(Ms(t,bt(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=Mt.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(...Xt(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({target:this,type:Ji,...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{...super.toObject(["subTargetCheck","interactive",...t]),...e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{},objects:this.__serializeObjects("toObject",t)}}toString(){return`#<Group: (${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=Ae.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",` >
45
- `],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>
46
- `),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?`opacity: ${Z(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,...r}=t;return Promise.all([Es(i,e),Js(r,e)]).then(o=>{let[l,h]=o;const c=new this(l,{...r,...h,layoutManager:new nu});if(n){const u=I.getClass(n.type),d=I.getClass(n.strategy);c.layoutManager=new u(new d)}else c.layoutManager=new li;return c.layoutManager.subscribeTargets({type:je,target:c,targets:c.getObjects()}),c.setCoords(),c})}}x(te,"type","Group"),x(te,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),I.setClass(te);const qa=(a,t)=>Math.min(t.width/a.width,t.height/a.height),Ka=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Fr="\\s*,?\\s*",hi=`${Fr}(${ge})`,ru=`${hi}${hi}${hi}${Fr}([01])${Fr}([01])${hi}${hi}`,ou={m:"l",M:"L"},au=(a,t,e,s,i,n,r,o,l,h,c)=>{const u=ce(a),d=ue(a),f=ce(t),g=ue(t),p=e*i*f-s*n*g+r,b=s*i*f+e*n*g+o;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),b+l*(s*i*g-e*n*f),p,b]},Qa=(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 Ir(a,t,e,s,i,n,r,o){let l;if(it.cachesBoundsOfCurve&&(l=[...arguments].join(),Us.boundsOfCurveCache[l]))return Us.boundsOfCurveCache[l];const h=Math.sqrt,c=Math.abs,u=[],d=[[0,0],[0,0]];let f=6*a-12*e+6*i,g=-3*a+9*e-9*i+3*r,p=3*e-3*a;for(let y=0;y<2;++y){if(y>0&&(f=6*t-12*s+6*n,g=-3*t+9*s-9*n+3*o,p=3*s-3*t),c(g)<1e-12){if(c(f)<1e-12)continue;const k=-p/f;0<k&&k<1&&u.push(k);continue}const w=f*f-4*p*g;if(w<0)continue;const C=h(w),A=(-f+C)/(2*g);0<A&&A<1&&u.push(A);const T=(-f-C)/(2*g);0<T&&T<1&&u.push(T)}let b=u.length;const m=b,v=Za(a,t,e,s,i,n,r,o);for(;b--;){const{x:y,y:w}=v(u[b]);d[0][b]=y,d[1][b]=w}d[0][m]=a,d[1][m]=t,d[0][m+1]=r,d[1][m+1]=o;const _=[new S(Math.min(...d[0]),Math.min(...d[1])),new S(Math.max(...d[0]),Math.max(...d[1]))];return it.cachesBoundsOfCurve&&(Us.boundsOfCurveCache[l]=_),_}const lu=(a,t,e)=>{let[s,i,n,r,o,l,h,c]=e;const u=((d,f,g,p,b,m,v)=>{if(g===0||p===0)return[];let _=0,y=0,w=0;const C=Math.PI,A=v*Kn,T=ue(A),k=ce(A),L=.5*(-k*d-T*f),R=.5*(-k*f+T*d),F=g**2,P=p**2,O=R**2,$=L**2,M=F*P-F*O-P*$;let D=Math.abs(g),V=Math.abs(p);if(M<0){const Qt=Math.sqrt(1-M/(F*P));D*=Qt,V*=Qt}else w=(b===m?-1:1)*Math.sqrt(M/(F*O+P*$));const lt=w*D*R/V,ut=-w*V*L/D,E=k*lt-T*ut+.5*d,B=T*lt+k*ut+.5*f;let z=Qa(1,0,(L-lt)/D,(R-ut)/V),J=Qa((L-lt)/D,(R-ut)/V,(-L-lt)/D,(-R-ut)/V);m===0&&J>0?J-=2*C:m===1&&J<0&&(J+=2*C);const Et=Math.ceil(Math.abs(J/C*2)),nt=[],j=J/Et,dt=8/3*Math.sin(j/4)*Math.sin(j/4)/Math.sin(j/2);let Tt=z+j;for(let Qt=0;Qt<Et;Qt++)nt[Qt]=au(z,Tt,k,T,D,V,E,B,dt,_,y),_=nt[Qt][5],y=nt[Qt][6],z=Tt,Tt+=j;return nt})(h-a,c-t,i,n,o,l,r);for(let d=0,f=u.length;d<f;d++)u[d][1]+=a,u[d][2]+=t,u[d][3]+=a,u[d][4]+=t,u[d][5]+=a,u[d][6]+=t;return u},Ja=a=>{let t=0,e=0,s=0,i=0;const n=[];let r,o=0,l=0;for(const h of a){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":o=c[3],l=c[4],t=c[5],e=c[6],u=["C",c[1],c[2],o,l,t,e];break;case"s":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"S":r==="C"?(o=2*t-o,l=2*e-l):(o=t,l=e),t=c[3],e=c[4],u=["C",o,l,c[1],c[2],t,e],o=u[3],l=u[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":o=c[1],l=c[2],t=c[3],e=c[4],u=["Q",o,l,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":r==="Q"?(o=2*t-o,l=2*e-l):(o=t,l=e),t=c[1],e=c[2],u=["Q",o,l,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":lu(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},tn=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),Za=(a,t,e,s,i,n,r,o)=>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 S(r*h+i*c+e*u+a*d,o*h+n*c+s*u+t*d)},tl=a=>a**2,el=a=>2*a*(1-a),sl=a=>(1-a)**2,hu=(a,t,e,s,i,n,r,o)=>l=>{const h=tl(l),c=el(l),u=sl(l),d=3*(u*(e-a)+c*(i-e)+h*(r-i)),f=3*(u*(s-t)+c*(n-s)+h*(o-n));return Math.atan2(f,d)},cu=(a,t,e,s,i,n)=>r=>{const o=tl(r),l=el(r),h=sl(r);return new S(i*o+e*l+a*h,n*o+s*l+t*h)},uu=(a,t,e,s,i,n)=>r=>{const o=1-r,l=2*(o*(e-a)+r*(i-e)),h=2*(o*(s-t)+r*(n-s));return Math.atan2(h,l)},il=(a,t,e)=>{let s=new S(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=tn(s.x,s.y,r.x,r.y),s=r}return i},du=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r={...n},o=.01,l=0;const h=a.iterator,c=a.angleFinder;for(;i<t&&o>1e-4;)r=h(s),l=s,e=tn(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return{...r,angle:c(l)}},jr=a=>{let t,e,s=0,i=0,n=0,r=0,o=0;const l=[];for(const h of a){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=o=n=h[2];break;case"L":e=c,e.length=tn(i,n,h[1],h[2]),i=h[1],n=h[2];break;case"C":t=Za(i,n,h[1],h[2],h[3],h[4],h[5],h[6]),e=c,e.iterator=t,e.angleFinder=hu(i,n,h[1],h[2],h[3],h[4],h[5],h[6]),e.length=il(t,i,n),i=h[5],n=h[6];break;case"Q":t=cu(i,n,h[1],h[2],h[3],h[4]),e=c,e.iterator=t,e.angleFinder=uu(i,n,h[1],h[2],h[3],h[4]),e.length=il(t,i,n),i=h[3],n=h[4];break;case"Z":e=c,e.destX=r,e.destY=o,e.length=tn(i,n,r,o),i=r,n=o}s+=e.length,l.push(e)}return l.push({length:s,x:i,y:n}),l},nl=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jr(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{...new S(i.x,i.y).lerp(new S(i.destX,i.destY),n),angle:Math.atan2(i.destY-i.y,i.destX-i.x)};case"L":return{...new S(i.x,i.y).lerp(new S(r[1],r[2]),n),angle:Math.atan2(r[2]-i.y,r[1]-i.x)};case"C":case"Q":return du(i,t)}},fu=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),rl=new RegExp(ru,"g"),gu=new RegExp(ge,"gi"),pu={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},ol=a=>{var t;const e=[],s=(t=a.match(fu))!==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=pu[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){rl.lastIndex=0;for(let l=null;l=rl.exec(i);)o.push(...l.slice(1))}else o=i.match(gu)||[];for(let l=0;l<o.length;l+=r){const h=new Array(r),c=ou[n];h[0]=l>0&&c?c:n;for(let u=0;u<r;u++)h[u+1]=parseFloat(o[l+u]);e.push(h)}}return e},mu=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new S(a[0]),s=new S(a[1]),i=1,n=0;const r=[],o=a.length,l=o>2;let h;for(l&&(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]),h=1;h<o;h++){if(!e.eq(s)){const c=e.midPointFrom(s);r.push(["Q",e.x,e.y,c.x,c.y])}e=a[h],h+1<a.length&&(s=a[h+1])}return l&&(i=e.x>a[h-2].x?1:e.x===a[h-2].x?0:-1,n=e.y>a[h-2].y?1:e.y===a[h-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},al=(a,t)=>a.map(e=>e.map((s,i)=>i===0||t===void 0?s:rt(s,t)).join(" ")).join(" "),bu=(a,t)=>Math.floor(Math.random()*(t-a+1))+a,en=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=ss(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(It,i),s.set(Jt,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,U,U)};var vu=Object.freeze({__proto__:null,addTransformToObject:na,animate:Er,animateColor:Ma,applyTransformToObject:Ms,calcAngleBetweenVectors:Bi,calcDimensionsMatrix:Ks,calcPlaneChangeMatrix:ei,calcVectorRotation:fr,cancelAnimFrame:Go,capValue:ls,composeMatrix:Yo,copyCanvasElement:a=>{var t;const e=Zt(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:ce,createCanvasElement:xe,createImage:Wo,createRotateMatrix:is,createScaleMatrix:Li,createSkewXMatrix:or,createSkewYMatrix:ar,createTranslateMatrix:Ts,createVector:si,crossProduct:Ps,degreesToRadians:gt,dotProduct:la,ease:vc,enlivenObjectEnlivables:Js,enlivenObjects:Es,findScaleToCover:Ka,findScaleToFit:qa,getBoundsOfCurve:Ir,getOrthonormalVector:gr,getPathSegmentsInfo:jr,getPointOnPath:nl,getPointer:sa,getRandomInt:bu,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-Ge;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:l}=new S(ce(r),ue(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,l]}return i[a]=["Z"],i},getSmoothPathFromPoints:mu,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:$i,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new te(a,t),hasStyleChanged:qi,invertTransform:Xt,isBetweenVectors:pr,isIdentityMatrix:Vo,isTouchEvent:Ii,isTransparent:Ba,joinPath:al,loadImage:Qs,magnitude:Ni,makeBoundingBoxFromPoints:Se,makePathSimpler:Ja,matrixToSVG:ks,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),ur(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 te([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:bt,multiplyTransformMatrixArray:Ri,parsePath:ol,parsePreserveAspectRatioAttribute:vr,parseUnit:Nt,pick:ns,projectStrokeOnPoints:za,qrDecompose:ss,radiansToDegrees:De,removeFromArray:es,removeTransformFromObject:(a,t)=>{const e=Xt(t),s=bt(e,a.calcOwnMatrix());Ms(a,s)},removeTransformMatrixForSvgParsing:en,requestAnimFrame:qs,resetObjectTransform:ra,rotateVector:dr,saveObjectTransform:cr,sendObjectToPlane:ur,sendPointToPlane:os,sendVectorToPlane:oa,sin:ue,sizeAfterTransform:ji,string:oc,stylesFromArray:Wa,stylesToArray:Ga,toBlob:rr,toDataURL:nr,toFixed:rt,transformPath:(a,t,e)=>(e&&(t=bt(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}=kt({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i})),transformPoint:kt});function Nr(a,t){const e=a.style;e&&Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)})}class yu extends ea{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),x(this,"upper",void 0),x(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=xe();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=xs().createElement("div");return t.setAttribute("data-fabric","wrapper"),Nr(t,{position:"relative"}),ta(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;Nr(t,{...s,"touch-action":i?"manipulation":Ft}),ta(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;Zo(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),hr(this.upper.el,t),hr(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(),we().dispose(this.upper.el),delete this.upper,delete this.container}}const _u=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,l=s-r,h=!fe(i,"lockMovementX")&&i.left!==o,c=!fe(i,"lockMovementY")&&i.top!==l;return h&&i.set(st,o),c&&i.set(Wt,l),(h||c)&&Pa(No,ua(a,t,e,s)),h||c};class sn extends ti{constructor(){super(...arguments),x(this,"_hoveredTargets",[]),x(this,"_currentTransform",null),x(this,"_groupSelector",null),x(this,"contextTopDirty",!1)}static getDefaults(){return{...super.getDefaults(),...sn.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 yu(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 Ba(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===Mi||e===It||e===Jt||e===Ys?i=this.centeredScaling||t.centeredScaling:e===tr&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s=e?t.controls[e].getTransformAnchorPoint():{x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=mt:["mr","tr","br"].includes(e)&&(s.x=st),["tl","mt","tr"].includes(e)?s.y=Jn:["bl","mb","br"].includes(e)&&(s.y=Wt)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?os(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},l=s&&o?(i=o.getActionHandler(t,e,o))===null||i===void 0?void 0:i.bind(o):_u,h=((T,k,L,R)=>{if(!k||!T)return"drag";const F=R.controls[k];return F.getActionName(L,F,R)})(s,r,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,h,c)?{x:U,y:U}:this._getOriginFromCorner(e,r),{scaleX:d,scaleY:f,skewX:g,skewY:p,left:b,top:m,angle:v,width:_,height:y,cropX:w,cropY:C}=e,A={target:e,action:h,actionHandler:l,actionPerformed:!1,corner:r,scaleX:d,scaleY:f,skewX:g,skewY:p,offsetX:n.x-b,offsetY:n.y-m,originX:u.x,originY:u.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:gt(v),width:_,height:y,shiftKey:t.shiftKey,altKey:c,original:{...cr(e),originX:u.x,originY:u.y,cropX:w,cropY:C}};this._currentTransform=A,this.fire("before:transform",{e:t,transform:A})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new S(e,s).transform(this.viewportTransform),o=new S(e+i,s+n).transform(this.viewportTransform),l=this.selectionLineWidth/2;let h=Math.min(r.x,o.x),c=Math.min(r.y,o.y),u=Math.max(r.x,o.x),d=Math.max(r.y,o.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,Mt.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(h,c,u-h,d-c))}findTarget(t){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};const e=this.getScenePoint(t),s=this._activeObject,i=this.getActiveObjects(),n=this.searchPossibleTargets(this._objects,e),{subTargets:r,container:o,target:l}=n,h={...n,currentSubTargets:r,currentContainer:o,currentTarget:l};if(!s)return h;const c={...this.searchPossibleTargets([s],e),currentSubTargets:r,currentContainer:o,currentTarget:l};return s.findControl(this.getViewportPoint(t),Ii(t))?{...c,target:s}:c.target&&(i.length>1||!this.preserveObjectStacking||this.preserveObjectStacking&&t[this.altSelectionKey])?c:h}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,o,l,h]=s,c=Math.atan2(o.y-r.y,o.x-r.x),u=ce(c)*n,d=ue(c)*n,f=u+d,g=u-d;s=[new S(r.x-g,r.y-f),new S(o.x+f,o.y-g),new S(l.x+g,l.y+f),new S(h.x-f,h.y+g)]}return ft.isPointInPolygon(e,s)}_checkTarget(t,e){if(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;{const s=e.transform(this.viewportTransform);if(!this.isTargetTransparent(t,s.x,s.y))return!0}}return!1}_searchPossibleTargets(t,e,s){let i=t.length;for(;i--;){const n=t[i];if(this._checkTarget(n,e)){if(Di(n)&&n.subTargetCheck){const{target:r}=this._searchPossibleTargets(n._objects,e,s);r&&s.push(r)}return{target:n,subTargets:s}}}return{subTargets:[]}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e,[]);s.container=s.target;const{container:i,subTargets:n}=s;if(i&&Di(i)&&i.interactive&&n[0]){for(let r=n.length-1;r>0;r--){const o=n[r];if(!Di(o)||!o.interactive)return s.target=o,s}return s.target=n[0],s}return s}getViewportPoint(t){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(t,!0)}getScenePoint(t){return this._scenePoint?this._scenePoint:this._getPointerImpl(t)}_getPointerImpl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=sa(t),r=i.width||0,o=i.height||0;r&&o||(Wt in i&&Jn in i&&(o=Math.abs(i.top-i.bottom)),mt in i&&st 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=os(n,void 0,this.viewportTransform));const l=this.getRetinaScaling();l!==1&&(n.x/=l,n.y/=l);const h=r===0||o===0?new S(1,1):new S(s.width/r,s.height/o);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=xe(),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 rs(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach(l=>{n.includes(l)||(s=!0,l.fire("deselected",{e,target:l}),o.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: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,rs(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),rs(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(Pi,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;rs(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&&rs(e)&&this._activeObject===e){const s=ns(t,["angle","flipX","flipY",st,It,Jt,Ss,Cs,Wt]);return na(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}x(sn,"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:!0,fireRightClick:!0,fireMiddleClick:!0,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!0});class wu{constructor(t){x(this,"targets",[]),x(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),es(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 ee={passive:!1},hs=(a,t)=>({viewportPoint:a.getViewportPoint(t),scenePoint:a.getScenePoint(t)}),Ue=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)},re=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)},xu={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 Br extends sn{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),x(this,"_isClick",void 0),x(this,"textEditingManager",new wu(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(Ue)}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=this._getEventPrefix();t(Jo(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,`${i}move`,this._onMouseMove,ee),t(s,`${i}out`,this._onMouseOut),t(s,`${i}enter`,this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),e||(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,ee)}removeListeners(){this.addOrRemove(re);const t=this._getEventPrefix(),e=de(this.upperCanvasEl);re(e,`${t}up`,this._onMouseUp),re(e,"touchend",this._onTouchEnd,ee),re(e,`${t}move`,this._onMouseMove,ee),re(e,"touchmove",this._onMouseMove,ee),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_onMouseOut(t){const e=this._hoveredTarget,s={e:t,...hs(this,t)};this.fire("mouse:out",{...s,target:e}),this._hoveredTarget=void 0,e&&e.fire("mouseout",{...s}),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",{...s,target:i}),i&&i.fire("mouseout",{...s})}),this._hoveredTargets=[]}_onMouseEnter(t){const{target:e}=this.findTarget(t);this._currentTransform||e||(this.fire("mouse:over",{e:t,...hs(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 Ue(this.upperCanvasEl,"drag",this._onDragProgress)}ia(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{currentSubTargets:e}=this.findTarget(t),s=!!t.dataTransfer&&t.dataTransfer.dropEffect!==Ft,i=s?this._activeObject:void 0,n={e:t,target:this._dragSource,subTargets:e,dragSource:this._dragSource,didDrop:s,dropTarget:i};re(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",n),this._dragSource&&this._dragSource.fire("dragend",n),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)}_onDragOver(t){const e="dragover",{currentContainer:s,currentSubTargets:i}=this.findTarget(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(t,s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let l=0;l<i.length;l++){const h=i[l];h.canDrop(t)&&(o=h),h.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{currentContainer:e,currentSubTargets:s}=this.findTarget(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(t,e,i)}_onDragLeave(t){const{currentSubTargets:e}=this.findTarget(t),s={e:t,target:this._draggedoverTarget,subTargets:e,dragSource:this._dragSource};this.fire("dragleave",s),this._fireEnterLeaveEvents(t,void 0,s),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(t){const{currentContainer:e,currentSubTargets:s}=this.findTarget(t),i=this._basicEventHandler("drop:before",{e:t,target:e,subTargets:s,dragSource:this._dragSource,...hs(this,t)});i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const{target:e,subTargets:s}=this.findTarget(t),i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&ia(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())}fireEventFromPointerEvent(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};this._cacheTransformEventData(t);const{target:n,subTargets:r}=this.findTarget(t),o={e:t,target:n,subTargets:r,...hs(this,t),transform:this._currentTransform,...i};this.fire(e,o),n&&n.fire(s,o);for(let l=0;l<r.length;l++)r[l]!==n&&r[l].fire(s,o);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){this._cacheTransformEventData(t);let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t);const{target:i}=this.findTarget(t);(this.isDrawingMode||s&&i===s)&&(e=!0),e&&t.preventDefault();const n=this.upperCanvasEl,r=this._getEventPrefix(),o=de(n);Ue(o,"touchend",this._onTouchEnd,ee),e&&Ue(o,"touchmove",this._onMouseMove,ee),re(n,`${r}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(t){this._cacheTransformEventData(t),this.__onMouseDown(t);const e=this.upperCanvasEl,s=this._getEventPrefix();re(e,`${s}move`,this._onMouseMove,ee);const i=de(e);Ue(i,`${s}up`,this._onMouseUp),Ue(i,`${s}move`,this._onMouseMove,ee),this._resetTransformEventData()}_onTouchEnd(t){if(t.touches.length>0)return;this._cacheTransformEventData(t),this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=de(this.upperCanvasEl);re(s,"touchend",this._onTouchEnd,ee),re(s,"touchmove",this._onMouseMove,ee),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{Ue(this.upperCanvasEl,`${e}down`,this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this._cacheTransformEventData(t),this.__onMouseUp(t);const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=de(this.upperCanvasEl);re(i,`${s}up`,this._onMouseUp),re(i,`${s}move`,this._onMouseMove,ee),Ue(e,`${s}move`,this._onMouseMove,ee)}this._resetTransformEventData()}_onMouseMove(t){this._cacheTransformEventData(t);const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t),this._resetTransformEventData()}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,{target:n}=this.findTarget(t),{button:r}=t;if(r)return void((this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o,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),Ii(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&&(o=this.getScenePoint(t),f.call(d,t,s,o.x,o.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);o=o||this.getScenePoint(t),u&&u.call(c,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),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{target:i,subTargets:n}=this.findTarget(t),r={e:t,target:i,subTargets:n,...hs(this,t),transform:this._currentTransform,...e==="down:before"||e==="down"?s:{}};e!=="up:before"&&e!=="up"||(r.isClick=this._isClick),this.fire(`mouse:${e}`,r),i&&i.fire(`mouse${e}`,r);for(let o=0;o<n.length;o++)n[o]!==i&&n[o].fire(`mouse${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._handleEvent(t,"down:before");let{target:e}=this.findTarget(t),s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return void((this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}));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),Ii(t));if(e===this._activeObject&&(o||!r)){this._setupCurrentTransform(t,e,s);const l=o?o.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._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(t),this._scenePoint=os(this._viewportPoint,void 0,this.viewportTransform),this._targetInfo=this.findTarget(t),this._currentTransform&&(this._targetInfo.target=this._currentTransform.target)}__onMouseMove(t){if(this._isClick=!1,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{target:s}=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move")}_fireOverOutEvents(t,e){const{_hoveredTarget:s,_hoveredTargets:i}=this,{subTargets:n}=this.findTarget(t),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++)n[o]===e||i[o]&&i[o]===s||this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=n}_fireEnterLeaveEvents(t,e,s){const i=this._draggedoverTarget,n=this._hoveredTargets,{subTargets:r}=this.findTarget(t),o=Math.max(n.length,r.length);this.fireSyntheticInOutEvents("drag",{...s,target:e,oldTarget:i,fireCanvas:!0});for(let l=0;l<o;l++)this.fireSyntheticInOutEvents("drag",{...s,target:r[l],oldTarget:n[l]});this._draggedoverTarget=e}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r,...o}=e;const{targetIn:l,targetOut:h,canvasIn:c,canvasOut:u}=xu[t],d=i!==s;if(i&&d){const f={...o,e:r,target:i,nextTarget:s,...hs(this,r)};n&&this.fire(u,f),i.fire(h,f)}if(s&&d){const f={...o,e:r,target:s,previousTarget:i,...hs(this,r)};n&&this.fire(c,f),s.fire(l,f)}}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?os(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=rs(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const{control:r,coord:o}=n;this.setCursor(r.cursorStyleHandler(t,r,e,o))}else{if(e.subTargetCheck){const{subTargets:r}=this.findTarget(t);r.concat().reverse().forEach(o=>{s=o.hoverCursor||s})}this.setCursor(s)}}handleMultiSelection(t,e){const s=this._activeObject,i=rs(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();let r=[];if(e===s){const o=this.getScenePoint(t);let l=this.searchPossibleTargets(n,o);if(l.target?(e=l.target,r=l.subTargets):(l=this.searchPossibleTargets(this._objects,o),e=l.target,r=l.subTargets),!e||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=r,s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=r),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 S(e,s),o=r.add(new S(i,n)),l=r.min(o),h=r.max(o).subtract(l),c=this.collectObjects({left:l.x,top:l.y,width:h.x,height:h.y},{includeIntersecting:!this.selectionFullyContained}),u=r.eq(o)?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}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,e=arguments.length>1?arguments[1]:void 0;const{upper:s}=this.elements;s.ctx=void 0;const i=super.toCanvasElement(t,e);return s.ctx=s.el.getContext("2d"),i}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const ll={x1:0,y1:0,x2:0,y2:0},Su={...ll,r1:0,r2:0},Fs=(a,t)=>isNaN(a)&&typeof t=="number"?t:a;function hl(a){return a&&/%$/.test(a)&&Number.isFinite(parseFloat(a))}function cl(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(hl(a)?100:1):NaN;return ls(0,Fs(e,t),1)}const Cu=/\s*;\s*/,Au=/\s*:\s*/;function Tu(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(Cu);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[l,h]=r[o].split(Au).map(c=>c.trim());l==="stop-color"?e=h:l==="stop-opacity"&&(s=h)}}e=e||a.getAttribute("stop-color")||"rgb(0,0,0)",s=Fs(parseFloat(s||a.getAttribute("stop-opacity")||""),1);const n=new ot(e);return n.setAlpha(n.getAlpha()*s*t),{offset:cl(a.getAttribute("offset"),0),color:n.toRgba()}}function Eu(a,t){const e=[],s=a.getElementsByTagName("stop"),i=cl(t,1);for(let n=s.length;n--;)e.push(Tu(s[n],i));return e}function ul(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function dl(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function me(a,t){return a.getAttribute(t)}function ku(a,t){return(function(e,s){let i,{width:n,height:r,gradientUnits:o}=s;return Object.entries(e).reduce((l,h)=>{let[c,u]=h;if(u==="Infinity")i=1;else if(u==="-Infinity")i=0;else{const d=typeof u=="string";i=d?parseFloat(u):u,d&&hl(u)&&(i*=.01,o==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(i*=n),c!=="y1"&&c!=="y2"||(i*=r)))}return l[c]=i,l},{})})(ul(a)==="linear"?(function(e){return{x1:me(e,"x1")||0,y1:me(e,"y1")||0,x2:me(e,"x2")||"100%",y2:me(e,"y2")||0}})(a):(function(e){return{x1:me(e,"fx")||me(e,"cx")||"50%",y1:me(e,"fy")||me(e,"cy")||"50%",r1:0,x2:me(e,"cx")||"50%",y2:me(e,"cy")||"50%",r2:me(e,"r")||"50%"}})(a),{...t,gradientUnits:dl(a)})}class ci{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:l,id:h}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:{...e==="radial"?Su:ll,...i},colorStops:n,offsetX:r,offsetY:o,gradientTransform:l,id:h?`${h}_${Ve()}`:Ve()})}addColorStop(t){for(const e in t)this.colorStops.push({offset:parseFloat(e),color:t[e]});return this}toObject(t){return{...ns(this,t),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map(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():Lt.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(d=>({...d})).sort((d,f)=>d.offset-f.offset);let o=-this.offsetX,l=-this.offsetY;var h;n==="objectBoundingBox"?(o/=t.width,l/=t.height):(o+=t.width/2,l+=t.height/2),(h=t)&&typeof h._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,l-=t.pathOffset.y),i[4]-=o,i[5]-=l;const c=[`id="SVGID_${Z(String(this.id))}"`,`gradientUnits="${n}"`,`gradientTransform="${e?e+" ":""}${ks(i)}"`,""].join(" "),u=d=>parseFloat(String(d));if(this.type==="linear"){const{x1:d,y1:f,x2:g,y2:p}=this.coords,b=u(d),m=u(f),v=u(g),_=u(p);s.push("<linearGradient ",c,' x1="',b,'" y1="',m,'" x2="',v,'" y2="',_,`">
47
- `)}else if(this.type==="radial"){const{x1:d,y1:f,x2:g,y2:p,r1:b,r2:m}=this.coords,v=u(d),_=u(f),y=u(g),w=u(p),C=u(b),A=u(m),T=C>A;s.push("<radialGradient ",c,' cx="',T?v:y,'" cy="',T?_:w,'" r="',T?C:A,'" fx="',T?y:v,'" fy="',T?w:_,`">
48
- `),T&&(r.reverse(),r.forEach(L=>{L.offset=1-L.offset}));const k=Math.min(C,A);if(k>0){const L=k/Math.max(C,A);r.forEach(R=>{R.offset+=L*(1-R.offset)})}}return r.forEach(d=>{let{color:f,offset:g}=d;s.push(`<stop offset="${100*g}%" style="stop-color:${f};"/>
49
- `)}),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
50
- `),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:o}=this.coords,l=this.type==="linear"?t.createLinearGradient(e,s,i,n):t.createRadialGradient(e,s,r,i,n,o);return this.colorStops.forEach(h=>{let{color:c,offset:u}=h;l.addColorStop(u,c)}),l}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this({...t,colorStops:e?e.map(i=>({...i})):void 0,gradientTransform:s?[...s]:void 0})}static fromElement(t,e,s){const i=dl(t),n=e._findCenterFromElement();return new this({id:t.getAttribute("id")||void 0,type:ul(t),coords:ku(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:Eu(t,s.opacity),gradientUnits:i,gradientTransform:Ki(t.getAttribute("gradientTransform")||""),...i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}})}}x(ci,"type","Gradient"),I.setClass(ci,"gradient"),I.setClass(ci,"linear"),I.setClass(ci,"radial");class $r{get type(){return"pattern"}set type(t){Pe("warn","Setting type has no effect",t)}constructor(t){x(this,"repeat","repeat"),x(this,"offsetX",0),x(this,"offsetY",0),x(this,"crossOrigin",""),this.id=Ve(),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{...ns(this,t),type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:rt(this.offsetX,it.NUM_FRACTION_DIGITS),offsetY:rt(this.offsetY,it.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=Fs(this.offsetX/e,0),l=Fs(this.offsetY/s,0),h=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):Fs(i.width/e,0),c=n==="repeat-x"||n==="no-repeat"?1+Math.abs(l||0):Fs(i.height/s,0);return[`<pattern id="SVGID_${Z(r)}" x="${o}" y="${l}" width="${h}" height="${c}">`,`<image x="0" y="0" width="${i.width}" height="${i.height}" xlink:href="${Z(this.sourceToString())}"></image>`,"</pattern>",""].join(`
51
- `)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n,...r}=t;const o=await Qs(i,{...e,crossOrigin:r.crossOrigin});return new this({...r,patternTransform:n&&n.slice(0),source:o})}}x($r,"type","Pattern"),I.setClass($r),I.setClass($r,"pattern");class cs extends Mt{constructor(t){let{path:e,left:s,top:i,...n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,cs.ownDefaults),this.setOptions(n),this._setPath(t||[],!0),typeof s=="number"&&this.set(st,s),typeof i=="number"&&this.set(Wt,i)}_setPath(t,e){this.path=Ja(Array.isArray(t)?t:ol(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new S(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 (${this.complexity()}): { "top": ${this.top}, "left": ${this.left} }>`}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return{...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(){return["<path ","COMMON_PARTS",`d="${al(this.path,it.NUM_FRACTION_DIGITS)}" stroke-linecap="round" />
52
- `]}_getOffsetTransform(){const t=it.NUM_FRACTION_DIGITS;return` translate(${rt(-this.pathOffset.x,t)}, ${rt(-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,U,U)}_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(...Ir(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(...Ir(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 Se(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return{...t,pathOffset:new S(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{d:i,...n}=Ie(t,this.ATTRIBUTE_NAMES,s);return new this(i,{...n,...e,left:void 0,top:void 0})}}x(cs,"type","Path"),x(cs,"cacheProperties",[...Le,"path","fillRule"]),x(cs,"ATTRIBUTE_NAMES",[...Xe,"d"]),I.setClass(cs),I.setSVGClass(cs);const fl=["radius","startAngle","endAngle","counterClockwise"];class Ne extends Mt{static getDefaults(){return{...super.getDefaults(),...Ne.ownDefaults}}constructor(t){super(),Object.assign(this,Ne.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,gt(this.startAngle),gt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(It)}getRadiusY(){return this.get("radius")*this.get(Jt)}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([...fl,...t])}_toSVG(){const{radius:t,startAngle:e,endAngle:s}=this,i=(s-e)%360;if(i===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',`${Z(t)}`,`" />
53
- `];{const n=gt(e),r=gt(s),o=ce(n)*t,l=ue(n)*t,h=ce(r)*t,c=ue(r)*t;return[`<path d="M ${o} ${l} A ${t} ${t} 0 ${i>180?1:0} ${this.counterClockwise?0:1} ${h} ${c}" `,"COMMON_PARTS",` />
54
- `]}}static async fromElement(t,e,s){const{left:i=0,top:n=0,radius:r=0,...o}=Ie(t,this.ATTRIBUTE_NAMES,s);return new this({...o,radius:r,left:i-r,top:n-r})}static fromObject(t){return super._fromObject(t)}}x(Ne,"type","Circle"),x(Ne,"cacheProperties",[...Le,...fl]),x(Ne,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),x(Ne,"ATTRIBUTE_NAMES",["cx","cy","r",...Xe]),I.setClass(Ne),I.setSVGClass(Ne);const Hr=["x1","x2","y1","y2"];class us extends Mt{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,us.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(st,r),typeof o=="number"&&this.set(Wt,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:l}=Se([{x:t,y:e},{x:s,y:i}]),h=new S(n+o/2,r+l/2);this.setPositionByOrigin(h,U,U)}_set(t,e){return super._set(t,e),Hr.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;ne(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 S((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return{...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?-.5:.5,l=s<=i?-.5:.5;return{x1:o*n,x2:o*-n,y1:l*r,y2:l*-r}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",`x1="${t}" y1="${s}" x2="${e}" y2="${i}" />
55
- `]}static async fromElement(t,e,s){const{x1:i=0,y1:n=0,x2:r=0,y2:o=0,...l}=Ie(t,this.ATTRIBUTE_NAMES,s);return new this([i,n,r,o],l)}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n,...r}=t;return this._fromObject({...r,points:[e,s,i,n]},{extraParam:"points"})}}x(us,"type","Line"),x(us,"cacheProperties",[...Le,...Hr]),x(us,"ATTRIBUTE_NAMES",Xe.concat(Hr)),I.setClass(us),I.setSVGClass(us);class ds extends Mt{static getDefaults(){return{...super.getDefaults(),...ds.ownDefaults}}constructor(t){super(),Object.assign(this,ds.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="',`${-t} ${e},0 ${-e},${t} ${e}`,'" />']}}x(ds,"type","Triangle"),x(ds,"ownDefaults",{width:100,height:100}),I.setClass(ds),I.setSVGClass(ds);const gl=["rx","ry"];class Be extends Mt{static getDefaults(){return{...super.getDefaults(),...Be.ownDefaults}}constructor(t){super(),Object.assign(this,Be.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(It)}getRy(){return this.get("ry")*this.get(Jt)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...gl,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",`cx="0" cy="0" rx="${Z(this.rx)}" ry="${Z(this.ry)}" />
56
- `]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,he,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=Ie(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}x(Be,"type","Ellipse"),x(Be,"cacheProperties",[...Le,...gl]),x(Be,"ownDefaults",{rx:0,ry:0}),x(Be,"ATTRIBUTE_NAMES",[...Xe,"cx","cy","rx","ry"]),I.setClass(Be),I.setSVGClass(Be);const pl={exactBoundingBox:!1};class be extends Mt{static getDefaults(){return{...super.getDefaults(),...be.ownDefaults}}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),x(this,"strokeDiff",void 0),Object.assign(this,be.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(st,s),typeof i=="number"&&this.set(Wt,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return za(this.points,t,this.isOpen())}_calcDimensions(t){t={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth,...t||{}};const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(h=>h.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new S,strokeOffset:new S,strokeDiff:new S};const s=Se(e),i=Ks({...t,scaleX:1,scaleY:1}),n=Se(this.points.map(h=>kt(h,i,!0))),r=new S(this.scaleX,this.scaleY);let o=s.left+s.width/2,l=s.top+s.height/2;return this.exactBoundingBox&&(o-=l*Math.tan(gt(this.skewX)),l-=o*Math.tan(gt(this.skewY))),{...s,pathOffset:new S(o,l),strokeOffset:new S(n.left,n.top).subtract(new S(s.left,s.top)).multiply(r),strokeDiff:new S(s.width,s.height).subtract(new S(n.width,n.height)).multiply(r)}}_findCenterFromElement(){const t=Se(this.points);return new S(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:l}=this._calcDimensions();this.set({width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:l}),t&&this.setPositionByOrigin(new S(e+i/2,s+n/2),U,U)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new S(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:l}=this._calcDimensions(t);r=new S((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:l)}else{var i,n;r=new S((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new S(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===It||t===Jt)&&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{...super.toObject(t),points:this.points.map(e=>{let{x:s,y:i}=e;return{x:s,y:i}})}}_toSVG(){const t=this.pathOffset.x,e=this.pathOffset.y,s=it.NUM_FRACTION_DIGITS,i=this.points.map(n=>{let{x:r,y:o}=n;return`${rt(r-t,s)},${rt(o-e,s)}`}).join(" ");return[`<${Z(this.constructor.type).toLowerCase()} `,"COMMON_PARTS",`points="${i}" />
57
- `]}_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){const i=(function(l){if(!l)return[];const h=l.replace(/,/g," ").trim().split(/\s+/),c=[];for(let u=0;u<h.length;u+=2)c.push({x:parseFloat(h[u]),y:parseFloat(h[u+1])});return c})(t.getAttribute("points")),{left:n,top:r,...o}=Ie(t,this.ATTRIBUTE_NAMES,s);return new this(i,{...o,...e})}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}x(be,"ownDefaults",pl),x(be,"type","Polyline"),x(be,"layoutProperties",[Ss,Cs,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),x(be,"cacheProperties",[...Le,"points"]),x(be,"ATTRIBUTE_NAMES",[...Xe]),I.setClass(be),I.setSVGClass(be);class nn extends be{isOpen(){return!1}}x(nn,"ownDefaults",pl),x(nn,"type","Polygon"),I.setClass(nn),I.setSVGClass(nn);class ml extends Mt{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 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++)o+=this._textLines[l].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=lr({...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{...ns(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]}}x(ml,"_styleProperties",cc);const Mu=/ +/g,Pu=/"/g;function zr(a,t,e,s,i){return` ${(function(n,r){let{left:o,top:l,width:h,height:c}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:it.NUM_FRACTION_DIGITS;const d=ii(xt,n,!1),[f,g,p,b]=[o,l,h,c].map(m=>rt(m,u));return`<rect ${d} x="${f}" y="${g}" width="${p}" height="${b}"></rect>`})(a,{left:t,top:e,width:s,height:i})}
58
- `}let Gr;class Pt extends ml{static getDefaults(){return{...super.getDefaults(),...Pt.ownDefaults}}constructor(t,e){super(),x(this,"__charBounds",[]),Object.assign(this,Pt.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=jr(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(Ce)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,o;for(let l=0,h=this._textLines.length;l<h;l++)if((this.textAlign===Ce||l!==h-1&&!this.isEndOfWrapping(l))&&(i=0,n=this._textLines[l],e=this.getLineWidth(l),e<this.width&&(o=this.textLines[l].match(this._reSpacesAndTabs)))){s=o.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 (${this.complexity()}): { "text": "${this.text}", "fontFamily": "${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===Vt?(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 U:t.textBaseline="middle";break;case"ascender":t.textBaseline=Wt;break;case"descender":t.textBaseline=Jn}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 l=this._textLines[n].length,h=this._getLineLeftOffset(n);let c,u,d=0,f=0,g=this.getValueOfPropertyAt(n,0,"textBackgroundColor");const p=this.getHeightOfLineImpl(n);for(let b=0;b<l;b++){const m=this.__charBounds[n][b];u=this.getValueOfPropertyAt(n,b,"textBackgroundColor"),this.path?(t.save(),t.translate(m.renderLeft,m.renderTop),t.rotate(m.angle),t.fillStyle=u,u&&t.fillRect(-m.width/2,-p*(1-this._fontSizeFraction),m.width,p),t.restore()):u!==g?(c=s+h+f,this.direction===Oe&&(c=this.width-c-d),t.fillStyle=g,g&&t.fillRect(c,i,d,p),f=m.left,d=m.width,g=u):d+=m.kernedWidth}u&&!this.path&&(c=s+h+f,this.direction===Oe&&(c=this.width-c-d),t.fillStyle=u,t.fillRect(c,i,d,p)),i+=o}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=Us.getFontCache(e),r=this._getFontDeclaration(e),o=s?s+t:t,l=s&&r===this._getFontDeclaration(i),h=e.fontSize/this.CACHE_FONT_SIZE;let c,u,d,f;if(s&&n.has(s)&&(d=n.get(s)),n.has(t)&&(f=c=n.get(t)),l&&n.has(o)&&(u=n.get(o),f=u-d),c===void 0||d===void 0||u===void 0){const g=(function(){return Gr||(Gr=Zt({width:0,height:0}).getContext("2d")),Gr})();this._setTextStyles(g,e,!0),c===void 0&&(f=c=g.measureText(t).width,n.set(t,c)),d===void 0&&l&&s&&(d=g.measureText(s).width,n.set(s,d)),l&&u===void 0&&(u=g.measureText(o).width,n.set(o,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===mt,r=this.path,o=this._textLines[t],l=o.length,h=new Array(l);this.__charBounds[t]=h;for(let c=0;c<l;c++){const u=o[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 st:c=n?u-i:0;break;case U:c=(u-i)/2;break;case mt: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=nl(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===mt?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),o=i?this.getCompleteStyleDeclaration(e,s-1):{},l=this._measureChar(t,r,i,o);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}getHeightOfLineImpl(t){const e=this.__lineHeights;if(e[t])return e[t];let s=this.getHeightOfChar(t,0);for(let i=1,n=this._textLines[t].length;i<n;i++)s=Math.max(this.getHeightOfChar(t,i),s);return e[t]=s*this._fontSizeMult}getHeightOfLine(t){return this.getHeightOfLineImpl(t)*this.lineHeight}calcTextHeight(){let t=0;for(let e=0,s=this._textLines.length;e<s;e++)t+=e===s-1?this.getHeightOfLineImpl(e):this.getHeightOfLine(e);return t}_getLeftOffset(){return this.direction===ts?-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++)this._renderTextLine(e,t,this._textLines[r],i+this._getLineLeftOffset(r),n+s+this.getHeightOfLineImpl(r),r),s+=this.getHeightOfLine(r);t.restore()}_renderTextFill(t){(this.fill||this.styleHas(xt))&&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.textAlign.includes(Ce),l=this.path,h=!o&&this.charSpacing===0&&this.isEmptyStyles(r)&&!l,c=this.direction===ts,u=this.direction===ts?1:-1,d=e.direction;let f,g,p,b,m,v="",_=0;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",c?ts:Oe),e.direction=c?ts:Oe,e.textAlign=c?st:mt),n-=this.getHeightOfLineImpl(r)*this._fontSizeFraction,h)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let y=0,w=s.length-1;y<=w;y++)b=y===w||this.charSpacing||l,v+=s[y],p=this.__charBounds[r][y],_===0?(i+=u*(p.kernedWidth-p.width),_+=p.width):_+=p.kernedWidth,o&&!b&&this._reSpaceAndTab.test(s[y])&&(b=!0),b||(f=f||this.getCompleteStyleDeclaration(r,y),g=this.getCompleteStyleDeclaration(r,y+1),b=qi(f,g,!1)),b&&(l?(e.save(),e.translate(p.renderLeft,p.renderTop),e.rotate(p.angle),this._renderChar(t,e,r,y,v,-_/2,0),e.restore()):(m=i,this._renderChar(t,e,r,y,v,m,n)),v="",f=g,i+=u*_,_=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=Zt({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 ne(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 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&&(o+=l.deltaY),c){const d=this._setFillStyles(e,h);e.fillText(n,r-d.offsetX,o-d.offsetY)}if(u){const d=this._setStrokeStyles(e,h);e.strokeText(n,r-d.offsetX,o-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"),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===Ce||i===ri&&!r||i===ni&&!r||i===Vi&&!r?0:(i===U&&(o=s/2),i===mt&&(o=s),i===ri&&(o=s/2),i===ni&&(o=s),n===Oe&&(i===mt||i===ni?o=0:i===st||i===Vi?o=-s:i!==U&&i!==ri||(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,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,b=0,m=this.getValueOfPropertyAt(h,0,e),v=this.getValueOfPropertyAt(h,0,xt),_=this.getValueOfPropertyAt(h,0,as),y=m,w=v,C=_;const A=s+f*(1-this._fontSizeFraction);let T=this.getHeightOfChar(h,0),k=this.getValueOfPropertyAt(h,0,"deltaY");for(let F=0,P=d.length;F<P;F++){const O=this.__charBounds[h][F];y=this.getValueOfPropertyAt(h,F,e),w=this.getValueOfPropertyAt(h,F,xt),C=this.getValueOfPropertyAt(h,F,as);const $=this.getHeightOfChar(h,F),M=this.getValueOfPropertyAt(h,F,"deltaY");if(n&&y&&w){const D=this.fontSize*C/1e3;t.save(),t.fillStyle=v,t.translate(O.renderLeft,O.renderTop),t.rotate(O.angle),t.fillRect(-O.kernedWidth/2,l*$+M-o*D,O.kernedWidth,D),t.restore()}else if((y!==m||w!==v||$!==T||C!==_||M!==k)&&b>0){const D=this.fontSize*_/1e3;let V=i+g+p;this.direction===Oe&&(V=this.width-V-b),m&&v&&_&&(t.fillStyle=v,t.fillRect(V,A+l*T+k-o*D,b,D)),p=O.left,b=O.width,m=y,_=C,v=w,T=$,k=M}else b+=O.kernedWidth}let L=i+g+p;this.direction===Oe&&(L=this.width-L-b),t.fillStyle=w;const R=this.fontSize*C/1e3;y&&w&&C&&t.fillRect(L,A+l*T+k-o*R,b-r,R),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(",")||Pt.genericFonts.includes(t.toLowerCase())?t:`"${t}"`;return[e,s,`${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 Fi(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
59
- `];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{...super.toObject([...wa,...t]),styles:Ga(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=Ie(t,Pt.ATTRIBUTE_NAMES,s),{textAnchor:n=st,textDecoration:r="",dx:o=0,dy:l=0,top:h=0,left:c=0,fontSize:u=Qn,strokeWidth:d=1,...f}={...e,...i},g=new this(zi(t.textContent||"").trim(),{left:c+o,top:h+l,underline:r.includes("underline"),overline:r.includes("overline"),linethrough:r.includes("line-through"),strokeWidth:0,fontSize:u,...f}),p=g.getScaledHeight()/g.height,b=((g.height+g.strokeWidth)*g.lineHeight-g.height)*p,m=g.getScaledHeight()+b;let v=0;return n===U&&(v=g.getScaledWidth()/2),n===mt&&(v=g.getScaledWidth()),g.set({left:g.left-v,top:g.top-(m-g.fontSize*(.07+g._fontSizeFraction))/g.lineHeight,strokeWidth:d}),g}static fromObject(t){return this._fromObject({...t,styles:Wa(t.styles||{},t.text)},{extraParam:"text"})}}x(Pt,"textLayoutProperties",_a),x(Pt,"cacheProperties",[...Le,...wa]),x(Pt,"ownDefaults",uc),x(Pt,"type","Text"),x(Pt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),x(Pt,"ATTRIBUTE_NAMES",Xe.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Na(Pt,[class extends ba{_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:ks(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="${Z(this.fontFamily.replace(Pu,"'"))}" `,`font-size="${Z(this.fontSize)}" `,this.fontStyle?`font-style="${Z(this.fontStyle)}" `:"",this.fontWeight?`font-weight="${Z(this.fontWeight)}" `:"",s?`text-decoration="${s}" `:"",this.direction==="rtl"?'direction="rtl" ':"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
60
- `]}_getSVGTextAndBg(a,t){const e=[],s=[];let i,n=a;this.backgroundColor&&s.push(zr(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=it.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,a!==a.trim()||!!a.match(Mu)),o=r?`style="${r}"`:"",l=t.deltaY,h=l?` dy="${rt(l,n)}" `:"",{angle:c,renderLeft:u,renderTop:d,width:f}=i;let g="";if(u!==void 0){const p=f/2;c&&(g=` rotate="${rt(De(c),n)}"`);const b=is({angle:De(c)});b[4]=u,b[5]=d;const m=new S(-p,0).transform(b);e=m.x,s=m.y}return`<tspan x="${rt(e,n)}" y="${rt(s,n)}" ${h}${g}${o}>${Z(a)}</tspan>`}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Ce),r=this._textLines[t];let o,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||(o=o||this.getCompleteStyleDeclaration(t,g),l=this.getCompleteStyleDeclaration(t,g+1),u=qi(o,l,!0)),u&&(c=this._getStyleDeclaration(t,g),a.push(this._createTextCharSpan(d,c,e,s,h)),d="",o=l,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(a,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,o=0,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&&a.push(zr(h,e+l,s,o,n)),l=u,o=d,h=r):o+=f}r&&a.push(zr(h,e+l,s,o,n))}getSvgStyles(a){return`${super.getSvgStyles(a)} text-decoration-thickness: ${rt(this.textDecorationThickness*this.getObjectScaling().y/10,it.NUM_FRACTION_DIGITS)}%; white-space: pre;`}getSvgSpanStyles(a,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:o,fontWeight:l,textDecorationThickness:h,linethrough:c,overline:u,underline:d}=a,f=this.getSvgTextDecoration({underline:d??this.underline,overline:u??this.overline,linethrough:c??this.linethrough}),g=h||this.textDecorationThickness;return[i?ii(Vt,i):"",s?`stroke-width: ${Z(s)}; `:"",e?`font-family: ${e.includes("'")||e.includes('"')?Z(e):`'${Z(e)}'`}; `:"",r?`font-size: ${Z(r)}px; `:"",o?`font-style: ${Z(o)}; `:"",l?`font-weight: ${Z(l)}; `:"",f?`text-decoration: ${f}; text-decoration-thickness: ${rt(g*this.getObjectScaling().y/10,it.NUM_FRACTION_DIGITS)}%; `:"",n?ii(xt,n):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter(t=>a[t.replace("-","")]).join(" ")}}]),I.setClass(Pt),I.setSVGClass(Pt);class Ou{constructor(t){x(this,"target",void 0),x(this,"__mouseDownInPlace",!1),x(this,"__dragStartFired",!1),x(this,"__isDraggingOver",!1),x(this,"__dragStartSelection",void 0),x(this,"__dragImageDisposer",void 0),x(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,l=new S(r.flipX?-1:1,r.flipY?-1:1),h=r._getCursorBoundaries(i),c=new S(h.left+h.leftOffset,h.top+h.topOffset).multiply(l).transform(r.calcTransformMatrix()),u=o.getScenePoint(t).subtract(c),d=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),g=c.subtract(new S(f.left,f.top)),p=o.viewportTransform,b=g.add(u).transform(p,!0),m=r.backgroundColor,v=Pr(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 y=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=m,r.styles=v,r.dirty=!0,Nr(y,{position:"fixed",left:-y.width+"px",border:Ft,width:y.width/d+"px",height:y.height/d+"px"}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{y.remove()},de(t.target||this.target.hiddenTextarea).body.appendChild(y),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(y,b.x,b.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={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 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),o.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(ki,{index:l+u,action:"drop"}),o.fire("text:changed",{target:r}),o.contextTopDirty=!0,o.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:o}=this.__dragStartSelection,l=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||Ft;l===Ft?(i.selectionStart=r,i.selectionEnd=o,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),l==="move"&&(i.removeChars(r,o),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(ki,{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 bl=/[ \n\.,;!\?\-]/;class Du extends Pt{constructor(){super(...arguments),x(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 Er({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||!Zn.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!bl.test(n);)i+=e,n=s[i];return e===-1&&bl.test(n)&&i++,i}selectWord(t){t=t??this.selectionStart;const e=this.searchWordBoundary(t,-1),s=Math.max(e,this.searchWordBoundary(t,1));this.selectionStart=e,this.selectionEnd=s,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){t=t??this.selectionStart;const e=this.findLineBoundaryLeft(t),s=this.findLineBoundaryRight(t);this.selectionStart=e,this.selectionEnd=s,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;de(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(){const{hiddenTextarea:t,direction:e,textAlign:s,inCompositionMode:i}=this;if(!t)return;const n=s!==Ce?s.replace("justify-",""):e===ts?st:mt,r=this.getPositionByOrigin(n,"top");this.cursorOffsetCache={},this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setPositionByOrigin(r,n,"top"),this.setCoords();const o=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=o.selectionEnd,i||(this.selectionStart=o.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,l=this.getCanvasRetinaScaling(),h=this.canvas.upperCanvasEl,c=h.width/l,u=h.height/l,d=c-r,f=u-r,g=new S(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new S(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:`${g.x}px`,top:`${g.y}px`,fontSize:`${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)}exitEditingImpl(){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(),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(Pi),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 l=this.styles[n][o];l&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=l)}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],l=r-i;for(let h=i;h<r;h++)delete o[h];for(const h in this.styles[s]){const c=parseInt(h,10);c>=r&&(o[c-l]=o[h],delete o[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,o=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],o&&e===0||delete this.styles[t][u])}let c=!1;for(l&&!o&&(this.styles[t+s]=n,c=!0),(c||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:{...i[s-1]}}:h?this.styles[t+s]={0:{...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?{...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]={...i[s]});return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]={...o}}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let l=0;l<t.length;l++)t[l]===`
61
- `?(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=st:this._selectionDirection===mt&&(this._selectionDirection=st,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===mt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=mt:this._selectionDirection===st&&(this._selectionDirection=mt,this.selectionStart=e),this.selectionEnd=s)}}class Ru extends Du{initHiddenTextarea(){const t=this.canvas&&de(this.canvas.getElement())||xs(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off",name:"fabricTextarea"}).map(r=>{let[o,l]=r;return e.setAttribute(o,l)});const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText=`position: absolute; top: ${s}; left: ${i}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${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,l]=r;return e.addEventListener(o,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(ki),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,l=this._text.length,h=o.length,c=this.selectionStart,u=this.selectionEnd,d=c!==u;let f,g,p,b,m=h-l;const v=this.fromStringToGraphemeSelection(i,n,s),_=c>v.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 y=o.slice(v.selectionEnd-m,v.selectionEnd);if(g&&g.length&&(y.length&&(f=this.getSelectionStyles(c,c+1,!1),f=y.map(()=>f[0])),d?(p=c,b=u):_?(p=u-g.length,b=u):(p=u,b=u+g.length),this.removeStyleFromTo(p,b)),y.length){const{copyPasteData:w}=we();e&&y.join("")===w.copiedText&&!it.disableStyleCopyPaste&&(f=w.copiedTextStyle),this.insertNewStyleBlock(y,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}=we();t.copiedText=this.getSelectedText(),it.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),l=this._getIndexOnLine(n+1,o);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,o=this._getWidthBeforeCursor(n,r),l=this._getIndexOnLine(n-1,o),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),o=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);o=Math.abs(u-e)<d?l:l-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${t}CursorOffset`](e,this._selectionDirection===mt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=ls(0,this.selectionStart,i),this.selectionEnd=ls(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===st?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${s}`](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this[`findLineBoundary${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=st,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===mt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=st,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${t}${e.shiftKey?"WithShift":"WithoutShift"}`;this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===st&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=mt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=mt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const vl=a=>!!a.button;class Lu extends Ru{constructor(){super(...arguments),x(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 Ou(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&&!vl(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||vl(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(Xt(this.calcTransformMatrix())).add(new S(-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 o=this._textLines[n].length,l=this.__charBounds[n];for(let h=0;h<o;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?o-i:i,this._text.length)}}const rn="moveCursorUp",on="moveCursorDown",an="moveCursorLeft",ln="moveCursorRight",hn="exitEditing",yl=(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])},Fu={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:hn,27:hn,33:rn,34:on,35:ln,36:an,37:an,38:rn,39:ln,40:on},keysMapRtl:{9:hn,27:hn,33:rn,34:on,35:an,36:ln,37:ln,38:rn,39:an,40:on},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"},_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1};class $e extends Lu{static getDefaults(){return{...super.getDefaults(),...$e.ownDefaults}}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,{...$e.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 Br&&this.canvas.textEditingManager.remove(this),e instanceof Br&&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=Zt(t.canvas),r=n.getContext("2d"),yl(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 l=o.clipPath,h=Zt(t.canvas),c=h.getContext("2d");if(yl(c,this.canvas),!l.absolutePositioned){const u=o.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),{textAlign:r,direction:o}=this;for(let u=0;u<n;u++)e+=this.getHeightOfLine(u);const l=this._getLineLeftOffset(n),h=this.__charBounds[n][i];h&&(s=h.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());let c=l+(s>0?s:0);return o===Oe&&(r===mt||r===Ce||r===ni?c*=-1:r===st||r===Vi?c=l-(s>0?s:0):r!==U&&r!==ri||(c=l-(s>0?s:0))),{top:e,left:c}}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(),l=this.cursorWidth/o,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:o,width:l,height:h}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,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{textAlign:i,direction:n}=this,r=e.selectionStart,o=e.selectionEnd,l=i.includes(Ce),h=this.get2DCursorLocation(r),c=this.get2DCursorLocation(o),u=h.lineIndex,d=c.lineIndex,f=h.charIndex<0?0:h.charIndex,g=c.charIndex<0?0:c.charIndex;for(let p=u;p<=d;p++){const b=this._getLineLeftOffset(p)||0;let m=this.getHeightOfLine(p),v=0,_=0,y=0;if(p===u&&(_=this.__charBounds[u][f].left),p>=u&&p<d)y=l&&!this.isEndOfWrapping(p)?this.width:this.getLineWidth(p)||5;else if(p===d)if(g===0)y=this.__charBounds[d][g].left;else{const k=this._getWidthOfCharSpacing();y=this.__charBounds[d][g-1].left+this.__charBounds[d][g-1].width-k}v=m,(this.lineHeight<1||p===d&&this.lineHeight>1)&&(m/=this.lineHeight);let w=s.left+b+_,C=m,A=0;const T=y-_;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",C=1,A=m):t.fillStyle=this.selectionColor,n===Oe&&(i===mt||i===Ce||i===ni?w=this.width-w-T:i===st||i===Vi?w=s.left+b-y:i!==U&&i!==ri||(w=s.left+b-y)),t.fillRect(w,s.top+s.topOffset+A,T,C),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,xt)}_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()}}x($e,"ownDefaults",Fu),x($e,"type","IText"),I.setClass($e),I.setClass($e,"i-text");class fs extends $e{static getDefaults(){return{...super.getDefaults(),...fs.ownDefaults}}constructor(t,e){super(t,{...fs.ownDefaults,...e})}static createControls(){return{controls:Bc()}}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(Ce)&&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]===`
62
- `&&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 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 o=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,o);return i=Math.max(u,i),o+=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,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(),l=this.splitByGrapheme,h=[],c=l?"":" ";let u=0,d=[],f=0,g=0,p=!0;e-=r;const b=Math.max(e,i,this.dynamicMinWidth),m=n[t];let v;for(f=0,v=0;v<m.length;v++){const{word:_,width:y}=m[v];f+=_.length,u+=g+y-o,u>b&&!p?(h.push(d),d=[],u=y,p=!0):u+=o,p||l||d.push(c),d=d.concat(_),g=l?0:this._measureWord([c],t,f),f++,p=!1}return v&&h.push(d),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+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(`${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])}}x(fs,"type","Textbox"),x(fs,"textLayoutProperties",[...$e.textLayoutProperties,"width"]),x(fs,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),I.setClass(fs);class _l extends Zi{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}=Se(Ua(s,i)),l=new S(r,o);if(i.absolutePositioned)return{center:os(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 S,correction:u=new S}=this.calcBoundingBox(e,t)||{};return{center:c.add(h),correction:u.subtract(h),size:l}}return{center:s.getRelativeCenterPoint().add(h),size:l}}}}x(_l,"type","clip-path"),I.setClass(_l);class wl extends Zi{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new S(s.width||i.x,s.height||i.y)}}x(wl,"type","fixed"),I.setClass(wl);class Iu extends li{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 gs extends te{static getDefaults(){return{...super.getDefaults(),...gs.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,gs.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new Iu})}_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))?(Pe("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===Rr?s.forEach(i=>{i._onAfterObjectsChange(Qi,e)}):s.forEach(i=>{i._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return`#<ActiveSelection: (${this.complexity()})>`}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i={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()}}x(gs,"type","ActiveSelection"),x(gs,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),I.setClass(gs),I.setClass(gs,"activeSelection");class ju{constructor(){x(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d",{willReadFrequently:!0,desynchronized:!0});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(h=>{h.applyTo(o)});const{imageData:l}=o;return l.width===s&&l.height===i||(n.width=l.width,n.height=l.height),r.putImageData(l,0,0),o}}class xl{constructor(){let{tileSize:t=it.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};x(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),x(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=Zt({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,l=n.getContext("2d");if(!o||!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:o,sourceTexture:this.createTexture(o,s,i,h?void 0:e),targetTexture:this.createTexture(o,s,i),originalTexture:h||this.createTexture(o,s,i,h?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),t.forEach(d=>{d&&d.applyTo(c)}),(function(d){const f=d.targetCanvas,g=f.width,p=f.height,b=d.destinationWidth,m=d.destinationHeight;g===b&&p===m||(f.width=b,f.height=m)})(c),this.copyGLTo2D(o,c),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(c.sourceTexture),o.deleteTexture(c.targetTexture),o.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:o,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(o,p),t.texParameteri(o,u,n||r),t.texParameteri(o,d,n||r),t.texParameteri(o,f,c),t.texParameteri(o,g,c),i?t.texImage2D(o,0,l,l,h,i):t.texImage2D(o,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 o=new Uint8Array(this.imageBuffer,0,r),l=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,o);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 Wr;function Nu(){const{WebGLProbe:a}=we();return a.queryWebGL(xe()),it.enableGLFiltering&&a.isSupported(it.textureSize)?new xl({tileSize:it.textureSize}):new ju}function Vr(){return!Wr&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(Wr=Nu()),Wr}const Sl=["cropX","cropY"];class Ut extends Mt{static getDefaults(){return{...super.getDefaults(),...Ut.ownDefaults}}constructor(t,e){super(),x(this,"_lastScaleX",1),x(this,"_lastScaleY",1),x(this,"_filterScalingX",1),x(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Ut.ownDefaults),this.setOptions(e),this.cacheKey=`texture${Ve()}`,this.setElement(typeof t=="string"?(this.canvas&&de(this.canvas.getElement())||xs()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._element=t,this._originalElement=t,this._setWidthHeight(e),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=Vr(!1);e instanceof xl&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{const e=this[t];e&&we().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())}),{...super.toObject([...Sl,...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="",l="";if(!e)return[];if(this.hasCrop()){const h=Ve();n.push('<clipPath id="imageCrop_'+h+`">
63
- `,' <rect x="'+s+'" y="'+i+'" width="'+Z(this.width)+'" height="'+Z(this.height)+`" />
8
+ `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),`</defs>
9
+ `)}createSVGClipPathMarkup(e){let t=this.clipPath;return t?(t.clipPathId=`CLIPPATH_${Pe()}`,`<clipPath id="${t.clipPathId}" >\n${t.toClipPathSVG(e.reviver)}</clipPath>\n`):``}createSVGRefElementsMarkup(){return[`background`,`overlay`].map(e=>{let t=this[`${e}Color`];if(ut(t)){let n=this[`${e}Vpt`],r=this.viewportTransform,i={isType:()=>!1,width:this.width/(n?r[0]:1),height:this.height/(n?r[3]:1)};return t.toSVG(i,{additionalTransform:n?lt(r):``})}}).join(``)}createSVGFontFacesMarkup(){let e=[],t={},n=h.fontPaths;this._objects.forEach(function t(n){e.push(n),Oe(n)&&n._objects.forEach(t)}),e.forEach(e=>{if(!(r=e)||typeof r._renderText!=`function`)return;var r;let{styles:i,fontFamily:a}=e;!t[a]&&n[a]&&(t[a]=!0,i&&Object.values(i).forEach(e=>{Object.values(e).forEach(({fontFamily:e=``})=>{!t[e]&&n[e]&&(t[e]=!0)})}))});let r=Object.keys(t).map(e=>`\t\t@font-face {\n\t\t\tfont-family: '${e}';\n\t\t\tsrc: url('${n[e]}');\n\t\t}\n`).join(``);return r?`\t<style type="text/css"><![CDATA[\n${r}]]></style>\n`:``}_setSVGObjects(e,t){this.forEachObject(n=>{n.excludeFromExport||this._setSVGObject(e,n,t)})}_setSVGObject(e,t,n){e.push(t.toSVG(n))}_setSVGBgOverlayImage(e,t,n){let r=this[t];r&&!r.excludeFromExport&&r.toSVG&&e.push(r.toSVG(n))}_setSVGBgOverlayColor(e,t){let n=this[`${t}Color`];if(n){if(ut(n)){let r=n.repeat||``,i=this.width,a=this.height,o=this[`${t}Vpt`]?lt(We(this.viewportTransform)):``;e.push(`<rect transform="${o} translate(${i/2},${a/2})" x="${n.offsetX-i/2}" y="${n.offsetY-a/2}" width="${r!==`repeat-y`&&r!==`no-repeat`||!ft(n)?i:n.source.width}" height="${r!==`repeat-x`&&r!==`no-repeat`||!ft(n)?a:n.source.height}" fill="url(#SVGID_${n.id})"></rect>\n`)}else e.push(`<rect x="0" y="0" width="100%" height="100%" `,`fill="`,n,`"`,`></rect>
10
+ `)}}loadFromJSON(e,t,{signal:n}={}){if(!e)return Promise.reject(new _("`json` is undefined"));let{objects:r=[],...i}=typeof e==`string`?JSON.parse(e):e,{backgroundImage:a,background:o,overlayImage:s,overlay:c,clipPath:l}=i,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([at(r,{reviver:t,signal:n}),ot({backgroundImage:a,backgroundColor:o,overlayImage:s,overlayColor:c,clipPath:l},{signal:n})]).then(([e,t])=>(this.clear(),this.add(...e),this.set(i),this.set(t),this.renderOnAddRemove=u,this))}clone(e){let t=this.toObject(e);return this.cloneWithoutData().loadFromJSON(t)}cloneWithoutData(){let e=Re(this);return new this.constructor(e)}toDataURL(e={}){let{format:t=`png`,quality:n=1,multiplier:r=1,enableRetinaScaling:i=!1}=e,a=r*(i?this.getRetinaScaling():1);return ze(this.toCanvasElement(a,e),t,n)}toBlob(e={}){let{format:t=`png`,quality:n=1,multiplier:r=1,enableRetinaScaling:i=!1}=e,a=r*(i?this.getRetinaScaling():1);return Be(this.toCanvasElement(a,e),t,n)}toCanvasElement(e=1,{width:t,height:n,left:r,top:i,filter:a}={}){let o=(t||this.width)*e,s=(n||this.height)*e,c=this.getZoom(),l=this.width,u=this.height,d=this.skipControlsDrawing,f=c*e,p=this.viewportTransform,m=[f,0,0,f,(p[4]-(r||0))*e,(p[5]-(i||0))*e],h=this.enableRetinaScaling,g=Re({width:o,height:s}),_=a?this._objects.filter(e=>a(e)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=s,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(g.getContext(`2d`),_),this.viewportTransform=p,this.width=l,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=h,this.skipControlsDrawing=d,g}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Se.cancelByCanvas(this),this.disposed=!0,new Promise((e,t)=>{let n=()=>{this.destroy(),e(!0)};n.kill=t,this.__cleanupTask&&this.__cleanupTask.kill(`aborted`),this.destroyed?e(!1):this.nextRenderHandle?this.__cleanupTask=n:n()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(e=>e.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 (${this.complexity()}): { objects: ${this._objects.length} }>`}};p(Ot,`ownDefaults`,xt);var kt=[`touchstart`,`touchmove`,`touchend`],At=e=>{let t=mt(e.target),n=function(e){let t=e.changedTouches;return t&&t[0]?t[0]:e}(e);return new R(n.clientX+t.left,n.clientY+t.top)},jt=e=>kt.includes(e.type)||e.pointerType===`touch`,Mt=e=>{e.preventDefault(),e.stopPropagation()},Nt=e=>{let t=0,n=0,r=0,i=0;for(let a=0,o=e.length;a<o;a++){let{x:o,y:s}=e[a];(o>r||!a)&&(r=o),(o<t||!a)&&(t=o),(s>i||!a)&&(i=s),(s<n||!a)&&(n=s)}return{left:t,top:n,width:r-t,height:i-n}},Pt=(e,t)=>{It(e,B(We(t),e.calcOwnMatrix()))},Ft=(e,t)=>It(e,B(t,e.calcOwnMatrix())),It=(e,t)=>{let{translateX:n,translateY:r,scaleX:i,scaleY:a,...o}=Ye(t),s=new R(n,r);e.flipX=!1,e.flipY=!1,Object.assign(e,o),e.set({scaleX:i,scaleY:a}),e.setPositionByOrigin(s,P,P)},Lt=e=>{e.scaleX=1,e.scaleY=1,e.skewX=0,e.skewY=0,e.flipX=!1,e.flipY=!1,e.rotate(0)},Rt=e=>({scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,angle:e.angle,left:e.left,flipX:e.flipX,flipY:e.flipY,top:e.top}),zt=(e,t,n)=>{let r=e/2,i=t/2,a=Nt([new R(-r,-i),new R(r,-i),new R(-r,i),new R(r,i)].map(e=>e.transform(n)));return new R(a.width,a.height)},Bt=(e=N,t=N)=>B(We(t),e),Vt=(e,t=N,n=N)=>e.transform(Bt(t,n)),Ht=(e,t=N,n=N)=>e.transform(Bt(t,n),!0),Ut=(e,t,n)=>{let r=Bt(t,n);return It(e,B(r,e.calcOwnMatrix())),r},Wt={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Gt=e=>typeof e==`string`?Wt[e]:e-.5,Kt=new R(1,0),qt=new R,Jt=(e,t)=>e.rotate(t),Yt=(e,t)=>new R(t).subtract(e),Xt=e=>e.distanceFrom(qt),Zt=(e,t)=>Math.atan2(tn(e,t),nn(e,t)),Qt=e=>Zt(Kt,e),$t=e=>e.eq(qt)?e:e.scalarDivide(Xt(e)),en=(e,t=!0)=>$t(new R(-e.y,e.x).scalarMultiply(t?1:-1)),tn=(e,t)=>e.x*t.y-e.y*t.x,nn=(e,t)=>e.x*t.x+e.y*t.y,rn=(e,t,n)=>{if(e.eq(t)||e.eq(n))return!0;let r=tn(t,n),i=tn(t,e),a=tn(n,e);return r>=0?i>=0&&a<=0:!(i<=0&&a>=0)},an=`not-allowed`;function on(e){return Gt(e.originX)===Gt(`center`)&&Gt(e.originY)===Gt(`center`)}function sn(e){return .5-Gt(e)}var cn=(e,t)=>e[t],ln=(e,t,n,r)=>({e,transform:t,pointer:new R(n,r)});function un(e,t,n){let r=n,i=Qt(Yt(Vt(e.getCenterPoint(),e.canvas.viewportTransform,void 0),r))+M;return Math.round(i%M/j)}function dn({target:e,corner:t},n,r,i,a){let o=e.controls[t],s=e.canvas?.getZoom()||1,c=e.padding/s,l=function(e,t,n,r){let i=e.getRelativeCenterPoint(),a=n!==void 0&&r!==void 0?e.translateToGivenOrigin(i,P,P,n,r):new R(e.left,e.top);return(e.angle?t.rotate(-z(e.angle),i):t).subtract(a)}(e,new R(i,a),n,r);return l.x>=c&&(l.x-=c),l.x<=-c&&(l.x+=c),l.y>=c&&(l.y-=c),l.y<=c&&(l.y+=c),l.x-=o.offsetX,l.y-=o.offsetY,l}var fn=new RegExp(String.raw`[\0-\x1F\x7F;<>\\]|\/\*|\*\/|url\s*\(|expression\s*\(|(?:java|vb)script\s*:|data\s*:|@import\b`,`iu`),pn=e=>typeof e==`string`&&e.trim().length>0&&!fn.test(e),mn=(e,t=``)=>{let n=Number(e);return Number.isFinite(n)?`${n}`:t},hn=(e,t=``)=>typeof e==`string`&&pn(e)?e:t,gn=e=>e.replace(/\s+/g,` `),_n={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`},vn=(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e),yn=(e,t,n,r)=>{e/=255,t/=255,n/=255;let i=Math.max(e,t,n),a=Math.min(e,t,n),o,s,c=(i+a)/2;if(i===a)o=s=0;else{let r=i-a;switch(s=c>.5?r/(2-i-a):r/(i+a),i){case e:o=(t-n)/r+(t<n?6:0);break;case t:o=(n-e)/r+2;break;case n:o=(e-t)/r+4}o/=6}return[Math.round(360*o),Math.round(100*s),Math.round(100*c),r]},bn=(e=`1`)=>parseFloat(e)/(e.endsWith(`%`)?100:1),xn=e=>Math.min(Math.round(e),255).toString(16).toUpperCase().padStart(2,`0`),Sn=([e,t,n,r=1])=>{let i=Math.round(.3*e+.59*t+.11*n);return[i,i,i,r]},Cn=class e{constructor(t){if(p(this,`isUnrecognised`,!1),t){if(t instanceof e)this.setSource([...t._source]);else if(Array.isArray(t)){let[e,n,r,i=1]=t;this.setSource([e,n,r,i])}else this.setSource(this._tryParsingColor(t))}else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in _n&&(t=_n[t]),t===`transparent`?[255,255,255,0]:e.sourceFromHex(t)||e.sourceFromRgb(t)||e.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(e){this._source=e}toRgb(){let[e,t,n]=this.getSource();return`rgb(${e},${t},${n})`}toRgba(){return`rgba(${this.getSource().join(`,`)})`}toHsl(){let[e,t,n]=yn(...this.getSource());return`hsl(${e},${t}%,${n}%)`}toHsla(){let[e,t,n,r]=yn(...this.getSource());return`hsla(${e},${t}%,${n}%,${r})`}toHex(){return this.toHexa().slice(0,6)}toHexa(){let[e,t,n,r]=this.getSource();return`${xn(e)}${xn(t)}${xn(n)}${xn(Math.round(255*r))}`}getAlpha(){return this.getSource()[3]}setAlpha(e){return this._source[3]=e,this}toGrayscale(){return this.setSource(Sn(this.getSource())),this}toBlackWhite(e){let[t,,,n]=Sn(this.getSource()),r=t<(e||127)?0:255;return this.setSource([r,r,r,n]),this}overlayWith(t){t instanceof e||(t=new e(t));let n=this.getSource(),r=t.getSource(),[i,a,o]=n.map((e,t)=>Math.round(.5*e+.5*r[t]));return this.setSource([i,a,o,n[3]]),this}static fromRgb(t){return e.fromRgba(t)}static fromRgba(t){return new e(e.sourceFromRgb(t))}static sourceFromRgb(e){let t=gn(e).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(t){let[e,n,r]=t.slice(1,4).map(e=>{let t=parseFloat(e);return e.endsWith(`%`)?Math.round(2.55*t):t});return[e,n,r,bn(t[4])]}}static fromHsl(t){return e.fromHsla(t)}static fromHsla(t){return new e(e.sourceFromHsl(t))}static sourceFromHsl(t){let n=gn(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(!n)return;let r=(e.parseAngletoDegrees(n[1])%360+360)%360/360,i=parseFloat(n[2])/100,a=parseFloat(n[3])/100,o,s,c;if(i===0)o=s=c=a;else{let e=a<=.5?a*(i+1):a+i-a*i,t=2*a-e;o=vn(t,e,r+1/3),s=vn(t,e,r),c=vn(t,e,r-1/3)}return[Math.round(255*o),Math.round(255*s),Math.round(255*c),bn(n[4])]}static fromHex(t){return new e(e.sourceFromHex(t))}static sourceFromHex(e){if(e.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){let t=e.slice(e.indexOf(`#`)+1),n;n=t.length<=4?t.split(``).map(e=>e+e):t.match(/.{2}/g);let[r,i,a,o=255]=n.map(e=>parseInt(e,16));return[r,i,a,o/255]}}static parseAngletoDegrees(e){let t=e.toLowerCase(),n=parseFloat(t);return t.includes(`rad`)?Ve(n):t.includes(`turn`)?360*n:n}},wn=e=>{let t=[`instantiated_by_use`,`style`,`id`,`class`];switch(e){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},Tn=(e,t=16)=>{let n=/\D{0,2}$/.exec(e),r=parseFloat(e),i=h.DPI;switch(n?.[0]){case`mm`:return r*i/25.4;case`cm`:return r*i/2.54;case`in`:return r*i;case`pt`:return r*i/72;case`pc`:return r*i/72*12;case`em`:return r*t;default:return r}},En=e=>{let[t,n]=e.trim().split(` `),[r,i]=(a=t)&&a!==`none`?[a.slice(1,4),a.slice(5,8)]:a===`none`?[a,a]:[`Mid`,`Mid`];var a;return{meetOrSlice:n||`meet`,alignX:r,alignY:i}},Dn=(e,t,n=!0)=>{let r,i;if(t){if(t.toLive)r=`url(#SVGID_${H(t.id)})`;else{let e=String(t);if(pn(e)){let t=new Cn(e),n=t.getAlpha();r=t.toRgb(),n!==1&&(i=n.toString())}else r=new Cn(`black`).toRgb()}}else r=`none`;return n?`${e}: ${r}; ${i?`${e}-opacity: ${i}; `:``}`:`${e}="${r}" ${i?`${e}-opacity="${i}" `:``}`},On=class{getSvgStyles(e){let t=this.fillRule==null?`nonzero`:hn(this.fillRule),n=this.strokeWidth==null?`0`:mn(this.strokeWidth),r=this.strokeDashArray==null?ne:this.strokeDashArray.every(e=>Number.isFinite(Number(e)))?this.strokeDashArray.join(` `):``,i=this.strokeDashOffset==null?`0`:mn(this.strokeDashOffset),a=this.strokeLineCap==null?`butt`:hn(this.strokeLineCap),o=this.strokeLineJoin==null?`miter`:hn(this.strokeLineJoin),s=this.strokeMiterLimit==null?`4`:mn(this.strokeMiterLimit),c=this.opacity==null?`1`:mn(this.opacity),l=this.visible?``:` visibility: hidden;`,u=e?``:this.getSvgFilter(),d=Dn(_e,this.fill);return[Dn(ve,this.stroke),n?`stroke-width: ${n}; `:``,r?`stroke-dasharray: ${r}; `:``,a?`stroke-linecap: ${a}; `:``,i?`stroke-dashoffset: ${i}; `:``,o?`stroke-linejoin: ${o}; `:``,s?`stroke-miterlimit: ${s}; `:``,d,t?`fill-rule: ${t}; `:``,c?`opacity: ${c};`:``,u,l].map(e=>H(e)).join(``)}getSvgFilter(){return this.shadow?`filter: url(#SVGID_${H(this.shadow.id)});`:``}getSvgCommons(){return[this.id?`id="${H(String(this.id))}" `:``,this.clipPath?`clip-path="url(#${H(this.clipPath.clipPathId)})" `:``].join(``)}getSvgTransform(e,t=``){return`transform="${lt(e?this.calcTransformMatrix():this.calcOwnMatrix())}${t}" `}_toSVG(e){return[``]}toSVG(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})}toClipPathSVG(e){return` `+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})}_createBaseClipPathSVGMarkup(e,{reviver:t,additionalTransform:n=``}={}){let r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(``),i=e.indexOf(`COMMON_PARTS`);return e[i]=r,t?t(e.join(``)):e.join(``)}_createBaseSVGMarkup(e,{noStyle:t,reviver:n,withShadow:r,additionalTransform:i}={}){let a=t?``:`style="${this.getSvgStyles()}" `,o=r?`style="${this.getSvgFilter()}" `:``,s=this.clipPath,c=this.strokeUniform?`vector-effect="non-scaling-stroke" `:``,l=s&&s.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,p=[],m=e.indexOf(`COMMON_PARTS`),h;return s&&(s.clipPathId=`CLIPPATH_${Pe()}`,h=`<clipPath id="${s.clipPathId}" >\n${s.toClipPathSVG(n)}</clipPath>\n`),l&&p.push(`<g `,o,this.getSvgCommons(),` >
11
+ `),p.push(`<g `,this.getSvgTransform(!1),l?``:o+this.getSvgCommons(),` >
12
+ `),e[m]=[a,c,t?``:this.addPaintOrder(),` `,i?`transform="${i}" `:``].join(``),ut(d)&&p.push(d.toSVG(this)),ut(u)&&p.push(u.toSVG(this)),f&&p.push(f.toSVG(this)),s&&p.push(h),p.push(e.join(``)),p.push(`</g>
13
+ `),l&&p.push(`</g>
14
+ `),n?n(p.join(``)):p.join(``)}addPaintOrder(){return this.paintFirst===`fill`?``:` paint-order="${H(this.paintFirst)}" `}};function kn(e){return RegExp(`^(`+e.join(`|`)+`)\\b`,`i`)}var An=`textDecorationThickness`,jn=`textDecorationColor`,Mn=[`fontSize`,`fontWeight`,`fontFamily`,`fontStyle`],Nn=[`underline`,`overline`,`linethrough`],Pn=[...Mn,`lineHeight`,`text`,`charSpacing`,`textAlign`,`styles`,`path`,`pathStartOffset`,`pathSide`,`pathAlign`],Fn=[...Pn,...Nn,`textBackgroundColor`,`direction`,An,jn],In=[...Mn,...Nn,ve,`strokeWidth`,_e,`deltaY`,`textBackgroundColor`,An,jn],Ln={_reNewline:re,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:be,fontFamily:`Times New Roman`,underline:!1,overline:!1,linethrough:!1,textAlign:F,fontStyle:be,lineHeight:1.16,textBackgroundColor:``,stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:F,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,[An]:66.667},Rn=`justify`,zn=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,Bn=String.raw`(?:\s*,?\s+|\s*,\s*)`,Vn=`http://www.w3.org/2000/svg`,Hn=RegExp(`(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(`+zn+`(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|`+zn+`))?\\s+(.*)`),Un={cx:F,x:F,r:`radius`,cy:`top`,y:`top`,display:`visible`,visibility:`visible`,transform:`transformMatrix`,"fill-opacity":`fillOpacity`,"fill-rule":`fillRule`,"font-family":`fontFamily`,"font-size":`fontSize`,"font-style":`fontStyle`,"font-weight":`fontWeight`,"letter-spacing":`charSpacing`,"paint-order":`paintFirst`,"stroke-dasharray":`strokeDashArray`,"stroke-dashoffset":`strokeDashOffset`,"stroke-linecap":`strokeLineCap`,"stroke-linejoin":`strokeLineJoin`,"stroke-miterlimit":`strokeMiterLimit`,"stroke-opacity":`strokeOpacity`,"stroke-width":`strokeWidth`,"text-decoration":`textDecoration`,"text-anchor":`textAnchor`,opacity:`opacity`,"clip-path":`clipPath`,"clip-rule":`clipRule`,"vector-effect":`strokeUniform`,"image-rendering":`imageSmoothing`,"text-decoration-thickness":An,"text-decoration-color":jn},Wn=`font-size`,Gn=`clip-path`,Kn=kn([`path`,`circle`,`polygon`,`polyline`,`ellipse`,`rect`,`line`,`image`,`text`]),qn=kn([`symbol`,`image`,`marker`,`pattern`,`view`,`svg`]),Jn=kn([`symbol`,`g`,`a`,`svg`,`clipPath`,`defs`]),Yn=new RegExp(String.raw`^\s*(${zn})${Bn}(${zn})${Bn}(${zn})${Bn}(${zn})\s*$`),Xn=`(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?`,Zn=RegExp(`(?:\\s|^)`+Xn+Xn+`(`+zn+`?(?:px)?)?(?:\\s?|$)(?:$|\\s)`),Qn=class e{constructor(t={}){let n=typeof t==`string`?e.parseShadow(t):t;Object.assign(this,e.ownDefaults,n),this.id=Pe()}static parseShadow(e){let t=e.trim(),[,n=0,r=0,i=0]=(Zn.exec(t)||[]).map(e=>parseFloat(e)||0);return{color:(t.replace(Zn,``)||`rgb(0,0,0)`).trim(),offsetX:n,offsetY:r,blur:i}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join(`px `)}toSVG(e){let t=Jt(new R(this.offsetX,this.offsetY),z(-e.angle)),n=h.NUM_FRACTION_DIGITS,r=new Cn(this.color),i=40,a=40;return e.width&&e.height&&(i=100*V((Math.abs(t.x)+this.blur)/e.width,n)+20,a=100*V((Math.abs(t.y)+this.blur)/e.height,n)+20),e.flipX&&(t.x*=-1),e.flipY&&(t.y*=-1),`<filter id="SVGID_${H(this.id)}" y="-${a}%" height="${100+2*a}%" x="-${i}%" width="${100+2*i}%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="${V(this.blur?this.blur/2:0,n)}"></feGaussianBlur>\n\t<feOffset dx="${V(t.x,n)}" dy="${V(t.y,n)}" result="oBlur" ></feOffset>\n\t<feFlood flood-color="${r.toRgb()}" flood-opacity="${r.getAlpha()}"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n`}toObject(){let t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},n=e.ownDefaults;return this.includeDefaultValues?t:ct(t,(e,t)=>e!==n[t])}static async fromObject(e){return new this(e)}};p(Qn,`ownDefaults`,{color:`rgb(0,0,0)`,blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),p(Qn,`type`,`shadow`),L.setClass(Qn,`shadow`);var $n=(e,t,n)=>Math.max(e,Math.min(t,n)),er=[`top`,F,pe,me,`flipX`,`flipY`,`originX`,`originY`,`angle`,`opacity`,`globalCompositeOperation`,`shadow`,`visible`,he,ge],tr=[_e,ve,`strokeWidth`,`strokeDashArray`,`width`,`height`,`paintFirst`,`strokeUniform`,`strokeLineCap`,`strokeDashOffset`,`strokeLineJoin`,`strokeMiterLimit`,`backgroundColor`,`clipPath`],nr={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:P,originY:P,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:_e,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},rr=u({defaultEasing:()=>or,easeInBack:()=>Or,easeInBounce:()=>Mr,easeInCirc:()=>Sr,easeInCubic:()=>sr,easeInElastic:()=>Tr,easeInExpo:()=>yr,easeInOutBack:()=>Ar,easeInOutBounce:()=>Nr,easeInOutCirc:()=>wr,easeInOutCubic:()=>lr,easeInOutElastic:()=>Dr,easeInOutExpo:()=>xr,easeInOutQuad:()=>Ir,easeInOutQuart:()=>fr,easeInOutQuint:()=>hr,easeInOutSine:()=>vr,easeInQuad:()=>Pr,easeInQuart:()=>ur,easeInQuint:()=>pr,easeInSine:()=>gr,easeOutBack:()=>kr,easeOutBounce:()=>jr,easeOutCirc:()=>Cr,easeOutCubic:()=>cr,easeOutElastic:()=>Er,easeOutExpo:()=>br,easeOutQuad:()=>Fr,easeOutQuart:()=>dr,easeOutQuint:()=>mr,easeOutSine:()=>_r}),ir=(e,t,n,r)=>(e<Math.abs(t)?(e=t,r=n/4):r=t===0&&e===0?n/M*Math.asin(1):n/M*Math.asin(t/e),{a:e,c:t,p:n,s:r}),ar=(e,t,n,r,i)=>e*2**(10*--r)*Math.sin((r*i-t)*M/n),or=(e,t,n,r)=>-n*Math.cos(e/r*A)+n+t,sr=(e,t,n,r)=>n*(e/r)**3+t,cr=(e,t,n,r)=>n*((e/r-1)**3+1)+t,lr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**3+t:n/2*((e-2)**3+2)+t,ur=(e,t,n,r)=>n*(e/=r)*e**3+t,dr=(e,t,n,r)=>-n*((e=e/r-1)*e**3-1)+t,fr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**4+t:-n/2*((e-=2)*e**3-2)+t,pr=(e,t,n,r)=>n*(e/r)**5+t,mr=(e,t,n,r)=>n*((e/r-1)**5+1)+t,hr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**5+t:n/2*((e-2)**5+2)+t,gr=(e,t,n,r)=>-n*Math.cos(e/r*A)+n+t,_r=(e,t,n,r)=>n*Math.sin(e/r*A)+t,vr=(e,t,n,r)=>-n/2*(Math.cos(Math.PI*e/r)-1)+t,yr=(e,t,n,r)=>e===0?t:n*2**(10*(e/r-1))+t,br=(e,t,n,r)=>e===r?t+n:n*-(2**(-10*e/r)+1)+t,xr=(e,t,n,r)=>e===0?t:e===r?t+n:(e/=r/2)<1?n/2*2**(10*(e-1))+t:n/2*-(2**(-10*(e-1))+2)+t,Sr=(e,t,n,r)=>-n*(Math.sqrt(1-(e/=r)*e)-1)+t,Cr=(e,t,n,r)=>n*Math.sqrt(1-(e=e/r-1)*e)+t,wr=(e,t,n,r)=>(e/=r/2)<1?-n/2*(Math.sqrt(1-e**2)-1)+t:n/2*(Math.sqrt(1-(e-=2)*e)+1)+t,Tr=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r)===1)return t+n;a||=.3*r;let{a:o,s,p:c}=ir(i,n,a,1.70158);return-ar(o,s,c,e,r)+t},Er=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r)===1)return t+n;a||=.3*r;let{a:o,s,p:c,c:l}=ir(i,n,a,1.70158);return o*2**(-10*e)*Math.sin((e*r-s)*M/c)+l+t},Dr=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r/2)==2)return t+n;a||=.3*1.5*r;let{a:o,s,p:c,c:l}=ir(i,n,a,1.70158);return e<1?-.5*ar(o,s,c,e,r)+t:o*2**(-10*--e)*Math.sin((e*r-s)*M/c)*.5+l+t},Or=(e,t,n,r,i=1.70158)=>n*(e/=r)*e*((i+1)*e-i)+t,kr=(e,t,n,r,i=1.70158)=>n*((e=e/r-1)*e*((i+1)*e+i)+1)+t,Ar=(e,t,n,r,i=1.70158)=>(e/=r/2)<1?n/2*(e*e*((1+(i*=1.525))*e-i))+t:n/2*((e-=2)*e*((1+(i*=1.525))*e+i)+2)+t,jr=(e,t,n,r)=>(e/=r)<1/2.75?n*(7.5625*e*e)+t:e<2/2.75?n*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?n*(7.5625*(e-=2.25/2.75)*e+.9375)+t:n*(7.5625*(e-=2.625/2.75)*e+.984375)+t,Mr=(e,t,n,r)=>n-jr(r-e,0,n,r)+t,Nr=(e,t,n,r)=>e<r/2?.5*Mr(2*e,0,n,r)+t:.5*jr(2*e-r,0,n,r)+.5*n+t,Pr=(e,t,n,r)=>n*(e/=r)*e+t,Fr=(e,t,n,r)=>-n*(e/=r)*(e-2)+t,Ir=(e,t,n,r)=>(e/=r/2)<1?n/2*e**2+t:-n/2*(--e*(e-2)-1)+t,Lr=()=>!1,Rr=class{constructor({startValue:e,byValue:t,duration:n=500,delay:r=0,easing:i=or,onStart:a=k,onChange:o=k,onComplete:s=k,abort:c=Lr,target:l}){p(this,`_state`,`pending`),p(this,`durationProgress`,0),p(this,`valueProgress`,0),this.tick=this.tick.bind(this),this.duration=n,this.delay=r,this.easing=i,this._onStart=a,this._onChange=o,this._onComplete=s,this._abort=c,this.target=l,this.startValue=e,this.byValue=t,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(){let e=e=>{this._state===`pending`&&(this.startTime=e||+new Date,this._state=`running`,this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?this.timeout=T().setTimeout(()=>je(e),this.delay):je(e)}tick(e){let t=(e||+new Date)-this.startTime,n=Math.min(t,this.duration);this.durationProgress=n/this.duration;let{value:r,valueProgress:i}=this.calculate(n);this.value=Object.freeze(r),this.valueProgress=i,this._state!==`aborted`&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state=`aborted`,this.unregister()):t>=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.timeout=null):(this._onChange(this.value,this.valueProgress,this.durationProgress),je(this.tick)))}register(){Se.push(this)}unregister(){Se.remove(this)}abort(){this._state=`aborted`,this.unregister(),this.timeout&&T().clearTimeout(this.timeout)}},zr=class extends Rr{constructor({startValue:e=0,endValue:t=100,...n}){super({...n,startValue:e,byValue:t-e})}calculate(e){let t=this.easing(e,this.startValue,this.byValue,this.duration);return{value:t,valueProgress:Math.abs((t-this.startValue)/this.byValue)}}},Br=class extends Rr{constructor({startValue:e=[0],endValue:t=[100],...n}){super({...n,startValue:e,byValue:t.map((t,n)=>t-e[n])})}calculate(e){let t=this.startValue.map((t,n)=>this.easing(e,t,this.byValue[n],this.duration,n));return{value:t,valueProgress:Math.abs((t[0]-this.startValue[0])/this.byValue[0])}}},Vr=(e,t,n,r)=>t+n*(1-Math.cos(e/r*A)),Hr=e=>e&&((t,n,r)=>e(new Cn(t).toRgba(),n,r)),Ur=class extends Rr{constructor({startValue:e,endValue:t,easing:n=Vr,onChange:r,onComplete:i,abort:a,...o}){let s=new Cn(e).getSource(),c=new Cn(t).getSource();super({...o,startValue:s,byValue:c.map((e,t)=>e-s[t]),easing:n,onChange:Hr(r),onComplete:Hr(i),abort:Hr(a)})}calculate(e){let[t,n,r,i]=this.startValue.map((t,n)=>this.easing(e,t,this.byValue[n],this.duration,n)),a=[...[t,n,r].map(Math.round),$n(0,i,1)];return{value:a,valueProgress:a.map((e,t)=>this.byValue[t]===0?0:Math.abs((e-this.startValue[t])/this.byValue[t])).find(e=>e!==0)||0}}};function Wr(e){let t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(e)?new Br(e):new zr(e);return t.start(),t}function Gr(e){let t=new Ur(e);return t.start(),t}var Kr=class e{constructor(e){this.status=e,this.points=[]}includes(e){return this.points.some(t=>t.eq(e))}append(...e){return this.points=this.points.concat(e.filter(e=>!this.includes(e))),this}static isPointContained(e,t,n,r=!1){if(t.eq(n))return e.eq(t);if(t.x===n.x)return e.x===t.x&&(r||e.y>=Math.min(t.y,n.y)&&e.y<=Math.max(t.y,n.y));if(t.y===n.y)return e.y===t.y&&(r||e.x>=Math.min(t.x,n.x)&&e.x<=Math.max(t.x,n.x));{let i=Yt(t,n),a=Yt(t,e).divide(i);return r?Math.abs(a.x)===Math.abs(a.y):a.x===a.y&&a.x>=0&&a.x<=1}}static isPointInPolygon(e,t){let n=new R(e).setX(Math.min(e.x-1,...t.map(e=>e.x))),r=0;for(let i=0;i<t.length;i++){let a=this.intersectSegmentSegment(t[i],t[(i+1)%t.length],e,n);if(a.includes(e))return!0;r+=Number(a.status===`Intersection`)}return r%2==1}static intersectLineLine(t,n,r,i,a=!0,o=!0){let s=n.x-t.x,c=n.y-t.y,l=i.x-r.x,u=i.y-r.y,d=t.x-r.x,f=t.y-r.y,p=l*f-u*d,m=s*f-c*d,h=u*s-l*c;if(h!==0){let n=p/h,r=m/h;return(a||0<=n&&n<=1)&&(o||0<=r&&r<=1)?new e(`Intersection`).append(new R(t.x+n*s,t.y+n*c)):new e}return new e(p===0||m===0?a||o||e.isPointContained(t,r,i)||e.isPointContained(n,r,i)||e.isPointContained(r,t,n)||e.isPointContained(i,t,n)?`Coincident`:void 0:`Parallel`)}static intersectSegmentLine(t,n,r,i){return e.intersectLineLine(t,n,r,i,!1,!0)}static intersectSegmentSegment(t,n,r,i){return e.intersectLineLine(t,n,r,i,!1,!1)}static intersectLinePolygon(t,n,r,i=!0){let a=new e,o=r.length;for(let s,c,l,u=0;u<o;u++){if(s=r[u],c=r[(u+1)%o],l=e.intersectLineLine(t,n,s,c,i,!1),l.status===`Coincident`)return l;a.append(...l.points)}return a.points.length>0&&(a.status=`Intersection`),a}static intersectSegmentPolygon(t,n,r){return e.intersectLinePolygon(t,n,r,!1)}static intersectPolygonPolygon(t,n){let r=new e,i=t.length,a=[];for(let o=0;o<i;o++){let s=t[o],c=t[(o+1)%i],l=e.intersectSegmentPolygon(s,c,n);l.status===`Coincident`?(a.push(l),r.append(s,c)):r.append(...l.points)}return a.length>0&&a.length===t.length?new e(`Coincident`):(r.points.length>0&&(r.status=`Intersection`),r)}static intersectPolygonRectangle(t,n,r){let i=n.min(r),a=n.max(r),o=new R(a.x,i.y),s=new R(i.x,a.y);return e.intersectPolygonPolygon(t,[i,o,a,s])}},qr=class extends Ae{getX(){return this.getXY().x}setX(e){this.setXY(this.getXY().setX(e))}getY(){return this.getXY().y}setY(e){this.setXY(this.getXY().setY(e))}getRelativeX(){return this.left}setRelativeX(e){this.left=e}getRelativeY(){return this.top}setRelativeY(e){this.top=e}getXY(){let e=this.getRelativeXY();return this.group?Ue(e,this.group.calcTransformMatrix()):e}setXY(e,t,n){this.group&&(e=Ue(e,We(this.group.calcTransformMatrix()))),this.setRelativeXY(e,t,n)}getRelativeXY(){return new R(this.left,this.top)}setRelativeXY(e,t=this.originX,n=this.originY){this.setPositionByOrigin(e,t,n)}isStrokeAccountedForInDimensions(){return!1}getCoords(){let{tl:e,tr:t,br:n,bl:r}=this.aCoords||=this.calcACoords(),i=[e,t,n,r];if(this.group){let e=this.group.calcTransformMatrix();return i.map(t=>Ue(t,e))}return i}intersectsWithRect(e,t){return Kr.intersectPolygonRectangle(this.getCoords(),e,t).status===`Intersection`}intersectsWithObject(e){let t=Kr.intersectPolygonPolygon(this.getCoords(),e.getCoords());return t.status===`Intersection`||t.status===`Coincident`||e.isContainedWithinObject(this)||this.isContainedWithinObject(e)}isContainedWithinObject(e){return this.getCoords().every(t=>e.containsPoint(t))}isContainedWithinRect(e,t){let{left:n,top:r,width:i,height:a}=this.getBoundingRect();return n>=e.x&&n+i<=t.x&&r>=e.y&&r+a<=t.y}isOverlapping(e){return this.intersectsWithObject(e)||this.isContainedWithinObject(e)||e.isContainedWithinObject(this)}containsPoint(e){return Kr.isPointInPolygon(e,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;let{tl:e,br:t}=this.canvas.vptCoords;return!!this.getCoords().some(n=>n.x<=t.x&&n.x>=e.x&&n.y<=t.y&&n.y>=e.y)||!!this.intersectsWithRect(e,t)||this.containsPoint(e.midPointFrom(t))}isPartiallyOnScreen(){if(!this.canvas)return!1;let{tl:e,br:t}=this.canvas.vptCoords;return!!this.intersectsWithRect(e,t)||this.getCoords().every(n=>(n.x>=t.x||n.x<=e.x)&&(n.y>=t.y||n.y<=e.y))&&this.containsPoint(e.midPointFrom(t))}getBoundingRect(){return Nt(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(e){this._set(pe,e),this._set(me,e),this.setCoords()}scaleToWidth(e){let t=this.getBoundingRect().width/this.getScaledWidth();return this.scale(e/this.width/t)}scaleToHeight(e){let t=this.getBoundingRect().height/this.getScaledHeight();return this.scale(e/this.height/t)}getCanvasRetinaScaling(){return this.canvas?.getRetinaScaling()||1}getTotalAngle(){return this.group?Ve(Ke(this.calcTransformMatrix())):this.angle}getViewportTransform(){return this.canvas?.viewportTransform||N.concat()}calcACoords(){let e=Ze({angle:this.angle}),{x:t,y:n}=this.getRelativeCenterPoint(),r=B(Xe(t,n),e),i=this._getTransformedDimensions(),a=i.x/2,o=i.y/2;return{tl:Ue({x:-a,y:-o},r),tr:Ue({x:a,y:-o},r),bl:Ue({x:-a,y:o},r),br:Ue({x:a,y:o},r)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(e=!1){let t=[];return!e&&this.group&&(t=this.group.transformMatrixKey(e)),t.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,Gt(this.originX),Gt(this.originY)),t}calcTransformMatrix(e=!1){let t=this.calcOwnMatrix();if(e||!this.group)return t;let n=this.transformMatrixKey(e),r=this.matrixCache;return r&&r.key.every((e,t)=>e===n[t])?r.value:(this.group&&(t=B(this.group.calcTransformMatrix(!1),t)),this.matrixCache={key:n,value:t},t)}calcOwnMatrix(){let e=this.transformMatrixKey(!0),t=this.ownMatrixCache;if(t&&t.key.every((t,n)=>t===e[n]))return t.value;let n=this.getRelativeCenterPoint(),r=rt({angle:this.angle,translateX:n.x,translateY:n.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY});return this.ownMatrixCache={key:e,value:r},r}_getNonTransformedDimensions(){return new R(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(e){let t=this.canvas?.viewportTransform,n=this._getTransformedDimensions(e);return t?n.multiply(new R(qe(t),Je(t))).scalarAdd(2*this.padding):n.scalarAdd(2*this.padding)}_getTransformedDimensions(e={}){let t={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth,...e},n=t.strokeWidth,r=n,i=0;this.strokeUniform&&(r=0,i=n);let a=t.width+r,o=t.height+r,s;return s=t.skewX===0&&t.skewY===0?new R(a*t.scaleX,o*t.scaleY):zt(a,o,nt(t)),s.scalarAdd(i)}translateToGivenOrigin(e,t,n,r,i){let a=e.x,o=e.y,s=Gt(r)-Gt(t),c=Gt(i)-Gt(n);if(s||c){let e=this._getTransformedDimensions();a+=s*e.x,o+=c*e.y}return new R(a,o)}translateToCenterPoint(e,t,n){if(t===`center`&&n===`center`)return e;let r=this.translateToGivenOrigin(e,t,n,P,P);return this.angle?r.rotate(z(this.angle),e):r}translateToOriginPoint(e,t,n){let r=this.translateToGivenOrigin(e,P,P,t,n);return this.angle?r.rotate(z(this.angle),e):r}getCenterPoint(){let e=this.getRelativeCenterPoint();return this.group?Ue(e,this.group.calcTransformMatrix()):e}getRelativeCenterPoint(){return this.translateToCenterPoint(new R(this.left,this.top),this.originX,this.originY)}getPointByOrigin(e,t){return this.getPositionByOrigin(e,t)}getPositionByOrigin(e,t){return this.translateToOriginPoint(this.getRelativeCenterPoint(),e,t)}setPositionByOrigin(e,t,n){let r=this.translateToCenterPoint(e,t,n),i=this.translateToOriginPoint(r,this.originX,this.originY);this.set({left:i.x,top:i.y})}_getLeftTopCoords(){return this.getPositionByOrigin(F,`top`)}positionByLeftTop(e){return this.setPositionByOrigin(e,F,`top`)}},Jr=class e extends qr{static getDefaults(){return e.ownDefaults}get type(){let e=this.constructor.type;return e===`FabricObject`?`object`:e.toLowerCase()}set type(e){g(`warn`,`Setting type has no effect`,e)}constructor(t){super(),p(this,`_cacheContext`,null),Object.assign(this,e.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Fe(),this._cacheContext=this._cacheCanvas.getContext(`2d`),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(e){let t=e.width,n=e.height,r=h.maxCacheSideLimit,i=h.minCacheSideLimit;if(t<=r&&n<=r&&t*n<=h.perfLimitSizeTotal)return t<i&&(e.width=i),n<i&&(e.height=i),e;let a=t/n,[o,s]=D.limitDimsByArea(a),c=$n(i,o,r),l=$n(i,s,r);return t>c&&(e.zoomX/=t/c,e.width=c,e.capped=!0),n>l&&(e.zoomY/=n/l,e.height=l,e.capped=!0),e}_getCacheCanvasDimensions(){let e=this.getTotalObjectScaling(),t=this._getTransformedDimensions({skewX:0,skewY:0}),n=t.x*e.x/this.scaleX,r=t.y*e.y/this.scaleY;return{width:Math.ceil(n+2),height:Math.ceil(r+2),zoomX:e.x,zoomY:e.y,x:n,y:r}}_updateCacheCanvas(){let e=this._cacheCanvas,t=this._cacheContext,{width:n,height:r,zoomX:i,zoomY:a,x:o,y:s}=this._limitCacheSize(this._getCacheCanvasDimensions()),c=n!==e.width||r!==e.height,l=this.zoomX!==i||this.zoomY!==a;if(!e||!t)return!1;if(c||l){n!==e.width||r!==e.height?(e.width=n,e.height=r):(t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,e.width,e.height));let c=o/2,l=s/2;return this.cacheTranslationX=Math.round(e.width/2-c)+c,this.cacheTranslationY=Math.round(e.height/2-l)+l,t.translate(this.cacheTranslationX,this.cacheTranslationY),t.scale(i,a),this.zoomX=i,this.zoomY=a,!0}return!1}setOptions(e={}){this._setOptions(e)}transform(e){let t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,n=this.calcTransformMatrix(!t);e.transform(n[0],n[1],n[2],n[3],n[4],n[5])}getObjectScaling(){if(!this.group)return new R(Math.abs(this.scaleX),Math.abs(this.scaleY));let e=Ye(this.calcTransformMatrix());return new R(Math.abs(e.scaleX),Math.abs(e.scaleY))}getTotalObjectScaling(){let e=this.getObjectScaling();if(this.canvas){let t=this.canvas.getZoom(),n=this.getCanvasRetinaScaling();return e.scalarMultiply(t*n)}return e}getObjectOpacity(){let e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e}_constrainScale(e){return Math.abs(e)<this.minScaleLimit?e<0?-this.minScaleLimit:this.minScaleLimit:e===0?1e-4:e}_set(e,t){e!==`scaleX`&&e!==`scaleY`||(t=this._constrainScale(t)),e===`scaleX`&&t<0?(this.flipX=!this.flipX,t*=-1):e===`scaleY`&&t<0?(this.flipY=!this.flipY,t*=-1):e!==`shadow`||!t||t instanceof Qn||(t=new Qn(t));let n=this[e]!==t;return this[e]=t,n&&this.constructor.cacheProperties.includes(e)&&(this.dirty=!0),this.parent&&(this.dirty||n&&this.constructor.stateProperties.includes(e))&&this.parent._set(`dirty`,!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.drawObject(e,!1,{}),this.dirty=!1),e.restore())}drawSelectionBackground(e){}renderCache(e){if(e||={},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){let{zoomX:t,zoomY:n,cacheTranslationX:r,cacheTranslationY:i}=this,{width:a,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,e.forClipping,{zoomX:t,zoomY:n,cacheTranslationX:r,cacheTranslationY:i,width:a,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===`stroke`&&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(e,t,n){e.save(),e.globalCompositeOperation=t.inverted?`destination-out`:`destination-in`,e.setTransform(1,0,0,1,0,0),e.drawImage(n,0,0),e.restore()}drawObject(e,t,n){let r=this.fill,i=this.stroke;t?(this.fill=`black`,this.stroke=``,this._setClippingProperties(e)):this._renderBackground(e),this.fire(`before:render`,{ctx:e}),this._render(e),this._drawClipPath(e,this.clipPath,n),this.fill=r,this.stroke=i}createClipPathLayer(e,t){let n=Re(t),r=n.getContext(`2d`);if(r.translate(t.cacheTranslationX,t.cacheTranslationY),r.scale(t.zoomX,t.zoomY),e._cacheCanvas=n,t.parentClipPaths.forEach(e=>{e.transform(r)}),t.parentClipPaths.push(e),e.absolutePositioned){let e=We(this.calcTransformMatrix());r.transform(e[0],e[1],e[2],e[3],e[4],e[5])}return e.transform(r),e.drawObject(r,!0,t),n}_drawClipPath(e,t,n){if(!t)return;t._transformDone=!0;let r=this.createClipPathLayer(t,n);this.drawClipPathOnCache(e,t,r)}drawCacheOnCanvas(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(e=!1){if(this.isNotVisible())return!1;let t=this._cacheCanvas,n=this._cacheContext;return!(!t||!n||e||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(t&&n&&!e&&(n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,t.width,t.height),n.restore()),!0)}_renderBackground(e){if(!this.backgroundColor)return;let t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}_setOpacity(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity}_setStrokeStyles(e,t){let n=t.stroke;n&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,ut(n)?n.gradientUnits===`percentage`||n.gradientTransform||n.patternTransform?this._applyPatternForTransformedGradient(e,n):(e.strokeStyle=n.toLive(e),this._applyPatternGradientTransform(e,n)):e.strokeStyle=t.stroke)}_setFillStyles(e,{fill:t}){t&&(ut(t)?(e.fillStyle=t.toLive(e),this._applyPatternGradientTransform(e,t)):e.fillStyle=t)}_setClippingProperties(e){e.globalAlpha=1,e.strokeStyle=`transparent`,e.fillStyle=`#000000`}_setLineDash(e,t){t&&t.length!==0&&e.setLineDash(t)}_setShadow(e){if(!this.shadow)return;let t=this.shadow,n=this.canvas,r=this.getCanvasRetinaScaling(),[i,,,a]=n?.viewportTransform||N,o=i*r,s=a*r,c=t.nonScaling?new R(1,1):this.getObjectScaling();e.shadowColor=t.color,e.shadowBlur=t.blur*h.browserShadowBlurConstant*(o+s)*(c.x+c.y)/4,e.shadowOffsetX=t.offsetX*o*c.x,e.shadowOffsetY=t.offsetY*s*c.y}_removeShadow(e){this.shadow&&(e.shadowColor=``,e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)}_applyPatternGradientTransform(e,t){if(!ut(t))return{offsetX:0,offsetY:0};let n=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,i=-this.height/2+t.offsetY||0;return t.gradientUnits===`percentage`?e.transform(this.width,0,0,this.height,r,i):e.transform(1,0,0,1,r,i),n&&e.transform(n[0],n[1],n[2],n[3],n[4],n[5]),{offsetX:r,offsetY:i}}_renderPaintInOrder(e){this.paintFirst===`stroke`?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))}_render(e){}_renderFill(e){this.fill&&(e.save(),this._setFillStyles(e,this),this.fillRule===`evenodd`?e.fill(`evenodd`):e.fill(),e.restore())}_renderStroke(e){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform){let t=this.getObjectScaling();e.scale(1/t.x,1/t.y)}this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}}_applyPatternForTransformedGradient(e,t){let n=this._limitCacheSize(this._getCacheCanvasDimensions()),r=this.getCanvasRetinaScaling(),i=n.x/this.scaleX/r,a=n.y/this.scaleY/r,o=Re({width:Math.ceil(i),height:Math.ceil(a)}),s=o.getContext(`2d`);s&&(s.beginPath(),s.moveTo(0,0),s.lineTo(i,0),s.lineTo(i,a),s.lineTo(0,a),s.closePath(),s.translate(i/2,a/2),s.scale(n.zoomX/this.scaleX/r,n.zoomY/this.scaleY/r),this._applyPatternGradientTransform(s,t),s.fillStyle=t.toLive(e),s.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(r*this.scaleX/n.zoomX,r*this.scaleY/n.zoomY),e.strokeStyle=s.createPattern(o,`no-repeat`)??``)}_findCenterFromElement(){return new R(this.left+this.width/2,this.top+this.height/2)}clone(e){let t=this.toObject(e);return this.constructor.fromObject(t)}cloneAsImage(e){let t=this.toCanvasElement(e);return new(L.getClass(`image`))(t)}toCanvasElement(e={}){let t=Rt(this),n=this.group,r=this.shadow,i=Math.abs,a=e.enableRetinaScaling?E():1,o=(e.multiplier||1)*a,s=e.canvasProvider||(e=>new Ot(e,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,e.withoutTransform&&Lt(this),e.withoutShadow&&(this.shadow=null),e.viewportTransform&&Ut(this,this.getViewportTransform()),this.setCoords();let c=Fe(),l=this.getBoundingRect(),u=this.shadow,d=new R;if(u){let e=u.blur,t=u.nonScaling?new R(1,1):this.getObjectScaling();d.x=2*Math.round(i(u.offsetX)+e)*i(t.x),d.y=2*Math.round(i(u.offsetY)+e)*i(t.y)}let f=l.width+d.x,p=l.height+d.y;c.width=Math.ceil(f),c.height=Math.ceil(p);let m=s(c);e.format===`jpeg`&&(m.backgroundColor=`#fff`),this.setPositionByOrigin(new R(m.width/2,m.height/2),P,P);let h=this.canvas;m._objects=[this],this.set(`canvas`,m),this.setCoords();let g=m.toCanvasElement(o||1,e);return this.set(`canvas`,h),this.shadow=r,n&&(this.group=n),this.set(t),this.setCoords(),m._objects=[],m.destroy(),g}toDataURL(e={}){return ze(this.toCanvasElement(e),e.format||`png`,e.quality||1)}toBlob(e={}){return Be(this.toCanvasElement(e),e.format||`png`,e.quality||1)}isType(...e){return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(e){let{centeredRotation:t,originX:n,originY:r}=this;if(t){let{x:e,y:t}=this.getRelativeCenterPoint();this.originX=P,this.originY=P,this.left=e,this.top=t}if(this.set(`angle`,e),t){let{x:e,y:t}=this.getPositionByOrigin(n,r);this.left=e,this.top=t,this.originX=n,this.originY=r}}setOnGroup(){}_setupCompositeOperation(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Se.cancelByTarget(this),this.off(),this._set(`canvas`,void 0),this._cacheCanvas&&C().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(e,t){return Object.entries(e).reduce((e,[n,r])=>(e[n]=this._animate(n,r,t),e),{})}_animate(e,t,n={}){let r=e.split(`.`),i=this.constructor.colorProperties.includes(r[r.length-1]),{abort:a,startValue:o,onChange:s,onComplete:c}=n,l={...n,target:this,startValue:o??r.reduce((e,t)=>e[t],this),endValue:t,abort:a?.bind(this),onChange:(e,t,n)=>{r.reduce((t,n,i)=>(i===r.length-1&&(t[n]=e),t[n]),this),s&&s(e,t,n)},onComplete:(e,t,n)=>{this.setCoords(),c&&c(e,t,n)}};return i?Gr(l):Wr(l)}isDescendantOf(e){let{parent:t,group:n}=this;return t===e||n===e||!!t&&t.isDescendantOf(e)||!!n&&n!==t&&n.isDescendantOf(e)}getAncestors(){let e=[],t=this;do t=t.parent,t&&e.push(t);while(t);return e}findCommonAncestors(e){if(this===e)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};let t=this.getAncestors(),n=e.getAncestors();if(t.length===0&&n.length>0&&this===n[n.length-1])return{fork:[],otherFork:[e,...n.slice(0,n.length-1)],common:[this]};for(let r,i=0;i<t.length;i++){if(r=t[i],r===e)return{fork:[this,...t.slice(0,i)],otherFork:[],common:t.slice(i)};for(let a=0;a<n.length;a++){if(this===n[a])return{fork:[],otherFork:[e,...n.slice(0,a)],common:[this,...t]};if(r===n[a])return{fork:[this,...t.slice(0,i)],otherFork:[e,...n.slice(0,a)],common:t.slice(i)}}}return{fork:[this,...t],otherFork:[e,...n],common:[]}}hasCommonAncestors(e){let t=this.findCommonAncestors(e);return t&&!!t.common.length}isInFrontOf(e){if(this===e)return;let t=this.findCommonAncestors(e);if(t.fork.includes(e))return!0;if(t.otherFork.includes(this))return!1;let n=t.common[0]||this.canvas;if(!n)return;let r=t.fork.pop(),i=t.otherFork.pop(),a=n._objects.indexOf(r),o=n._objects.indexOf(i);return a>-1&&a>o}toObject(t=[]){let n=t.concat(e.customProperties,this.constructor.customProperties||[]),r,i=h.NUM_FRACTION_DIGITS,{clipPath:a,fill:o,stroke:s,shadow:c,strokeDashArray:l,left:u,top:d,originX:f,originY:p,width:m,height:g,strokeWidth:_,strokeLineCap:v,strokeDashOffset:y,strokeLineJoin:b,strokeUniform:x,strokeMiterLimit:S,scaleX:C,scaleY:w,angle:T,flipX:E,flipY:D,opacity:k,visible:A,backgroundColor:j,fillRule:M,paintFirst:ee,globalCompositeOperation:N,skewX:P,skewY:F}=this;a&&!a.excludeFromExport&&(r=a.toObject(n.concat(`inverted`,`absolutePositioned`)));let I=e=>V(e,i),te={...st(this,n),type:this.constructor.type,version:O,originX:f,originY:p,left:I(u),top:I(d),width:I(m),height:I(g),fill:dt(o)?o.toObject():o,stroke:dt(s)?s.toObject():s,strokeWidth:I(_),strokeDashArray:l&&l.concat(),strokeLineCap:v,strokeDashOffset:y,strokeLineJoin:b,strokeUniform:x,strokeMiterLimit:I(S),scaleX:I(C),scaleY:I(w),angle:I(T),flipX:E,flipY:D,opacity:I(k),shadow:c&&c.toObject(),visible:A,backgroundColor:j,fillRule:M,paintFirst:ee,globalCompositeOperation:N,skewX:I(P),skewY:I(F),...r?{clipPath:r}:null};return this.includeDefaultValues?te:this._removeDefaultValues(te)}toDatalessObject(e){return this.toObject(e)}_removeDefaultValues(e){let t=this.constructor.getDefaults(),n=Object.keys(t).length>0?t:Object.getPrototypeOf(this);return ct(e,(e,t)=>{if(t===`left`||t===`top`||t===`type`)return!0;let r=n[t];return e!==r&&!(Array.isArray(e)&&Array.isArray(r)&&e.length===0&&r.length===0)})}toString(){return`#<${this.constructor.type}>`}static _fromObject({type:e,...t},{extraParam:n,...r}={}){return ot(t,r).then(e=>n?(delete e[n],new this(t[n],e)):new this(e))}static fromObject(e,t){return this._fromObject(e,t)}};p(Jr,`stateProperties`,er),p(Jr,`cacheProperties`,tr),p(Jr,`ownDefaults`,nr),p(Jr,`type`,`FabricObject`),p(Jr,`colorProperties`,[_e,ve,`backgroundColor`]),p(Jr,`customProperties`,[]),L.setClass(Jr),L.setClass(Jr,`object`);var Yr=(e,t)=>{var n;let{transform:{target:r}}=t;(n=r.canvas)==null||n.fire(`object:${e}`,{...t,target:r}),r.fire(e,t)},Xr=(e,t,n)=>(r,i,a,o)=>{let s=t(r,i,a,o);return s&&Yr(e,{...ln(r,i,a,o),...n}),s};function Zr(e){return(t,n,r,i)=>{let{target:a,originX:o,originY:s}=n,c=a.getPositionByOrigin(o,s),l=e(t,n,r,i);return a.setPositionByOrigin(c,n.originX,n.originY),l}}var Qr=(e,t,n,r)=>(i,a,o,s)=>{let c=dn(a,a.originX,a.originY,o,s)[n],l=Gt(a[t]);if(l===0||l>0&&c<0||l<0&&c>0){let{target:t}=a,n=t.strokeWidth/(t.strokeUniform?t[r]:1),i=on(a)?2:1,o=t[e],s=Math.abs(c*i/t[r])-n;return t.set(e,Math.max(s,1)),o!==t[e]}return!1},$r=Qr(`width`,`originX`,`x`,`scaleX`),ei=Qr(`height`,`originY`,`y`,`scaleY`),ti=Xr(le,Zr($r)),ni=Xr(le,Zr(ei));function ri(e,t,n,r,i){e.save();let{stroke:a,xSize:o,ySize:s,opName:c}=this.commonRenderProps(e,t,n,i,r),l=o;o>s?e.scale(1,s/o):s>o&&(l=s,e.scale(o/s,1)),e.beginPath(),e.arc(0,0,l/2,0,M,!1),e[c](),a&&e.stroke(),e.restore()}function ii(e,t,n,r,i){e.save();let{stroke:a,xSize:o,ySize:s,opName:c}=this.commonRenderProps(e,t,n,i,r),l=o/2,u=s/2;e[`${c}Rect`](-l,-u,o,s),a&&e.strokeRect(-l,-u,o,s),e.restore()}var ai=class{constructor(e){p(this,`visible`,!0),p(this,`actionName`,fe),p(this,`angle`,0),p(this,`x`,0),p(this,`y`,0),p(this,`offsetX`,0),p(this,`offsetY`,0),p(this,`sizeX`,0),p(this,`sizeY`,0),p(this,`touchSizeX`,0),p(this,`touchSizeY`,0),p(this,`cursorStyle`,`crosshair`),p(this,`withConnection`,!1),Object.assign(this,e)}getTransformAnchorPoint(){return this.transformAnchorPoint??new R(.5-this.x,.5-this.y)}shouldActivate(e,t,n,{tl:r,tr:i,br:a,bl:o}){return t.canvas?.getActiveObject()===t&&t.isControlVisible(e)&&Kr.isPointInPolygon(n,[r,i,a,o])}getActionHandler(e,t,n){return this.actionHandler}getMouseDownHandler(e,t,n){return this.mouseDownHandler}getMouseUpHandler(e,t,n){return this.mouseUpHandler}cursorStyleHandler(e,t,n,r){return t.cursorStyle}getActionName(e,t,n){return t.actionName}getVisibility(e,t){return e._controlsVisibility?.[t]??this.visible}setVisibility(e,t,n){this.visible=e}positionHandler(e,t,n,r){return new R(this.x*e.x+this.offsetX,this.y*e.y+this.offsetY).transform(t)}calcCornerCoords(e,t,n,r,i,a){let o=Ge([Xe(n,r),Ze({angle:e}),Qe((i?this.touchSizeX:this.sizeX)||t,(i?this.touchSizeY:this.sizeY)||t)]);return{tl:new R(-.5,-.5).transform(o),tr:new R(.5,-.5).transform(o),br:new R(.5,.5).transform(o),bl:new R(-.5,.5).transform(o)}}commonRenderProps(e,t,n,r,i={}){let{cornerSize:a,cornerColor:o,transparentCorners:s,cornerStrokeColor:c}=i,l=a||r.cornerSize,u=this.sizeX||l,d=this.sizeY||l,f=s===void 0?r.transparentCorners:s,p=f?ve:_e,m=c||r.cornerStrokeColor,h=!f&&!!m;return e.fillStyle=o||r.cornerColor||``,e.strokeStyle=m||``,e.translate(t,n),e.rotate(z(r.getTotalAngle())),{stroke:h,xSize:u,ySize:d,transparentCorners:f,opName:p}}render(e,t,n,r,i){((r||={}).cornerStyle||i.cornerStyle)===`circle`?ri.call(this,e,t,n,r,i):ii.call(this,e,t,n,r,i)}},oi=(e,t,n)=>n.lockRotation?an:t.cursorStyle,si=Xr(oe,Zr((e,{target:t,ex:n,ey:r,theta:i,originX:a,originY:o},s,c)=>{let l=t.getPositionByOrigin(a,o);if(cn(t,`lockRotation`))return!1;let u=Math.atan2(r-l.y,n-l.x),d=Ve(Math.atan2(c-l.y,s-l.x)-u+i);if(t.snapAngle&&t.snapAngle>0){let e=t.snapAngle,n=t.snapThreshold||e,r=Math.ceil(d/e)*e,i=Math.floor(d/e)*e;Math.abs(d-i)<n?d=i:Math.abs(d-r)<n&&(d=r)}d<0&&(d=360+d),d%=360;let f=t.angle!==d;return t.angle=d,f}));function ci(e,t){let n=t.canvas,r=e[n.uniScaleKey];return n.uniformScaling&&!r||!n.uniformScaling&&r}function li(e,t,n){let r=cn(e,`lockScalingX`),i=cn(e,`lockScalingY`);if(r&&i||!t&&(r||i)&&n||r&&t===`x`||i&&t===`y`)return!0;let{width:a,height:o,strokeWidth:s}=e;return a===0&&s===0&&t!==`y`||o===0&&s===0&&t!==`x`}var ui=[`e`,`se`,`s`,`sw`,`w`,`nw`,`n`,`ne`,`e`],di=(e,t,n,r)=>{let i=ci(e,n);return li(n,t.x!==0&&t.y===0?`x`:t.x===0&&t.y!==0?`y`:``,i)?an:`${ui[un(n,0,r)]}-resize`};function fi(e,t,n,r,i={}){let a=t.target,o=i.by,s=ci(e,a),c,l,u,d,f,p;if(li(a,o,s))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,u=t.scaleY*t.gestureScale;else{if(c=dn(t,t.originX,t.originY,n,r),f=o===`y`?1:Math.sign(c.x||t.signX||1),p=o===`x`?1:Math.sign(c.y||t.signY||1),t.signX||=f,t.signY||=p,cn(a,`lockScalingFlip`)&&(t.signX!==f||t.signY!==p))return!1;if(d=a._getTransformedDimensions(),s&&!o){let e=Math.abs(c.x)+Math.abs(c.y),{original:n}=t,r=e/(Math.abs(d.x*n.scaleX/a.scaleX)+Math.abs(d.y*n.scaleY/a.scaleY));l=n.scaleX*r,u=n.scaleY*r}else l=Math.abs(c.x*a.scaleX/d.x),u=Math.abs(c.y*a.scaleY/d.y);on(t)&&(l*=2,u*=2),t.signX!==f&&o!==`y`&&(t.originX=sn(t.originX),l*=-1,t.signX=f),t.signY!==p&&o!==`x`&&(t.originY=sn(t.originY),u*=-1,t.signY=p)}let m=a.scaleX,h=a.scaleY;return o?(o===`x`&&a.set(`scaleX`,l),o===`y`&&a.set(`scaleY`,u)):(!cn(a,`lockScalingX`)&&a.set(`scaleX`,l),!cn(a,`lockScalingY`)&&a.set(`scaleY`,u)),m!==a.scaleX||h!==a.scaleY}var pi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r))),mi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r,{by:`x`}))),hi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r,{by:`y`}))),gi={x:{counterAxis:`y`,scale:pe,skew:he,lockSkewing:`lockSkewingX`,origin:`originX`,flip:`flipX`},y:{counterAxis:`x`,scale:me,skew:ge,lockSkewing:`lockSkewingY`,origin:`originY`,flip:`flipY`}},_i=[`ns`,`nesw`,`ew`,`nwse`],vi=(e,t,n,r)=>t.x!==0&&cn(n,`lockSkewingY`)||t.y!==0&&cn(n,`lockSkewingX`)?an:`${_i[un(n,0,r)%4]}-resize`;function yi(e,t,n,r,i){let{target:a}=n,{counterAxis:o,origin:s,lockSkewing:c,skew:l,flip:u}=gi[e];if(cn(a,c))return!1;let{origin:d,flip:f}=gi[o],p=Gt(n[d])*(a[f]?-1:1),m=-Math.sign(p)*(a[u]?-1:1),h=-(a[l]===0&&dn(n,`center`,`center`,r,i)[e]>0||a[l]>0?1:-1)*m*.5+.5;return Xr(ce,Zr((t,n,r,i)=>function(e,{target:t,ex:n,ey:r,skewingSide:i,...a},o){let{skew:s}=gi[e],c=o.subtract(new R(n,r)).divide(new R(t.scaleX,t.scaleY))[e],l=t[s],u=a[s],d=Math.tan(z(u)),f=e===`y`?t._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:t._getTransformedDimensions({scaleX:1,scaleY:1}).y,p=2*c*i/Math.max(f,1)+d,m=Ve(Math.atan(p));t.set(s,m);let h=l!==t[s];if(h&&e===`y`){let{skewX:e,scaleX:n}=t,r=t._getTransformedDimensions({skewY:l}),i=t._getTransformedDimensions(),a=e===0?1:r.x/i.x;a!==1&&t.set(`scaleX`,a*n)}return h}(e,n,new R(r,i))))(t,{...n,[s]:h,skewingSide:m},r,i)}var bi=(e,t,n,r)=>yi(`x`,e,t,n,r),xi=(e,t,n,r)=>yi(`y`,e,t,n,r);function Si(e,t){return e[t.canvas.altActionKey]}var Ci=(e,t,n)=>{let r=Si(e,n);return t.x===0?r?he:me:t.y===0?r?ge:pe:``},wi=(e,t,n,r)=>Si(e,n)?vi(0,t,n,r):di(e,t,n,r),Ti=(e,t,n,r)=>Si(e,t.target)?xi(e,t,n,r):mi(e,t,n,r),Ei=(e,t,n,r)=>Si(e,t.target)?bi(e,t,n,r):hi(e,t,n,r),Di=()=>({ml:new ai({x:-.5,y:0,cursorStyleHandler:wi,actionHandler:Ti,getActionName:Ci}),mr:new ai({x:.5,y:0,cursorStyleHandler:wi,actionHandler:Ti,getActionName:Ci}),mb:new ai({x:0,y:.5,cursorStyleHandler:wi,actionHandler:Ei,getActionName:Ci}),mt:new ai({x:0,y:-.5,cursorStyleHandler:wi,actionHandler:Ei,getActionName:Ci}),tl:new ai({x:-.5,y:-.5,cursorStyleHandler:di,actionHandler:pi}),tr:new ai({x:.5,y:-.5,cursorStyleHandler:di,actionHandler:pi}),bl:new ai({x:-.5,y:.5,cursorStyleHandler:di,actionHandler:pi}),br:new ai({x:.5,y:.5,cursorStyleHandler:di,actionHandler:pi}),mtr:new ai({x:0,y:-.5,actionHandler:si,cursorStyleHandler:oi,offsetY:-40,withConnection:!0,actionName:se})}),Oi=()=>({mr:new ai({x:.5,y:0,actionHandler:ti,cursorStyleHandler:wi,actionName:le}),ml:new ai({x:-.5,y:0,actionHandler:ti,cursorStyleHandler:wi,actionName:le})}),ki=()=>({...Di(),...Oi()}),Ai=class e extends Jr{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,this.constructor.createControls(),e.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Di()}}_updateCacheCanvas(){let e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){let t=e._currentTransform,n=t.target,r=t.action;if(this===n&&r&&r.startsWith(`scale`))return!1}return super._updateCacheCanvas()}getActiveControl(){let e=this.__corner;return e?{key:e,control:this.controls[e],coord:this.oCoords[e]}:void 0}findControl(e,t=!1){if(!this.hasControls||!this.canvas)return;this.__corner=void 0;let n=Object.entries(this.oCoords);for(let r=n.length-1;r>=0;r--){let[i,a]=n[r],o=this.controls[i];if(o.shouldActivate(i,this,e,t?a.touchCorner:a.corner))return this.__corner=i,{key:i,control:o,coord:this.oCoords[i]}}}calcOCoords(){let e=this.getViewportTransform(),t=qe(e),n=Je(e),r=this.getCenterPoint(),i=B(B(e,B(Xe(r.x,r.y),Ze({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}))),[1/t,0,0,1/n,0,0]),a=this.group?Ye(this.calcTransformMatrix()):void 0;a&&(a.scaleX=Math.abs(a.scaleX),a.scaleY=Math.abs(a.scaleY));let o=this._calculateCurrentDimensions(a),s={};return this.forEachControl((e,t)=>{let n=e.positionHandler(o,i,this,e);s[t]=Object.assign(n,this._calcCornerCoords(e,n))}),s}_calcCornerCoords(e,t){let n=this.getTotalAngle();return{corner:e.calcCornerCoords(n,this.cornerSize,t.x,t.y,!1,this),touchCorner:e.calcCornerCoords(n,this.touchCornerSize,t.x,t.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(e){for(let t in this.controls)e(this.controls[t],t,this)}drawSelectionBackground(e){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;e.save();let t=this.getRelativeCenterPoint(),n=this._calculateCurrentDimensions(),r=this.getViewportTransform();e.translate(t.x,t.y),e.scale(1/r[0],1/r[3]),e.rotate(z(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore()}strokeBorders(e,t){e.strokeRect(-t.x/2,-t.y/2,t.x,t.y)}_drawBorders(e,t,n={}){let r={hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray,...n};e.save(),e.strokeStyle=r.borderColor,this._setLineDash(e,r.borderDashArray),this.strokeBorders(e,t),r.hasControls&&this.drawControlsConnectingLines(e,t),e.restore()}_renderControls(e,t={}){let{hasBorders:n,hasControls:r}=this,i={hasBorders:n,hasControls:r,...t},a=this.getViewportTransform(),o=i.hasBorders,s=i.hasControls,c=Ye(B(a,this.calcTransformMatrix()));e.save(),e.translate(c.translateX,c.translateY),e.lineWidth=this.borderScaleFactor,this.group===this.parent&&(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180);let l=Ke(a);e.rotate(this.group?z(c.angle):z(this.angle)+l),o&&this.drawBorders(e,c,t),s&&this.drawControls(e,t),e.restore()}drawBorders(e,t,n){let r;if(n&&n.forActiveSelection||this.group){let e=zt(this.width,this.height,nt(t)),n=this.isStrokeAccountedForInDimensions()?De:(this.strokeUniform?new R().scalarAdd(this.canvas?this.canvas.getZoom():1):new R(t.scaleX,t.scaleY)).scalarMultiply(this.strokeWidth);r=e.add(n).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else r=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(e,r,n)}drawControlsConnectingLines(e,t){let n=!1;e.beginPath(),this.forEachControl((r,i)=>{r.withConnection&&r.getVisibility(this,i)&&(n=!0,e.moveTo(r.x*t.x,r.y*t.y),e.lineTo(r.x*t.x+r.offsetX,r.y*t.y+r.offsetY))}),n&&e.stroke()}drawControls(e,t={}){e.save();let n=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:i,cornerColor:a}=this,o={cornerStrokeColor:r,cornerDashArray:i,cornerColor:a,...t};e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=o.cornerColor,this.transparentCorners||(e.strokeStyle=o.cornerStrokeColor),this._setLineDash(e,o.cornerDashArray),this.forEachControl((t,n)=>{if(t.getVisibility(this,n)){let r=this.oCoords[n];t.render(e,r.x,r.y,o,this)}}),e.restore()}isControlVisible(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)}setControlVisible(e,t){this._controlsVisibility||={},this._controlsVisibility[e]=t}setControlsVisibility(e={}){Object.entries(e).forEach(([e,t])=>this.setControlVisible(e,t))}clearContextTop(e){if(!this.canvas)return;let t=this.canvas.contextTop;if(!t)return;let n=this.canvas.viewportTransform;t.save(),t.transform(n[0],n[1],n[2],n[3],n[4],n[5]),this.transform(t);let r=this.width+4,i=this.height+4;return t.clearRect(-r/2,-i/2,r,i),e||t.restore(),t}onDeselect(e){return!1}onSelect(e){return!1}shouldStartDragging(e){return!1}onDragStart(e){return!1}canDrop(e){return!1}renderDragSourceEffect(e){}renderDropTargetEffect(e){}};function ji(e,t){return t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(n=>{n!==`constructor`&&Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)||Object.create(null))})}),e}p(Ai,`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});var Mi=class extends Ai{};ji(Mi,[On]),L.setClass(Mi),L.setClass(Mi,`object`);var Ni=(e,t,n,r)=>{let i=2*(r=Math.round(r))+1,{data:a}=e.getImageData(t-r,n-r,i,i);for(let e=3;e<a.length;e+=4)if(a[e]>0)return!1;return!0},Pi=class{constructor(e){this.options=e,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new R(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new R(1/this.options.scaleX,1/this.options.scaleY):new R(1,1)}createSideVector(e,t){let n=Yt(e,t);return this.options.strokeUniform?n.multiply(this.scale):n}projectOrthogonally(e,t,n){return this.applySkew(e.add(this.calcOrthogonalProjection(e,t,n)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(e){let t=new R(e);return t.y+=t.x*Math.tan(z(this.options.skewY)),t.x+=t.y*Math.tan(z(this.options.skewX)),t}scaleUnitVector(e,t){return e.multiply(this.strokeUniformScalar).scalarMultiply(t)}},Fi=new R,Ii=class e extends Pi{static getOrthogonalRotationFactor(e,t){let n=t?Zt(e,t):Qt(e);return Math.abs(n)<A?-1:1}constructor(e,t,n,r){super(r),p(this,`AB`,void 0),p(this,`AC`,void 0),p(this,`alpha`,void 0),p(this,`bisector`,void 0),this.A=new R(e),this.B=new R(t),this.C=new R(n),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Zt(this.AB,this.AC),this.bisector=$t(Jt(this.AB.eq(Fi)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,n,r=this.strokeProjectionMagnitude){let i=en(this.createSideVector(t,n)),a=e.getOrthogonalRotationFactor(i,this.bisector);return this.scaleUnitVector(i,r*a)}projectBevel(){let e=[];return(this.alpha%M===0?[this.B]:[this.B,this.C]).forEach(t=>{e.push(this.projectOrthogonally(this.A,t)),e.push(this.projectOrthogonally(this.A,t,-this.strokeProjectionMagnitude))}),e}projectMiter(){let e=[],t=Math.abs(this.alpha),n=1/Math.sin(t/2),r=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*n),i=this.options.strokeUniform?Xt(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Xt(r)/this.strokeProjectionMagnitude<=i&&e.push(this.applySkew(this.A.add(r))),e.push(...this.projectBevel()),e}projectRoundNoSkew(t,n){let r=[],i=new R(e.getOrthogonalRotationFactor(this.bisector),e.getOrthogonalRotationFactor(new R(this.bisector.y,this.bisector.x)));return[new R(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new R(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(e=>{rn(e,t,n)&&r.push(this.A.add(e))}),r}projectRoundWithSkew(e,t){let n=[],{skewX:r,skewY:i,scaleX:a,scaleY:o,strokeUniform:s}=this.options,c=new R(Math.tan(z(r)),Math.tan(z(i))),l=this.strokeProjectionMagnitude,u=s?l/o/Math.sqrt(1/o**2+1/a**2*c.y**2):l/Math.sqrt(1+c.y**2),d=new R(Math.sqrt(Math.max(l**2-u**2,0)),u),f=s?l/Math.sqrt(1+c.x**2*(1/o)**2/(1/a+1/a*c.x*c.y)**2):l/Math.sqrt(1+c.x**2/(1+c.x*c.y)**2),p=new R(f,Math.sqrt(Math.max(l**2-f**2,0)));return[p,p.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(e=>this.applySkew(s?e.multiply(this.strokeUniformScalar):e)).forEach(r=>{rn(r,e,t)&&n.push(this.applySkew(this.A).add(r))}),n}projectRound(){let e=[];e.push(...this.projectBevel());let t=this.alpha%M===0,n=this.applySkew(this.A),r=e[t?0:2].subtract(n),i=e[+!!t].subtract(n),a=tn(r,t?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)))>0,o=a?r:i,s=a?i:r;return this.isSkewed()?e.push(...this.projectRoundWithSkew(o,s)):e.push(...this.projectRoundNoSkew(o,s)),e}projectPoints(){switch(this.options.strokeLineJoin){case`miter`:return this.projectMiter();case`round`:return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(e=>({originPoint:this.A,projectedPoint:e,angle:this.alpha,bisector:this.bisector}))}},Li=class extends Pi{constructor(e,t,n){super(n),this.A=new R(e),this.T=new R(t)}calcOrthogonalProjection(e,t,n=this.strokeProjectionMagnitude){let r=this.createSideVector(e,t);return this.scaleUnitVector(en(r),n)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){let e=[];if(!this.isSkewed()&&this.A.eq(this.T)){let t=new R(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);e.push(this.applySkew(this.A.add(t)),this.applySkew(this.A.subtract(t)))}else e.push(...new Ii(this.A,this.T,this.T,this.options).projectRound());return e}projectSquare(){let e=[];if(this.A.eq(this.T)){let t=new R(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);e.push(this.A.add(t),this.A.subtract(t))}else{let t=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),n=this.scaleUnitVector($t(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),r=this.A.add(n);e.push(r.add(t),r.subtract(t))}return e.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(e=>({originPoint:this.A,projectedPoint:e}))}},Ri=(e,t,n=!1)=>{let r=[];if(e.length===0)return r;let i=e.reduce((e,t)=>(e[e.length-1].eq(t)||e.push(new R(t)),e),[new R(e[0])]);if(i.length===1)n=!0;else if(!n){let e=i[0],t=((e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n],n,e))return n;return-1})(i,t=>!t.eq(e));i.splice(t+1)}return i.forEach((e,i,a)=>{let o,s;i===0?(s=a[1],o=n?e:a[a.length-1]):i===a.length-1?(o=a[i-1],s=n?e:a[0]):(o=a[i-1],s=a[i+1]),n&&a.length===1?r.push(...new Li(e,e,t).project()):!n||i!==0&&i!==a.length-1?r.push(...new Ii(e,o,s,t).project()):r.push(...new Li(e,i===0?s:o,t).project())}),r},zi=e=>{let t={};return Object.keys(e).forEach(n=>{t[n]={},Object.keys(e[n]).forEach(r=>{t[n][r]={...e[n][r]}})}),t},Bi=(e,t,n=!1)=>e.fill!==t.fill||e.stroke!==t.stroke||e.strokeWidth!==t.strokeWidth||e.fontSize!==t.fontSize||e.fontFamily!==t.fontFamily||e.fontWeight!==t.fontWeight||e.fontStyle!==t.fontStyle||e.textDecorationThickness!==t.textDecorationThickness||e.textDecorationColor!==t.textDecorationColor||e.textBackgroundColor!==t.textBackgroundColor||e.deltaY!==t.deltaY||n&&(e.overline!==t.overline||e.underline!==t.underline||e.linethrough!==t.linethrough),Vi=(e,t)=>{let n=t.split(`
15
+ `),r=[],i=-1,a={};e=zi(e);for(let t=0;t<n.length;t++){let o=Tt(n[t]);if(e[t])for(let n=0;n<o.length;n++){i++;let o=e[t][n];o&&Object.keys(o).length>0&&(Bi(a,o,!0)?r.push({start:i,end:i+1,style:o}):r[r.length-1].end++),a=o||{}}else i+=o.length,a={}}return r},Hi=(e,t)=>{if(!Array.isArray(e))return zi(e);let n=t.split(re),r={},i=-1,a=0;for(let t=0;t<n.length;t++){let o=Tt(n[t]);for(let n=0;n<o.length;n++)i++,e[a]&&e[a].start<=i&&i<e[a].end&&(r[t]=r[t]||{},r[t][n]={...e[a].style},i===e[a].end-1&&a++)}return r},Ui=[`display`,`transform`,_e,`fill-opacity`,`fill-rule`,`opacity`,ve,`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 Wi(e,t){let n=e.nodeName,r=e.getAttribute(`class`),i=e.getAttribute(`id`),a=`(?![a-zA-Z\\-]+)`,o;if(o=RegExp(`^`+n,`i`),t=t.replace(o,``),i&&t.length&&(o=RegExp(`#`+i+a,`i`),t=t.replace(o,``)),r&&t.length){let e=r.split(` `);for(let n=e.length;n--;)o=RegExp(`\\.`+e[n]+a,`i`),t=t.replace(o,``)}return t.length===0}function Gi(e,t){let n=!0,r=Wi(e,t.pop());return r&&t.length&&(n=function(e,t){let n,r=!0;for(;e.parentElement&&e.parentElement.nodeType===1&&t.length;)r&&(n=t.pop()),r=Wi(e=e.parentElement,n);return t.length===0}(e,t)),r&&n&&t.length===0}function Ki(e,t={}){let n={};for(let r in t)Gi(e,r.split(` `))&&(n={...n,...t[r]});return n}var qi=e=>Un[e]??e,Ji=RegExp(`(${zn})`,`gi`),Yi=`(${zn})`,Xi=String.raw`(skewX)\(${Yi}\)`,Zi=String.raw`(skewY)\(${Yi}\)`,Qi=String.raw`(rotate)\(${Yi}(?: ${Yi} ${Yi})?\)`,$i=String.raw`(scale)\(${Yi}(?: ${Yi})?\)`,ea=String.raw`(translate)\(${Yi}(?: ${Yi})?\)`,ta=`(?:${String.raw`(matrix)\(${Yi} ${Yi} ${Yi} ${Yi} ${Yi} ${Yi}\)`}|${ea}|${Qi}|${$i}|${Xi}|${Zi})`,na=`(?:${ta}*)`,ra=String.raw`^\s*(?:${na}?)\s*$`,ia=new RegExp(ra),aa=new RegExp(ta),oa=new RegExp(ta,`g`);function sa(e){let t=[];if(!(e=(e=>gn(e.replace(Ji,` $1 `).replace(/,/gi,` `)))(e).replace(/\s*([()])\s*/gi,`$1`))||e&&!ia.test(e))return[...N];for(let n of e.matchAll(oa)){let e=aa.exec(n[0]);if(!e)continue;let r=N,[,i,...a]=e.filter(e=>!!e),[o,s,c,l,u,d]=a.map(e=>parseFloat(e));switch(i){case`translate`:r=Xe(o,s);break;case se:r=Ze({angle:o},{x:s,y:c});break;case fe:r=Qe(o,s);break;case he:r=et(o);break;case ge:r=tt(o);break;case`matrix`:r=[o,s,c,l,u,d]}t.push(r)}return Ge(t)}function ca(e,t,n,r){let i=Array.isArray(t),a,o=t;if(e!==`fill`&&e!==`stroke`||t!==`none`){if(e===`strokeUniform`)return t===`non-scaling-stroke`;if(e===`strokeDashArray`)o=t===`none`?null:t.replace(/,/g,` `).split(/\s+/).map(parseFloat);else if(e===`transformMatrix`)o=n&&n.transformMatrix?B(n.transformMatrix,sa(t)):sa(t);else if(e===`visible`)o=t!==`none`&&t!==`hidden`,n&&!1===n.visible&&(o=!1);else if(e===`opacity`)o=parseFloat(t),n&&n.opacity!==void 0&&(o*=n.opacity);else if(e===`textAnchor`)o=t===`start`?F:t===`end`?te:P;else if(e===`charSpacing`||e===`textDecorationThickness`)a=Tn(t,r)/r*1e3;else if(e===`paintFirst`){let e=t.indexOf(_e),n=t.indexOf(ve);o=_e,(e>-1&&n>-1&&n<e||e===-1&&n>-1)&&(o=ve)}else{if(e===`href`||e===`xlink:href`||e===`font`||e===`id`)return t;if(e===`imageSmoothing`)return t===`optimizeQuality`;a=i?t.map(Tn):Tn(t,r)}}else o=``;return!i&&isNaN(a)?o:a}function la(e,t){e.replace(/;\s*$/,``).split(`;`).forEach(e=>{if(!e)return;let[n,r]=e.split(`:`);t[n.trim().toLowerCase()]=r.trim()})}function ua(e){let t={},n=e.getAttribute(`style`);return n&&(typeof n==`string`?la(n,t):function(e,t){Object.entries(e).forEach(([e,n])=>{n!==void 0&&(t[e.toLowerCase()]=n)})}(n,t)),t}var da={stroke:`strokeOpacity`,fill:`fillOpacity`};function fa(e,t,n){if(!e)return{};let r,i={},a=16;e.parentNode&&Jn.test(e.parentNode.nodeName)&&(i=fa(e.parentElement,t,n),i.fontSize&&(r=a=Tn(i.fontSize)));let o={...t.reduce((t,n)=>{let r=e.getAttribute(n);return r&&(t[n]=r),t},{}),...Ki(e,n),...ua(e)};o[`clip-path`]&&e.setAttribute(Gn,o[Gn]),o[`font-size`]&&(r=Tn(o[Wn],a),o[Wn]=`${r}`);let s={};for(let e in o){let t=qi(e);s[t]=ca(t,o[e],i,r)}s&&s.font&&function(e,t){let n=e.match(Hn);if(!n)return;let r=n[1],i=n[3],a=n[4],o=n[5],s=n[6];r&&(t.fontStyle=r),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),a&&(t.fontSize=Tn(a)),s&&(t.fontFamily=s),o&&(t.lineHeight=o===`normal`?1:o)}(s.font,s);let c={...i,...s};return Jn.test(e.nodeName)?c:function(e){let t=Mi.getDefaults();return Object.entries(da).forEach(([n,r])=>{if(e[r]===void 0||e[n]===``)return;if(e[n]===void 0){if(!t[n])return;e[n]=t[n]}if(e[n].indexOf(`url(`)===0)return;let i=new Cn(e[n]);e[n]=i.setAlpha(V(i.getAlpha()*e[r],2)).toRgba()}),e}(c)}var pa=[`rx`,`ry`],ma=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){let{rx:e,ry:t}=this;e&&!t?this.ry=e:t&&!e&&(this.rx=t)}_render(e){let{width:t,height:n}=this,r=-t/2,i=-n/2,a=this.rx?Math.min(this.rx,t/2):0,o=this.ry?Math.min(this.ry,n/2):0,s=a!==0||o!==0;e.beginPath(),e.moveTo(r+a,i),e.lineTo(r+t-a,i),s&&e.bezierCurveTo(r+t-.4477152502*a,i,r+t,i+.4477152502*o,r+t,i+o),e.lineTo(r+t,i+n-o),s&&e.bezierCurveTo(r+t,i+n-.4477152502*o,r+t-.4477152502*a,i+n,r+t-a,i+n),e.lineTo(r+a,i+n),s&&e.bezierCurveTo(r+.4477152502*a,i+n,r,i+n-.4477152502*o,r,i+n-o),e.lineTo(r,i+o),s&&e.bezierCurveTo(r,i+.4477152502*o,r+.4477152502*a,i,r+a,i),e.closePath(),this._renderPaintInOrder(e)}toObject(e=[]){return super.toObject([...pa,...e])}_toSVG(){let{width:e,height:t,rx:n,ry:r}=this;return[`<rect `,`COMMON_PARTS`,`x="${-e/2}" y="${-t/2}" rx="${H(n)}" ry="${H(r)}" width="${H(e)}" height="${H(t)}" />\n`]}static async fromElement(e,t,n){let{left:r=0,top:i=0,width:a=0,height:o=0,visible:s=!0,...c}=fa(e,this.ATTRIBUTE_NAMES,n);return new this({...t,...c,left:r,top:i,width:a,height:o,visible:!!(s&&a&&o)})}};p(ma,`type`,`Rect`),p(ma,`cacheProperties`,[...tr,...pa]),p(ma,`ownDefaults`,{rx:0,ry:0}),p(ma,`ATTRIBUTE_NAMES`,[...Ui,`x`,`y`,`rx`,`ry`,`width`,`height`]),L.setClass(ma),L.setSVGClass(ma);var ha=`initialization`,ga=`added`,_a=(e,t)=>{let{strokeUniform:n,strokeWidth:r,width:i,height:a,group:o}=t,s=o&&o!==e?Bt(o.calcTransformMatrix(),e.calcTransformMatrix()):null,c=s?t.getRelativeCenterPoint().transform(s):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),u=n&&l?Ht(new R(r,r),void 0,e.calcTransformMatrix()):De,d=!n&&l?r:0,f=zt(i+d,a+d,Ge([s,t.calcOwnMatrix()],!0)).add(u).scalarDivide(2);return[c.subtract(f),c.add(f)]},va=class{calcLayoutResult(e,t){if(this.shouldPerformLayout(e))return this.calcBoundingBox(t,e)}shouldPerformLayout({type:e,prevStrategy:t,strategy:n}){return e===`initialization`||e===`imperative`||!!t&&n!==t}shouldLayoutClipPath({type:e,target:{clipPath:t}}){return e!==`initialization`&&t&&!t.absolutePositioned}getInitialSize(e,t){return t.size}calcBoundingBox(e,t){let{type:n,target:r}=t;if(n===`imperative`&&t.overrides)return t.overrides;if(e.length===0)return;let{left:i,top:a,width:o,height:s}=Nt(e.map(e=>_a(r,e)).reduce((e,t)=>e.concat(t),[])),c=new R(o,s),l=new R(i,a).add(c.scalarDivide(2));if(n===`initialization`){let e=this.getInitialSize(t,{size:c,center:l});return{center:l,relativeCorrection:new R(0,0),size:e}}return{center:l.transform(r.calcOwnMatrix()),size:c}}};p(va,`type`,`strategy`);var ya=class extends va{shouldPerformLayout(e){return!0}};p(ya,`type`,`fit-content`),L.setClass(ya);var ba=`layoutManager`,xa=class{constructor(e=new ya){p(this,`strategy`,void 0),this.strategy=e,this._subscriptions=new Map}performLayout(e){let t={bubbles:!0,strategy:this.strategy,...e,prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}};this.onBeforeLayout(t);let n=this.getLayoutResult(t);n&&this.commitLayout(t,n),this.onAfterLayout(t,n),this._prevLayoutStrategy=t.strategy}attachHandlers(e,t){let{target:n}=t;return[ye,ie,le,oe,ae,ce,de,ue,`modifyPath`].map(t=>e.on(t,e=>this.performLayout(t===`modified`?{type:`object_modified`,trigger:t,e,target:n}:{type:`object_modifying`,trigger:t,e,target:n})))}subscribe(e,t){this.unsubscribe(e,t);let n=this.attachHandlers(e,t);this._subscriptions.set(e,n)}unsubscribe(e,t){(this._subscriptions.get(e)||[]).forEach(e=>e()),this._subscriptions.delete(e)}unsubscribeTargets(e){e.targets.forEach(t=>this.unsubscribe(t,e))}subscribeTargets(e){e.targets.forEach(t=>this.subscribe(t,e))}onBeforeLayout(e){let{target:t,type:n}=e,{canvas:r}=t;if(n===`initialization`||n===`added`?this.subscribeTargets(e):n===`removed`&&this.unsubscribeTargets(e),t.fire(`layout:before`,{context:e}),r&&r.fire(`object:layout:before`,{target:t,context:e}),n===`imperative`&&e.deep){let{strategy:n,...r}=e;t.forEachObject(e=>e.layoutManager&&e.layoutManager.performLayout({...r,bubbles:!1,target:e}))}}getLayoutResult(e){let{target:t,strategy:n,type:r}=e,i=n.calcLayoutResult(e,t.getObjects());if(!i)return;let a=r===`initialization`?new R:t.getRelativeCenterPoint(),{center:o,correction:s=new R,relativeCorrection:c=new R}=i;return{result:i,prevCenter:a,nextCenter:o,offset:a.subtract(o).add(s).transform(r===`initialization`?N:We(t.calcOwnMatrix()),!0).add(c)}}commitLayout(e,t){let{target:n}=e,{result:{size:r},nextCenter:i}=t;n.set({width:r.x,height:r.y}),this.layoutObjects(e,t),e.type===`initialization`?n.set({left:e.x??i.x+r.x*Gt(n.originX),top:e.y??i.y+r.y*Gt(n.originY)}):(n.setPositionByOrigin(i,P,P),n.setCoords(),n.set(`dirty`,!0))}layoutObjects(e,t){let{target:n}=e;n.forEachObject(r=>{r.group===n&&this.layoutObject(e,t,r)}),e.strategy.shouldLayoutClipPath(e)&&this.layoutObject(e,t,n.clipPath)}layoutObject(e,{offset:t},n){n.set({left:n.left+t.x,top:n.top+t.y})}onAfterLayout(e,t){let{target:n,strategy:r,bubbles:i,prevStrategy:a,...o}=e,{canvas:s}=n;n.fire(`layout:after`,{context:e,result:t}),s&&s.fire(`object:layout:after`,{context:e,result:t,target:n});let c=n.parent;i&&c!=null&&c.layoutManager&&((o.path||=[]).push(n),c.layoutManager.performLayout({...o,target:c})),n.set(`dirty`,!0)}dispose(){let{_subscriptions:e}=this;e.forEach(e=>e.forEach(e=>e())),e.clear()}toObject(){return{type:ba,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}};L.setClass(xa,ba);var Sa=class extends xa{performLayout(){}},Ca=class e extends ke(Mi){static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t=[],n={}){super(),p(this,`_activeObjects`,[]),p(this,`__objectSelectionTracker`,void 0),p(this,`__objectSelectionDisposer`,void 0),Object.assign(this,e.ownDefaults),this.setOptions(n),this.groupInit(t,n)}groupInit(e,t){this._objects=[...e],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(e=>{this.enterGroup(e,!1)}),this.layoutManager=t.layoutManager??new xa,this.layoutManager.performLayout({type:ha,target:this,targets:[...e],x:t.left,y:t.top})}canEnterGroup(e){return e===this||this.isDescendantOf(e)?(g(`error`,`Group: circular object trees are not supported, this call has no effect`),!1):this._objects.indexOf(e)===-1||(g(`error`,`Group: duplicate objects are not supported inside group, this call has no effect`),!1)}_filterObjectsBeforeEnteringGroup(e){return e.filter((e,t,n)=>this.canEnterGroup(e)&&n.indexOf(e)===t)}add(...e){let t=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...t);return this._onAfterObjectsChange(ga,t),n}insertAt(e,...t){let n=this._filterObjectsBeforeEnteringGroup(t),r=super.insertAt(e,...n);return this._onAfterObjectsChange(ga,n),r}remove(...e){let t=super.remove(...e);return this._onAfterObjectsChange(`removed`,t),t}_onObjectAdded(e){this.enterGroup(e,!0),this.fire(`object:added`,{target:e}),e.fire(`added`,{target:this})}_onObjectRemoved(e,t){this.exitGroup(e,t),this.fire(`object:removed`,{target:e}),e.fire(`removed`,{target:this})}_onAfterObjectsChange(e,t){this.layoutManager.performLayout({type:e,targets:t,target:this})}_onStackOrderChanged(){this._set(`dirty`,!0)}_set(e,t){let n=this[e];return super._set(e,t),e===`canvas`&&n!==t&&(this._objects||[]).forEach(n=>{n._set(e,t)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(e,{target:t}){let n=this._activeObjects;if(e)n.push(t),this._set(`dirty`,!0);else if(n.length>0){let e=n.indexOf(t);e>-1&&(n.splice(e,1),this._set(`dirty`,!0))}}_watchObject(e,t){e&&this._watchObject(!1,t),e?(t.on(`selected`,this.__objectSelectionTracker),t.on(`deselected`,this.__objectSelectionDisposer)):(t.off(`selected`,this.__objectSelectionTracker),t.off(`deselected`,this.__objectSelectionDisposer))}enterGroup(e,t){e.group&&e.group.remove(e),e._set(`parent`,this),this._enterGroup(e,t)}_enterGroup(e,t){t&&It(e,B(We(this.calcTransformMatrix()),e.calcTransformMatrix())),this._shouldSetNestedCoords()&&e.setCoords(),e._set(`group`,this),e._set(`canvas`,this.canvas),this._watchObject(!0,e);let n=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();n&&(n===e||e.isDescendantOf(n))&&this._activeObjects.push(e)}exitGroup(e,t){this._exitGroup(e,t),e._set(`parent`,void 0),e._set(`canvas`,void 0)}_exitGroup(e,t){e._set(`group`,void 0),t||(It(e,B(this.calcTransformMatrix(),e.calcTransformMatrix())),e.setCoords()),this._watchObject(!1,e);let n=this._activeObjects.length>0?this._activeObjects.indexOf(e):-1;n>-1&&this._activeObjects.splice(n,1)}shouldCache(){let e=Mi.prototype.shouldCache.call(this);if(e){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return e}willDrawShadow(){if(super.willDrawShadow())return!0;for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(e,t,n){this._renderBackground(e);for(let t=0;t<this._objects.length;t++){var r;let n=this._objects[t];(r=this.canvas)!=null&&r.preserveObjectStacking&&n.group!==this?(e.save(),e.transform(...We(this.calcTransformMatrix())),n.render(e),e.restore()):n.group===this&&n.render(e)}this._drawClipPath(e,this.clipPath,n)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(e=>e.setCoords())}triggerLayout(e={}){this.layoutManager.performLayout({target:this,type:`imperative`,...e})}render(e){this._transformDone=!0,super.render(e),this._transformDone=!1}__serializeObjects(e,t){let n=this.includeDefaultValues;return this._objects.filter(function(e){return!e.excludeFromExport}).map(function(r){let i=r.includeDefaultValues;r.includeDefaultValues=n;let a=r[e||`toObject`](t);return r.includeDefaultValues=i,a})}toObject(e=[]){let t=this.layoutManager.toObject();return{...super.toObject([`subTargetCheck`,`interactive`,...e]),...t.strategy!==`fit-content`||this.includeDefaultValues?{layoutManager:t}:{},objects:this.__serializeObjects(`toObject`,e)}}toString(){return`#<Group: (${this.complexity()})>`}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(e=>{this._watchObject(!1,e),e.dispose()}),super.dispose()}_createSVGBgRect(e){if(!this.backgroundColor)return``;let t=ma.prototype._toSVG.call(this),n=t.indexOf(`COMMON_PARTS`);t[n]=`for="group" `;let r=t.join(``);return e?e(r):r}_toSVG(e){let t=[`<g `,`COMMON_PARTS`,` >
16
+ `],n=this._createSVGBgRect(e);n&&t.push(` `,n);for(let n=0;n<this._objects.length;n++)t.push(` `,this._objects[n].toSVG(e));return t.push(`</g>
17
+ `),t}getSvgStyles(){let e=this.opacity!==void 0&&this.opacity!==1?`opacity: ${H(this.opacity)};`:``,t=this.visible?``:` visibility: hidden;`;return[e,this.getSvgFilter(),t].join(``)}toClipPathSVG(e){let t=[],n=this._createSVGBgRect(e);n&&t.push(` `,n);for(let n=0;n<this._objects.length;n++)t.push(` `,this._objects[n].toClipPathSVG(e));return this._createBaseClipPathSVGMarkup(t,{reviver:e})}static fromObject({type:e,objects:t=[],layoutManager:n,...r},i){return Promise.all([at(t,i),ot(r,i)]).then(([e,t])=>{let i=new this(e,{...r,...t,layoutManager:new Sa});return i.layoutManager=n?new(L.getClass(n.type))(new(L.getClass(n.strategy))):new xa,i.layoutManager.subscribeTargets({type:ha,target:i,targets:i.getObjects()}),i.setCoords(),i})}};p(Ca,`type`,`Group`),p(Ca,`ownDefaults`,{strokeWidth:0,subTargetCheck:!1,interactive:!1}),L.setClass(Ca);var wa=(e,t)=>e&&e.length===1?e[0]:new Ca(e,t),Ta=(e,t)=>Math.min(t.width/e.width,t.height/e.height),Ea=(e,t)=>Math.max(t.width/e.width,t.height/e.height),Da=`\\s*,?\\s*`,Oa=`${Da}(${zn})`,ka=`${Oa}${Oa}${Oa}${Da}([01])${Da}([01])${Oa}${Oa}`,Aa={m:`l`,M:`L`},ja=(e,t,n,r,i,a,o,s,c,l,u)=>{let d=Te(e),f=Ee(e),p=Te(t),m=Ee(t),h=n*i*p-r*a*m+o,g=r*i*p+n*a*m+s;return[`C`,l+c*(-n*i*f-r*a*d),u+c*(-r*i*f+n*a*d),h+c*(n*i*m+r*a*p),g+c*(r*i*m-n*a*p),h,g]},Ma=(e,t,n,r)=>{let i=Math.atan2(t,e),a=Math.atan2(r,n);return a>=i?a-i:2*Math.PI-(i-a)};function Na(e,t,n,r,i,a,o,s){let c;if(h.cachesBoundsOfCurve&&(c=[...arguments].join(),D.boundsOfCurveCache[c]))return D.boundsOfCurveCache[c];let l=Math.sqrt,u=Math.abs,d=[],f=[[0,0],[0,0]],p=6*e-12*n+6*i,m=-3*e+9*n-9*i+3*o,g=3*n-3*e;for(let e=0;e<2;++e){if(e>0&&(p=6*t-12*r+6*a,m=-3*t+9*r-9*a+3*s,g=3*r-3*t),u(m)<1e-12){if(u(p)<1e-12)continue;let e=-g/p;0<e&&e<1&&d.push(e);continue}let n=p*p-4*g*m;if(n<0)continue;let i=l(n),o=(-p+i)/(2*m);0<o&&o<1&&d.push(o);let c=(-p-i)/(2*m);0<c&&c<1&&d.push(c)}let _=d.length,v=_,y=La(e,t,n,r,i,a,o,s);for(;_--;){let{x:e,y:t}=y(d[_]);f[0][_]=e,f[1][_]=t}f[0][v]=e,f[1][v]=t,f[0][v+1]=o,f[1][v+1]=s;let b=[new R(Math.min(...f[0]),Math.min(...f[1])),new R(Math.max(...f[0]),Math.max(...f[1]))];return h.cachesBoundsOfCurve&&(D.boundsOfCurveCache[c]=b),b}var Pa=(e,t,[n,r,i,a,o,s,c,l])=>{let u=((e,t,n,r,i,a,o)=>{if(n===0||r===0)return[];let s=0,c=0,l=0,u=Math.PI,d=o*ee,f=Ee(d),p=Te(d),m=.5*(-p*e-f*t),h=.5*(-p*t+f*e),g=n**2,_=r**2,v=h**2,y=m**2,b=g*_-g*v-_*y,x=Math.abs(n),S=Math.abs(r);if(b<0){let e=Math.sqrt(1-b/(g*_));x*=e,S*=e}else l=(i===a?-1:1)*Math.sqrt(b/(g*v+_*y));let C=l*x*h/S,w=-l*S*m/x,T=p*C-f*w+.5*e,E=f*C+p*w+.5*t,D=Ma(1,0,(m-C)/x,(h-w)/S),O=Ma((m-C)/x,(h-w)/S,(-m-C)/x,(-h-w)/S);a===0&&O>0?O-=2*u:a===1&&O<0&&(O+=2*u);let k=Math.ceil(Math.abs(O/u*2)),A=[],j=O/k,M=8/3*Math.sin(j/4)*Math.sin(j/4)/Math.sin(j/2),N=D+j;for(let e=0;e<k;e++)A[e]=ja(D,N,p,f,x,S,T,E,M,s,c),s=A[e][5],c=A[e][6],D=N,N+=j;return A})(c-e,l-t,r,i,o,s,a);for(let n=0,r=u.length;n<r;n++)u[n][1]+=e,u[n][2]+=t,u[n][3]+=e,u[n][4]+=t,u[n][5]+=e,u[n][6]+=t;return u},Fa=e=>{let t=0,n=0,r=0,i=0,a=[],o,s=0,c=0;for(let l of e){let e=[...l],u;switch(e[0]){case`l`:e[1]+=t,e[2]+=n;case`L`:t=e[1],n=e[2],u=[`L`,t,n];break;case`h`:e[1]+=t;case`H`:t=e[1],u=[`L`,t,n];break;case`v`:e[1]+=n;case`V`:n=e[1],u=[`L`,t,n];break;case`m`:e[1]+=t,e[2]+=n;case`M`:t=e[1],n=e[2],r=e[1],i=e[2],u=[`M`,t,n];break;case`c`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n,e[5]+=t,e[6]+=n;case`C`:s=e[3],c=e[4],t=e[5],n=e[6],u=[`C`,e[1],e[2],s,c,t,n];break;case`s`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n;case`S`:o===`C`?(s=2*t-s,c=2*n-c):(s=t,c=n),t=e[3],n=e[4],u=[`C`,s,c,e[1],e[2],t,n],s=u[3],c=u[4];break;case`q`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n;case`Q`:s=e[1],c=e[2],t=e[3],n=e[4],u=[`Q`,s,c,t,n];break;case`t`:e[1]+=t,e[2]+=n;case`T`:o===`Q`?(s=2*t-s,c=2*n-c):(s=t,c=n),t=e[1],n=e[2],u=[`Q`,s,c,t,n];break;case`a`:e[6]+=t,e[7]+=n;case`A`:Pa(t,n,e).forEach(e=>a.push(e)),t=e[6],n=e[7];break;case`z`:case`Z`:t=r,n=i,u=[`Z`]}u?(a.push(u),o=u[0]):o=``}return a},Ia=(e,t,n,r)=>Math.sqrt((n-e)**2+(r-t)**2),La=(e,t,n,r,i,a,o,s)=>c=>{let l=c**3,u=(e=>3*e**2*(1-e))(c),d=(e=>3*e*(1-e)**2)(c),f=(e=>(1-e)**3)(c);return new R(o*l+i*u+n*d+e*f,s*l+a*u+r*d+t*f)},Ra=e=>e**2,za=e=>2*e*(1-e),Ba=e=>(1-e)**2,Va=(e,t,n,r,i,a,o,s)=>c=>{let l=Ra(c),u=za(c),d=Ba(c),f=3*(d*(n-e)+u*(i-n)+l*(o-i)),p=3*(d*(r-t)+u*(a-r)+l*(s-a));return Math.atan2(p,f)},Ha=(e,t,n,r,i,a)=>o=>{let s=Ra(o),c=za(o),l=Ba(o);return new R(i*s+n*c+e*l,a*s+r*c+t*l)},Ua=(e,t,n,r,i,a)=>o=>{let s=1-o,c=2*(s*(n-e)+o*(i-n)),l=2*(s*(r-t)+o*(a-r));return Math.atan2(l,c)},Wa=(e,t,n)=>{let r=new R(t,n),i=0;for(let t=1;t<=100;t+=1){let n=e(t/100);i+=Ia(r.x,r.y,n.x,n.y),r=n}return i},Ga=(e,t)=>{let n,r=0,i=0,a={x:e.x,y:e.y},o={...a},s=.01,c=0,l=e.iterator,u=e.angleFinder;for(;i<t&&s>1e-4;)o=l(r),c=r,n=Ia(a.x,a.y,o.x,o.y),n+i>t?(r-=s,s/=2):(a=o,r+=s,i+=n);return{...o,angle:u(c)}},Ka=e=>{let t,n,r=0,i=0,a=0,o=0,s=0,c=[];for(let l of e){let e={x:i,y:a,command:l[0],length:0};switch(l[0]){case`M`:n=e,n.x=o=i=l[1],n.y=s=a=l[2];break;case`L`:n=e,n.length=Ia(i,a,l[1],l[2]),i=l[1],a=l[2];break;case`C`:t=La(i,a,l[1],l[2],l[3],l[4],l[5],l[6]),n=e,n.iterator=t,n.angleFinder=Va(i,a,l[1],l[2],l[3],l[4],l[5],l[6]),n.length=Wa(t,i,a),i=l[5],a=l[6];break;case`Q`:t=Ha(i,a,l[1],l[2],l[3],l[4]),n=e,n.iterator=t,n.angleFinder=Ua(i,a,l[1],l[2],l[3],l[4]),n.length=Wa(t,i,a),i=l[3],a=l[4];break;case`Z`:n=e,n.destX=o,n.destY=s,n.length=Ia(i,a,o,s),i=o,a=s}r+=n.length,c.push(n)}return c.push({length:r,x:i,y:a}),c},qa=(e,t,n=Ka(e))=>{let r=0;for(;t-n[r].length>0&&r<n.length-2;)t-=n[r].length,r++;let i=n[r],a=t/i.length,o=e[r];switch(i.command){case`M`:return{x:i.x,y:i.y,angle:0};case`Z`:return{...new R(i.x,i.y).lerp(new R(i.destX,i.destY),a),angle:Math.atan2(i.destY-i.y,i.destX-i.x)};case`L`:return{...new R(i.x,i.y).lerp(new R(o[1],o[2]),a),angle:Math.atan2(o[2]-i.y,o[1]-i.x)};case`C`:case`Q`:return Ga(i,t)}},Ja=RegExp(`[mzlhvcsqta][^mzlhvcsqta]*`,`gi`),Ya=new RegExp(ka,`g`),Xa=new RegExp(zn,`gi`),Za={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Qa=e=>{let t=[],n=e.match(Ja)??[];for(let e of n){let n=e[0];if(n===`z`||n===`Z`){t.push([n]);continue}let r=Za[n.toLowerCase()],i=[];if(n===`a`||n===`A`){let t;for(Ya.lastIndex=0;t=Ya.exec(e);)i.push(...t.slice(1))}else i=e.match(Xa)||[];for(let e=0;e<i.length;e+=r){let a=Array(r),o=Aa[n];a[0]=e>0&&o?o:n;for(let t=0;t<r;t++)a[t+1]=parseFloat(i[e+t]);t.push(a)}}return t},$a=(e,t=0)=>{let n=new R(e[0]),r=new R(e[1]),i=1,a=0,o=[],s=e.length,c=s>2,l;for(c&&(i=e[2].x<r.x?-1:e[2].x===r.x?0:1,a=e[2].y<r.y?-1:e[2].y===r.y?0:1),o.push([`M`,n.x-i*t,n.y-a*t]),l=1;l<s;l++){if(!n.eq(r)){let e=n.midPointFrom(r);o.push([`Q`,n.x,n.y,e.x,e.y])}n=e[l],l+1<e.length&&(r=e[l+1])}return c&&(i=n.x>e[l-2].x?1:n.x===e[l-2].x?0:-1,a=n.y>e[l-2].y?1:n.y===e[l-2].y?0:-1),o.push([`L`,n.x+i*t,n.y+a*t]),o},eo=(e,t,n)=>(n&&(t=B(t,[1,0,0,1,-n.x,-n.y])),e.map(e=>{let n=[...e];for(let r=1;r<e.length-1;r+=2){let{x:i,y:a}=Ue({x:e[r],y:e[r+1]},t);n[r]=i,n[r+1]=a}return n})),to=(e,t)=>{let n=2*Math.PI/e,r=-A;e%2==0&&(r+=n/2);let i=Array(e+1);for(let a=0;a<e;a++){let e=a*n+r,{x:o,y:s}=new R(Te(e),Ee(e)).scalarMultiply(t);i[a]=[a===0?`M`:`L`,o,s]}return i[e]=[`Z`],i},no=(e,t)=>e.map(e=>e.map((e,n)=>n===0||t===void 0?e:V(e,t)).join(` `)).join(` `),ro=(e,t)=>{let n=e,r=t;n.inverted&&!r.inverted&&(n=t,r=e),Ut(r,r.group?.calcTransformMatrix(),n.calcTransformMatrix());let i=n.inverted&&r.inverted;return i&&(n.inverted=r.inverted=!1),new Ca([n],{clipPath:r,inverted:i})},io=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,ao=(e,t)=>{let n=e._findCenterFromElement();e.transformMatrix&&((e=>{if(e.transformMatrix){let{scaleX:t,scaleY:n,angle:r,skewX:i}=Ye(e.transformMatrix);e.flipX=!1,e.flipY=!1,e.set(pe,t),e.set(me,n),e.angle=r,e.skewX=i,e.skewY=0}})(e),n=n.transform(e.transformMatrix)),delete e.transformMatrix,t&&(e.scaleX*=t.scaleX,e.scaleY*=t.scaleY,e.cropX=t.cropX,e.cropY=t.cropY,n.x+=t.offsetLeft,n.y+=t.offsetTop,e.width=t.width,e.height=t.height),e.setPositionByOrigin(n,P,P)},oo=u({addTransformToObject:()=>Ft,animate:()=>Wr,animateColor:()=>Gr,applyTransformToObject:()=>It,calcAngleBetweenVectors:()=>Zt,calcDimensionsMatrix:()=>nt,calcPlaneChangeMatrix:()=>Bt,calcVectorRotation:()=>Qt,cancelAnimFrame:()=>Me,capValue:()=>$n,composeMatrix:()=>rt,copyCanvasElement:()=>Le,cos:()=>Te,createCanvasElement:()=>Fe,createImage:()=>Ie,createRotateMatrix:()=>Ze,createScaleMatrix:()=>Qe,createSkewXMatrix:()=>et,createSkewYMatrix:()=>tt,createTranslateMatrix:()=>Xe,createVector:()=>Yt,crossProduct:()=>tn,degreesToRadians:()=>z,dotProduct:()=>nn,ease:()=>rr,enlivenObjectEnlivables:()=>ot,enlivenObjects:()=>at,findScaleToCover:()=>Ea,findScaleToFit:()=>Ta,getBoundsOfCurve:()=>Na,getOrthonormalVector:()=>en,getPathSegmentsInfo:()=>Ka,getPointOnPath:()=>qa,getPointer:()=>At,getRandomInt:()=>io,getRegularPolygonPath:()=>to,getSmoothPathFromPoints:()=>$a,getSvgAttributes:()=>wn,getUnitVector:()=>$t,groupSVGElements:()=>wa,hasStyleChanged:()=>Bi,invertTransform:()=>We,isBetweenVectors:()=>rn,isIdentityMatrix:()=>He,isTouchEvent:()=>jt,isTransparent:()=>Ni,joinPath:()=>no,loadImage:()=>it,magnitude:()=>Xt,makeBoundingBoxFromPoints:()=>Nt,makePathSimpler:()=>Fa,matrixToSVG:()=>lt,mergeClipPaths:()=>ro,multiplyTransformMatrices:()=>B,multiplyTransformMatrixArray:()=>Ge,parsePath:()=>Qa,parsePreserveAspectRatioAttribute:()=>En,parseUnit:()=>Tn,pick:()=>st,projectStrokeOnPoints:()=>Ri,qrDecompose:()=>Ye,radiansToDegrees:()=>Ve,removeFromArray:()=>we,removeTransformFromObject:()=>Pt,removeTransformMatrixForSvgParsing:()=>ao,requestAnimFrame:()=>je,resetObjectTransform:()=>Lt,rotateVector:()=>Jt,saveObjectTransform:()=>Rt,sendObjectToPlane:()=>Ut,sendPointToPlane:()=>Vt,sendVectorToPlane:()=>Ht,sin:()=>Ee,sizeAfterTransform:()=>zt,string:()=>St,stylesFromArray:()=>Hi,stylesToArray:()=>Vi,toBlob:()=>Be,toDataURL:()=>ze,toFixed:()=>V,transformPath:()=>eo,transformPoint:()=>Ue});function so(e,t){let n=e.style;n&&Object.entries(t).forEach(([e,t])=>n.setProperty(e,t))}var co=class extends bt{constructor(e,{allowTouchScrolling:t=!1,containerClass:n=``}={}){super(e),p(this,`upper`,void 0),p(this,`container`,void 0);let{el:r}=this.lower,i=this.createUpperCanvas();this.upper={el:i,ctx:i.getContext(`2d`)},this.applyCanvasStyle(r,{allowTouchScrolling:t}),this.applyCanvasStyle(i,{allowTouchScrolling:t,styles:{position:`absolute`,left:`0`,top:`0`}});let a=this.createContainerElement();a.classList.add(n),r.parentNode&&r.parentNode.replaceChild(a,r),a.append(r,i),this.container=a}createUpperCanvas(){let{el:e}=this.lower,t=Fe();return t.className=e.className,t.classList.remove(`lower-canvas`),t.classList.add(`upper-canvas`),t.setAttribute(`data-fabric`,`top`),t.style.cssText=e.style.cssText,t.setAttribute(`draggable`,`true`),t}createContainerElement(){let e=w().createElement(`div`);return e.setAttribute(`data-fabric`,`wrapper`),so(e,{position:`relative`}),yt(e),e}applyCanvasStyle(e,t){let{styles:n,allowTouchScrolling:r}=t;so(e,{...n,"touch-action":r?`manipulation`:ne}),yt(e)}setDimensions(e,t){super.setDimensions(e,t);let{el:n,ctx:r}=this.upper;_t(n,r,e,t)}setCSSDimensions(e){super.setCSSDimensions(e),vt(this.upper.el,e),vt(this.container,e)}cleanupDOM(e){let t=this.container,{el:n}=this.lower,{el:r}=this.upper;super.cleanupDOM(e),t.removeChild(r),t.removeChild(n),t.parentNode&&t.parentNode.replaceChild(n,t)}dispose(){super.dispose(),C().dispose(this.upper.el),delete this.upper,delete this.container}},lo=(e,t,n,r)=>{let{target:i,offsetX:a,offsetY:o}=t,s=n-a,c=r-o,l=!cn(i,`lockMovementX`)&&i.left!==s,u=!cn(i,`lockMovementY`)&&i.top!==c;return l&&i.set(`left`,s),u&&i.set(`top`,c),(l||u)&&Yr(ie,ln(e,t,n,r)),l||u},uo=ue,fo=e=>function(t,n,r){let{points:i,pathOffset:a}=r;return new R(i[e]).subtract(a).transform(B(r.getViewportTransform(),r.calcTransformMatrix()))},po=(e,t,n,r)=>{let{target:i,pointIndex:a}=t,o=i,s=Vt(new R(n,r),void 0,o.calcOwnMatrix());return o.points[a]=s.add(o.pathOffset),o.setDimensions(),o.set(`dirty`,!0),!0},mo=(e,t)=>function(n,r,i,a){let o=r.target,s=new R(o.points[(e>0?e:o.points.length)-1]),c=s.subtract(o.pathOffset).transform(o.calcOwnMatrix()),l=t(n,{...r,pointIndex:e},i,a),u=s.subtract(o.pathOffset).transform(o.calcOwnMatrix()).subtract(c);return o.left-=u.x,o.top-=u.y,l},ho=e=>Xr(uo,mo(e,po));function go(e,t={}){let n={};for(let r=0;r<(typeof e==`number`?e:e.points.length);r++)n[`p${r}`]=new ai({actionName:uo,positionHandler:fo(r),actionHandler:ho(r),...t});return n}var _o=(e,t,n)=>{let{path:r,pathOffset:i}=e,a=r[t];return new R(a[n]-i.x,a[n+1]-i.y).transform(B(e.getViewportTransform(),e.calcTransformMatrix()))};function vo(e,t,n){let{commandIndex:r,pointIndex:i}=this;return _o(n,r,i)}function yo(e,t,n,r){let{target:i}=t,{commandIndex:a,pointIndex:o}=this,s=((e,t,n,r,i)=>{let{path:a,pathOffset:o}=e,s=a[(r>0?r:a.length)-1],c=new R(s[i],s[i+1]),l=c.subtract(o).transform(e.calcOwnMatrix()),u=Vt(new R(t,n),void 0,e.calcOwnMatrix());a[r][i]=u.x+o.x,a[r][i+1]=u.y+o.y,e.setDimensions();let d=c.subtract(e.pathOffset).transform(e.calcOwnMatrix()).subtract(l);return e.left-=d.x,e.top-=d.y,e.set(`dirty`,!0),!0})(i,n,r,a,o);return s&&Yr(this.actionName,{...ln(e,t,n,r),commandIndex:a,pointIndex:o}),s}var bo=class extends ai{constructor(e){super(e)}render(e,t,n,r,i){let a={...r,cornerColor:this.controlFill,cornerStrokeColor:this.controlStroke,transparentCorners:!this.controlFill};super.render(e,t,n,a,i)}},xo=class extends bo{constructor(e){super(e)}render(e,t,n,r,i){let{path:a}=i,{commandIndex:o,pointIndex:s,connectToCommandIndex:c,connectToPointIndex:l}=this;e.save(),e.strokeStyle=this.controlStroke,this.connectionDashArray&&e.setLineDash(this.connectionDashArray);let[u]=a[o],d=_o(i,c,l);if(u===`Q`){let r=_o(i,o,s+2);e.moveTo(r.x,r.y),e.lineTo(t,n)}else e.moveTo(t,n);e.lineTo(d.x,d.y),e.stroke(),e.restore(),super.render(e,t,n,r,i)}},So=(e,t,n,r,i,a)=>new(n?xo:bo)({commandIndex:e,pointIndex:t,actionName:`modifyPath`,positionHandler:vo,actionHandler:yo,connectToCommandIndex:i,connectToPointIndex:a,...r,...n?r.controlPointStyle:r.pointStyle});function Co(e,t={}){let n={},r=`M`;return e.path.forEach((e,i)=>{let a=e[0];switch(a!==`Z`&&(n[`c_${i}_${a}`]=So(i,e.length-2,!1,t)),a){case`C`:n[`c_${i}_C_CP_1`]=So(i,1,!0,t,i-1,(e=>e===`C`?5:e===`Q`?3:1)(r)),n[`c_${i}_C_CP_2`]=So(i,3,!0,t,i,5);break;case`Q`:n[`c_${i}_Q_CP_1`]=So(i,1,!0,t,i,3)}r=a}),n}u({changeHeight:()=>ni,changeObjectHeight:()=>ei,changeObjectWidth:()=>$r,changeWidth:()=>ti,createObjectDefaultControls:()=>Di,createPathControls:()=>Co,createPolyActionHandler:()=>ho,createPolyControls:()=>go,createPolyPositionHandler:()=>fo,createResizeControls:()=>Oi,createTextboxDefaultControls:()=>ki,dragHandler:()=>lo,factoryPolyActionHandler:()=>mo,getLocalPoint:()=>dn,polyActionHandler:()=>po,renderCircleControl:()=>ri,renderSquareControl:()=>ii,rotationStyleHandler:()=>oi,rotationWithSnapping:()=>si,scaleCursorStyleHandler:()=>di,scaleOrSkewActionName:()=>Ci,scaleSkewCursorStyleHandler:()=>wi,scalingEqually:()=>pi,scalingX:()=>mi,scalingXOrSkewingY:()=>Ti,scalingY:()=>hi,scalingYOrSkewingX:()=>Ei,skewCursorStyleHandler:()=>vi,skewHandlerX:()=>bi,skewHandlerY:()=>xi,wrapWithFireEvent:()=>Xr,wrapWithFixedAnchor:()=>Zr});var wo=class e extends Ot{constructor(...e){super(...e),p(this,`_hoveredTargets`,[]),p(this,`_currentTransform`,null),p(this,`_groupSelector`,null),p(this,`contextTopDirty`,!1)}static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}get upperCanvasEl(){return this.elements.upper?.el}get contextTop(){return this.elements.upper?.ctx}get wrapperEl(){return this.elements.container}initElements(e){this.elements=new co(e,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(e){this._objectsToRender=void 0,super._onObjectAdded(e)}_onObjectRemoved(e){this._objectsToRender=void 0,e===this._activeObject&&(this.fire(`before:selection:cleared`,{deselected:[e]}),this._discardActiveObject(),this.fire(`selection:cleared`,{deselected:[e]}),e.fire(`deselected`,{target:e})),e===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(e)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){let e=this._activeObject;return!this.preserveObjectStacking&&e?this._objects.filter(t=>!t.group&&t!==e).concat(e):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),!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()}renderTop(){let e=this.contextTop;this.clearContext(e),this.renderTopLayer(e),this.fire(`after:render`,{ctx:e})}setTargetFindTolerance(e){e=Math.round(e),this.targetFindTolerance=e;let t=this.getRetinaScaling(),n=Math.ceil((2*e+1)*t);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=n,this.pixelFindContext.scale(t,t)}isTargetTransparent(e,t,n){let r=this.targetFindTolerance,i=this.pixelFindContext;this.clearContext(i),i.save(),i.translate(-t+r,-n+r),i.transform(...this.viewportTransform);let a=e.selectionBackgroundColor;e.selectionBackgroundColor=``,e.render(i),e.selectionBackgroundColor=a,i.restore();let o=Math.round(r*this.getRetinaScaling());return Ni(i,o,o,o)}_isSelectionKeyPressed(e){let t=this.selectionKey;return!!t&&(Array.isArray(t)?!!t.find(t=>!!t&&!0===e[t]):e[t])}_shouldClearSelection(e,t){let n=this.getActiveObjects(),r=this._activeObject;return!!(!t||t&&r&&n.length>1&&n.indexOf(t)===-1&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t)}_shouldCenterTransform(e,t,n){if(!e)return;let r;return t===`scale`||t===`scaleX`||t===`scaleY`||t===`resizing`?r=this.centeredScaling||e.centeredScaling:t===`rotate`&&(r=this.centeredRotation||e.centeredRotation),r?!n:n}_getOriginFromCorner(e,t){let n=t?e.controls[t].getTransformAnchorPoint():{x:e.originX,y:e.originY};return t?([`ml`,`tl`,`bl`].includes(t)?n.x=te:[`mr`,`tr`,`br`].includes(t)&&(n.x=F),[`tl`,`mt`,`tr`].includes(t)?n.y=I:[`bl`,`mb`,`br`].includes(t)&&(n.y=`top`),n):n}_setupCurrentTransform(e,t,n){let r=t.group?Vt(this.getScenePoint(e),void 0,t.group.calcTransformMatrix()):this.getScenePoint(e),{key:i=``,control:a}=t.getActiveControl()||{},o=n&&a?a.getActionHandler(e,t,a)?.bind(a):lo,s=((e,t,n,r)=>{if(!t||!e)return`drag`;let i=r.controls[t];return i.getActionName(n,i,r)})(n,i,e,t),c=e[this.centeredKey],l=this._shouldCenterTransform(t,s,c)?{x:P,y:P}:this._getOriginFromCorner(t,i),{scaleX:u,scaleY:d,skewX:f,skewY:p,left:m,top:h,angle:g,width:_,height:v,cropX:y,cropY:b}=t,x={target:t,action:s,actionHandler:o,actionPerformed:!1,corner:i,scaleX:u,scaleY:d,skewX:f,skewY:p,offsetX:r.x-m,offsetY:r.y-h,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:z(g),width:_,height:v,shiftKey:e.shiftKey,altKey:c,original:{...Rt(t),originX:l.x,originY:l.y,cropX:y,cropY:b}};this._currentTransform=x,this.fire(`before:transform`,{e,transform:x})}setCursor(e){this.upperCanvasEl.style.cursor=e}_drawSelection(e){let{x:t,y:n,deltaX:r,deltaY:i}=this._groupSelector,a=new R(t,n).transform(this.viewportTransform),o=new R(t+r,n+i).transform(this.viewportTransform),s=this.selectionLineWidth/2,c=Math.min(a.x,o.x),l=Math.min(a.y,o.y),u=Math.max(a.x,o.x),d=Math.max(a.y,o.y);this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(c,l,u-c,d-l)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,c+=s,l+=s,u-=s,d-=s,Mi.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(c,l,u-c,d-l))}findTarget(e){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};let t=this.getScenePoint(e),n=this._activeObject,r=this.getActiveObjects(),i=this.searchPossibleTargets(this._objects,t),{subTargets:a,container:o,target:s}=i,c={...i,currentSubTargets:a,currentContainer:o,currentTarget:s};if(!n)return c;let l={...this.searchPossibleTargets([n],t),currentSubTargets:a,currentContainer:o,currentTarget:s};return n.findControl(this.getViewportPoint(e),jt(e))?{...l,target:n}:l.target&&(r.length>1||!this.preserveObjectStacking||this.preserveObjectStacking&&e[this.altSelectionKey])?l:c}_pointIsInObjectSelectionArea(e,t){let n=e.getCoords(),r=this.getZoom(),i=e.padding/r;if(i){let[e,t,r,a]=n,o=Math.atan2(t.y-e.y,t.x-e.x),s=Te(o)*i,c=Ee(o)*i,l=s+c,u=s-c;n=[new R(e.x-u,e.y-l),new R(t.x+l,t.y-u),new R(r.x+u,r.y+l),new R(a.x-l,a.y+u)]}return Kr.isPointInPolygon(t,n)}_checkTarget(e,t){if(e&&e.visible&&e.evented&&this._pointIsInObjectSelectionArea(e,t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;{let n=t.transform(this.viewportTransform);if(!this.isTargetTransparent(e,n.x,n.y))return!0}}return!1}_searchPossibleTargets(e,t,n){let r=e.length;for(;r--;){let i=e[r];if(this._checkTarget(i,t)){if(Oe(i)&&i.subTargetCheck){let{target:e}=this._searchPossibleTargets(i._objects,t,n);e&&n.push(e)}return{target:i,subTargets:n}}}return{subTargets:[]}}searchPossibleTargets(e,t){let n=this._searchPossibleTargets(e,t,[]);n.container=n.target;let{container:r,subTargets:i}=n;if(r&&Oe(r)&&r.interactive&&i[0]){for(let e=i.length-1;e>0;e--){let t=i[e];if(!Oe(t)||!t.interactive)return n.target=t,n}return n.target=i[0],n}return n}getViewportPoint(e){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(e,!0)}getScenePoint(e){return this._scenePoint?this._scenePoint:this._getPointerImpl(e)}_getPointerImpl(e,t=!1){let n=this.upperCanvasEl,r=n.getBoundingClientRect(),i=At(e),a=r.width||0,o=r.height||0;a&&o||(`top`in r&&`bottom`in r&&(o=Math.abs(r.top-r.bottom)),`right`in r&&`left`in r&&(a=Math.abs(r.right-r.left))),this.calcOffset(),i.x-=this._offset.left,i.y-=this._offset.top,t||(i=Vt(i,void 0,this.viewportTransform));let s=this.getRetinaScaling();s!==1&&(i.x/=s,i.y/=s);let c=a===0||o===0?new R(1,1):new R(n.width/a,n.height/o);return i.multiply(c)}_setDimensionsImpl(e,t){this._resetTransformEventData(),super._setDimensionsImpl(e,t),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Fe(),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(){let e=this._activeObject;return pt(e)?e.getObjects():e?[e]:[]}_fireSelectionEvents(e,t){let n=!1,r=!1,i=this.getActiveObjects(),a=[],o=[];e.forEach(e=>{i.includes(e)||(n=!0,e.fire(`deselected`,{e:t,target:e}),o.push(e))}),i.forEach(r=>{e.includes(r)||(n=!0,r.fire(`selected`,{e:t,target:r}),a.push(r))}),e.length>0&&i.length>0?(r=!0,n&&this.fire(`selection:updated`,{e:t,selected:a,deselected:o})):i.length>0?(r=!0,this.fire(`selection:created`,{e:t,selected:a})):e.length>0&&(r=!0,this.fire(`selection:cleared`,{e:t,deselected:o})),r&&(this._objectsToRender=void 0)}setActiveObject(e,t){let n=this.getActiveObjects(),r=this._setActiveObject(e,t);return this._fireSelectionEvents(n,t),r}_setActiveObject(e,t){let n=this._activeObject;return n!==e&&!(!this._discardActiveObject(t,e)&&this._activeObject)&&!e.onSelect({e:t})&&(this._activeObject=e,pt(e)&&n!==e&&e.set(`canvas`,this),e.setCoords(),!0)}_discardActiveObject(e,t){let n=this._activeObject;return!!n&&!n.onDeselect({e,object:t})&&(this._currentTransform&&this._currentTransform.target===n&&this.endCurrentTransform(e),pt(n)&&n===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(e){let t=this.getActiveObjects(),n=this.getActiveObject();t.length&&this.fire(`before:selection:cleared`,{e,deselected:[n]});let r=this._discardActiveObject(e);return this._fireSelectionEvents(t,e),r}endCurrentTransform(e){let t=this._currentTransform;this._finalizeCurrentTransform(e),t&&t.target&&(t.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(e){let t=this._currentTransform,n=t.target,r={e,target:n,transform:t,action:t.action};n._scaling&&=!1,n.setCoords(),t.actionPerformed&&(this.fire(`object:modified`,r),n.fire(ye,r))}setViewportTransform(e){super.setViewportTransform(e);let t=this._activeObject;t&&t.setCoords()}destroy(){let e=this._activeObject;pt(e)&&(e.removeAll(),e.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(e){let t=this._activeObject;t&&t._renderControls(e)}_toObject(e,t,n){let r=this._realizeGroupTransformOnObject(e),i=super._toObject(e,t,n);return e.set(r),i}_realizeGroupTransformOnObject(e){let{group:t}=e;if(t&&pt(t)&&this._activeObject===t){let n=st(e,[`angle`,`flipX`,`flipY`,F,pe,me,he,ge,`top`]);return Ft(e,t.calcOwnMatrix()),n}return{}}_setSVGObject(e,t,n){let r=this._realizeGroupTransformOnObject(t);super._setSVGObject(e,t,n),t.set(r)}};p(wo,`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:!0,fireRightClick:!0,fireMiddleClick:!0,enablePointerEvents:!1,containerClass:`canvas-container`,preserveObjectStacking:!0});var To=class{constructor(e){p(this,`targets`,[]),p(this,`__disposer`,void 0);let t=()=>{let{hiddenTextarea:t}=e.getActiveObject()||{};t&&t.focus()},n=e.upperCanvasEl;n.addEventListener(`click`,t),this.__disposer=()=>n.removeEventListener(`click`,t)}exitTextEditing(){this.target=void 0,this.targets.forEach(e=>{e.isEditing&&e.exitEditing()})}add(e){this.targets.push(e)}remove(e){this.unregister(e),we(this.targets,e)}register(e){this.target=e}unregister(e){e===this.target&&(this.target=void 0)}onMouseMove(e){var t;(t=this.target)!=null&&t.isEditing&&this.target.updateSelectionOnMouseMove(e)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}},Eo={passive:!1},Do=(e,t)=>({viewportPoint:e.getViewportPoint(t),scenePoint:e.getScenePoint(t)}),Oo=(e,...t)=>e.addEventListener(...t),ko=(e,...t)=>e.removeEventListener(...t),Ao={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`}},jo=class extends wo{constructor(e,t={}){super(e,t),p(this,`_isClick`,void 0),p(this,`textEditingManager`,new To(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(Oo)}_getEventPrefix(){return this.enablePointerEvents?`pointer`:`mouse`}addOrRemove(e,t=!1){let n=this.upperCanvasEl,r=this._getEventPrefix();e(gt(n),`resize`,this._onResize),e(n,r+`down`,this._onMouseDown),e(n,`${r}move`,this._onMouseMove,Eo),e(n,`${r}out`,this._onMouseOut),e(n,`${r}enter`,this._onMouseEnter),e(n,`wheel`,this._onMouseWheel,{passive:!1}),e(n,`contextmenu`,this._onContextMenu),t||(e(n,`click`,this._onClick),e(n,`dblclick`,this._onClick)),e(n,`dragstart`,this._onDragStart),e(n,`dragend`,this._onDragEnd),e(n,`dragover`,this._onDragOver),e(n,`dragenter`,this._onDragEnter),e(n,`dragleave`,this._onDragLeave),e(n,`drop`,this._onDrop),this.enablePointerEvents||e(n,`touchstart`,this._onTouchStart,Eo)}removeListeners(){this.addOrRemove(ko);let e=this._getEventPrefix(),t=ht(this.upperCanvasEl);ko(t,`${e}up`,this._onMouseUp),ko(t,`touchend`,this._onTouchEnd,Eo),ko(t,`${e}move`,this._onMouseMove,Eo),ko(t,`touchmove`,this._onMouseMove,Eo),clearTimeout(this._willAddMouseDown)}_onMouseWheel(e){this._cacheTransformEventData(e),this._handleEvent(e,`wheel`),this._resetTransformEventData()}_onMouseOut(e){let t=this._hoveredTarget,n={e,...Do(this,e)};this.fire(`mouse:out`,{...n,target:t}),this._hoveredTarget=void 0,t&&t.fire(`mouseout`,{...n}),this._hoveredTargets.forEach(e=>{this.fire(`mouse:out`,{...n,target:e}),e&&e.fire(`mouseout`,{...n})}),this._hoveredTargets=[]}_onMouseEnter(e){let{target:t}=this.findTarget(e);this._currentTransform||t||(this.fire(`mouse:over`,{e,...Do(this,e)}),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(e){this._isClick=!1;let t=this.getActiveObject();if(t&&t.onDragStart(e)){this._dragSource=t;let n={e,target:t};this.fire(`dragstart`,n),t.fire(`dragstart`,n),Oo(this.upperCanvasEl,`drag`,this._onDragProgress);return}Mt(e)}_renderDragEffects(e,t,n){let r=!1,i=this._dropTarget;i&&i!==t&&i!==n&&(i.clearContextTop(),r=!0),t?.clearContextTop(),n!==t&&n?.clearContextTop();let a=this.contextTop;a.save(),a.transform(...this.viewportTransform),t&&(a.save(),t.transform(a),t.renderDragSourceEffect(e),a.restore(),r=!0),n&&(a.save(),n.transform(a),n.renderDropTargetEffect(e),a.restore(),r=!0),a.restore(),r&&(this.contextTopDirty=!0)}_onDragEnd(e){let{currentSubTargets:t}=this.findTarget(e),n=!!e.dataTransfer&&e.dataTransfer.dropEffect!==`none`,r=n?this._activeObject:void 0,i={e,target:this._dragSource,subTargets:t,dragSource:this._dragSource,didDrop:n,dropTarget:r};ko(this.upperCanvasEl,`drag`,this._onDragProgress),this.fire(`dragend`,i),this._dragSource&&this._dragSource.fire(`dragend`,i),delete this._dragSource,this._onMouseUp(e)}_onDragProgress(e){let t={e,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire(`drag`,t),this._dragSource&&this._dragSource.fire(`drag`,t)}_onDragOver(e){let t=`dragover`,{currentContainer:n,currentSubTargets:r}=this.findTarget(e),i=this._dragSource,a={e,target:n,subTargets:r,dragSource:i,canDrop:!1,dropTarget:void 0},o;this.fire(t,a),this._fireEnterLeaveEvents(e,n,a),n&&(n.canDrop(e)&&(o=n),n.fire(t,a));for(let n=0;n<r.length;n++){let i=r[n];i.canDrop(e)&&(o=i),i.fire(t,a)}this._renderDragEffects(e,i,o),this._dropTarget=o}_onDragEnter(e){let{currentContainer:t,currentSubTargets:n}=this.findTarget(e),r={e,target:t,subTargets:n,dragSource:this._dragSource};this.fire(`dragenter`,r),this._fireEnterLeaveEvents(e,t,r)}_onDragLeave(e){let{currentSubTargets:t}=this.findTarget(e),n={e,target:this._draggedoverTarget,subTargets:t,dragSource:this._dragSource};this.fire(`dragleave`,n),this._fireEnterLeaveEvents(e,void 0,n),this._renderDragEffects(e,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(e){let{currentContainer:t,currentSubTargets:n}=this.findTarget(e),r=this._basicEventHandler(`drop:before`,{e,target:t,subTargets:n,dragSource:this._dragSource,...Do(this,e)});r.didDrop=!1,r.dropTarget=void 0,this._basicEventHandler(`drop`,r),this.fire(`drop:after`,r)}_onContextMenu(e){let{target:t,subTargets:n}=this.findTarget(e),r=this._basicEventHandler(`contextmenu:before`,{e,target:t,subTargets:n});return this.stopContextMenu&&Mt(e),this._basicEventHandler(`contextmenu`,r),!1}_onClick(e){let t=e.detail;t>3||t<2||(this._cacheTransformEventData(e),t==2&&e.type===`dblclick`&&this._handleEvent(e,`dblclick`),t==3&&this._handleEvent(e,`tripleclick`),this._resetTransformEventData())}fireEventFromPointerEvent(e,t,n,r={}){this._cacheTransformEventData(e);let{target:i,subTargets:a}=this.findTarget(e),o={e,target:i,subTargets:a,...Do(this,e),transform:this._currentTransform,...r};this.fire(t,o),i&&i.fire(n,o);for(let e=0;e<a.length;e++)a[e]!==i&&a[e].fire(n,o);this._resetTransformEventData()}getPointerId(e){let t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1}_isMainEvent(e){return!0===e.isPrimary||!1!==e.isPrimary&&(e.type===`touchend`&&e.touches.length===0||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(e){this._cacheTransformEventData(e);let t=!this.allowTouchScrolling,n=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(e)),this.__onMouseDown(e);let{target:r}=this.findTarget(e);(this.isDrawingMode||n&&r===n)&&(t=!0),t&&e.preventDefault();let i=this.upperCanvasEl,a=this._getEventPrefix(),o=ht(i);Oo(o,`touchend`,this._onTouchEnd,Eo),t&&Oo(o,`touchmove`,this._onMouseMove,Eo),ko(i,`${a}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(e){this._cacheTransformEventData(e),this.__onMouseDown(e);let t=this.upperCanvasEl,n=this._getEventPrefix();ko(t,`${n}move`,this._onMouseMove,Eo);let r=ht(t);Oo(r,`${n}up`,this._onMouseUp),Oo(r,`${n}move`,this._onMouseMove,Eo),this._resetTransformEventData()}_onTouchEnd(e){if(e.touches.length>0)return;this._cacheTransformEventData(e),this.__onMouseUp(e),this._resetTransformEventData(),delete this.mainTouchId;let t=this._getEventPrefix(),n=ht(this.upperCanvasEl);ko(n,`touchend`,this._onTouchEnd,Eo),ko(n,`touchmove`,this._onMouseMove,Eo),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{Oo(this.upperCanvasEl,`${t}down`,this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(e){this._cacheTransformEventData(e),this.__onMouseUp(e);let t=this.upperCanvasEl,n=this._getEventPrefix();if(this._isMainEvent(e)){let e=ht(this.upperCanvasEl);ko(e,`${n}up`,this._onMouseUp),ko(e,`${n}move`,this._onMouseMove,Eo),Oo(t,`${n}move`,this._onMouseMove,Eo)}this._resetTransformEventData()}_onMouseMove(e){this._cacheTransformEventData(e);let t=this.getActiveObject();!this.allowTouchScrolling&&(!t||!t.shouldStartDragging(e))&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e),this._resetTransformEventData()}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(e){let t=this.getActiveObject();return!!t!=!!e||t&&e&&t!==e}__onMouseUp(e){var t;this._handleEvent(e,`up:before`);let n=this._currentTransform,r=this._isClick,{target:i}=this.findTarget(e),{button:a}=e;if(a)return void((this.fireMiddleClick&&a===1||this.fireRightClick&&a===2)&&this._handleEvent(e,`up`));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(e);if(!this._isMainEvent(e))return;let o,s,c=!1;if(n&&(this._finalizeCurrentTransform(e),c=n.actionPerformed),!r){let t=i===this._activeObject;this.handleSelection(e),c||=this._shouldRender(i)||!t&&i===this._activeObject}if(i){let{key:t,control:r}=i.findControl(this.getViewportPoint(e),jt(e))||{};if(s=t,i.selectable&&i!==this._activeObject&&i.activeOn===`up`)this.setActiveObject(i,e),c=!0;else if(r){let t=r.getMouseUpHandler(e,i,r);t&&(o=this.getScenePoint(e),t.call(r,e,n,o.x,o.y))}i.isMoving=!1}if(n&&(n.target!==i||n.corner!==s)){let t=n.target&&n.target.controls[n.corner],r=t&&t.getMouseUpHandler(e,n.target,t);o||=this.getScenePoint(e),r&&r.call(t,e,n,o.x,o.y)}this._setCursorFromEvent(e,i),this._handleEvent(e,`up`),this._groupSelector=null,this._currentTransform=null,i&&(i.__corner=void 0),c?this.requestRenderAll():r||(t=this._activeObject)!=null&&t.isEditing||this.renderTop()}_basicEventHandler(e,t){let{target:n,subTargets:r=[]}=t;this.fire(e,t),n&&n.fire(e,t);for(let i=0;i<r.length;i++)r[i]!==n&&r[i].fire(e,t);return t}_handleEvent(e,t,n){let{target:r,subTargets:i}=this.findTarget(e),a={e,target:r,subTargets:i,...Do(this,e),transform:this._currentTransform,...t===`down:before`||t===`down`?n:{}};t!==`up:before`&&t!==`up`||(a.isClick=this._isClick),this.fire(`mouse:${t}`,a),r&&r.fire(`mouse${t}`,a);for(let e=0;e<i.length;e++)i[e]!==r&&i[e].fire(`mouse${t}`,a)}_onMouseDownInDrawingMode(e){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(e),this.requestRenderAll());let t=this.getScenePoint(e);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(t,{e,pointer:t}),this._handleEvent(e,`down`,{alreadySelected:!1})}_onMouseMoveInDrawingMode(e){if(this._isCurrentlyDrawing){let t=this.getScenePoint(e);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(t,{e,pointer:t})}this.setCursor(this.freeDrawingCursor),this._handleEvent(e,`move`)}_onMouseUpInDrawingMode(e){let t=this.getScenePoint(e);this._isCurrentlyDrawing=this.freeDrawingBrush?!!this.freeDrawingBrush.onMouseUp({e,pointer:t}):!1,this._handleEvent(e,`up`)}__onMouseDown(e){this._isClick=!0,this._handleEvent(e,`down:before`);let{target:t}=this.findTarget(e),n=!!t&&t===this._activeObject,{button:r}=e;if(r)return void((this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(e,`down`,{alreadySelected:n}));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(e);if(!this._isMainEvent(e)||this._currentTransform)return;let i=this._shouldRender(t),a=!1;if(this.handleMultiSelection(e,t)?(t=this._activeObject,a=!0,i=!0):this._shouldClearSelection(e,t)&&this.discardActiveObject(e),this.selection&&(!t||!t.selectable&&!t.isEditing&&t!==this._activeObject)){let t=this.getScenePoint(e);this._groupSelector={x:t.x,y:t.y,deltaY:0,deltaX:0}}if(n=!!t&&t===this._activeObject,t){t.selectable&&t.activeOn===`down`&&this.setActiveObject(t,e);let r=t.findControl(this.getViewportPoint(e),jt(e));if(t===this._activeObject&&(r||!a)){this._setupCurrentTransform(e,t,n);let i=r?r.control:void 0,a=this.getScenePoint(e),o=i&&i.getMouseDownHandler(e,t,i);o&&o.call(i,e,this._currentTransform,a.x,a.y)}}i&&(this._objectsToRender=void 0),this._handleEvent(e,`down`,{alreadySelected:n}),i&&this.requestRenderAll()}_resetTransformEventData(){this._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(e){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(e),this._scenePoint=Vt(this._viewportPoint,void 0,this.viewportTransform),this._targetInfo=this.findTarget(e),this._currentTransform&&(this._targetInfo.target=this._currentTransform.target)}__onMouseMove(e){if(this._isClick=!1,this._handleEvent(e,`move:before`),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(e);if(!this._isMainEvent(e))return;let t=this._groupSelector;if(t){let n=this.getScenePoint(e);t.deltaX=n.x-t.x,t.deltaY=n.y-t.y,this.renderTop()}else if(this._currentTransform)this._transformObject(e);else{let{target:t}=this.findTarget(e);this._setCursorFromEvent(e,t),this._fireOverOutEvents(e,t)}this.textEditingManager.onMouseMove(e),this._handleEvent(e,`move`)}_fireOverOutEvents(e,t){let{_hoveredTarget:n,_hoveredTargets:r}=this,{subTargets:i,currentTarget:a}=this.findTarget(e),o=Math.max(r.length,i.length);this.fireSyntheticInOutEvents(`mouse`,{e,target:t,oldTarget:n,actualTarget:a,oldActualTarget:this._hoveredActualTarget,fireCanvas:!0});for(let a=0;a<o;a++)i[a]===t||r[a]&&r[a]===n||this.fireSyntheticInOutEvents(`mouse`,{e,target:i[a],oldTarget:r[a]});this._hoveredActualTarget=a,this._hoveredTarget=t,this._hoveredTargets=i}_fireEnterLeaveEvents(e,t,n){let r=this._draggedoverTarget,i=this._hoveredTargets,{subTargets:a}=this.findTarget(e),o=Math.max(i.length,a.length);this.fireSyntheticInOutEvents(`drag`,{...n,target:t,oldTarget:r,fireCanvas:!0});for(let e=0;e<o;e++)this.fireSyntheticInOutEvents(`drag`,{...n,target:a[e],oldTarget:i[e]});this._draggedoverTarget=t}fireSyntheticInOutEvents(e,{target:t,oldTarget:n,actualTarget:r,oldActualTarget:i,fireCanvas:a,e:o,...s}){let{targetIn:c,targetOut:l,canvasIn:u,canvasOut:d}=Ao[e],f=n!==t,p=i!==r,m=t&&f,h=r&&p,g=n&&f,_=i&&p,v={...s,e:o,...Do(this,o)},y={...v,target:n,nextTarget:t,actualTarget:i,nextActualTarget:r};(g||_)&&a&&this.fire(d,y),g&&n.fire(l,y),_&&n!==i&&i.fire(l,y);let b={...v,target:t,previousTarget:n,actualTarget:r,previousActualTarget:i};(m||h)&&a&&this.fire(u,b),m&&t.fire(c,b),h&&r!==t&&r.fire(c,b)}_transformObject(e){let t=this.getScenePoint(e),n=this._currentTransform,r=n.target,i=r.group?Vt(t,void 0,r.group.calcTransformMatrix()):t;n.shiftKey=e.shiftKey,n.altKey=!!this.centeredKey&&e[this.centeredKey],this._performTransformAction(e,n,i),n.actionPerformed&&this.requestRenderAll()}_performTransformAction(e,t,n){let{action:r,actionHandler:i,target:a}=t,o=!!i&&i(e,t,n.x,n.y);o&&a.setCoords(),r===`drag`&&o&&(t.target.isMoving=!0,this.setCursor(t.target.moveCursor||this.moveCursor)),t.actionPerformed=t.actionPerformed||o}_setCursorFromEvent(e,t){if(!t)return void this.setCursor(this.defaultCursor);let n=t.hoverCursor||this.hoverCursor,r=pt(this._activeObject)?this._activeObject:null,i=(!r||t.group!==r)&&t.findControl(this.getViewportPoint(e));if(i){let{control:n,coord:r}=i;this.setCursor(n.cursorStyleHandler(e,n,t,r))}else{if(t.subTargetCheck){let{subTargets:t}=this.findTarget(e);t.concat().reverse().forEach(e=>{n=e.hoverCursor||n})}this.setCursor(n)}}handleMultiSelection(e,t){let n=this._activeObject,r=pt(n);if(n&&this._isSelectionKeyPressed(e)&&this.selection&&t&&t.selectable&&(n!==t||r)&&(r||!t.isDescendantOf(n)&&!n.isDescendantOf(t))&&!t.onSelect({e})&&!n.getActiveControl()){if(r){let r=n.getObjects(),i=[];if(t===n){let n=this.getScenePoint(e),a=this.searchPossibleTargets(r,n);if(a.target?(t=a.target,i=a.subTargets):(a=this.searchPossibleTargets(this._objects,n),t=a.target,i=a.subTargets),!t||!t.selectable)return!1}t.group===n?(n.remove(t),this._hoveredTarget=t,this._hoveredTargets=i,n.size()===1&&this._setActiveObject(n.item(0),e)):(n.multiSelectAdd(t),this._hoveredTarget=n,this._hoveredTargets=i),this._fireSelectionEvents(r,e)}else{n.isEditing&&n.exitEditing();let r=new(L.getClass(`ActiveSelection`))([],{canvas:this});r.multiSelectAdd(n,t),this._hoveredTarget=r,this._setActiveObject(r,e),this._fireSelectionEvents([n],e)}return!0}return!1}handleSelection(e){if(!this.selection||!this._groupSelector)return!1;let{x:t,y:n,deltaX:r,deltaY:i}=this._groupSelector,a=new R(t,n),o=a.add(new R(r,i)),s=a.min(o),c=a.max(o).subtract(s),l=this.collectObjects({left:s.x,top:s.y,width:c.x,height:c.y},{includeIntersecting:!this.selectionFullyContained}),u=a.eq(o)?l[0]?[l[0]]:[]:l.length>1?l.filter(t=>!t.onSelect({e})).reverse():l;if(u.length===1)this.setActiveObject(u[0],e);else if(u.length>1){let t=L.getClass(`ActiveSelection`);this.setActiveObject(new t(u,{canvas:this}),e)}return this._groupSelector=null,!0}toCanvasElement(e=1,t){let{upper:n}=this.elements;n.ctx=void 0;let r=super.toCanvasElement(e,t);return n.ctx=n.el.getContext(`2d`),r}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}},Mo={x1:0,y1:0,x2:0,y2:0},No={...Mo,r1:0,r2:0},Po=(e,t)=>isNaN(e)&&typeof t==`number`?t:e;function Fo(e){return e&&/%$/.test(e)&&Number.isFinite(parseFloat(e))}function Io(e,t){return $n(0,Po(typeof e==`number`?e:typeof e==`string`?parseFloat(e)/(Fo(e)?100:1):NaN,t),1)}var Lo=/\s*;\s*/,Ro=/\s*:\s*/;function zo(e,t){let n,r,i=e.getAttribute(`style`);if(i){let e=i.split(Lo);e[e.length-1]===``&&e.pop();for(let t=e.length;t--;){let[i,a]=e[t].split(Ro).map(e=>e.trim());i===`stop-color`?n=a:i===`stop-opacity`&&(r=a)}}n=n||e.getAttribute(`stop-color`)||`rgb(0,0,0)`,r=Po(parseFloat(r||e.getAttribute(`stop-opacity`)||``),1);let a=new Cn(n);return a.setAlpha(a.getAlpha()*r*t),{offset:Io(e.getAttribute(`offset`),0),color:a.toRgba()}}function Bo(e,t){let n=[],r=e.getElementsByTagName(`stop`),i=Io(t,1);for(let e=r.length;e--;)n.push(zo(r[e],i));return n}function Vo(e){return e.nodeName===`linearGradient`||e.nodeName===`LINEARGRADIENT`?`linear`:`radial`}function Ho(e){return e.getAttribute(`gradientUnits`)===`userSpaceOnUse`?`pixels`:`percentage`}function Uo(e,t){return e.getAttribute(t)}function Wo(e,t){return function(e,{width:t,height:n,gradientUnits:r}){let i;return Object.entries(e).reduce((e,[a,o])=>{if(o===`Infinity`)i=1;else if(o===`-Infinity`)i=0;else{let e=typeof o==`string`;i=e?parseFloat(o):o,e&&Fo(o)&&(i*=.01,r===`pixels`&&(a!==`x1`&&a!==`x2`&&a!==`r2`||(i*=t),a!==`y1`&&a!==`y2`||(i*=n)))}return e[a]=i,e},{})}(Vo(e)===`linear`?function(e){return{x1:Uo(e,`x1`)||0,y1:Uo(e,`y1`)||0,x2:Uo(e,`x2`)||`100%`,y2:Uo(e,`y2`)||0}}(e):function(e){return{x1:Uo(e,`fx`)||Uo(e,`cx`)||`50%`,y1:Uo(e,`fy`)||Uo(e,`cy`)||`50%`,r1:0,x2:Uo(e,`cx`)||`50%`,y2:Uo(e,`cy`)||`50%`,r2:Uo(e,`r`)||`50%`}}(e),{...t,gradientUnits:Ho(e)})}var Go=class{constructor(e){let{type:t=`linear`,gradientUnits:n=`pixels`,coords:r={},colorStops:i=[],offsetX:a=0,offsetY:o=0,gradientTransform:s,id:c}=e||{};Object.assign(this,{type:t,gradientUnits:n,coords:{...t===`radial`?No:Mo,...r},colorStops:i,offsetX:a,offsetY:o,gradientTransform:s,id:c?`${c}_${Pe()}`:Pe()})}addColorStop(e){for(let t in e)this.colorStops.push({offset:parseFloat(t),color:e[t]});return this}toObject(e){return{...st(this,e),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map(e=>({...e})),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0}}toSVG(e,{additionalTransform:t}={}){let n=[],r=this.gradientTransform?this.gradientTransform.concat():N.concat(),i=this.gradientUnits===`pixels`?`userSpaceOnUse`:`objectBoundingBox`,a=this.colorStops.map(e=>({...e})).sort((e,t)=>e.offset-t.offset),o=-this.offsetX,s=-this.offsetY;var c;i===`objectBoundingBox`?(o/=e.width,s/=e.height):(o+=e.width/2,s+=e.height/2),(c=e)&&typeof c._renderPathCommands==`function`&&this.gradientUnits!==`percentage`&&(o-=e.pathOffset.x,s-=e.pathOffset.y),r[4]-=o,r[5]-=s;let l=[`id="SVGID_${H(String(this.id))}"`,`gradientUnits="${i}"`,`gradientTransform="${t?t+` `:``}${lt(r)}"`,``].join(` `),u=e=>parseFloat(String(e));if(this.type===`linear`){let{x1:e,y1:t,x2:r,y2:i}=this.coords,a=u(e),o=u(t),s=u(r),c=u(i);n.push(`<linearGradient `,l,` x1="`,a,`" y1="`,o,`" x2="`,s,`" y2="`,c,`">
18
+ `)}else if(this.type===`radial`){let{x1:e,y1:t,x2:r,y2:i,r1:o,r2:s}=this.coords,c=u(e),d=u(t),f=u(r),p=u(i),m=u(o),h=u(s),g=m>h;n.push(`<radialGradient `,l,` cx="`,g?c:f,`" cy="`,g?d:p,`" r="`,g?m:h,`" fx="`,g?f:c,`" fy="`,g?p:d,`">
19
+ `),g&&(a.reverse(),a.forEach(e=>{e.offset=1-e.offset}));let _=Math.min(m,h);if(_>0){let e=_/Math.max(m,h);a.forEach(t=>{t.offset+=e*(1-t.offset)})}}return a.forEach(({color:e,offset:t})=>{let r=String(e),i=pn(r)?r:new Cn(r).toRgba();n.push(`<stop offset="${100*t}%" style="stop-color:${H(i)};"/>\n`)}),n.push(this.type===`linear`?`</linearGradient>`:`</radialGradient>`,`
20
+ `),n.join(``)}toLive(e){let{x1:t,y1:n,x2:r,y2:i,r1:a,r2:o}=this.coords,s=this.type===`linear`?e.createLinearGradient(t,n,r,i):e.createRadialGradient(t,n,a,r,i,o);return this.colorStops.forEach(({color:e,offset:t})=>{s.addColorStop(t,e)}),s}static async fromObject(e){let{colorStops:t,gradientTransform:n}=e;return new this({...e,colorStops:t?t.map(e=>({...e})):void 0,gradientTransform:n?[...n]:void 0})}static fromElement(e,t,n){let r=Ho(e),i=t._findCenterFromElement();return new this({id:e.getAttribute(`id`)||void 0,type:Vo(e),coords:Wo(e,{width:n.viewBoxWidth||n.width,height:n.viewBoxHeight||n.height}),colorStops:Bo(e,n.opacity),gradientUnits:r,gradientTransform:sa(e.getAttribute(`gradientTransform`)||``),...r===`pixels`?{offsetX:t.width/2-i.x,offsetY:t.height/2-i.y}:{offsetX:0,offsetY:0}})}};p(Go,`type`,`Gradient`),L.setClass(Go,`gradient`),L.setClass(Go,`linear`),L.setClass(Go,`radial`);var Ko=class{get type(){return`pattern`}set type(e){g(`warn`,`Setting type has no effect`,e)}constructor(e){p(this,`repeat`,`repeat`),p(this,`offsetX`,0),p(this,`offsetY`,0),p(this,`crossOrigin`,``),this.id=Pe(),Object.assign(this,e)}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(e){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?e.createPattern(this.source,this.repeat):null}toObject(e=[]){let{repeat:t,crossOrigin:n}=this;return{...st(this,e),type:`pattern`,source:this.sourceToString(),repeat:t,crossOrigin:n,offsetX:V(this.offsetX,h.NUM_FRACTION_DIGITS),offsetY:V(this.offsetY,h.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null}}toSVG({width:e,height:t}){let{source:n,repeat:r,id:i}=this,a=Po(this.offsetX/e,0),o=Po(this.offsetY/t,0),s=r===`repeat-y`||r===`no-repeat`?1+Math.abs(a||0):Po(n.width/e,0),c=r===`repeat-x`||r===`no-repeat`?1+Math.abs(o||0):Po(n.height/t,0);return[`<pattern id="SVGID_${H(i)}" x="${a}" y="${o}" width="${s}" height="${c}">`,`<image x="0" y="0" width="${n.width}" height="${n.height}" xlink:href="${H(this.sourceToString())}"></image>`,`</pattern>`,``].join(`
21
+ `)}static async fromObject({type:e,source:t,patternTransform:n,...r},i){let a=await it(t,{...i,crossOrigin:r.crossOrigin});return new this({...r,patternTransform:n&&n.slice(0),source:a})}};p(Ko,`type`,`Pattern`),L.setClass(Ko),L.setClass(Ko,`pattern`);var qo=class e extends Mi{constructor(t,{path:n,left:r,top:i,...a}={}){super(),Object.assign(this,e.ownDefaults),this.setOptions(a),this._setPath(t||[],!0),typeof r==`number`&&this.set(`left`,r),typeof i==`number`&&this.set(`top`,i)}_setPath(e,t){this.path=Fa(Array.isArray(e)?e:Qa(e)),this.setBoundingBox(t)}_findCenterFromElement(){let e=this._calcBoundsFromPath();return new R(e.left+e.width/2,e.top+e.height/2)}_renderPathCommands(e){let t=-this.pathOffset.x,n=-this.pathOffset.y;e.beginPath();for(let r of this.path)switch(r[0]){case`L`:e.lineTo(r[1]+t,r[2]+n);break;case`M`:e.moveTo(r[1]+t,r[2]+n);break;case`C`:e.bezierCurveTo(r[1]+t,r[2]+n,r[3]+t,r[4]+n,r[5]+t,r[6]+n);break;case`Q`:e.quadraticCurveTo(r[1]+t,r[2]+n,r[3]+t,r[4]+n);break;case`Z`:e.closePath()}}_render(e){this._renderPathCommands(e),this._renderPaintInOrder(e)}toString(){return`#<Path (${this.complexity()}): { "top": ${this.top}, "left": ${this.left} }>`}toObject(e=[]){return{...super.toObject(e),path:this.path.map(e=>e.slice())}}toDatalessObject(e=[]){let t=this.toObject(e);return this.sourcePath&&(delete t.path,t.sourcePath=this.sourcePath),t}_toSVG(){return[`<path `,`COMMON_PARTS`,`d="${no(this.path,h.NUM_FRACTION_DIGITS)}" stroke-linecap="round" />\n`]}_getOffsetTransform(){let e=h.NUM_FRACTION_DIGITS;return` translate(${V(-this.pathOffset.x,e)}, ${V(-this.pathOffset.y,e)})`}toClipPathSVG(e){let t=this._getOffsetTransform();return` `+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})}toSVG(e){let t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(e){let{width:t,height:n,pathOffset:r}=this._calcDimensions();this.set({width:t,height:n,pathOffset:r}),e&&this.setPositionByOrigin(r,`center`,`center`)}_calcBoundsFromPath(){let e=[],t=0,n=0,r=0,i=0;for(let a of this.path)switch(a[0]){case`L`:r=a[1],i=a[2],e.push({x:t,y:n},{x:r,y:i});break;case`M`:r=a[1],i=a[2],t=r,n=i;break;case`C`:e.push(...Na(r,i,a[1],a[2],a[3],a[4],a[5],a[6])),r=a[5],i=a[6];break;case`Q`:e.push(...Na(r,i,a[1],a[2],a[1],a[2],a[3],a[4])),r=a[3],i=a[4];break;case`Z`:r=t,i=n}return Nt(e)}_calcDimensions(){let e=this._calcBoundsFromPath();return{...e,pathOffset:new R(e.left+e.width/2,e.top+e.height/2)}}static fromObject(e){return this._fromObject(e,{extraParam:`path`})}static async fromElement(e,t,n){let{d:r,...i}=fa(e,this.ATTRIBUTE_NAMES,n);return new this(r,{...i,...t,left:void 0,top:void 0})}};p(qo,`type`,`Path`),p(qo,`cacheProperties`,[...tr,`path`,`fillRule`]),p(qo,`ATTRIBUTE_NAMES`,[...Ui,`d`]),L.setClass(qo),L.setSVGClass(qo);var Jo=[`radius`,`startAngle`,`endAngle`,`counterClockwise`],Yo=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_set(e,t){return super._set(e,t),e===`radius`&&this.setRadius(t),this}_render(e){e.beginPath(),e.arc(0,0,this.radius,z(this.startAngle),z(this.endAngle),this.counterClockwise),this._renderPaintInOrder(e)}getRadiusX(){return this.get(`radius`)*this.get(pe)}getRadiusY(){return this.get(`radius`)*this.get(me)}setRadius(e){this.radius=e,this.set({width:2*e,height:2*e})}toObject(e=[]){return super.toObject([...Jo,...e])}_toSVG(){let{radius:e,startAngle:t,endAngle:n}=this,r=(n-t)%360;if(r===0)return[`<circle `,`COMMON_PARTS`,`cx="0" cy="0" `,`r="`,`${H(e)}`,`" />
22
+ `];{let i=z(t),a=z(n),o=Te(i)*e,s=Ee(i)*e,c=Te(a)*e,l=Ee(a)*e;return[`<path d="M ${o} ${s} A ${e} ${e} 0 ${+(r>180)} ${+!this.counterClockwise} ${c} ${l}" `,`COMMON_PARTS`,` />
23
+ `]}}static async fromElement(e,t,n){let{left:r=0,top:i=0,radius:a=0,...o}=fa(e,this.ATTRIBUTE_NAMES,n);return new this({...o,radius:a,left:r-a,top:i-a})}static fromObject(e){return super._fromObject(e)}};p(Yo,`type`,`Circle`),p(Yo,`cacheProperties`,[...tr,...Jo]),p(Yo,`ownDefaults`,{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),p(Yo,`ATTRIBUTE_NAMES`,[`cx`,`cy`,`r`,...Ui]),L.setClass(Yo),L.setSVGClass(Yo);var Xo=[`x1`,`x2`,`y1`,`y2`],Zo=class e extends Mi{constructor([t,n,r,i]=[0,0,0,0],a={}){super(),Object.assign(this,e.ownDefaults),this.setOptions(a),this.x1=t,this.x2=r,this.y1=n,this.y2=i,this._setWidthHeight();let{left:o,top:s}=a;typeof o==`number`&&this.set(`left`,o),typeof s==`number`&&this.set(`top`,s)}_setWidthHeight(){let{x1:e,y1:t,x2:n,y2:r}=this;this.width=Math.abs(n-e),this.height=Math.abs(r-t);let{left:i,top:a,width:o,height:s}=Nt([{x:e,y:t},{x:n,y:r}]),c=new R(i+o/2,a+s/2);this.setPositionByOrigin(c,P,P)}_set(e,t){return super._set(e,t),Xo.includes(e)&&this._setWidthHeight(),this}_render(e){e.beginPath();let t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;let n=e.strokeStyle;e.strokeStyle=ut(this.stroke)?this.stroke.toLive(e):this.stroke??e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=n}_findCenterFromElement(){return new R((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(e=[]){return{...super.toObject(e),...this.calcLinePoints()}}_getNonTransformedDimensions(){let e=super._getNonTransformedDimensions();return this.strokeLineCap===`butt`&&(this.width===0&&(e.y-=this.strokeWidth),this.height===0&&(e.x-=this.strokeWidth)),e}calcLinePoints(){let{x1:e,x2:t,y1:n,y2:r,width:i,height:a}=this,o=e<=t?-.5:.5,s=n<=r?-.5:.5;return{x1:o*i,x2:o*-i,y1:s*a,y2:s*-a}}_toSVG(){let{x1:e,x2:t,y1:n,y2:r}=this.calcLinePoints();return[`<line `,`COMMON_PARTS`,`x1="${e}" y1="${n}" x2="${t}" y2="${r}" />\n`]}static async fromElement(e,t,n){let{x1:r=0,y1:i=0,x2:a=0,y2:o=0,...s}=fa(e,this.ATTRIBUTE_NAMES,n);return new this([r,i,a,o],s)}static fromObject({x1:e,y1:t,x2:n,y2:r,...i}){return this._fromObject({...i,points:[e,t,n,r]},{extraParam:`points`})}};p(Zo,`type`,`Line`),p(Zo,`cacheProperties`,[...tr,...Xo]),p(Zo,`ATTRIBUTE_NAMES`,Ui.concat(Xo)),L.setClass(Zo),L.setSVGClass(Zo);var Qo=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_render(e){let t=this.width/2,n=this.height/2;e.beginPath(),e.moveTo(-t,n),e.lineTo(0,-n),e.lineTo(t,n),e.closePath(),this._renderPaintInOrder(e)}_toSVG(){let e=this.width/2,t=this.height/2;return[`<polygon `,`COMMON_PARTS`,`points="`,`${-e} ${t},0 ${-t},${e} ${t}`,`" />`]}};p(Qo,`type`,`Triangle`),p(Qo,`ownDefaults`,{width:100,height:100}),L.setClass(Qo),L.setSVGClass(Qo);var $o=[`rx`,`ry`],es=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_set(e,t){switch(super._set(e,t),e){case`rx`:this.rx=t,this.set(`width`,2*t);break;case`ry`:this.ry=t,this.set(`height`,2*t)}return this}getRx(){return this.get(`rx`)*this.get(pe)}getRy(){return this.get(`ry`)*this.get(me)}toObject(e=[]){return super.toObject([...$o,...e])}_toSVG(){return[`<ellipse `,`COMMON_PARTS`,`cx="0" cy="0" rx="${H(this.rx)}" ry="${H(this.ry)}" />\n`]}_render(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,M,!1),e.restore(),this._renderPaintInOrder(e)}static async fromElement(e,t,n){let r=fa(e,this.ATTRIBUTE_NAMES,n);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}};p(es,`type`,`Ellipse`),p(es,`cacheProperties`,[...tr,...$o]),p(es,`ownDefaults`,{rx:0,ry:0}),p(es,`ATTRIBUTE_NAMES`,[...Ui,`cx`,`cy`,`rx`,`ry`]),L.setClass(es),L.setSVGClass(es);var ts={exactBoundingBox:!1},ns=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t=[],n={}){super(),p(this,`strokeDiff`,void 0),Object.assign(this,e.ownDefaults),this.setOptions(n),this.points=t;let{left:r,top:i}=n;this.initialized=!0,this.setBoundingBox(!0),typeof r==`number`&&this.set(`left`,r),typeof i==`number`&&this.set(`top`,i)}isOpen(){return!0}_projectStrokeOnPoints(e){return Ri(this.points,e,this.isOpen())}_calcDimensions(e){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,...e||{}};let t=this.exactBoundingBox?this._projectStrokeOnPoints(e).map(e=>e.projectedPoint):this.points;if(t.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new R,strokeOffset:new R,strokeDiff:new R};let n=Nt(t),r=nt({...e,scaleX:1,scaleY:1}),i=Nt(this.points.map(e=>Ue(e,r,!0))),a=new R(this.scaleX,this.scaleY),o=n.left+n.width/2,s=n.top+n.height/2;return this.exactBoundingBox&&(o-=s*Math.tan(z(this.skewX)),s-=o*Math.tan(z(this.skewY))),{...n,pathOffset:new R(o,s),strokeOffset:new R(i.left,i.top).subtract(new R(n.left,n.top)).multiply(a),strokeDiff:new R(n.width,n.height).subtract(new R(i.width,i.height)).multiply(a)}}_findCenterFromElement(){let e=Nt(this.points);return new R(e.left+e.width/2,e.top+e.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(e){let{left:t,top:n,width:r,height:i,pathOffset:a,strokeOffset:o,strokeDiff:s}=this._calcDimensions();this.set({width:r,height:i,pathOffset:a,strokeOffset:o,strokeDiff:s}),e&&this.setPositionByOrigin(new R(t+r/2,n+i/2),`center`,`center`)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new R(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(e={}){if(this.exactBoundingBox){let t;if(Object.keys(e).some(e=>this.strokeUniform||this.constructor.layoutProperties.includes(e))){let{width:n,height:r}=this._calcDimensions(e);t=new R(e.width??n,e.height??r)}else t=new R(e.width??this.width,e.height??this.height);return t.multiply(new R(e.scaleX||this.scaleX,e.scaleY||this.scaleY))}return super._getTransformedDimensions(e)}_set(e,t){let n=this.initialized&&this[e]!==t,r=super._set(e,t);return this.exactBoundingBox&&n&&((e===`scaleX`||e===`scaleY`)&&this.strokeUniform&&this.constructor.layoutProperties.includes(`strokeUniform`)||this.constructor.layoutProperties.includes(e))&&this.setDimensions(),r}toObject(e=[]){return{...super.toObject(e),points:this.points.map(({x:e,y:t})=>({x:e,y:t}))}}_toSVG(){let e=this.pathOffset.x,t=this.pathOffset.y,n=h.NUM_FRACTION_DIGITS,r=this.points.map(({x:r,y:i})=>`${V(r-e,n)},${V(i-t,n)}`).join(` `);return[`<${H(this.constructor.type).toLowerCase()} `,`COMMON_PARTS`,`points="${r}" />\n`]}_render(e){let t=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(t&&!isNaN(this.points[t-1].y)){e.beginPath(),e.moveTo(this.points[0].x-n,this.points[0].y-r);for(let i=0;i<t;i++){let t=this.points[i];e.lineTo(t.x-n,t.y-r)}!this.isOpen()&&e.closePath(),this._renderPaintInOrder(e)}}complexity(){return this.points.length}static async fromElement(e,t,n){let r=function(e){if(!e)return[];let t=e.replace(/,/g,` `).trim().split(/\s+/),n=[];for(let e=0;e<t.length;e+=2)n.push({x:parseFloat(t[e]),y:parseFloat(t[e+1])});return n}(e.getAttribute(`points`)),{left:i,top:a,...o}=fa(e,this.ATTRIBUTE_NAMES,n);return new this(r,{...o,...t})}static fromObject(e){return this._fromObject(e,{extraParam:`points`})}};p(ns,`ownDefaults`,ts),p(ns,`type`,`Polyline`),p(ns,`layoutProperties`,[he,ge,`strokeLineCap`,`strokeLineJoin`,`strokeMiterLimit`,`strokeWidth`,`strokeUniform`,`points`]),p(ns,`cacheProperties`,[...tr,`points`]),p(ns,`ATTRIBUTE_NAMES`,[...Ui]),L.setClass(ns),L.setSVGClass(ns);var rs=class extends ns{isOpen(){return!1}};p(rs,`ownDefaults`,ts),p(rs,`type`,`Polygon`),L.setClass(rs),L.setSVGClass(rs);var is=class extends Mi{isEmptyStyles(e){if(!this.styles||e!==void 0&&!this.styles[e])return!0;let t=e===void 0?this.styles:{line:this.styles[e]};for(let e in t)for(let n in t[e])for(let r in t[e][n])return!1;return!0}styleHas(e,t){if(!this.styles||t!==void 0&&!this.styles[t])return!1;let n=t===void 0?this.styles:{0:this.styles[t]};for(let t in n)for(let r in n[t])if(n[t][r][e]!==void 0)return!0;return!1}cleanStyle(e){if(!this.styles)return!1;let t=this.styles,n,r,i=0,a=!0,o=0;for(let o in t){n=0;for(let s in t[o]){let c=t[o][s]||{};i++,c[e]===void 0?a=!1:(r?c[e]!==r&&(a=!1):r=c[e],c[e]===this[e]&&delete c[e]),Object.keys(c).length===0?delete t[o][s]:n++}n===0&&delete t[o]}for(let e=0;e<this._textLines.length;e++)o+=this._textLines[e].length;a&&i===o&&(this[e]=r,this.removeStyle(e))}removeStyle(e){if(!this.styles)return;let t=this.styles,n,r,i;for(r in t){for(i in n=t[r],n)delete n[i][e],Object.keys(n[i]).length===0&&delete n[i];Object.keys(n).length===0&&delete t[r]}}_extendStyles(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e);this._getLineStyle(n)||this._setLineStyle(n);let i=ct({...this._getStyleDeclaration(n,r),...t},e=>e!==void 0);this._setStyleDeclaration(n,r,i)}getSelectionStyles(e,t,n){let r=[];for(let i=e;i<(t||e);i++)r.push(this.getStyleAtPosition(i,n));return r}getStyleAtPosition(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e);return t?this.getCompleteStyleDeclaration(n,r):this._getStyleDeclaration(n,r)}setSelectionStyles(e,t,n){for(let r=t;r<(n||t);r++)this._extendStyles(r,e);this._forceClearCache=!0}_getStyleDeclaration(e,t){var n;let r=this.styles&&this.styles[e];return r&&(n=r[t])!=null?n:{}}getCompleteStyleDeclaration(e,t){return{...st(this,this.constructor._styleProperties),...this._getStyleDeclaration(e,t)}}_setStyleDeclaration(e,t,n){this.styles[e][t]=n}_deleteStyleDeclaration(e,t){delete this.styles[e][t]}_getLineStyle(e){return!!this.styles[e]}_setLineStyle(e){this.styles[e]={}}_deleteLineStyle(e){delete this.styles[e]}};p(is,`_styleProperties`,In);var as=/ +/g,os=/"/g;function ss(e,t,n,r,i){return`\t\t${((e,{left:t,top:n,width:r,height:i},a=h.NUM_FRACTION_DIGITS)=>{let o=Dn(_e,e,!1),[s,c,l,u]=[t,n,r,i].map(e=>V(e,a));return`<rect ${o} x="${s}" y="${c}" width="${l}" height="${u}"></rect>`})(e,{left:t,top:n,width:r,height:i})}\n`}var cs,ls=class e extends is{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(),p(this,`__charBounds`,[]),Object.assign(this,e.ownDefaults),this.setOptions(n),this.styles||={},this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){let e=this.path;e&&(e.segmentsInfo=Ka(e.path))}_splitText(){let e=this._splitTextIntoLines(this.text);return this.textLines=e.lines,this._textLines=e.graphemeLines,this._unwrappedTextLines=e._unwrappedLines,this._text=e.graphemeText,e}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(`justify`)&&this.enlargeSpaces()}enlargeSpaces(){let e,t,n,r,i,a,o;for(let s=0,c=this._textLines.length;s<c;s++)if((this.textAlign===`justify`||s!==c-1&&!this.isEndOfWrapping(s))&&(r=0,i=this._textLines[s],t=this.getLineWidth(s),t<this.width&&(o=this.textLines[s].match(this._reSpacesAndTabs)))){n=o.length,e=(this.width-t)/n;for(let t=0;t<=i.length;t++)a=this.__charBounds[s][t],this._reSpaceAndTab.test(i[t])?(a.width+=e,a.kernedWidth+=e,a.left+=r,r+=e):a.left+=r}}isEndOfWrapping(e){return e===this._textLines.length-1}missingNewlineOffset(e){return 1}get2DCursorLocation(e,t){let n=t?this._unwrappedTextLines:this._textLines,r;for(r=0;r<n.length;r++){if(e<=n[r].length)return{lineIndex:r,charIndex:e};e-=n[r].length+this.missingNewlineOffset(r,t)}return{lineIndex:r-1,charIndex:n[r-1].length<e?n[r-1].length:e}}toString(){return`#<Text (${this.complexity()}): { "text": "${this.text}", "fontFamily": "${this.fontFamily}" }>`}_getCacheCanvasDimensions(){let e=super._getCacheCanvasDimensions(),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e}_render(e){let t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,`underline`),this._renderText(e),this._renderTextDecoration(e,`overline`),this._renderTextDecoration(e,`linethrough`)}_renderText(e){this.paintFirst===`stroke`?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))}_setTextStyles(e,t,n){if(e.textBaseline=`alphabetic`,this.path)switch(this.pathAlign){case P:e.textBaseline=`middle`;break;case`ascender`:e.textBaseline=`top`;break;case`descender`:e.textBaseline=I}e.font=this._getFontDeclaration(t,n)}calcTextWidth(){let e=this.getLineWidth(0);for(let t=1,n=this._textLines.length;t<n;t++){let n=this.getLineWidth(t);n>e&&(e=n)}return e}_renderTextLine(e,t,n,r,i,a){this._renderChars(e,t,n,r,i,a)}_renderTextLinesBackground(e){if(!this.textBackgroundColor&&!this.styleHas(`textBackgroundColor`))return;let t=e.fillStyle,n=this._getLeftOffset(),r=this._getTopOffset();for(let t=0,i=this._textLines.length;t<i;t++){let i=this.getHeightOfLine(t);if(!this.textBackgroundColor&&!this.styleHas(`textBackgroundColor`,t)){r+=i;continue}let a=this._textLines[t].length,o=this._getLineLeftOffset(t),s,c,l=0,u=0,d=this.getValueOfPropertyAt(t,0,`textBackgroundColor`),f=this.getHeightOfLineImpl(t);for(let i=0;i<a;i++){let a=this.__charBounds[t][i];c=this.getValueOfPropertyAt(t,i,`textBackgroundColor`),this.path?(e.save(),e.translate(a.renderLeft,a.renderTop),e.rotate(a.angle),e.fillStyle=c,c&&e.fillRect(-a.width/2,-f*(1-this._fontSizeFraction),a.width,f),e.restore()):c===d?l+=a.kernedWidth:(s=n+o+u,this.direction===`rtl`&&(s=this.width-s-l),e.fillStyle=d,d&&e.fillRect(s,r,l,f),u=a.left,l=a.width,d=c)}c&&!this.path&&(s=n+o+u,this.direction===`rtl`&&(s=this.width-s-l),e.fillStyle=c,e.fillRect(s,r,l,f)),r+=i}e.fillStyle=t,this._removeShadow(e)}_measureChar(e,t,n,r){let i=D.getFontCache(t),a=this._getFontDeclaration(t),o=n?n+e:e,s=n&&a===this._getFontDeclaration(r),c=t.fontSize/this.CACHE_FONT_SIZE,l,u,d,f;if(n&&i.has(n)&&(d=i.get(n)),i.has(e)&&(f=l=i.get(e)),s&&i.has(o)&&(u=i.get(o),f=u-d),l===void 0||d===void 0||u===void 0){let r=(cs||=Re({width:0,height:0}).getContext(`2d`),cs);this._setTextStyles(r,t,!0),l===void 0&&(f=l=r.measureText(e).width,i.set(e,l)),d===void 0&&s&&n&&(d=r.measureText(n).width,i.set(n,d)),s&&u===void 0&&(u=r.measureText(o).width,i.set(o,u),f=u-d)}return{width:l*c,kernedWidth:f*c}}getHeightOfChar(e,t){return this.getValueOfPropertyAt(e,t,`fontSize`)}measureLine(e){let t=this._measureLine(e);return this.charSpacing!==0&&(t.width-=this._getWidthOfCharSpacing()),t.width<0&&(t.width=0),t}_measureLine(e){let t,n,r=0,i=this.pathSide===te,a=this.path,o=this._textLines[e],s=o.length,c=Array(s);this.__charBounds[e]=c;for(let i=0;i<s;i++){let a=o[i];n=this._getGraphemeBox(a,e,i,t),c[i]=n,r+=n.kernedWidth,t=a}if(c[s]={left:n?n.left+n.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},a&&a.segmentsInfo){let e=0,t=a.segmentsInfo[a.segmentsInfo.length-1].length;switch(this.textAlign){case F:e=i?t-r:0;break;case P:e=(t-r)/2;break;case te:e=i?0:t-r}e+=this.pathStartOffset*(i?-1:1);for(let r=i?s-1:0;i?r>=0:r<s;i?r--:r++)n=c[r],e>t?e%=t:e<0&&(e+=t),this._setGraphemeOnPath(e,n),e+=n.kernedWidth}return{width:r,numOfSpaces:0}}_setGraphemeOnPath(e,t){let n=e+t.kernedWidth/2,r=this.path,i=qa(r.path,n,r.segmentsInfo);t.renderLeft=i.x-r.pathOffset.x,t.renderTop=i.y-r.pathOffset.y,t.angle=i.angle+(this.pathSide===`right`?Math.PI:0)}_getGraphemeBox(e,t,n,r,i){let a=this.getCompleteStyleDeclaration(t,n),o=r?this.getCompleteStyleDeclaration(t,n-1):{},s=this._measureChar(e,a,r,o),c,l=s.kernedWidth,u=s.width;this.charSpacing!==0&&(c=this._getWidthOfCharSpacing(),u+=c,l+=c);let d={width:u,left:0,height:a.fontSize,kernedWidth:l,deltaY:a.deltaY};if(n>0&&!i){let e=this.__charBounds[t][n-1];d.left=e.left+e.width+s.kernedWidth-s.width}return d}getHeightOfLineImpl(e){let t=this.__lineHeights;if(t[e])return t[e];let n=this.getHeightOfChar(e,0);for(let t=1,r=this._textLines[e].length;t<r;t++)n=Math.max(this.getHeightOfChar(e,t),n);return t[e]=n*this._fontSizeMult}getHeightOfLine(e){return this.getHeightOfLineImpl(e)*this.lineHeight}calcTextHeight(){let e=0;for(let t=0,n=this._textLines.length;t<n;t++)e+=t===n-1?this.getHeightOfLineImpl(t):this.getHeightOfLine(t);return e}_getLeftOffset(){return this.direction===`ltr`?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(e,t){e.save();let n=0,r=this._getLeftOffset(),i=this._getTopOffset();for(let a=0,o=this._textLines.length;a<o;a++)this._renderTextLine(t,e,this._textLines[a],r+this._getLineLeftOffset(a),i+n+this.getHeightOfLineImpl(a),a),n+=this.getHeightOfLine(a);e.restore()}_renderTextFill(e){(this.fill||this.styleHas(`fill`))&&this._renderTextCommon(e,`fillText`)}_renderTextStroke(e){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this._setLineDash(e,this.strokeDashArray),e.beginPath(),this._renderTextCommon(e,`strokeText`),e.closePath(),e.restore())}_renderChars(e,t,n,r,i,a){let o=this.textAlign.includes(Rn),s=this.path,c=!o&&this.charSpacing===0&&this.isEmptyStyles(a)&&!s,l=this.direction===`ltr`,u=this.direction===`ltr`?1:-1,d=t.direction,f,p,m,h,g,_=``,v=0;if(t.save(),d!==this.direction&&(t.canvas.setAttribute(`dir`,l?`ltr`:`rtl`),t.direction=l?`ltr`:`rtl`,t.textAlign=l?F:te),i-=this.getHeightOfLineImpl(a)*this._fontSizeFraction,c)return this._renderChar(e,t,a,0,n.join(``),r,i),void t.restore();for(let c=0,l=n.length-1;c<=l;c++)h=c===l||this.charSpacing||s,_+=n[c],m=this.__charBounds[a][c],v===0?(r+=u*(m.kernedWidth-m.width),v+=m.width):v+=m.kernedWidth,o&&!h&&this._reSpaceAndTab.test(n[c])&&(h=!0),h||=(f||=this.getCompleteStyleDeclaration(a,c),p=this.getCompleteStyleDeclaration(a,c+1),Bi(f,p,!1)),h&&(s?(t.save(),t.translate(m.renderLeft,m.renderTop),t.rotate(m.angle),this._renderChar(e,t,a,c,_,-v/2,0),t.restore()):(g=r,this._renderChar(e,t,a,c,_,g,i)),_=``,f=p,r+=u*v,v=0);t.restore()}_applyPatternGradientTransformText(e){let t=this.width+this.strokeWidth,n=this.height+this.strokeWidth,r=Re({width:t,height:n}),i=r.getContext(`2d`);return r.width=t,r.height=n,i.beginPath(),i.moveTo(0,0),i.lineTo(t,0),i.lineTo(t,n),i.lineTo(0,n),i.closePath(),i.translate(t/2,n/2),i.fillStyle=e.toLive(i),this._applyPatternGradientTransform(i,e),i.fill(),i.createPattern(r,`no-repeat`)}handleFiller(e,t,n){let r,i;return ut(n)?n.gradientUnits===`percentage`||n.gradientTransform||n.patternTransform?(r=-this.width/2,i=-this.height/2,e.translate(r,i),e[t]=this._applyPatternGradientTransformText(n),{offsetX:r,offsetY:i}):(e[t]=n.toLive(e),this._applyPatternGradientTransform(e,n)):(e[t]=n,{offsetX:0,offsetY:0})}_setStrokeStyles(e,{stroke:t,strokeWidth:n}){return e.lineWidth=n,e.lineCap=this.strokeLineCap,e.lineDashOffset=this.strokeDashOffset,e.lineJoin=this.strokeLineJoin,e.miterLimit=this.strokeMiterLimit,this.handleFiller(e,`strokeStyle`,t)}_setFillStyles(e,{fill:t}){return this.handleFiller(e,`fillStyle`,t)}_renderChar(e,t,n,r,i,a,o){let s=this._getStyleDeclaration(n,r),c=this.getCompleteStyleDeclaration(n,r),l=e===`fillText`&&c.fill,u=e===`strokeText`&&c.stroke&&c.strokeWidth;if(u||l){if(t.save(),t.font=this._getFontDeclaration(c),s.textBackgroundColor&&this._removeShadow(t),s.deltaY&&(o+=s.deltaY),l){let e=this._setFillStyles(t,c);t.fillText(i,a-e.offsetX,o-e.offsetY)}if(u){let e=this._setStrokeStyles(t,c);t.strokeText(i,a-e.offsetX,o-e.offsetY)}t.restore()}}setSuperscript(e,t){this._setScript(e,t,this.superscript)}setSubscript(e,t){this._setScript(e,t,this.subscript)}_setScript(e,t,n){let r=this.get2DCursorLocation(e,!0),i=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,`fontSize`),a=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,`deltaY`),o={fontSize:i*n.size,deltaY:a+i*n.baseline};this.setSelectionStyles(o,e,t)}_getLineLeftOffset(e){let t=this.getLineWidth(e),n=this.width-t,r=this.textAlign,i=this.direction,a=this.isEndOfWrapping(e),o=0;return r===`justify`||r===`justify-center`&&!a||r===`justify-right`&&!a||r===`justify-left`&&!a?0:(r===`center`&&(o=n/2),r===`right`&&(o=n),r===`justify-center`&&(o=n/2),r===`justify-right`&&(o=n),i===`rtl`&&(r===`right`||r===`justify-right`?o=0:r===`left`||r===`justify-left`?o=-n:r!==`center`&&r!==`justify-center`||(o=-n/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(e){if(this.__lineWidths[e]!==void 0)return this.__lineWidths[e];let{width:t}=this.measureLine(e);return this.__lineWidths[e]=t,t}_getWidthOfCharSpacing(){return this.charSpacing===0?0:this.fontSize*this.charSpacing/1e3}getValueOfPropertyAt(e,t,n){return this._getStyleDeclaration(e,t)[n]??this[n]}_renderTextDecoration(e,t){if(!this[t]&&!this.styleHas(t))return;let n=this._getTopOffset(),r=this._getLeftOffset(),i=this.path,a=this._getWidthOfCharSpacing(),o=t===`linethrough`?.5:+(t===`overline`),s=this.offsets[t];for(let c=0,l=this._textLines.length;c<l;c++){let l=this.getHeightOfLine(c);if(!this[t]&&!this.styleHas(t,c)){n+=l;continue}let u=this._textLines[c],d=l/this.lineHeight,f=this._getLineLeftOffset(c),p,m=0,h=0,g=this.getValueOfPropertyAt(c,0,t),_=this.getValueOfPropertyAt(c,0,_e),v=this.getValueOfPropertyAt(c,0,`textDecorationColor`)||_,y=this.getValueOfPropertyAt(c,0,An),b=g,x=v,S=y,C=n+d*(1-this._fontSizeFraction),w=this.getHeightOfChar(c,0),T=this.getValueOfPropertyAt(c,0,`deltaY`);for(let n=0,a=u.length;n<a;n++){let a=this.__charBounds[c][n];b=this.getValueOfPropertyAt(c,n,t),p=this.getValueOfPropertyAt(c,n,_e),x=this.getValueOfPropertyAt(c,n,`textDecorationColor`)||p,S=this.getValueOfPropertyAt(c,n,An);let l=this.getHeightOfChar(c,n),u=this.getValueOfPropertyAt(c,n,`deltaY`);if(i&&b&&p){let t=this.fontSize*S/1e3;e.save(),e.fillStyle=x,e.translate(a.renderLeft,a.renderTop),e.rotate(a.angle),e.fillRect(-a.kernedWidth/2,s*l+u-o*t,a.kernedWidth,t),e.restore()}else if((b!==g||p!==_||x!==v||l!==w||S!==y||u!==T)&&h>0){let t=this.fontSize*y/1e3,n=r+f+m;this.direction===`rtl`&&(n=this.width-n-h),g&&v&&y&&(e.fillStyle=v,e.fillRect(n,C+s*w+T-o*t,h,t)),m=a.left,h=a.width,g=b,v=x,y=S,_=p,w=l,T=u}else h+=a.kernedWidth}let E=r+f+m;this.direction===`rtl`&&(E=this.width-E-h),e.fillStyle=x;let D=this.fontSize*S/1e3;b&&x&&S&&e.fillRect(E,C+s*w+T-o*D,h-a,D),n+=l}this._removeShadow(e)}_getFontDeclaration({fontFamily:t=this.fontFamily,fontStyle:n=this.fontStyle,fontWeight:r=this.fontWeight,fontSize:i=this.fontSize}={},a){let o=t.includes(`'`)||t.includes(`"`)||t.includes(`,`)||e.genericFonts.includes(t.toLowerCase())?t:`"${t}"`;return[n,r,`${a?this.CACHE_FONT_SIZE:i}px`,o].join(` `)}render(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(e)))}graphemeSplit(e){return Tt(e)}_splitTextIntoLines(e){let t=e.split(this._reNewline),n=Array(t.length),r=[`
24
+ `],i=[];for(let e=0;e<t.length;e++)n[e]=this.graphemeSplit(t[e]),i=i.concat(n[e],r);return i.pop(),{_unwrappedLines:n,lines:t,graphemeText:i,graphemeLines:n}}toObject(e=[]){return{...super.toObject([...Fn,...e]),styles:Vi(this.styles,this.text),...this.path?{path:this.path.toObject()}:{}}}set(e,t){let{textLayoutProperties:n}=this.constructor;super.set(e,t);let r=!1,i=!1;if(typeof e==`object`)for(let t in e)t===`path`&&this.setPathInfo(),r||=n.includes(t),i||=t===`path`;else r=n.includes(e),i=e===`path`;return i&&this.setPathInfo(),r&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,n,r){let i=fa(t,e.ATTRIBUTE_NAMES,r),{textAnchor:a=F,textDecoration:o=``,dx:s=0,dy:c=0,top:l=0,left:u=0,fontSize:d=16,strokeWidth:f=1,...p}={...n,...i},m=new this(gn(t.textContent||``).trim(),{left:u+s,top:l+c,underline:o.includes(`underline`),overline:o.includes(`overline`),linethrough:o.includes(`line-through`),strokeWidth:0,fontSize:d,...p}),h=m.getScaledHeight()/m.height,g=((m.height+m.strokeWidth)*m.lineHeight-m.height)*h,_=m.getScaledHeight()+g,v=0;return a===`center`&&(v=m.getScaledWidth()/2),a===`right`&&(v=m.getScaledWidth()),m.set({left:m.left-v,top:m.top-(_-m.fontSize*(.07+m._fontSizeFraction))/m.lineHeight,strokeWidth:f}),m}static fromObject(e){return this._fromObject({...e,styles:Hi(e.styles||{},e.text)},{extraParam:`text`})}};p(ls,`textLayoutProperties`,Pn),p(ls,`cacheProperties`,[...tr,...Fn]),p(ls,`ownDefaults`,Ln),p(ls,`type`,`Text`),p(ls,`genericFonts`,[`serif`,`sans-serif`,`monospace`,`cursive`,`fantasy`,`system-ui`,`ui-serif`,`ui-sans-serif`,`ui-monospace`,`ui-rounded`,`math`,`emoji`,`fangsong`]),p(ls,`ATTRIBUTE_NAMES`,Ui.concat(`x`,`y`,`dx`,`dy`,`font-family`,`font-style`,`font-weight`,`font-size`,`letter-spacing`,`text-decoration`,`text-decoration-thickness`,`text-decoration-color`,`text-anchor`)),ji(ls,[class extends On{_toSVG(){let e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(e){let t=this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0}),n=this.path;return n?t+n._createBaseSVGMarkup(n._toSVG(),{reviver:e,withShadow:!0,additionalTransform:lt(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg({textBgRects:e,textSpans:t}){let n=this.getSvgTextDecoration(this);return[e.join(``),` <text xml:space="preserve" `,`font-family="${H(this.fontFamily.replace(os,`'`))}" `,`font-size="${H(this.fontSize)}" `,this.fontStyle?`font-style="${H(this.fontStyle)}" `:``,this.fontWeight?`font-weight="${H(this.fontWeight)}" `:``,n?`text-decoration="${n}" `:``,this.direction===`rtl`?`direction="rtl" `:``,`style="`,this.getSvgStyles(!0),`"`,this.addPaintOrder(),` >`,t.join(``),`</text>
25
+ `]}_getSVGTextAndBg(e,t){let n=[],r=[],i,a=e;this.backgroundColor&&r.push(ss(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let e=0,o=this._textLines.length;e<o;e++)i=this._getLineLeftOffset(e),this.direction===`rtl`&&(i+=this.width),(this.textBackgroundColor||this.styleHas(`textBackgroundColor`,e))&&this._setSVGTextLineBg(r,e,t+i,a),this._setSVGTextLineText(n,e,t+i,a),a+=this.getHeightOfLine(e);return{textSpans:n,textBgRects:r}}_createTextCharSpan(e,t,n,r,i){let a=h.NUM_FRACTION_DIGITS,o=this.getSvgSpanStyles(t,e!==e.trim()||!!e.match(as)),s=o?`style="${o}"`:``,c=t.deltaY,l=c?` dy="${V(c,a)}" `:``,{angle:u,renderLeft:d,renderTop:f,width:p}=i,m=``;if(d!==void 0){let e=p/2;u&&(m=` rotate="${V(Ve(u),a)}"`);let t=Ze({angle:Ve(u)});t[4]=d,t[5]=f;let i=new R(-e,0).transform(t);n=i.x,r=i.y}return`<tspan x="${V(n,a)}" y="${V(r,a)}" ${l}${m}${s}>${H(e)}</tspan>`}_setSVGTextLineText(e,t,n,r){let i=this.getHeightOfLine(t),a=this.textAlign.includes(Rn),o=this._textLines[t],s,c,l,u,d,f=``,p=0;r+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let i=0,m=o.length-1;i<=m;i++)d=i===m||this.charSpacing||this.path,f+=o[i],l=this.__charBounds[t][i],p===0?(n+=l.kernedWidth-l.width,p+=l.width):p+=l.kernedWidth,a&&!d&&this._reSpaceAndTab.test(o[i])&&(d=!0),d||=(s||=this.getCompleteStyleDeclaration(t,i),c=this.getCompleteStyleDeclaration(t,i+1),Bi(s,c,!0)),d&&(u=this._getStyleDeclaration(t,i),e.push(this._createTextCharSpan(f,u,n,r,l)),f=``,s=c,this.direction===`rtl`?n-=p:n+=p,p=0)}_setSVGTextLineBg(e,t,n,r){let i=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,o,s=0,c=0,l=this.getValueOfPropertyAt(t,0,`textBackgroundColor`);for(let u=0;u<i.length;u++){let{left:i,width:d,kernedWidth:f}=this.__charBounds[t][u];o=this.getValueOfPropertyAt(t,u,`textBackgroundColor`),o===l?s+=f:(l&&e.push(ss(l,n+c,r,s,a)),c=i,s=d,l=o)}o&&e.push(ss(l,n+c,r,s,a))}getSvgStyles(e){let t=pn(this.textDecorationColor)?` text-decoration-color: ${H(this[jn])};`:``;return`${super.getSvgStyles(e)} text-decoration-thickness: ${V(this.textDecorationThickness*this.getObjectScaling().y/10,h.NUM_FRACTION_DIGITS)}%;${t} white-space: pre;`}getSvgSpanStyles(e,t){let{fontFamily:n,strokeWidth:r,stroke:i,fill:a,fontSize:o,fontStyle:s,fontWeight:c,textDecorationThickness:l,textDecorationColor:u,linethrough:d,overline:f,underline:p}=e,m=this.getSvgTextDecoration({underline:p??this.underline,overline:f??this.overline,linethrough:d??this.linethrough}),g=l||this.textDecorationThickness,_=u||this.textDecorationColor,v=mn(r),y=hn(n),b=mn(o),x=hn(s),S=mn(c)||hn(c),C=hn(_);return[i?Dn(ve,i):``,v?`stroke-width: ${H(v)}; `:``,y?`font-family: ${y.includes(`'`)||y.includes(`"`)?H(y):`'${H(y)}'`}; `:``,b?`font-size: ${H(b)}px; `:``,x?`font-style: ${H(x)}; `:``,S?`font-weight: ${H(S)}; `:``,m?`text-decoration: ${m}; text-decoration-thickness: ${V(g*this.getObjectScaling().y/10,h.NUM_FRACTION_DIGITS)}%;${C?` text-decoration-color: ${H(C)};`:``} `:``,a?Dn(_e,a):``,t?`white-space: pre; `:``].join(``)}getSvgTextDecoration(e){return[`overline`,`underline`,`line-through`].filter(t=>e[t.replace(`-`,``)]).join(` `)}}]),L.setClass(ls),L.setSVGClass(ls);var us=class{constructor(e){p(this,`target`,void 0),p(this,`__mouseDownInPlace`,!1),p(this,`__dragStartFired`,!1),p(this,`__isDraggingOver`,!1),p(this,`__dragStartSelection`,void 0),p(this,`__dragImageDisposer`,void 0),p(this,`_dispose`,void 0),this.target=e;let t=[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=()=>{t.forEach(e=>e()),this._dispose=void 0}}isPointerOverSelection(e){let t=this.target,n=t.getSelectionStartFromPointer(e);return t.isEditing&&n>=t.selectionStart&&n<=t.selectionEnd&&t.selectionStart<t.selectionEnd}start(e){return this.__mouseDownInPlace=this.isPointerOverSelection(e)}isActive(){return this.__mouseDownInPlace}end(e){let t=this.isActive();return t&&!this.__dragStartFired&&(this.target.setCursorByClick(e),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,t}getDragStartSelection(){return this.__dragStartSelection}setDragImage(e,{selectionStart:t,selectionEnd:n}){var r;let i=this.target,a=i.canvas,o=new R(i.flipX?-1:1,i.flipY?-1:1),s=i._getCursorBoundaries(t),c=new R(s.left+s.leftOffset,s.top+s.topOffset).multiply(o).transform(i.calcTransformMatrix()),l=a.getScenePoint(e).subtract(c),u=i.getCanvasRetinaScaling(),d=i.getBoundingRect(),f=c.subtract(new R(d.left,d.top)),p=a.viewportTransform,m=f.add(l).transform(p,!0),h=i.backgroundColor,g=zi(i.styles);i.backgroundColor=``;let _={stroke:`transparent`,fill:`transparent`,textBackgroundColor:`transparent`};i.setSelectionStyles(_,0,t),i.setSelectionStyles(_,n,i.text.length),i.dirty=!0;let v=i.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});i.backgroundColor=h,i.styles=g,i.dirty=!0,so(v,{position:`fixed`,left:-v.width+`px`,border:ne,width:v.width/u+`px`,height:v.height/u+`px`}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{v.remove()},ht(e.target||this.target.hiddenTextarea).body.appendChild(v),(r=e.dataTransfer)==null||r.setDragImage(v,m.x,m.y)}onDragStart(e){this.__dragStartFired=!0;let t=this.target,n=this.isActive();if(n&&e.dataTransfer){let n=this.__dragStartSelection={selectionStart:t.selectionStart,selectionEnd:t.selectionEnd},r=t._text.slice(n.selectionStart,n.selectionEnd).join(``),i={text:t.text,value:r,...n};e.dataTransfer.setData(`text/plain`,r),e.dataTransfer.setData(`application/fabric`,JSON.stringify({value:r,styles:t.getSelectionStyles(n.selectionStart,n.selectionEnd,!0)})),e.dataTransfer.effectAllowed=`copyMove`,this.setDragImage(e,i)}return t.abortCursorAnimation(),n}canDrop(e){if(this.target.editable&&!this.target.getActiveControl()&&!e.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){let t=this.target.getSelectionStartFromPointer(e),n=this.__dragStartSelection;return t<n.selectionStart||t>n.selectionEnd}return!0}return!1}targetCanDrop(e){return this.target.canDrop(e)}dragEnterHandler({e}){let t=this.targetCanDrop(e);!this.__isDraggingOver&&t&&(this.__isDraggingOver=!0)}dragOverHandler(e){let{e:t}=e,n=this.targetCanDrop(t);!this.__isDraggingOver&&n?this.__isDraggingOver=!0:this.__isDraggingOver&&!n&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(t.preventDefault(),e.canDrop=!0,e.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(e){let{e:t}=e,n=t.defaultPrevented;this.__isDraggingOver=!1,t.preventDefault();let r=t.dataTransfer?.getData(`text/plain`);if(r&&!n){let n=this.target,i=n.canvas,a=n.getSelectionStartFromPointer(t),{styles:o}=t.dataTransfer.types.includes(`application/fabric`)?JSON.parse(t.dataTransfer.getData(`application/fabric`)):{},s=r[Math.max(0,r.length-1)];if(this.__dragStartSelection){let e=this.__dragStartSelection.selectionStart,t=this.__dragStartSelection.selectionEnd;a>e&&a<=t?a=e:a>t&&(a-=t-e),n.removeChars(e,t),delete this.__dragStartSelection}n._reNewline.test(s)&&(n._reNewline.test(n._text[a])||a===n._text.length)&&(r=r.trimEnd()),e.didDrop=!0,e.dropTarget=n,n.insertChars(r,o,a),i.setActiveObject(n),n.enterEditing(t),n.selectionStart=Math.min(a+0,n._text.length),n.selectionEnd=Math.min(n.selectionStart+r.length,n._text.length),n.hiddenTextarea.value=n.text,n._updateTextarea(),n.hiddenTextarea.focus(),n.fire(de,{index:a+0,action:`drop`}),i.fire(`text:changed`,{target:n}),i.contextTopDirty=!0,i.requestRenderAll()}}dragEndHandler({e}){if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){let t=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:i}=this.__dragStartSelection,a=e.dataTransfer?.dropEffect||`none`;a===`none`?(t.selectionStart=r,t.selectionEnd=i,t._updateTextarea(),t.hiddenTextarea.focus()):(t.clearContextTop(),a===`move`&&(t.removeChars(r,i),t.selectionStart=t.selectionEnd=r,t.hiddenTextarea&&(t.hiddenTextarea.value=t.text),t._updateTextarea(),t.fire(de,{index:r,action:`dragend`}),n.fire(`text:changed`,{target:t}),n.requestRenderAll()),t.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}},ds=/[ \n\.,;!\?\-]/,fs=class extends ls{constructor(...e){super(...e),p(this,`_currentCursorOpacity`,1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(e){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(e)}_animateCursor({toValue:e,duration:t,delay:n,onComplete:r}){return Wr({startValue:this._currentCursorOpacity,endValue:e,duration:t,delay:n,onComplete:r,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:e=>{this._currentCursorOpacity=e,this.renderCursorOrSelection()}})}_tick(e){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(e||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var e;(e=this._currentTickCompleteState)==null||e.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(e){this.abortCursorAnimation(),this._tick(e?0:this.cursorDelay)}abortCursorAnimation(){let e=!1;[this._currentTickState,this._currentTickCompleteState].forEach(t=>{t&&!t.isDone()&&(e=!0,t.abort())}),this._currentCursorOpacity=1,e&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(e=>!e||e.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(e){let t=0,n=e-1;if(this._reSpace.test(this._text[n]))for(;this._reSpace.test(this._text[n]);)t++,n--;for(;/\S/.test(this._text[n])&&n>-1;)t++,n--;return e-t}findWordBoundaryRight(e){let t=0,n=e;if(this._reSpace.test(this._text[n]))for(;this._reSpace.test(this._text[n]);)t++,n++;for(;/\S/.test(this._text[n])&&n<this._text.length;)t++,n++;return e+t}findLineBoundaryLeft(e){let t=0,n=e-1;for(;!/\n/.test(this._text[n])&&n>-1;)t++,n--;return e-t}findLineBoundaryRight(e){let t=0,n=e;for(;!/\n/.test(this._text[n])&&n<this._text.length;)t++,n++;return e+t}searchWordBoundary(e,t){let n=this._text,r=e>0&&this._reSpace.test(n[e])&&(t===-1||!re.test(n[e-1]))?e-1:e,i=n[r];for(;r>0&&r<n.length&&!ds.test(i);)r+=t,i=n[r];return t===-1&&ds.test(i)&&r++,r}selectWord(e){e??=this.selectionStart;let t=this.searchWordBoundary(e,-1),n=Math.max(t,this.searchWordBoundary(e,1));this.selectionStart=t,this.selectionEnd=n,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(e){e??=this.selectionStart;let t=this.findLineBoundaryLeft(e),n=this.findLineBoundaryRight(e);this.selectionStart=t,this.selectionEnd=n,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(e){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire(`editing:entered`,e?{e}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire(`text:editing:entered`,{target:this,e}),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(e){if(this.getActiveControl())return;let t=this.hiddenTextarea;ht(t).activeElement!==t&&t.focus();let n=this.getSelectionStartFromPointer(e),r=this.selectionStart,i=this.selectionEnd;(n===this.__selectionStartOnMouseDown&&r!==i||r!==n&&i!==n)&&(n>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=n):(this.selectionStart=n,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===r&&this.selectionEnd===i||(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(e,t,n){let r=n.slice(0,e),i=this.graphemeSplit(r).length;if(e===t)return{selectionStart:i,selectionEnd:i};let a=n.slice(e,t);return{selectionStart:i,selectionEnd:i+this.graphemeSplit(a).length}}fromGraphemeToStringSelection(e,t,n){let r=n.slice(0,e).join(``).length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+n.slice(e,t).join(``).length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){let e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){let{hiddenTextarea:e,direction:t,textAlign:n,inCompositionMode:r}=this;if(!e)return;let i=n===`justify`?t===`ltr`?F:te:n.replace(`justify-`,``),a=this.getPositionByOrigin(i,`top`);this.cursorOffsetCache={},this.text=e.value,this.set(`dirty`,!0),this.initDimensions(),this.setPositionByOrigin(a,i,`top`),this.setCoords();let o=this.fromStringToGraphemeSelection(e.selectionStart,e.selectionEnd,e.value);this.selectionEnd=this.selectionStart=o.selectionEnd,r||(this.selectionStart=o.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){let e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}}_calcTextareaPosition(){if(!this.canvas)return{left:`1px`,top:`1px`};let e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),n=this.get2DCursorLocation(e),r=n.lineIndex,i=n.charIndex,a=this.getValueOfPropertyAt(r,i,`fontSize`)*this.lineHeight,o=t.leftOffset,s=this.getCanvasRetinaScaling(),c=this.canvas.upperCanvasEl,l=c.width/s,u=c.height/s,d=l-a,f=u-a,p=new R(t.left+o,t.top+t.topOffset+a).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new R(c.clientWidth/l,c.clientHeight/u));return p.x<0&&(p.x=0),p.x>d&&(p.x=d),p.y<0&&(p.y=0),p.y>f&&(p.y=f),p.x+=this.canvas._offset.left,p.y+=this.canvas._offset.top,{left:`${p.x}px`,top:`${p.y}px`,fontSize:`${a}px`,charHeight:a}}_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)}exitEditingImpl(){let e=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){let e=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire(`editing:exited`),e&&this.fire(`modified`),this.canvas&&(this.canvas.fire(`text:editing:exited`,{target:this}),e&&this.canvas.fire(`object:modified`,{target:this})),this}_removeExtraneousStyles(){for(let e in this.styles)this._textLines[e]||delete this.styles[e]}removeStyleFromTo(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0),{lineIndex:i,charIndex:a}=this.get2DCursorLocation(t,!0);if(n!==i){if(this.styles[n])for(let e=r;e<this._unwrappedTextLines[n].length;e++)delete this.styles[n][e];if(this.styles[i])for(let e=a;e<this._unwrappedTextLines[i].length;e++){let t=this.styles[i][e];t&&(this.styles[n]||(this.styles[n]={}),this.styles[n][r+e-a]=t)}for(let e=n+1;e<=i;e++)delete this.styles[e];this.shiftLineStyles(i,n-i)}else if(this.styles[n]){let e=this.styles[n],t=a-r;for(let t=r;t<a;t++)delete e[t];for(let r in this.styles[n]){let n=parseInt(r,10);n>=a&&(e[n-t]=e[r],delete e[r])}}}shiftLineStyles(e,t){let n=Object.assign({},this.styles);for(let r in this.styles){let i=parseInt(r,10);i>e&&(this.styles[i+t]=n[i],n[i-t]||delete this.styles[i])}}insertNewlineStyleObject(e,t,n,r){let i={},a=this._unwrappedTextLines[e].length,o=a===t,s=!1;n||=1,this.shiftLineStyles(e,n);let c=this.styles[e]?this.styles[e][t===0?t:t-1]:void 0;for(let n in this.styles[e]){let r=parseInt(n,10);r>=t&&(s=!0,i[r-t]=this.styles[e][n],o&&t===0||delete this.styles[e][n])}let l=!1;for(s&&!o&&(this.styles[e+n]=i,l=!0),(l||a>t)&&n--;n>0;)r&&r[n-1]?this.styles[e+n]={0:{...r[n-1]}}:c?this.styles[e+n]={0:{...c}}:delete this.styles[e+n],n--;this._forceClearCache=!0}insertCharStyleObject(e,t,n,r){this.styles||={};let i=this.styles[e],a=i?{...i}:{};n||=1;for(let e in a){let r=parseInt(e,10);r>=t&&(i[r+n]=a[r],a[r-n]||delete i[r])}if(this._forceClearCache=!0,r){for(;n--;)Object.keys(r[n]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+n]={...r[n]});return}if(!i)return;let o=i[t?t-1:1];for(;o&&n--;)this.styles[e][t+n]={...o}}insertNewStyleBlock(e,t,n){let r=this.get2DCursorLocation(t,!0),i=[0],a,o=0;for(let t=0;t<e.length;t++)e[t]===`
26
+ `?(o++,i[o]=0):i[o]++;for(i[0]>0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,i[0],n),n&&=n.slice(i[0]+1)),o&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+i[0],o),a=1;a<o;a++)i[a]>0?this.insertCharStyleObject(r.lineIndex+a,0,i[a],n):n&&this.styles[r.lineIndex+a]&&n[0]&&(this.styles[r.lineIndex+a][0]=n[0]),n&&=n.slice(i[a]+1);i[a]>0&&this.insertCharStyleObject(r.lineIndex+a,0,i[a],n)}removeChars(e,t=e+1){this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(``),this.set(`dirty`,!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(e,t,n,r=n){r>n&&this.removeStyleFromTo(n,r);let i=this.graphemeSplit(e);this.insertNewStyleBlock(i,n,t),this._text=[...this._text.slice(0,n),...i,...this._text.slice(r)],this.text=this._text.join(``),this.set(`dirty`,!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(e,t,n){n<=e?(t===e?this._selectionDirection=F:this._selectionDirection===`right`&&(this._selectionDirection=F,this.selectionEnd=e),this.selectionStart=n):n>e&&n<t?this._selectionDirection===`right`?this.selectionEnd=n:this.selectionStart=n:(t===e?this._selectionDirection=te:this._selectionDirection===`left`&&(this._selectionDirection=te,this.selectionStart=t),this.selectionEnd=n)}},ps=class extends fs{initHiddenTextarea(){let e=this.canvas&&ht(this.canvas.getElement())||w(),t=e.createElement(`textarea`);Object.entries({autocapitalize:`off`,autocorrect:`off`,autocomplete:`off`,spellcheck:`false`,"data-fabric":`textarea`,wrap:`off`,name:`fabricTextarea`}).map(([e,n])=>t.setAttribute(e,n));let{top:n,left:r,fontSize:i}=this._calcTextareaPosition();t.style.cssText=`position: absolute; top: ${n}; left: ${r}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${i};`,(this.hiddenTextareaContainer||e.body).appendChild(t),Object.entries({blur:`blur`,keydown:`onKeyDown`,keyup:`onKeyUp`,input:`onInput`,copy:`copy`,cut:`copy`,paste:`paste`,compositionstart:`onCompositionStart`,compositionupdate:`onCompositionUpdate`,compositionend:`onCompositionEnd`}).map(([e,n])=>t.addEventListener(e,this[n].bind(this))),this.hiddenTextarea=t}blur(){this.abortCursorAnimation()}onKeyDown(e){if(!this.isEditing)return;let t=this.direction===`rtl`?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(e){let t=this.fromPaste,{value:n,selectionStart:r,selectionEnd:i}=this.hiddenTextarea;if(this.fromPaste=!1,e&&e.stopPropagation(),!this.isEditing)return;let a=()=>{this.updateFromTextArea(),this.fire(de),this.canvas&&(this.canvas.fire(`text:changed`,{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value===``)return this.styles={},void a();let o=this._splitTextIntoLines(n).graphemeText,s=this._text.length,c=o.length,l=this.selectionStart,u=this.selectionEnd,d=l!==u,f,p,m,g,_=c-s,v=this.fromStringToGraphemeSelection(r,i,n),y=l>v.selectionStart;d?(p=this._text.slice(l,u),_+=u-l):c<s&&(p=y?this._text.slice(u+_,u):this._text.slice(l,l-_));let b=o.slice(v.selectionEnd-_,v.selectionEnd);if(p&&p.length&&(b.length&&(f=this.getSelectionStyles(l,l+1,!1),f=b.map(()=>f[0])),d?(m=l,g=u):y?(m=u-p.length,g=u):(m=u,g=u+p.length),this.removeStyleFromTo(m,g)),b.length){let{copyPasteData:e}=C();t&&b.join(``)===e.copiedText&&!h.disableStyleCopyPaste&&(f=e.copiedTextStyle),this.insertNewStyleBlock(b,l,f)}a()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate({target:e}){let{selectionStart:t,selectionEnd:n}=e;this.compositionStart=t,this.compositionEnd=n,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;let{copyPasteData:e}=C();e.copiedText=this.getSelectedText(),e.copiedTextStyle=h.disableStyleCopyPaste?void 0:this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(e,t){let n,r=this._getLineLeftOffset(e);return t>0&&(n=this.__charBounds[e][t-1],r+=n.left+n.width),r}getDownCursorOffset(e,t){let n=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(n),i=r.lineIndex;if(i===this._textLines.length-1||e.metaKey||e.keyCode===34)return this._text.length-n;let a=r.charIndex,o=this._getWidthBeforeCursor(i,a),s=this._getIndexOnLine(i+1,o);return this._textLines[i].slice(a).length+s+1+this.missingNewlineOffset(i)}_getSelectionForOffset(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart}getUpCursorOffset(e,t){let n=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(n),i=r.lineIndex;if(i===0||e.metaKey||e.keyCode===33)return-n;let a=r.charIndex,o=this._getWidthBeforeCursor(i,a),s=this._getIndexOnLine(i-1,o),c=this._textLines[i].slice(0,a),l=this.missingNewlineOffset(i-1);return-this._textLines[i-1].length+s-c.length+(1-l)}_getIndexOnLine(e,t){let n=this._textLines[e],r,i,a=this._getLineLeftOffset(e),o=0;for(let s=0,c=n.length;s<c;s++)if(r=this.__charBounds[e][s].width,a+=r,a>t){i=!0;let e=a-r,n=a,c=Math.abs(e-t);o=Math.abs(n-t)<c?s:s-1;break}return i||(o=n.length-1),o}moveCursorDown(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown(`Down`,e)}moveCursorUp(e){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown(`Up`,e)}_moveCursorUpOrDown(e,t){let n=this[`get${e}CursorOffset`](t,this._selectionDirection===te);if(t.shiftKey?this.moveCursorWithShift(n):this.moveCursorWithoutShift(n),n!==0){let e=this.text.length;this.selectionStart=$n(0,this.selectionStart,e),this.selectionEnd=$n(0,this.selectionEnd,e),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(e){let t=this._selectionDirection===`left`?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),e!==0}moveCursorWithoutShift(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),e!==0}moveCursorLeft(e){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight(`Left`,e)}_move(e,t,n){let r;if(e.altKey)r=this[`findWordBoundary${n}`](this[t]);else{if(!e.metaKey&&e.keyCode!==35&&e.keyCode!==36)return this[t]+=n===`Left`?-1:1,!0;r=this[`findLineBoundary${n}`](this[t])}return r!==void 0&&this[t]!==r&&(this[t]=r,!0)}_moveLeft(e,t){return this._move(e,t,`Left`)}_moveRight(e,t){return this._move(e,t,`Right`)}moveCursorLeftWithoutShift(e){let t=!0;return this._selectionDirection=F,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(t=this._moveLeft(e,`selectionStart`)),this.selectionEnd=this.selectionStart,t}moveCursorLeftWithShift(e){return this._selectionDirection===`right`&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,`selectionEnd`):this.selectionStart===0?void 0:(this._selectionDirection=F,this._moveLeft(e,`selectionStart`))}moveCursorRight(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight(`Right`,e)}_moveCursorLeftOrRight(e,t){let n=`moveCursor${e}${t.shiftKey?`WithShift`:`WithoutShift`}`;this._currentCursorOpacity=1,this[n](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(e){return this._selectionDirection===`left`&&this.selectionStart!==this.selectionEnd?this._moveRight(e,`selectionStart`):this.selectionEnd===this._text.length?void 0:(this._selectionDirection=te,this._moveRight(e,`selectionEnd`))}moveCursorRightWithoutShift(e){let t=!0;return this._selectionDirection=te,this.selectionStart===this.selectionEnd?(t=this._moveRight(e,`selectionStart`),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t}},ms=e=>!!e.button,hs=class extends ps{constructor(...e){super(...e),p(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 us(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(e){return this.draggableTextDelegate.onDragStart(e)}canDrop(e){return this.draggableTextDelegate.canDrop(e)}doubleClickHandler(e){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(e.e)),this.renderCursorOrSelection())}tripleClickHandler(e){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(e.e)),this.renderCursorOrSelection())}_mouseDownHandler({e,alreadySelected:t}){this.canvas&&this.editable&&!ms(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),t&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||=t||this.isEditing))}mouseUpHandler({e,transform:t}){let n=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);let e=this.canvas._activeObject;if(e&&e!==this)return}!this.editable||this.group&&!this.group.interactive||t&&t.actionPerformed||ms(e)||n||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(e){let t=this.getSelectionStartFromPointer(e),n=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(n,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(e){let t=this.canvas.getScenePoint(e).transform(We(this.calcTransformMatrix())).add(new R(-this._getLeftOffset(),-this._getTopOffset())),n=0,r=0,i=0;for(let e=0;e<this._textLines.length&&n<=t.y;e++)n+=this.getHeightOfLine(e),i=e,e>0&&(r+=this._textLines[e-1].length+this.missingNewlineOffset(e-1));let a=Math.abs(this._getLineLeftOffset(i)),o=this._textLines[i].length,s=this.__charBounds[i];for(let e=0;e<o;e++){let n=a+s[e].kernedWidth;if(t.x<=n){Math.abs(t.x-n)<=Math.abs(t.x-a)&&r++;break}a=n,r++}return Math.min(this.flipX?o-r:r,this._text.length)}},gs=`moveCursorUp`,_s=`moveCursorDown`,vs=`moveCursorLeft`,ys=`moveCursorRight`,bs=`exitEditing`,xs=(e,t)=>{let n=t.getRetinaScaling();e.setTransform(n,0,0,n,0,0);let r=t.viewportTransform;e.transform(r[0],r[1],r[2],r[3],r[4],r[5])},Ss={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:bs,27:bs,33:gs,34:_s,35:ys,36:vs,37:vs,38:gs,39:ys,40:_s},keysMapRtl:{9:bs,27:bs,33:gs,34:_s,35:vs,36:ys,37:ys,38:gs,39:vs,40:_s},ctrlKeysMapDown:{65:`cmdAll`},ctrlKeysMapUp:{67:`copy`,88:`cut`},_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1},Cs=class e extends hs{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}get type(){let e=super.type;return e===`itext`?`i-text`:e}constructor(t,n){super(t,{...e.ownDefaults,...n}),this.initBehavior()}_set(e,t){return this.isEditing&&this._savedProps&&e in this._savedProps?(this._savedProps[e]=t,this):(e===`canvas`&&(this.canvas instanceof jo&&this.canvas.textEditingManager.remove(this),t instanceof jo&&t.textEditingManager.add(this)),super._set(e,t))}setSelectionStart(e){e=Math.max(e,0),this._updateAndFire(`selectionStart`,e)}setSelectionEnd(e){e=Math.min(e,this.text.length),this._updateAndFire(`selectionEnd`,e)}_updateAndFire(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),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(e=this.selectionStart||0,t=this.selectionEnd,n){return super.getSelectionStyles(e,t,n)}setSelectionStyles(e,t=this.selectionStart||0,n=this.selectionEnd){return super.setSelectionStyles(e,t,n)}get2DCursorLocation(e=this.selectionStart,t){return super.get2DCursorLocation(e,t)}render(e){super.render(e),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(e){let t=this.isEditing;this.isEditing=!1;let n=super.toCanvasElement(e);return this.isEditing=t,n}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;let e=this.clearContextTop(!0);if(!e)return;let t=this._getCursorBoundaries(),n=this.findAncestorsWithClipPath(),r=n.length>0,i,a=e;if(r){i=Re(e.canvas),a=i.getContext(`2d`),xs(a,this.canvas);let t=this.calcTransformMatrix();a.transform(t[0],t[1],t[2],t[3],t[4],t[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(a,t):this.renderCursor(a,t),r)for(let t of n){let n=t.clipPath,r=Re(e.canvas),i=r.getContext(`2d`);if(xs(i,this.canvas),!n.absolutePositioned){let e=t.calcTransformMatrix();i.transform(e[0],e[1],e[2],e[3],e[4],e[5])}n.transform(i),n.drawObject(i,!0,{}),this.drawClipPathOnCache(a,n,r)}r&&(e.setTransform(1,0,0,1,0,0),e.drawImage(i,0,0)),this.canvas.contextTopDirty=!0,e.restore()}findAncestorsWithClipPath(){let e=[],t=this;for(;t;)t.clipPath&&e.push(t),t=t.parent;return e}_getCursorBoundaries(e=this.selectionStart,t){let n=this._getLeftOffset(),r=this._getTopOffset(),i=this._getCursorBoundariesOffsets(e,t);return{left:n,top:r,leftOffset:i.left,topOffset:i.top}}_getCursorBoundariesOffsets(e,t){return t?this.__getCursorBoundariesOffsets(e):this.cursorOffsetCache&&`top`in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(e)}__getCursorBoundariesOffsets(e){let t=0,n=0,{charIndex:r,lineIndex:i}=this.get2DCursorLocation(e),{textAlign:a,direction:o}=this;for(let e=0;e<i;e++)t+=this.getHeightOfLine(e);let s=this._getLineLeftOffset(i),c=this.__charBounds[i][r];c&&(n=c.left),this.charSpacing!==0&&r===this._textLines[i].length&&(n-=this._getWidthOfCharSpacing());let l=s+(n>0?n:0);return o===`rtl`&&(a===`right`||a===`justify`||a===`justify-right`?l*=-1:a===`left`||a===`justify-left`?l=s-(n>0?n:0):a!==`center`&&a!==`justify-center`||(l=s-(n>0?n:0))),{top:t,left:l}}renderCursorAt(e){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(e,!0),e)}renderCursor(e,t){this._renderCursor(e,t,this.selectionStart)}getCursorRenderingData(e=this.selectionStart,t=this._getCursorBoundaries(e)){let n=this.get2DCursorLocation(e),r=n.lineIndex,i=n.charIndex>0?n.charIndex-1:0,a=this.getValueOfPropertyAt(r,i,`fontSize`),o=this.getObjectScaling().x*this.canvas.getZoom(),s=this.cursorWidth/o,c=this.getValueOfPropertyAt(r,i,`deltaY`),l=t.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-a*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(r,i,`fill`),opacity:this._currentCursorOpacity,left:t.left+t.leftOffset-s/2,top:l+t.top+c,width:s,height:a}}_renderCursor(e,t,n){let{color:r,opacity:i,left:a,top:o,width:s,height:c}=this.getCursorRenderingData(n,t);e.fillStyle=r,e.globalAlpha=i,e.fillRect(a,o,s,c)}renderSelection(e,t){let n={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(e,n,t)}renderDragSourceEffect(){let e=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,e,this._getCursorBoundaries(e.selectionStart,!0))}renderDropTargetEffect(e){let t=this.getSelectionStartFromPointer(e);this.renderCursorAt(t)}_renderSelection(e,t,n){let{textAlign:r,direction:i}=this,a=t.selectionStart,o=t.selectionEnd,s=r.includes(Rn),c=this.get2DCursorLocation(a),l=this.get2DCursorLocation(o),u=c.lineIndex,d=l.lineIndex,f=c.charIndex<0?0:c.charIndex,p=l.charIndex<0?0:l.charIndex;for(let t=u;t<=d;t++){let a=this._getLineLeftOffset(t)||0,o=this.getHeightOfLine(t),c=0,l=0;if(t===u&&(c=this.__charBounds[u][f].left),t>=u&&t<d)l=s&&!this.isEndOfWrapping(t)?this.width:this.getLineWidth(t)||5;else if(t===d){if(p===0)l=this.__charBounds[d][p].left;else{let e=this._getWidthOfCharSpacing();l=this.__charBounds[d][p-1].left+this.__charBounds[d][p-1].width-e}}let m=o;(this.lineHeight<1||t===d&&this.lineHeight>1)&&(o/=this.lineHeight);let h=n.left+a+c,g=o,_=0,v=l-c;this.inCompositionMode?(e.fillStyle=this.compositionColor||`black`,g=1,_=o):e.fillStyle=this.selectionColor,i===`rtl`&&(r===`right`||r===`justify`||r===`justify-right`?h=this.width-h-v:r===`left`||r===`justify-left`?h=n.left+a-l:r!==`center`&&r!==`justify-center`||(h=n.left+a-l)),e.fillRect(h,n.top+n.topOffset+_,v,g),n.topOffset+=m}}getCurrentCharFontSize(){let e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,`fontSize`)}getCurrentCharColor(){let e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,_e)}_getCurrentCharIndex(){let e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}};p(Cs,`ownDefaults`,Ss),p(Cs,`type`,`IText`),L.setClass(Cs),L.setClass(Cs,`i-text`);var ws=class e extends Cs{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(t,{...e.ownDefaults,...n})}static createControls(){return{controls:ki()}}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(`justify`)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(e){let t=0,n=0,r=0,i={};for(let a=0;a<e.graphemeLines.length;a++)e.graphemeText[r]===`
27
+ `&&a>0?(n=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&a>0&&(n++,r++),i[a]={line:t,offset:n},r+=e.graphemeLines[a].length,n+=e.graphemeLines[a].length;return i}styleHas(e,t){if(this._styleMap&&!this.isWrapping){let e=this._styleMap[t];e&&(t=e.line)}return super.styleHas(e,t)}isEmptyStyles(e){if(!this.styles)return!0;let t,n,r=0,i=!1,a=this._styleMap[e],o=this._styleMap[e+1];a&&(e=a.line,r=a.offset),o&&(t=o.line,i=t===e,n=o.offset);let s=e===void 0?this.styles:{line:this.styles[e]};for(let e in s)for(let t in s[e]){let a=parseInt(t,10);if(a>=r&&(!i||a<n))for(let n in s[e][t])return!1}return!0}_getStyleDeclaration(e,t){if(this._styleMap&&!this.isWrapping){let n=this._styleMap[e];if(!n)return{};e=n.line,t=n.offset+t}return super._getStyleDeclaration(e,t)}_setStyleDeclaration(e,t,n){let r=this._styleMap[e];super._setStyleDeclaration(r.line,r.offset+t,n)}_deleteStyleDeclaration(e,t){let n=this._styleMap[e];super._deleteStyleDeclaration(n.line,n.offset+t)}_getLineStyle(e){let t=this._styleMap[e];return!!this.styles[t.line]}_setLineStyle(e){let t=this._styleMap[e];super._setLineStyle(t.line)}_wrapText(e,t){this.isWrapping=!0;let n=this.getGraphemeDataForRender(e),r=[];for(let e=0;e<n.wordsData.length;e++)r.push(...this._wrapLine(e,t,n));return this.isWrapping=!1,r}getGraphemeDataForRender(e){let t=this.splitByGrapheme,n=t?``:` `,r=0;return{wordsData:e.map((e,i)=>{let a=0,o=t?this.graphemeSplit(e):this.wordSplit(e);return o.length===0?[{word:[],width:0}]:o.map(e=>{let o=t?[e]:this.graphemeSplit(e),s=this._measureWord(o,i,a);return r=Math.max(s,r),a+=o.length+n.length,{word:o,width:s}})}),largestWordWidth:r}}_measureWord(e,t,n=0){let r,i=0;for(let a=0,o=e.length;a<o;a++)i+=this._getGraphemeBox(e[a],t,a+n,r,!0).kernedWidth,r=e[a];return i}wordSplit(e){return e.split(this._wordJoiners)}_wrapLine(e,t,{largestWordWidth:n,wordsData:r},i=0){let a=this._getWidthOfCharSpacing(),o=this.splitByGrapheme,s=[],c=o?``:` `,l=0,u=[],d=0,f=0,p=!0;t-=i;let m=Math.max(t,n,this.dynamicMinWidth),h=r[e],g;for(g=0;g<h.length;g++){let{word:t,width:n}=h[g];d+=t.length,l+=f+n-a,l>m&&!p?(s.push(u),u=[],l=n,p=!0):l+=a,p||o||u.push(c),u=u.concat(t),f=o?0:this._measureWord([c],e,d),d++,p=!1}return g&&s.push(u),n+i>this.dynamicMinWidth&&(this.dynamicMinWidth=n-a+i),s}isEndOfWrapping(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line}missingNewlineOffset(e,t){return this.splitByGrapheme&&!t?+!!this.isEndOfWrapping(e):1}_splitTextIntoLines(e){let t=super._splitTextIntoLines(e),n=this._wrapText(t.lines,this.width),r=Array(n.length);for(let e=0;e<n.length;e++)r[e]=n[e].join(``);return t.lines=r,t.graphemeLines=n,t}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){let e=new Map;for(let t in this._styleMap){let n=parseInt(t,10);if(this._textLines[n]){let n=this._styleMap[t].line;e.set(`${n}`,!0)}}for(let t in this.styles)e.has(t)||delete this.styles[t]}toObject(e=[]){return super.toObject([`minWidth`,`splitByGrapheme`,...e])}};p(ws,`type`,`Textbox`),p(ws,`textLayoutProperties`,[...Cs.textLayoutProperties,`width`]),p(ws,`ownDefaults`,{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),L.setClass(ws);var Ts=class extends va{shouldPerformLayout(e){return!!e.target.clipPath&&super.shouldPerformLayout(e)}shouldLayoutClipPath(){return!1}calcLayoutResult(e,t){let{target:n}=e,{clipPath:r,group:i}=n;if(!r||!this.shouldPerformLayout(e))return;let{width:a,height:o}=Nt(_a(n,r)),s=new R(a,o);if(r.absolutePositioned)return{center:Vt(r.getRelativeCenterPoint(),void 0,i?i.calcTransformMatrix():void 0),size:s};{let i=r.getRelativeCenterPoint().transform(n.calcOwnMatrix(),!0);if(this.shouldPerformLayout(e)){let{center:n=new R,correction:r=new R}=this.calcBoundingBox(t,e)||{};return{center:n.add(i),correction:r.subtract(i),size:s}}return{center:n.getRelativeCenterPoint().add(i),size:s}}}};p(Ts,`type`,`clip-path`),L.setClass(Ts);var Es=class extends va{getInitialSize({target:e},{size:t}){return new R(e.width||t.x,e.height||t.y)}};p(Es,`type`,`fixed`),L.setClass(Es);var Ds=class extends xa{subscribeTargets(e){let t=e.target;e.targets.reduce((e,t)=>(t.parent&&e.add(t.parent),e),new Set).forEach(e=>{e.layoutManager.subscribeTargets({target:e,targets:[t]})})}unsubscribeTargets(e){let t=e.target,n=t.getObjects();e.targets.reduce((e,t)=>(t.parent&&e.add(t.parent),e),new Set).forEach(e=>{!n.some(t=>t.parent===e)&&e.layoutManager.unsubscribeTargets({target:e,targets:[t]})})}},Os=class e extends Ca{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t=[],n={}){super(),Object.assign(this,e.ownDefaults),this.setOptions(n);let{left:r,top:i,layoutManager:a}=n;this.groupInit(t,{left:r,top:i,layoutManager:a??new Ds})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(...e){this.multiSelectionStacking===`selection-order`?this.add(...e):e.forEach(e=>{let t=this._objects.findIndex(t=>t.isInFrontOf(e)),n=t===-1?this.size():t;this.insertAt(n,e)})}canEnterGroup(e){return this.getObjects().some(t=>t.isDescendantOf(e)||e.isDescendantOf(t))?(g(`error`,`ActiveSelection: circular object trees are not supported, this call has no effect`),!1):super.canEnterGroup(e)}enterGroup(e,t){e.parent&&e.parent===e.group?e.parent._exitGroup(e):e.group&&e.parent!==e.group&&e.group.remove(e),this._enterGroup(e,t)}exitGroup(e,t){this._exitGroup(e,t),e.parent&&e.parent._enterGroup(e,!0)}_onAfterObjectsChange(e,t){super._onAfterObjectsChange(e,t);let n=new Set;t.forEach(e=>{let{parent:t}=e;t&&n.add(t)}),e===`removed`?n.forEach(e=>{e._onAfterObjectsChange(ga,t)}):n.forEach(e=>{e._set(`dirty`,!0)})}onDeselect(){return this.removeAll(),!1}toString(){return`#<ActiveSelection: (${this.complexity()})>`}shouldCache(){return!1}isOnACache(){return!1}_renderControls(e,t,n){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;let r={hasControls:!1,...n,forActiveSelection:!0};for(let t=0;t<this._objects.length;t++)this._objects[t]._renderControls(e,r);super._renderControls(e,t),e.restore()}};p(Os,`type`,`ActiveSelection`),p(Os,`ownDefaults`,{multiSelectionStacking:`canvas-stacking`}),L.setClass(Os),L.setClass(Os,`activeSelection`);var ks=class{constructor(){p(this,`resources`,{})}applyFilters(e,t,n,r,i){let a=i.getContext(`2d`,{willReadFrequently:!0,desynchronized:!0});if(!a)return;a.drawImage(t,0,0,n,r);let o={sourceWidth:n,sourceHeight:r,imageData:a.getImageData(0,0,n,r),originalEl:t,originalImageData:a.getImageData(0,0,n,r),canvasEl:i,ctx:a,filterBackend:this};e.forEach(e=>{e.applyTo(o)});let{imageData:s}=o;return s.width===n&&s.height===r||(i.width=s.width,i.height=s.height),a.putImageData(s,0,0),o}},As=class{constructor({tileSize:e=h.textureSize}={}){p(this,`aPosition`,new Float32Array([0,0,0,1,1,0,1,1])),p(this,`resources`,{}),this.tileSize=e,this.setupGLContext(e,e),this.captureGPUInfo()}setupGLContext(e,t){this.dispose(),this.createWebGLCanvas(e,t)}createWebGLCanvas(e,t){let n=Re({width:e,height:t}),r=n.getContext(`webgl`,{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});r&&(r.clearColor(0,0,0,0),this.canvas=n,this.gl=r)}applyFilters(e,t,n,r,i,a){let o=this.gl,s=i.getContext(`2d`);if(!o||!s)return;let c;a&&(c=this.getCachedTexture(a,t));let l={originalWidth:t.width||t.naturalWidth||0,originalHeight:t.height||t.naturalHeight||0,sourceWidth:n,sourceHeight:r,destinationWidth:n,destinationHeight:r,context:o,sourceTexture:this.createTexture(o,n,r,c?void 0:t),targetTexture:this.createTexture(o,n,r),originalTexture:c||this.createTexture(o,n,r,c?void 0:t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:i},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),e.forEach(e=>{e&&e.applyTo(l)}),function(e){let t=e.targetCanvas,n=t.width,r=t.height,i=e.destinationWidth,a=e.destinationHeight;n===i&&r===a||(t.width=i,t.height=a)}(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(u),s.setTransform(1,0,0,1,0,0),l}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(e,t,n,r,i){let{NEAREST:a,TEXTURE_2D:o,RGBA:s,UNSIGNED_BYTE:c,CLAMP_TO_EDGE:l,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:p}=e,m=e.createTexture();return e.bindTexture(o,m),e.texParameteri(o,u,i||a),e.texParameteri(o,d,i||a),e.texParameteri(o,f,l),e.texParameteri(o,p,l),r?e.texImage2D(o,0,s,s,c,r):e.texImage2D(o,0,s,t,n,0,s,c,null),m}getCachedTexture(e,t,n){let{textureCache:r}=this;if(r[e])return r[e];{let i=this.createTexture(this.gl,t.width,t.height,t,n);return i&&(r[e]=i),i}}evictCachesForKey(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])}copyGLTo2D(e,t){let n=e.canvas,r=t.targetCanvas,i=r.getContext(`2d`);if(!i)return;i.translate(0,r.height),i.scale(1,-1);let a=n.height-r.height;i.drawImage(n,0,a,r.width,r.height,0,0,r.width,r.height)}copyGLTo2DPutImageData(e,t){let n=t.targetCanvas.getContext(`2d`),r=t.destinationWidth,i=t.destinationHeight,a=r*i*4;if(!n)return;let o=new Uint8Array(this.imageBuffer,0,a),s=new Uint8ClampedArray(this.imageBuffer,0,a);e.readPixels(0,0,r,i,e.RGBA,e.UNSIGNED_BYTE,o);let c=new ImageData(s,r,i);n.putImageData(c,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;let e=this.gl,t={renderer:``,vendor:``};if(!e)return t;let n=e.getExtension(`WEBGL_debug_renderer_info`);if(n){let r=e.getParameter(n.UNMASKED_RENDERER_WEBGL),i=e.getParameter(n.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),i&&(t.vendor=i.toLowerCase())}return this.gpuInfo=t,t}},js;function Ms(){let{WebGLProbe:e}=C();return e.queryWebGL(Fe()),h.enableGLFiltering&&e.isSupported(h.textureSize)?new As({tileSize:h.textureSize}):new ks}function Ns(e=!0){return!js&&e&&(js=Ms()),js}var Ps=[`cropX`,`cropY`],Fs=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(),p(this,`_lastScaleX`,1),p(this,`_lastScaleY`,1),p(this,`_filterScalingX`,1),p(this,`_filterScalingY`,1),this.filters=[],Object.assign(this,e.ownDefaults),this.setOptions(n),this.cacheKey=`texture${Pe()}`,this.setElement(typeof t==`string`?(this.canvas&&ht(this.canvas.getElement())||w()).getElementById(t):t,n)}getElement(){return this._element}setElement(e,t={}){this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._element=e,this._originalElement=e,this._setWidthHeight(t),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(e){let t=Ns(!1);t instanceof As&&t.evictCachesForKey(e)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._cacheContext=null,[`_originalElement`,`_element`,`_filteredEl`,`_cacheCanvas`].forEach(e=>{let t=this[e];t&&C().dispose(t),this[e]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){let e=this.getElement();return e?{width:e.naturalWidth||e.width,height:e.naturalHeight||e.height}:{width:0,height:0}}_stroke(e){if(!this.stroke||this.strokeWidth===0)return;let t=this.width/2,n=this.height/2;e.beginPath(),e.moveTo(-t,-n),e.lineTo(t,-n),e.lineTo(t,n),e.lineTo(-t,n),e.lineTo(-t,-n),e.closePath()}toObject(e=[]){let t=[];return this.filters.forEach(e=>{e&&t.push(e.toObject())}),{...super.toObject([...Ps,...e]),src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:t,...this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{}}}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){let e=[],t=this._element,n=-this.width/2,r=-this.height/2,i=[],a=[],o=``,s=``;if(!t)return[];if(this.hasCrop()){let e=Pe();i.push(`<clipPath id="imageCrop_`+e+`">
28
+ `,` <rect x="`+n+`" y="`+r+`" width="`+H(this.width)+`" height="`+H(this.height)+`" />
64
29
  `,`</clipPath>
65
- `),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(l=' image-rendering="optimizeSpeed"'),t.push(" <image ","COMMON_PARTS",`xlink:href="${Z(this.getSrc(!0))}" x="${s-this.cropX}" y="${i-this.cropY}" width="${e.width||e.naturalWidth}" height="${e.height||e.naturalHeight}"${l}${o}></image>
66
- `),this.stroke||this.strokeDashArray){const h=this.fill;this.fill=null,r=[` <rect x="${s}" y="${i}" width="${Z(this.width)}" height="${Z(this.height)}" style="${this.getSvgStyles()}" />
67
- `],this.fill=h}return n=this.paintFirst!==xt?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 Qs(t,{crossOrigin:e,signal:s}).then(i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)})}toString(){return`#<Image: { src: "${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=Zt(r),{width:l,height:h}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,Vr().applyFilters([t],r,l,h,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(`${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=Zt({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);Vr().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),l=Math.max(this.cropY,0),h=e.naturalWidth||e.width,c=e.naturalHeight||e.height,u=o*s,d=l*i,f=Math.min(n*s,h-u),g=Math.min(r*i,c-d),p=-n/2,b=-r/2,m=Math.min(n,h/s-o),v=Math.min(r,c/i-l);e&&t.drawImage(e,u,d,f,g,p,b,m,v)}_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=vr(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,o=this._element.height,l=1,h=1,c=0,u=0,d=0,f=0;return!t||t.alignX===Ft&&t.alignY===Ft?(l=e/r,h=s/o):(t.meetOrSlice==="meet"&&(l=h=qa(this._element,i),n=(e-r*l)/2,t.alignX==="Min"&&(c=-n),t.alignX==="Max"&&(c=n),n=(s-o*h)/2,t.alignY==="Min"&&(u=-n),t.alignY==="Max"&&(u=n)),t.meetOrSlice==="slice"&&(l=h=Ka(this._element,i),n=r-e/l,t.alignX==="Mid"&&(d=n/2),t.alignX==="Max"&&(d=n),n=o-s/h,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/l,o=s/h)),{width:r,height:o,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:o,...l}=t;return Promise.all([Qs(n,{...e,crossOrigin:r}),s&&Es(s,e),i?Es([i],e):[],Js(l,e)]).then(h=>{let[c,u=[],[d],f={}]=h;return new this(c,{...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 Qs(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=Ie(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch(n=>(Pe("log","Unable to parse Image",n),null))}}function Xr(a){if(!pc.test(a.nodeName))return{};const t=a.getAttribute("viewBox");let e,s,i=1,n=1,r=0,o=0;const l=a.getAttribute("width"),h=a.getAttribute("height"),c=a.getAttribute("x")||0,u=a.getAttribute("y")||0,d=!(t&&Sa.test(t)),f=!l||!h||l==="100%"||h==="100%";let g="",p=0,b=0;if(d&&(c||u)&&a.parentNode&&a.parentNode.nodeName!=="#document"&&(g=" translate("+Nt(c||"0")+" "+Nt(u||"0")+") ",e=(a.getAttribute("transform")||"")+g,a.setAttribute("transform",e),a.removeAttribute("x"),a.removeAttribute("y")),d&&f)return{width:0,height:0};const m={width:0,height:0};if(d)return m.width=Nt(l),m.height=Nt(h),m;const v=t.match(Sa);r=-parseFloat(v[1]),o=-parseFloat(v[2]);const _=parseFloat(v[3]),y=parseFloat(v[4]);m.minX=r,m.minY=o,m.viewBoxWidth=_,m.viewBoxHeight=y,f?(m.width=_,m.height=y):(m.width=Nt(l),m.height=Nt(h),i=m.width/_,n=m.height/y);const w=vr(a.getAttribute("preserveAspectRatio")||"");if(w.alignX!==Ft&&(w.meetOrSlice==="meet"&&(n=i=i>n?n:i),w.meetOrSlice==="slice"&&(n=i=i>n?i:n),p=m.width-_*i,b=m.height-y*i,w.alignX==="Mid"&&(p/=2),w.alignY==="Mid"&&(b/=2),w.alignX==="Min"&&(p=0),w.alignY==="Min"&&(b=0)),i===1&&n===1&&r===0&&o===0&&c===0&&u===0)return m;if((c||u)&&a.parentNode.nodeName!=="#document"&&(g=" translate("+Nt(c||"0")+" "+Nt(u||"0")+") "),e=g+" matrix("+i+" 0 0 "+n+" "+(r*i+p)+" "+(o*n+b)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(_r,"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),m}x(Ut,"type","Image"),x(Ut,"cacheProperties",[...Le,...Sl]),x(Ut,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),x(Ut,"ATTRIBUTE_NAMES",[...Xe,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),I.setClass(Ut),I.setSVGClass(Ut);const cn=a=>a.tagName.replace("svg:",""),Bu=Wi(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function Cl(a,t){let e,s,i,n,r=[];for(i=0,n=t.length;i<n;i++)e=t[i],s=a.getElementsByTagNameNS("http://www.w3.org/2000/svg",e),r=r.concat(Array.from(s));return r}const $u=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Ur="xlink:href";function Al(a,t){var e;const s=((e=t.getAttribute(Ur))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(Ur)&&Al(a,i),i&&($u.forEach(n=>{const r=i.getAttribute(n);!t.hasAttribute(n)&&r&&t.setAttribute(n,r)}),!t.children.length)){const n=i.cloneNode(!0);for(;n.firstChild;)t.appendChild(n.firstChild)}t.removeAttribute(Ur)}const Hu=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"],Tl=a=>I.getSVGClass(cn(a).toLowerCase());class zu{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=Cl(r,Hu),l={};let h=o.length;for(;h--;){const c=o[h];c.getAttribute("xlink:href")&&Al(r,c);const u=c.getAttribute("id");u&&(l[u]=c)}return l})(i),this.cssRules=(function(r){const o=r.getElementsByTagName("style"),l={};for(let h=0;h<o.length;h++){const c=(o[h].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");c.trim()!==""&&c.split("}").filter((u,d,f)=>f.length>1&&u.trim()).forEach(u=>{if((u.match(/{/g)||[]).length>1&&u.trim().startsWith("@"))return;const d=u.split("{"),f={},g=d[1].trim().split(";").filter(function(p){return p.trim()});for(let p=0;p<g.length;p++){const b=g[p].split(":"),m=b[0].trim(),v=b[1].trim();f[m]=v}(u=d[0].trim()).split(",").forEach(p=>{(p=p.replace(/^svg/i,"").trim())!==""&&(l[p]={...l[p]||{},...f})})})}return l})(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=Tl(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,xt),this.resolveGradient(s,t,Vt),s instanceof Ut&&s._originalElement?en(s,s.parsePreserveAspectRatioAttribute()):en(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=ci.fromElement(i,t,{...this.options,opacity:n});t.set(s,r)}}async resolveClipPath(t,e,s){const i=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(i){const n=Xt(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 l=Ki(`${o.getAttribute("transform")||""} ${r.getAttribute("originalTransform")||""}`);r.setAttribute("transform",`matrix(${l.join(",")})`);const h=await Promise.all(i.map(v=>Tl(v).fromElement(v,this.options,this.cssRules).then(_=>(en(_),_.fillRule=_.clipRule,delete _.clipRule,_)))),c=h.length===1?h[0]:new te(h),u=bt(n,c.calcTransformMatrix());c.clipPath&&await this.resolveClipPath(c,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:d,scaleY:f,angle:g,skewX:p,translateX:b,translateY:m}=ss(u);c.set({flipX:!1,flipY:!1}),c.set({scaleX:d,scaleY:f,angle:g,skewX:p,skewY:0}),c.setPositionByOrigin(new S(b,m),U,U),t.clipPath=c}else delete t.clipPath}}const El=a=>gc.test(cn(a));async function Gu(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return Pe("log",new Fo("parseSVGDocument")),{objects:[],elements:[],options:{},allElements:[]};const i=a.documentElement;(function(c){const u=Cl(c,["use","svg:use"]),d=["x","y","xlink:href","href","transform"];for(const f of u){const g=f.attributes,p={};for(const k of g)k.value&&(p[k.name]=k.value);const b=(p["xlink:href"]||p.href||"").slice(1);if(b==="")return;const m=c.getElementById(b);if(m===null)return;let v=m.cloneNode(!0);const _=v.attributes,y={};for(const k of _)k.value&&(y[k.name]=k.value);const{x:w=0,y:C=0,transform:A=""}=p,T=`${A} ${y.transform||""} translate(${w}, ${C})`;if(Xr(v),/^svg$/i.test(v.nodeName)){const k=v.ownerDocument.createElementNS(_r,"g");Object.entries(y).forEach(L=>{let[R,F]=L;return k.setAttributeNS(_r,R,F)}),k.append(...v.childNodes),v=k}for(const k of g){if(!k)continue;const{name:L,value:R}=k;if(!d.includes(L))if(L==="style"){const F={};Dr(R,F),Object.entries(y).forEach(O=>{let[$,M]=O;F[$]=M}),Dr(y.style||"",F);const P=Object.entries(F).map(O=>O.join(":")).join(";");v.setAttribute(L,P)}else!y[L]&&v.setAttribute(L,R)}v.setAttribute("transform",T),v.setAttribute("instantiated_by_use","1"),v.removeAttribute("id"),f.parentNode.replaceChild(v,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r={...Xr(i),crossOrigin:e,signal:s},o=n.filter(c=>(Xr(c),El(c)&&!(function(u){let d=u;for(;d&&(d=d.parentElement);)if(d&&d.nodeName&&Bu.test(cn(d))&&!d.getAttribute("instantiated_by_use"))return!0;return!1})(c)));if(!o||o&&!o.length)return{objects:[],elements:[],options:{},allElements:[],options:r,allElements:n};const l={};return n.filter(c=>cn(c)==="clipPath").forEach(c=>{c.setAttribute("originalTransform",c.getAttribute("transform")||"");const u=c.getAttribute("id");l[u]=Array.from(c.getElementsByTagName("*")).filter(d=>El(d))}),{objects:await new zu(o,r,t,a,l).parse(),elements:o,options:r,allElements:n}}function Wu(a,t,e){return Gu(new(Xs()).DOMParser().parseFromString(a.trim(),"text/xml"),t,e)}function Vu(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return fetch(a.replace(/^\n\s*/,"").trim(),{signal:e.signal}).then(s=>{if(!s.ok)throw new le(`HTTP error! status: ${s.status}`);return s.text()}).then(s=>Wu(s,t,e)).catch(()=>({objects:[],elements:[],options:{},allElements:[]}))}const un=a=>a.webgl!==void 0,Yr="precision highp float",Xu=`
68
- ${Yr};
69
- varying vec2 vTexCoord;
70
- uniform sampler2D uTexture;
71
- void main() {
72
- gl_FragColor = texture2D(uTexture, vTexCoord);
73
- }`,Uu=new RegExp(Yr,"g");class St{get type(){return this.constructor.type}constructor(){let{type:t,...e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,this.constructor.defaults,e)}getFragmentSource(){return Xu}getVertexSource(){return`
30
+ `),o=` clip-path="url(#imageCrop_`+e+`)" `}if(this.imageSmoothing||(s=` image-rendering="optimizeSpeed"`),e.push(` <image `,`COMMON_PARTS`,`xlink:href="${H(this.getSrc(!0))}" x="${n-this.cropX}" y="${r-this.cropY}" width="${t.width||t.naturalWidth}" height="${t.height||t.naturalHeight}"${s}${o}></image>\n`),this.stroke||this.strokeDashArray){let e=this.fill;this.fill=null,a=[`\t<rect x="${n}" y="${r}" width="${H(this.width)}" height="${H(this.height)}" style="${this.getSvgStyles()}" />\n`],this.fill=e}return i=this.paintFirst===`fill`?i.concat(e,a):i.concat(a,e),i}getSrc(e){let t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute(`src`)||``:t.src:this.src||``}getSvgSrc(e){return this.getSrc(e)}setSrc(e,{crossOrigin:t,signal:n}={}){return it(e,{crossOrigin:t,signal:n}).then(e=>{t!==void 0&&this.set({crossOrigin:t}),this.setElement(e)})}toString(){return`#<Image: { src: "${this.getSrc()}" }>`}applyResizeFilters(){let e=this.resizeFilter,t=this.minimumScaleTrigger,n=this.getTotalObjectScaling(),r=n.x,i=n.y,a=this._filteredEl||this._originalElement;if(this.group&&this.set(`dirty`,!0),!e||r>t&&i>t)return this._element=a,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=i);let o=Re(a),{width:s,height:c}=a;this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=i,Ns().applyFilters([e],a,s,c,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(e=this.filters||[]){if(e=e.filter(e=>e&&!e.isNeutralState()),this.set(`dirty`,!0),this.removeTexture(`${this.cacheKey}_filtered`),e.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);let t=this._originalElement,n=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){let e=Re({width:n,height:r});this._element=e,this._filteredEl=e}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext(`2d`).clearRect(0,0,n,r),this._lastScaleX=1,this._lastScaleY=1);Ns().applyFilters(e,this._originalElement,n,r,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(e){e.imageSmoothingEnabled=this.imageSmoothing,!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)}drawCacheOnCanvas(e){e.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(e)}shouldCache(){return this.needsItsOwnCache()}_renderFill(e){let t=this._element;if(!t)return;let n=this._filterScalingX,r=this._filterScalingY,i=this.width,a=this.height,o=Math.max(this.cropX,0),s=Math.max(this.cropY,0),c=t.naturalWidth||t.width,l=t.naturalHeight||t.height,u=o*n,d=s*r,f=Math.min(i*n,c-u),p=Math.min(a*r,l-d),m=-i/2,h=-a/2,g=Math.min(i,c/n-o),_=Math.min(a,l/r-s);t&&e.drawImage(t,u,d,f,p,m,h,g,_)}_needsResize(){let e=this.getTotalObjectScaling();return e.x!==this._lastScaleX||e.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight({width:e,height:t}={}){let n=this.getOriginalSize();this.width=e||n.width,this.height=t||n.height}parsePreserveAspectRatioAttribute(){let e=En(this.preserveAspectRatio||``),t=this.width,n=this.height,r={width:t,height:n},i,a=this._element.width,o=this._element.height,s=1,c=1,l=0,u=0,d=0,f=0;return!e||e.alignX===`none`&&e.alignY===`none`?(s=t/a,c=n/o):(e.meetOrSlice===`meet`&&(s=c=Ta(this._element,r),i=(t-a*s)/2,e.alignX===`Min`&&(l=-i),e.alignX===`Max`&&(l=i),i=(n-o*c)/2,e.alignY===`Min`&&(u=-i),e.alignY===`Max`&&(u=i)),e.meetOrSlice===`slice`&&(s=c=Ea(this._element,r),i=a-t/s,e.alignX===`Mid`&&(d=i/2),e.alignX===`Max`&&(d=i),i=o-n/c,e.alignY===`Mid`&&(f=i/2),e.alignY===`Max`&&(f=i),a=t/s,o=n/c)),{width:a,height:o,scaleX:s,scaleY:c,offsetLeft:l,offsetTop:u,cropX:d,cropY:f}}static fromObject({filters:e,resizeFilter:t,src:n,crossOrigin:r,type:i,...a},o){return Promise.all([it(n,{...o,crossOrigin:r}),e&&at(e,o),t?at([t],o):[],ot(a,o)]).then(([e,t=[],[r],i={}])=>new this(e,{...a,src:n,filters:t,resizeFilter:r,...i}))}static fromURL(e,{crossOrigin:t=null,signal:n}={},r){return it(e,{crossOrigin:t,signal:n}).then(e=>new this(e,r))}static async fromElement(e,t={},n){let r=fa(e,this.ATTRIBUTE_NAMES,n);return this.fromURL(r[`xlink:href`]||r.href,t,r).catch(e=>(g(`log`,`Unable to parse Image`,e),null))}};function Is(e){if(!qn.test(e.nodeName))return{};let t=e.getAttribute(`viewBox`),n,r,i=1,a=1,o=e.getAttribute(`width`),s=e.getAttribute(`height`),c=e.getAttribute(`x`)||0,l=e.getAttribute(`y`)||0,u=!(t&&Yn.test(t)),d=!o||!s||o===`100%`||s===`100%`,f=``,p=0,m=0;if(u&&(c||l)&&e.parentNode&&e.parentNode.nodeName!==`#document`&&(f=` translate(`+Tn(c||`0`)+` `+Tn(l||`0`)+`) `,n=(e.getAttribute(`transform`)||``)+f,e.setAttribute(`transform`,n),e.removeAttribute(`x`),e.removeAttribute(`y`)),u&&d)return{width:0,height:0};let h={width:0,height:0};if(u)return h.width=Tn(o),h.height=Tn(s),h;let g=t.match(Yn),_=-parseFloat(g[1]),v=-parseFloat(g[2]),y=parseFloat(g[3]),b=parseFloat(g[4]);h.minX=_,h.minY=v,h.viewBoxWidth=y,h.viewBoxHeight=b,d?(h.width=y,h.height=b):(h.width=Tn(o),h.height=Tn(s),i=h.width/y,a=h.height/b);let x=En(e.getAttribute(`preserveAspectRatio`)||``);if(x.alignX!==`none`&&(x.meetOrSlice===`meet`&&(a=i=i>a?a:i),x.meetOrSlice===`slice`&&(a=i=i>a?i:a),p=h.width-y*i,m=h.height-b*i,x.alignX===`Mid`&&(p/=2),x.alignY===`Mid`&&(m/=2),x.alignX===`Min`&&(p=0),x.alignY===`Min`&&(m=0)),i===1&&a===1&&_===0&&v===0&&c===0&&l===0)return h;if((c||l)&&e.parentNode.nodeName!==`#document`&&(f=` translate(`+Tn(c||`0`)+` `+Tn(l||`0`)+`) `),n=f+` matrix(`+i+` 0 0 `+a+` `+(_*i+p)+` `+(v*a+m)+`) `,e.nodeName===`svg`){for(r=e.ownerDocument.createElementNS(Vn,`g`);e.firstChild;)r.appendChild(e.firstChild);e.appendChild(r)}else r=e,r.removeAttribute(`x`),r.removeAttribute(`y`),n=r.getAttribute(`transform`)+n;return r.setAttribute(`transform`,n),h}p(Fs,`type`,`Image`),p(Fs,`cacheProperties`,[...tr,...Ps]),p(Fs,`ownDefaults`,{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),p(Fs,`ATTRIBUTE_NAMES`,[...Ui,`x`,`y`,`width`,`height`,`preserveAspectRatio`,`xlink:href`,`href`,`crossOrigin`,`image-rendering`]),L.setClass(Fs),L.setSVGClass(Fs);var Ls=e=>e.tagName.replace(`svg:`,``),Rs=kn([`pattern`,`defs`,`symbol`,`metadata`,`clipPath`,`mask`,`desc`]);function zs(e,t){let n,r,i,a,o=[];for(i=0,a=t.length;i<a;i++)n=t[i],r=e.getElementsByTagNameNS(`http://www.w3.org/2000/svg`,n),o=o.concat(Array.from(r));return o}var Bs=[`gradientTransform`,`x1`,`x2`,`y1`,`y2`,`gradientUnits`,`cx`,`cy`,`r`,`fx`,`fy`],Vs=`xlink:href`;function Hs(e,t){let n=t.getAttribute(Vs)?.slice(1)||``,r=e.getElementById(n);if(r&&r.getAttribute(Vs)&&Hs(e,r),r&&(Bs.forEach(e=>{let n=r.getAttribute(e);!t.hasAttribute(e)&&n&&t.setAttribute(e,n)}),!t.children.length)){let e=r.cloneNode(!0);for(;e.firstChild;)t.appendChild(e.firstChild)}t.removeAttribute(Vs)}var Us=[`linearGradient`,`radialGradient`,`svg:linearGradient`,`svg:radialGradient`],Ws=e=>L.getSVGClass(Ls(e).toLowerCase()),Gs=class{constructor(e,t,n,r,i){this.elements=e,this.options=t,this.reviver=n,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=r,this.clipPaths=i,this.gradientDefs=function(e){let t=zs(e,Us),n={},r=t.length;for(;r--;){let i=t[r];i.getAttribute(`xlink:href`)&&Hs(e,i);let a=i.getAttribute(`id`);a&&(n[a]=i)}return n}(r),this.cssRules=function(e){let t=e.getElementsByTagName(`style`),n={};for(let e=0;e<t.length;e++){let r=(t[e].textContent||``).replace(/\/\*[\s\S]*?\*\//g,``);r.trim()!==``&&r.split(`}`).filter((e,t,n)=>n.length>1&&e.trim()).forEach(e=>{if((e.match(/{/g)||[]).length>1&&e.trim().startsWith(`@`))return;let t=e.split(`{`),r={},i=t[1].trim().split(`;`).filter(function(e){return e.trim()});for(let e=0;e<i.length;e++){let t=i[e].split(`:`),n=t[0].trim();r[n]=t[1].trim()}(e=t[0].trim()).split(`,`).forEach(e=>{(e=e.replace(/^svg/i,``).trim())!==``&&(n[e]={...n[e]||{},...r})})})}return n}(r)}parse(){return Promise.all(this.elements.map(e=>this.createObject(e)))}async createObject(e){let t=Ws(e);if(t){let n=await t.fromElement(e,this.options,this.cssRules);return this.resolveGradient(n,e,_e),this.resolveGradient(n,e,ve),n instanceof Fs&&n._originalElement?ao(n,n.parsePreserveAspectRatioAttribute()):ao(n),await this.resolveClipPath(n,e),this.reviver&&this.reviver(e,n),n}return null}extractPropertyDefinition(e,t,n){let r=e[t],i=this.regexUrl;if(!i.test(r))return;i.lastIndex=0;let a=i.exec(r)[1];return i.lastIndex=0,n[a]}resolveGradient(e,t,n){let r=this.extractPropertyDefinition(e,n,this.gradientDefs);if(r){let i=t.getAttribute(n+`-opacity`),a=Go.fromElement(r,e,{...this.options,opacity:i});e.set(n,a)}}async resolveClipPath(e,t,n){let r=this.extractPropertyDefinition(e,`clipPath`,this.clipPaths);if(r){let i=We(e.calcTransformMatrix()),a=r[0].parentElement,o=t;for(;!n&&o.parentElement&&o.getAttribute(`clip-path`)!==e.clipPath;)o=o.parentElement;o.parentElement.appendChild(a);let s=sa(`${o.getAttribute(`transform`)||``} ${a.getAttribute(`originalTransform`)||``}`);a.setAttribute(`transform`,`matrix(${s.join(`,`)})`);let c=await Promise.all(r.map(e=>Ws(e).fromElement(e,this.options,this.cssRules).then(e=>(ao(e),e.fillRule=e.clipRule,delete e.clipRule,e)))),l=c.length===1?c[0]:new Ca(c),u=B(i,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,o,a.getAttribute(`clip-path`)?o:void 0);let{scaleX:d,scaleY:f,angle:p,skewX:m,translateX:h,translateY:g}=Ye(u);l.set({flipX:!1,flipY:!1}),l.set({scaleX:d,scaleY:f,angle:p,skewX:m,skewY:0}),l.setPositionByOrigin(new R(h,g),P,P),e.clipPath=l}else delete e.clipPath}},Ks=e=>Kn.test(Ls(e));async function qs(e,t,{crossOrigin:n,signal:r}={}){if(r&&r.aborted)return g(`log`,new v(`parseSVGDocument`)),{objects:[],elements:[],options:{},allElements:[]};let i=e.documentElement;(function(e){let t=zs(e,[`use`,`svg:use`]),n=[`x`,`y`,`xlink:href`,`href`,`transform`];for(let r of t){let t=r.attributes,i={};for(let e of t)e.value&&(i[e.name]=e.value);let a=(i[`xlink:href`]||i.href||``).slice(1);if(a===``)return;let o=e.getElementById(a);if(o===null)return;let s=o.cloneNode(!0),c=s.attributes,l={};for(let e of c)e.value&&(l[e.name]=e.value);let{x:u=0,y:d=0,transform:f=``}=i,p=`${f} ${l.transform||``} translate(${u}, ${d})`;if(Is(s),/^svg$/i.test(s.nodeName)){let e=s.ownerDocument.createElementNS(Vn,`g`);Object.entries(l).forEach(([t,n])=>e.setAttributeNS(Vn,t,n)),e.append(...s.childNodes),s=e}for(let e of t){if(!e)continue;let{name:t,value:r}=e;if(!n.includes(t)){if(t===`style`){let e={};la(r,e),Object.entries(l).forEach(([t,n])=>{e[t]=n}),la(l.style||``,e);let n=Object.entries(e).map(e=>e.join(`:`)).join(`;`);s.setAttribute(t,n)}else!l[t]&&s.setAttribute(t,r)}}s.setAttribute(`transform`,p),s.setAttribute(`instantiated_by_use`,`1`),s.removeAttribute(`id`),r.parentNode.replaceChild(s,r)}})(e);let a=Array.from(i.getElementsByTagName(`*`)),o={...Is(i),crossOrigin:n,signal:r},s=a.filter(e=>(Is(e),Ks(e)&&!function(e){let t=e;for(;t&&=t.parentElement;)if(t&&t.nodeName&&Rs.test(Ls(t))&&!t.getAttribute(`instantiated_by_use`))return!0;return!1}(e)));if(!s||s&&!s.length)return{objects:[],elements:[],options:{},allElements:[],options:o,allElements:a};let c={};return a.filter(e=>Ls(e)===`clipPath`).forEach(e=>{e.setAttribute(`originalTransform`,e.getAttribute(`transform`)||``);let t=e.getAttribute(`id`);c[t]=Array.from(e.getElementsByTagName(`*`)).filter(e=>Ks(e))}),{objects:await new Gs(s,o,t,e,c).parse(),elements:s,options:o,allElements:a}}function Js(e,t,n){return qs(new(T()).DOMParser().parseFromString(e.trim(),`text/xml`),t,n)}function Ys(e,t,n={}){return fetch(e.replace(/^\n\s*/,``).trim(),{signal:n.signal}).then(e=>{if(!e.ok)throw new _(`HTTP error! status: ${e.status}`);return e.text()}).then(e=>Js(e,t,n)).catch(()=>({objects:[],elements:[],options:{},allElements:[]}))}var Xs=e=>e.webgl!==void 0,Zs=`precision highp float`,Qs=`\n ${Zs};\n varying vec2 vTexCoord;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n }`,$s=new RegExp(Zs,`g`),ec=class{get type(){return this.constructor.type}constructor({type:e,...t}={}){Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Qs}getVertexSource(){return`
74
31
  attribute vec2 aPosition;
75
32
  varying vec2 vTexCoord;
76
33
  void main() {
77
34
  vTexCoord = aPosition;
78
35
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
79
- }`}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"}}=we();i!=="highp"&&(e=e.replace(Uu,Yr.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 le("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new le(`Vertex shader compile error for ${this.type}: ${t.getShaderInfoLog(n)}`);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new le(`Fragment shader compile error for ${this.type}: ${t.getShaderInfoLog(r)}`);if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new le(`Shader link error for "${this.type}" ${t.getProgramInfoLog(o)}`);const l=this.getUniformLocations(t,o)||{};return l.uStepW=t.getUniformLocation(o,"uStepW"),l.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),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){un(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=Zt({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return{type:this.type,...t.reduce((e,s)=>(e[s]=this[s],e),{})}}toJSON(){return this.toObject()}static async fromObject(t,e){let{type:s,...i}=t;return new this(i)}}x(St,"type","BaseFilter"),x(St,"uniformLocations",[]);const Yu={multiply:`gl_FragColor.rgb *= uColor.rgb;
36
+ }`}createProgram(e,t=this.getFragmentSource(),n=this.getVertexSource()){let{WebGLProbe:{GLPrecision:r=`highp`}}=C();r!==`highp`&&(t=t.replace($s,Zs.replace(`highp`,r)));let i=e.createShader(e.VERTEX_SHADER),a=e.createShader(e.FRAGMENT_SHADER),o=e.createProgram();if(!i||!a||!o)throw new _(`Vertex, fragment shader or program creation error`);if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS))throw new _(`Vertex shader compile error for ${this.type}: ${e.getShaderInfoLog(i)}`);if(e.shaderSource(a,t),e.compileShader(a),!e.getShaderParameter(a,e.COMPILE_STATUS))throw new _(`Fragment shader compile error for ${this.type}: ${e.getShaderInfoLog(a)}`);if(e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS))throw new _(`Shader link error for "${this.type}" ${e.getProgramInfoLog(o)}`);let s=this.getUniformLocations(e,o)||{};return s.uStepW=e.getUniformLocation(o,`uStepW`),s.uStepH=e.getUniformLocation(o,`uStepH`),{program:o,attributeLocations:this.getAttributeLocations(e,o),uniformLocations:s}}getAttributeLocations(e,t){return{aPosition:e.getAttribLocation(t,`aPosition`)}}getUniformLocations(e,t){let n=this.constructor.uniformLocations,r={};for(let i=0;i<n.length;i++)r[n[i]]=e.getUniformLocation(t,n[i]);return r}sendAttributeData(e,t,n){let r=t.aPosition,i=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,i),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW)}_setupFrameBuffer(e){let t=e.context;if(e.passes>1){let n=e.destinationWidth,r=e.destinationHeight;e.sourceWidth===n&&e.sourceHeight===r||(t.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(t,n,r)),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e.targetTexture,0)}else t.bindFramebuffer(t.FRAMEBUFFER,null),t.finish()}_swapTextures(e){e.passes--,e.pass++;let t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t}isNeutralState(e){return!1}applyTo(e){Xs(e)?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)}applyTo2d(e){}getCacheKey(){return this.type}retrieveShader(e){let t=this.getCacheKey();return e.programCache[t]||(e.programCache[t]=this.createProgram(e.context)),e.programCache[t]}applyToWebGL(e){let t=e.context,n=this.retrieveShader(e);e.pass===0&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(n.program),this.sendAttributeData(t,n.attributeLocations,e.aPosition),t.uniform1f(n.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(n.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,n.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(e,t,n){e.activeTexture(n),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)}unbindAdditionalTexture(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)}sendUniformData(e,t){}createHelpLayer(e){if(!e.helpLayer){let{sourceWidth:t,sourceHeight:n}=e;e.helpLayer=Re({width:t,height:n})}}toObject(){let e=Object.keys(this.constructor.defaults||{});return{type:this.type,...e.reduce((e,t)=>(e[t]=this[t],e),{})}}toJSON(){return this.toObject()}static async fromObject({type:e,...t},n){return new this(t)}};p(ec,`type`,`BaseFilter`),p(ec,`uniformLocations`,[]);var tc={multiply:`gl_FragColor.rgb *= uColor.rgb;
80
37
  `,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
81
38
  `,add:`gl_FragColor.rgb += uColor.rgb;
82
39
  `,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
@@ -103,19 +60,7 @@ ${l.toClipPathSVG(s)}</clipPath>
103
60
  `,tint:`
104
61
  gl_FragColor.rgb *= (1.0 - uColor.a);
105
62
  gl_FragColor.rgb += uColor.rgb;
106
- `};class dn extends St{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return`
107
- precision highp float;
108
- uniform sampler2D uTexture;
109
- uniform vec4 uColor;
110
- varying vec2 vTexCoord;
111
- void main() {
112
- vec4 color = texture2D(uTexture, vTexCoord);
113
- gl_FragColor = color;
114
- if (color.a > 0.0) {
115
- ${Yu[this.mode]}
116
- }
117
- }
118
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=new ot(this.color).getSource(),i=this.alpha,n=s[0]*i,r=s[1]*i,o=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*o/255;break;case"screen":f=255-(255-c)*(255-n)/255,g=255-(255-u)*(255-r)/255,p=255-(255-d)*(255-o)/255;break;case"add":f=c+n,g=u+r,p=d+o;break;case"difference":f=Math.abs(c-n),g=Math.abs(u-r),p=Math.abs(d-o);break;case"subtract":f=c-n,g=u-r,p=d-o;break;case"darken":f=Math.min(c,n),g=Math.min(u,r),p=Math.min(d,o);break;case"lighten":f=Math.max(c,n),g=Math.max(u,r),p=Math.max(d,o);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=o<128?2*d*o/255:255-2*(255-d)*(255-o)/255;break;case"exclusion":f=n+c-2*n*c/255,g=r+u-2*r*u/255,p=o+d-2*o*d/255;break;case"tint":f=n+c*l,g=r+u*l,p=o+d*l}e[h]=f,e[h+1]=g,e[h+2]=p}}sendUniformData(t,e){const s=new ot(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)}}x(dn,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),x(dn,"type","BlendColor"),x(dn,"uniformLocations",["uColor"]),I.setClass(dn);const qu={multiply:`
63
+ `},nc=class extends ec{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n gl_FragColor = color;\n if (color.a > 0.0) {\n ${tc[this.mode]}\n }\n }\n `}applyTo2d({imageData:{data:e}}){let t=new Cn(this.color).getSource(),n=this.alpha,r=t[0]*n,i=t[1]*n,a=t[2]*n,o=1-n;for(let t=0;t<e.length;t+=4){let n=e[t],s=e[t+1],c=e[t+2],l,u,d;switch(this.mode){case`multiply`:l=n*r/255,u=s*i/255,d=c*a/255;break;case`screen`:l=255-(255-n)*(255-r)/255,u=255-(255-s)*(255-i)/255,d=255-(255-c)*(255-a)/255;break;case`add`:l=n+r,u=s+i,d=c+a;break;case`difference`:l=Math.abs(n-r),u=Math.abs(s-i),d=Math.abs(c-a);break;case`subtract`:l=n-r,u=s-i,d=c-a;break;case`darken`:l=Math.min(n,r),u=Math.min(s,i),d=Math.min(c,a);break;case`lighten`:l=Math.max(n,r),u=Math.max(s,i),d=Math.max(c,a);break;case`overlay`:l=r<128?2*n*r/255:255-2*(255-n)*(255-r)/255,u=i<128?2*s*i/255:255-2*(255-s)*(255-i)/255,d=a<128?2*c*a/255:255-2*(255-c)*(255-a)/255;break;case`exclusion`:l=r+n-2*r*n/255,u=i+s-2*i*s/255,d=a+c-2*a*c/255;break;case`tint`:l=r+n*o,u=i+s*o,d=a+c*o}e[t]=l,e[t+1]=u,e[t+2]=d}}sendUniformData(e,t){let n=new Cn(this.color).getSource();n[0]=this.alpha*n[0]/255,n[1]=this.alpha*n[1]/255,n[2]=this.alpha*n[2]/255,n[3]=this.alpha,e.uniform4fv(t.uColor,n)}};p(nc,`defaults`,{color:`#F95C63`,mode:`multiply`,alpha:1}),p(nc,`type`,`BlendColor`),p(nc,`uniformLocations`,[`uColor`]),L.setClass(nc);var rc={multiply:`
119
64
  precision highp float;
120
65
  uniform sampler2D uTexture;
121
66
  uniform sampler2D uImage;
@@ -141,7 +86,7 @@ ${l.toClipPathSVG(s)}</clipPath>
141
86
  color.a = color2.a;
142
87
  gl_FragColor = color;
143
88
  }
144
- `};class fn extends St{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return qu[this.mode]}getVertexSource(){return`
89
+ `},ic=class extends ec{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return rc[this.mode]}getVertexSource(){return`
145
90
  attribute vec2 aPosition;
146
91
  varying vec2 vTexCoord;
147
92
  varying vec2 vTexCoord2;
@@ -151,7 +96,7 @@ ${l.toClipPathSVG(s)}</clipPath>
151
96
  vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
152
97
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
153
98
  }
154
- `}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=xe());const o=n.blendImage,l=o.getContext("2d");o.width!==s||o.height!==i?(o.width=s,o.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],b=h[c+1],m=h[c+2],v=h[c+3];switch(this.mode){case"multiply":e[c]=u*p/255,e[c+1]=d*b/255,e[c+2]=f*m/255,e[c+3]=g*v/255;break;case"mask":e[c+3]=v}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject(t,e){let{type:s,image:i,...n}=t;return Ut.fromObject(i,e).then(r=>new this({...n,image:r}))}}x(fn,"type","BlendImage"),x(fn,"defaults",{mode:"multiply",alpha:1}),x(fn,"uniformLocations",["uTransformMatrix","uImage"]),I.setClass(fn);class gn extends St{getFragmentSource(){return`
99
+ `}applyToWebGL(e){let t=e.context,n=this.createTexture(e.filterBackend,this.image);this.bindAdditionalTexture(t,n,t.TEXTURE1),super.applyToWebGL(e),this.unbindAdditionalTexture(t,t.TEXTURE1)}createTexture(e,t){return e.getCachedTexture(t.cacheKey,t.getElement())}calculateMatrix(){let e=this.image,{width:t,height:n}=e.getElement();return[1/e.scaleX,0,0,0,1/e.scaleY,0,-e.left/t,-e.top/n,1]}applyTo2d({imageData:{data:e,width:t,height:n},filterBackend:{resources:r}}){let i=this.image;r.blendImage||=Fe();let a=r.blendImage,o=a.getContext(`2d`);a.width!==t||a.height!==n?(a.width=t,a.height=n):o.clearRect(0,0,t,n),o.setTransform(i.scaleX,0,0,i.scaleY,i.left,i.top),o.drawImage(i.getElement(),0,0,t,n);let s=o.getImageData(0,0,t,n).data;for(let t=0;t<e.length;t+=4){let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=s[t],c=s[t+1],l=s[t+2],u=s[t+3];switch(this.mode){case`multiply`:e[t]=n*o/255,e[t+1]=r*c/255,e[t+2]=i*l/255,e[t+3]=a*u/255;break;case`mask`:e[t+3]=u}}}sendUniformData(e,t){let n=this.calculateMatrix();e.uniform1i(t.uImage,1),e.uniformMatrix3fv(t.uTransformMatrix,!1,n)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject({type:e,image:t,...n},r){return Fs.fromObject(t,r).then(e=>new this({...n,image:e}))}};p(ic,`type`,`BlendImage`),p(ic,`defaults`,{mode:`multiply`,alpha:1}),p(ic,`uniformLocations`,[`uTransformMatrix`,`uImage`]),L.setClass(ic);var ac=class extends ec{getFragmentSource(){return`
155
100
  precision highp float;
156
101
  uniform sampler2D uTexture;
157
102
  uniform vec2 uDelta;
@@ -180,7 +125,7 @@ ${l.toClipPathSVG(s)}</clipPath>
180
125
  gl_FragColor.rgb = color.rgb / totalC;
181
126
  gl_FragColor.a = color.a / totalA;
182
127
  }
183
- `}applyTo(t){un(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,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,b=p+l;for(let m=-14;m<o;m++){const v=m/o,_=4*Math.floor(n*v),y=1-Math.abs(v);let w=h+_;w<p?w=p:w>b&&(w=b);const C=e[w+3]*y;c+=e[w]*C,u+=e[w+1]*C,d+=e[w+2]*C,f+=C,g+=y}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,b=r.length-l+p;for(let m=-14;m<o;m++){const v=m/o,_=Math.floor(n*v)*l,y=1-Math.abs(v);let w=h+_;w<p?w=p:w>b&&(w=b);const C=r[w+3]*y;c+=r[w]*C,u+=r[w+1]*C,d+=r[w+2]*C,f+=C,g+=y}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]}}x(gn,"type","Blur"),x(gn,"defaults",{blur:0}),x(gn,"uniformLocations",["uDelta"]),I.setClass(gn);class pn extends St{getFragmentSource(){return`
128
+ `}applyTo(e){Xs(e)?(this.aspectRatio=e.sourceWidth/e.sourceHeight,e.passes++,this._setupFrameBuffer(e),this.horizontal=!0,this.applyToWebGL(e),this._swapTextures(e),this._setupFrameBuffer(e),this.horizontal=!1,this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)}applyTo2d({imageData:{data:e,width:t,height:n}}){this.aspectRatio=t/n,this.horizontal=!0;let r=this.getBlurValue()*t,i=new Uint8ClampedArray(e),a=4*t;for(let t=0;t<e.length;t+=4){let n=0,o=0,s=0,c=0,l=0,u=t-t%a,d=u+a;for(let i=-14;i<15;i++){let a=i/15,f=4*Math.floor(r*a),p=1-Math.abs(a),m=t+f;m<u?m=u:m>d&&(m=d);let h=e[m+3]*p;n+=e[m]*h,o+=e[m+1]*h,s+=e[m+2]*h,c+=h,l+=p}i[t]=n/c,i[t+1]=o/c,i[t+2]=s/c,i[t+3]=c/l}this.horizontal=!1,r=this.getBlurValue()*n;for(let t=0;t<i.length;t+=4){let n=0,o=0,s=0,c=0,l=0,u=t%a,d=i.length-a+u;for(let e=-14;e<15;e++){let f=e/15,p=Math.floor(r*f)*a,m=1-Math.abs(f),h=t+p;h<u?h=u:h>d&&(h=d);let g=i[h+3]*m;n+=i[h]*g,o+=i[h+1]*g,s+=i[h+2]*g,c+=g,l+=m}e[t]=n/c,e[t+1]=o/c,e[t+2]=s/c,e[t+3]=c/l}}sendUniformData(e,t){let n=this.chooseRightDelta();e.uniform2fv(t.uDelta,n)}isNeutralState(){return this.blur===0}getBlurValue(){let e=1,{horizontal:t,aspectRatio:n}=this;return t?n>1&&(e=1/n):n<1&&(e=n),e*this.blur*.12}chooseRightDelta(){let e=this.getBlurValue();return this.horizontal?[e,0]:[0,e]}};p(ac,`type`,`Blur`),p(ac,`defaults`,{blur:0}),p(ac,`uniformLocations`,[`uDelta`]),L.setClass(ac);var oc=class extends ec{getFragmentSource(){return`
184
129
  precision highp float;
185
130
  uniform sampler2D uTexture;
186
131
  uniform float uBrightness;
@@ -190,7 +135,7 @@ ${l.toClipPathSVG(s)}</clipPath>
190
135
  color.rgb += uBrightness;
191
136
  gl_FragColor = color;
192
137
  }
193
- `}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)}}x(pn,"type","Brightness"),x(pn,"defaults",{brightness:0}),x(pn,"uniformLocations",["uBrightness"]),I.setClass(pn);const kl={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Is extends St{getFragmentSource(){return`
138
+ `}applyTo2d({imageData:{data:e}}){let t=Math.round(255*this.brightness);for(let n=0;n<e.length;n+=4)e[n]+=t,e[n+1]+=t,e[n+2]+=t}isNeutralState(){return this.brightness===0}sendUniformData(e,t){e.uniform1f(t.uBrightness,this.brightness)}};p(oc,`type`,`Brightness`),p(oc,`defaults`,{brightness:0}),p(oc,`uniformLocations`,[`uBrightness`]),L.setClass(oc);var sc={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0},cc=class extends ec{getFragmentSource(){return`
194
139
  precision highp float;
195
140
  uniform sampler2D uTexture;
196
141
  varying vec2 vTexCoord;
@@ -201,7 +146,7 @@ ${l.toClipPathSVG(s)}</clipPath>
201
146
  color *= uColorMatrix;
202
147
  color += uConstants;
203
148
  gl_FragColor = color;
204
- }`}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],l=e[n+2];if(e[n]=r*s[0]+o*s[1]+l*s[2]+255*s[4],e[n+1]=r*s[5]+o*s[6]+l*s[7]+255*s[9],e[n+2]=r*s[10]+o*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]+o*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{...super.toObject(),matrix:[...this.matrix]}}}function ps(a,t){var e;const s=(x(e=class extends Is{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),x(e,"defaults",{colorsOnly:!1,matrix:t}),e);return I.setClass(s,a),s}x(Is,"type","ColorMatrix"),x(Is,"defaults",kl),x(Is,"uniformLocations",["uColorMatrix","uConstants"]),I.setClass(Is),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 Ml extends St{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){un(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}))}}x(Ml,"type","Composed"),I.setClass(Ml);class mn extends St{getFragmentSource(){return`
149
+ }`}applyTo2d(e){let t=e.imageData.data,n=this.matrix,r=this.colorsOnly;for(let e=0;e<t.length;e+=4){let i=t[e],a=t[e+1],o=t[e+2];if(t[e]=i*n[0]+a*n[1]+o*n[2]+255*n[4],t[e+1]=i*n[5]+a*n[6]+o*n[7]+255*n[9],t[e+2]=i*n[10]+a*n[11]+o*n[12]+255*n[14],!r){let r=t[e+3];t[e]+=r*n[3],t[e+1]+=r*n[8],t[e+2]+=r*n[13],t[e+3]=i*n[15]+a*n[16]+o*n[17]+r*n[18]+255*n[19]}}}sendUniformData(e,t){let n=this.matrix,r=[n[0],n[1],n[2],n[3],n[5],n[6],n[7],n[8],n[10],n[11],n[12],n[13],n[15],n[16],n[17],n[18]],i=[n[4],n[9],n[14],n[19]];e.uniformMatrix4fv(t.uColorMatrix,!1,r),e.uniform4fv(t.uConstants,i)}toObject(){return{...super.toObject(),matrix:[...this.matrix]}}};function lc(e,t){var n;let r=(p(n=class extends cc{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},`type`,e),p(n,`defaults`,{colorsOnly:!1,matrix:t}),n);return L.setClass(r,e),r}p(cc,`type`,`ColorMatrix`),p(cc,`defaults`,sc),p(cc,`uniformLocations`,[`uColorMatrix`,`uConstants`]),L.setClass(cc);var uc=lc(`Brownie`,[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),dc=lc(`Vintage`,[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),fc=lc(`Kodachrome`,[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),pc=lc(`Technicolor`,[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),mc=lc(`Polaroid`,[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),hc=lc(`Sepia`,[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),gc=lc(`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]),_c=class extends ec{constructor(e={}){super(e),this.subFilters=e.subFilters||[]}applyTo(e){Xs(e)&&(e.passes+=this.subFilters.length-1),this.subFilters.forEach(t=>{t.applyTo(e)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(e=>e.toObject())}}isNeutralState(){return!this.subFilters.some(e=>!e.isNeutralState())}static fromObject(e,t){return Promise.all((e.subFilters||[]).map(e=>L.getClass(e.type).fromObject(e,t))).then(e=>new this({subFilters:e}))}};p(_c,`type`,`Composed`),L.setClass(_c);var vc=class extends ec{getFragmentSource(){return`
205
150
  precision highp float;
206
151
  uniform sampler2D uTexture;
207
152
  uniform float uContrast;
@@ -211,7 +156,7 @@ ${l.toClipPathSVG(s)}</clipPath>
211
156
  float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
212
157
  color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
213
158
  gl_FragColor = color;
214
- }`}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)}}x(mn,"type","Contrast"),x(mn,"defaults",{contrast:0}),x(mn,"uniformLocations",["uContrast"]),I.setClass(mn);const Ku={Convolute_3_1:`
159
+ }`}isNeutralState(){return this.contrast===0}applyTo2d({imageData:{data:e}}){let t=Math.floor(255*this.contrast),n=259*(t+255)/(255*(259-t));for(let t=0;t<e.length;t+=4)e[t]=n*(e[t]-128)+128,e[t+1]=n*(e[t+1]-128)+128,e[t+2]=n*(e[t+2]-128)+128}sendUniformData(e,t){e.uniform1f(t.uContrast,this.contrast)}};p(vc,`type`,`Contrast`),p(vc,`defaults`,{contrast:0}),p(vc,`uniformLocations`,[`uContrast`]),L.setClass(vc);var yc={Convolute_3_1:`
215
160
  precision highp float;
216
161
  uniform sampler2D uTexture;
217
162
  uniform float uMatrix[9];
@@ -355,7 +300,7 @@ ${l.toClipPathSVG(s)}</clipPath>
355
300
  gl_FragColor = color;
356
301
  gl_FragColor.a = alpha;
357
302
  }
358
- `};class bn extends St{getCacheKey(){return`${this.type}_${Math.sqrt(this.matrix.length)}_${this.opaque?1:0}`}getFragmentSource(){return Ku[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,l=e.height,h=t.ctx.createImageData(o,l),c=h.data,u=this.opaque?1:0;let d,f,g,p,b,m,v,_,y,w,C,A,T;for(C=0;C<l;C++)for(w=0;w<o;w++){for(b=4*(C*o+w),d=0,f=0,g=0,p=0,T=0;T<n;T++)for(A=0;A<n;A++)v=C+T-r,m=w+A-r,v<0||v>=l||m<0||m>=o||(_=4*(v*o+m),y=i[T*n+A],d+=s[_]*y,f+=s[_+1]*y,g+=s[_+2]*y,u||(p+=s[_+3]*y));c[b]=d,c[b+1]=f,c[b+2]=g,c[b+3]=u?s[b+3]:p}t.imageData=h}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return{...super.toObject(),opaque:this.opaque,matrix:[...this.matrix]}}}x(bn,"type","Convolute"),x(bn,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),x(bn,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),I.setClass(bn);const Pl="Gamma";class vn extends St{getFragmentSource(){return`
303
+ `},bc=class extends ec{getCacheKey(){return`${this.type}_${Math.sqrt(this.matrix.length)}_${+!!this.opaque}`}getFragmentSource(){return yc[this.getCacheKey()]}applyTo2d(e){let t=e.imageData,n=t.data,r=this.matrix,i=Math.round(Math.sqrt(r.length)),a=Math.floor(i/2),o=t.width,s=t.height,c=e.ctx.createImageData(o,s),l=c.data,u=+!!this.opaque,d,f,p,m,h,g,_,v,y,b,x,S,C;for(x=0;x<s;x++)for(b=0;b<o;b++){for(h=4*(x*o+b),d=0,f=0,p=0,m=0,C=0;C<i;C++)for(S=0;S<i;S++)_=x+C-a,g=b+S-a,_<0||_>=s||g<0||g>=o||(v=4*(_*o+g),y=r[C*i+S],d+=n[v]*y,f+=n[v+1]*y,p+=n[v+2]*y,u||(m+=n[v+3]*y));l[h]=d,l[h+1]=f,l[h+2]=p,l[h+3]=u?n[h+3]:m}e.imageData=c}sendUniformData(e,t){e.uniform1fv(t.uMatrix,this.matrix)}toObject(){return{...super.toObject(),opaque:this.opaque,matrix:[...this.matrix]}}};p(bc,`type`,`Convolute`),p(bc,`defaults`,{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),p(bc,`uniformLocations`,[`uMatrix`,`uOpaque`,`uHalfSize`,`uSize`]),L.setClass(bc);var xc=`Gamma`,Sc=class extends ec{getFragmentSource(){return`
359
304
  precision highp float;
360
305
  uniform sampler2D uTexture;
361
306
  uniform vec3 uGamma;
@@ -369,7 +314,7 @@ ${l.toClipPathSVG(s)}</clipPath>
369
314
  gl_FragColor = color;
370
315
  gl_FragColor.rgb *= color.a;
371
316
  }
372
- `}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 l=0;l<256;l++)o.r[l]=255*Math.pow(l/255,i),o.g[l]=255*Math.pow(l/255,n),o.b[l]=255*Math.pow(l/255,r);for(let l=0;l<e.length;l+=4)e[l]=o.r[e[l]],e[l+1]=o.g[e[l+1]],e[l+2]=o.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:Pl,gamma:this.gamma.concat()}}}x(vn,"type",Pl),x(vn,"defaults",{gamma:[1,1,1]}),x(vn,"uniformLocations",["uGamma"]),I.setClass(vn);const Qu={average:`
317
+ `}constructor(e={}){super(e),this.gamma=e.gamma||this.constructor.defaults.gamma.concat()}applyTo2d({imageData:{data:e}}){let t=this.gamma,n=1/t[0],r=1/t[1],i=1/t[2];this.rgbValues||={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)};let a=this.rgbValues;for(let e=0;e<256;e++)a.r[e]=255*(e/255)**n,a.g[e]=255*(e/255)**r,a.b[e]=255*(e/255)**i;for(let t=0;t<e.length;t+=4)e[t]=a.r[e[t]],e[t+1]=a.g[e[t+1]],e[t+2]=a.b[e[t+2]]}sendUniformData(e,t){e.uniform3fv(t.uGamma,this.gamma)}isNeutralState(){let{gamma:e}=this;return e[0]===1&&e[1]===1&&e[2]===1}toObject(){return{type:xc,gamma:this.gamma.concat()}}};p(Sc,`type`,xc),p(Sc,`defaults`,{gamma:[1,1,1]}),p(Sc,`uniformLocations`,[`uGamma`]),L.setClass(Sc);var Cc={average:`
373
318
  precision highp float;
374
319
  uniform sampler2D uTexture;
375
320
  varying vec2 vTexCoord;
@@ -398,7 +343,7 @@ ${l.toClipPathSVG(s)}</clipPath>
398
343
  float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
399
344
  gl_FragColor = vec4(average, average, average, col.a);
400
345
  }
401
- `};class yn extends St{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`${this.type}_${this.mode}`}getFragmentSource(){return Qu[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}x(yn,"type","Grayscale"),x(yn,"defaults",{mode:"average"}),x(yn,"uniformLocations",["uMode"]),I.setClass(yn);const Ju={...kl,rotation:0};class qr extends Is{calculateMatrix(){const t=this.rotation*Math.PI,e=ce(t),s=ue(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}}}x(qr,"type","HueRotation"),x(qr,"defaults",Ju),I.setClass(qr);class _n extends St{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`
346
+ `},wc=class extends ec{applyTo2d({imageData:{data:e}}){for(let t,n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2];switch(this.mode){case`average`:t=(r+i+a)/3;break;case`lightness`:t=(Math.min(r,i,a)+Math.max(r,i,a))/2;break;case`luminosity`:t=.21*r+.72*i+.07*a}e[n+2]=e[n+1]=e[n]=t}}getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Cc[this.mode]}sendUniformData(e,t){e.uniform1i(t.uMode,1)}isNeutralState(){return!1}};p(wc,`type`,`Grayscale`),p(wc,`defaults`,{mode:`average`}),p(wc,`uniformLocations`,[`uMode`]),L.setClass(wc);var Tc={...sc,rotation:0},Ec=class extends cc{calculateMatrix(){let e=this.rotation*Math.PI,t=Te(e),n=Ee(e),r=1/3,i=Math.sqrt(r)*n,a=1-t;this.matrix=[t+a/3,r*a-i,r*a+i,0,0,r*a+i,t+r*a,r*a-i,0,0,r*a-i,r*a+i,t+r*a,0,0,0,0,0,1,0]}isNeutralState(){return this.rotation===0}applyTo(e){this.calculateMatrix(),super.applyTo(e)}toObject(){return{type:this.type,rotation:this.rotation}}};p(Ec,`type`,`HueRotation`),p(Ec,`defaults`,Tc),L.setClass(Ec);var Dc=class extends ec{applyTo2d({imageData:{data:e}}){for(let t=0;t<e.length;t+=4)e[t]=255-e[t],e[t+1]=255-e[t+1],e[t+2]=255-e[t+2],this.alpha&&(e[t+3]=255-e[t+3])}getFragmentSource(){return`
402
347
  precision highp float;
403
348
  uniform sampler2D uTexture;
404
349
  uniform int uInvert;
@@ -416,7 +361,7 @@ ${l.toClipPathSVG(s)}</clipPath>
416
361
  gl_FragColor = color;
417
362
  }
418
363
  }
419
- `}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}x(_n,"type","Invert"),x(_n,"defaults",{alpha:!1,invert:!0}),x(_n,"uniformLocations",["uInvert","uAlpha"]),I.setClass(_n);class wn extends St{getFragmentSource(){return`
364
+ `}isNeutralState(){return!this.invert}sendUniformData(e,t){e.uniform1i(t.uInvert,Number(this.invert)),e.uniform1i(t.uAlpha,Number(this.alpha))}};p(Dc,`type`,`Invert`),p(Dc,`defaults`,{alpha:!1,invert:!0}),p(Dc,`uniformLocations`,[`uInvert`,`uAlpha`]),L.setClass(Dc);var Oc=class extends ec{getFragmentSource(){return`
420
365
  precision highp float;
421
366
  uniform sampler2D uTexture;
422
367
  uniform float uStepH;
@@ -431,7 +376,7 @@ ${l.toClipPathSVG(s)}</clipPath>
431
376
  color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
432
377
  gl_FragColor = color;
433
378
  }
434
- `}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}}x(wn,"type","Noise"),x(wn,"defaults",{noise:0}),x(wn,"uniformLocations",["uNoise","uSeed"]),I.setClass(wn);class xn extends St{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,l=e[o],h=e[o+1],c=e[o+2],u=e[o+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`
379
+ `}applyTo2d({imageData:{data:e}}){let t=this.noise;for(let n=0;n<e.length;n+=4){let r=(.5-Math.random())*t;e[n]+=r,e[n+1]+=r,e[n+2]+=r}}sendUniformData(e,t){e.uniform1f(t.uNoise,this.noise/255),e.uniform1f(t.uSeed,Math.random())}isNeutralState(){return this.noise===0}};p(Oc,`type`,`Noise`),p(Oc,`defaults`,{noise:0}),p(Oc,`uniformLocations`,[`uNoise`,`uSeed`]),L.setClass(Oc);var kc=class extends ec{applyTo2d({imageData:{data:e,width:t,height:n}}){for(let r=0;r<n;r+=this.blocksize)for(let i=0;i<t;i+=this.blocksize){let a=4*r*t+4*i,o=e[a],s=e[a+1],c=e[a+2],l=e[a+3];for(let a=r;a<Math.min(r+this.blocksize,n);a++)for(let n=i;n<Math.min(i+this.blocksize,t);n++){let r=4*a*t+4*n;e[r]=o,e[r+1]=s,e[r+2]=c,e[r+3]=l}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
435
380
  precision highp float;
436
381
  uniform sampler2D uTexture;
437
382
  uniform float uBlocksize;
@@ -449,7 +394,7 @@ ${l.toClipPathSVG(s)}</clipPath>
449
394
  vec4 color = texture2D(uTexture, squareCoords);
450
395
  gl_FragColor = color;
451
396
  }
452
- `}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}x(xn,"type","Pixelate"),x(xn,"defaults",{blocksize:4}),x(xn,"uniformLocations",["uBlocksize"]),I.setClass(xn);class Sn extends St{getFragmentSource(){return`
397
+ `}sendUniformData(e,t){e.uniform1f(t.uBlocksize,this.blocksize)}};p(kc,`type`,`Pixelate`),p(kc,`defaults`,{blocksize:4}),p(kc,`uniformLocations`,[`uBlocksize`]),L.setClass(kc);var Ac=class extends ec{getFragmentSource(){return`
453
398
  precision highp float;
454
399
  uniform sampler2D uTexture;
455
400
  uniform vec4 uLow;
@@ -461,23 +406,8 @@ void main() {
461
406
  gl_FragColor.a = 0.0;
462
407
  }
463
408
  }
464
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new ot(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 l=e[o],h=e[o+1],c=e[o+2];l>n[0]&&h>n[1]&&c>n[2]&&l<r[0]&&h<r[1]&&c<r[2]&&(e[o+3]=0)}}sendUniformData(t,e){const s=new ot(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)}}x(Sn,"type","RemoveColor"),x(Sn,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),x(Sn,"uniformLocations",["uLow","uHigh"]),I.setClass(Sn);class Cn extends St{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`${this.type}_${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]=`${s}.0 * uDelta`;return`
465
- precision highp float;
466
- uniform sampler2D uTexture;
467
- uniform vec2 uDelta;
468
- varying vec2 vTexCoord;
469
- uniform float uTaps[${t}];
470
- void main() {
471
- vec4 color = texture2D(uTexture, vTexCoord);
472
- float sum = 1.0;
473
- ${e.map((s,i)=>`
474
- color += texture2D(uTexture, vTexCoord + ${s}) * uTaps[${i}] + texture2D(uTexture, vTexCoord - ${s}) * uTaps[${i}];
475
- sum += 2.0 * uTaps[${i}];
476
- `).join(`
477
- `)}
478
- gl_FragColor = color / sum;
479
- }
480
- `}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){un(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),l=Math.round(r*i);let h;h=this.resizeType==="sliceHack"?this.sliceByTwo(t,n,r,o,l):this.resizeType==="hermite"?this.hermiteFastResize(t,n,r,o,l):this.resizeType==="bilinear"?this.bilinearFiltering(t,n,r,o,l):this.resizeType==="lanczos"?this.lanczosResize(t,n,r,o,l):new ImageData(o,l),t.imageData=h}sliceByTwo(t,e,s,i,n){const r=t.imageData,o=.5;let l=!1,h=!1,c=e*o,u=s*o;const d=t.filterBackend.resources;let f=0,g=0;const p=e;let b=0;d.sliceByTwo||(d.sliceByTwo=xe());const m=d.sliceByTwo;(m.width<1.5*e||m.height<s)&&(m.width=1.5*e,m.height=s);const v=m.getContext("2d");for(v.clearRect(0,0,1.5*e,s),v.putImageData(r,0,0),i=Math.floor(i),n=Math.floor(n);!l||!h;)e=c,s=u,i<Math.floor(c*o)?c=Math.floor(c*o):(c=i,l=!0),n<Math.floor(u*o)?u=Math.floor(u*o):(u=n,h=!0),v.drawImage(m,f,g,e,s,p,b,c,u),f=p,g=b,b+=u;return v.getImageData(f,g,i,n)}lanczosResize(t,e,s,i,n){const r=t.imageData.data,o=t.ctx.createImageData(i,n),l=o.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),b={},m={x:0,y:0},v={x:0,y:0};return(function _(y){let w,C,A,T,k,L,R,F,P,O,$;for(m.x=(y+.5)*c,v.x=Math.floor(m.x),w=0;w<n;w++){for(m.y=(w+.5)*u,v.y=Math.floor(m.y),k=0,L=0,R=0,F=0,P=0,C=v.x-g;C<=v.x+g;C++)if(!(C<0||C>=e)){O=Math.floor(1e3*Math.abs(C-m.x)),b[O]||(b[O]={});for(let M=v.y-p;M<=v.y+p;M++)M<0||M>=s||($=Math.floor(1e3*Math.abs(M-m.y)),b[O][$]||(b[O][$]=h(Math.sqrt(Math.pow(O*d,2)+Math.pow($*f,2))/1e3)),A=b[O][$],A>0&&(T=4*(M*e+C),k+=A,L+=A*r[T],R+=A*r[T+1],F+=A*r[T+2],P+=A*r[T+3]))}T=4*(w*i+y),l[T]=L/k,l[T+1]=R/k,l[T+2]=F/k,l[T+3]=P/k}return++y<i?_(y):o})(0)}bilinearFiltering(t,e,s,i,n){let r,o,l,h,c,u,d,f,g,p,b,m,v,_=0;const y=this.rcpScaleX,w=this.rcpScaleY,C=4*(e-1),A=t.imageData.data,T=t.ctx.createImageData(i,n),k=T.data;for(d=0;d<n;d++)for(f=0;f<i;f++)for(c=Math.floor(y*f),u=Math.floor(w*d),g=y*f-c,p=w*d-u,v=4*(u*e+c),b=0;b<4;b++)r=A[v+b],o=A[v+4+b],l=A[v+C+b],h=A[v+C+4+b],m=r*(1-g)*(1-p)+o*g*(1-p)+l*p*(1-g)+h*g*p,k[_++]=m;return T}hermiteFastResize(t,e,s,i,n){const r=this.rcpScaleX,o=this.rcpScaleY,l=Math.ceil(r/2),h=Math.ceil(o/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 b=0,m=0,v=0,_=0,y=0,w=0,C=0;const A=(f+.5)*o;for(let T=Math.floor(f*o);T<(f+1)*o;T++){const k=Math.abs(A-(T+.5))/h,L=(g+.5)*r,R=k*k;for(let F=Math.floor(g*r);F<(g+1)*r;F++){let P=Math.abs(L-(F+.5))/l;const O=Math.sqrt(R+P*P);O>1&&O<-1||(b=2*O*O*O-3*O*O+1,b>0&&(P=4*(F+T*e),C+=b*c[P+3],v+=b,c[P+3]<255&&(b=b*c[P+3]/250),_+=b*c[P],y+=b*c[P+1],w+=b*c[P+2],m+=b))}}d[p]=_/m,d[p+1]=y/m,d[p+2]=w/m,d[p+3]=C/v}return u}}x(Cn,"type","Resize"),x(Cn,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),x(Cn,"uniformLocations",["uDelta","uTaps"]),I.setClass(Cn);class An extends St{getFragmentSource(){return`
409
+ `}applyTo2d({imageData:{data:e}}){let t=255*this.distance,n=new Cn(this.color).getSource(),r=[n[0]-t,n[1]-t,n[2]-t],i=[n[0]+t,n[1]+t,n[2]+t];for(let t=0;t<e.length;t+=4){let n=e[t],a=e[t+1],o=e[t+2];n>r[0]&&a>r[1]&&o>r[2]&&n<i[0]&&a<i[1]&&o<i[2]&&(e[t+3]=0)}}sendUniformData(e,t){let n=new Cn(this.color).getSource(),r=this.distance,i=[0+n[0]/255-r,0+n[1]/255-r,0+n[2]/255-r,1],a=[n[0]/255+r,n[1]/255+r,n[2]/255+r,1];e.uniform4fv(t.uLow,i),e.uniform4fv(t.uHigh,a)}};p(Ac,`type`,`RemoveColor`),p(Ac,`defaults`,{color:`#FFFFFF`,distance:.02,useAlpha:!1}),p(Ac,`uniformLocations`,[`uLow`,`uHigh`]),L.setClass(Ac);var jc=class extends ec{sendUniformData(e,t){e.uniform2fv(t.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),e.uniform1fv(t.uTaps,this.taps)}getFilterWindow(){let e=this.tempScale;return Math.ceil(this.lanczosLobes/e)}getCacheKey(){let e=this.getFilterWindow();return`${this.type}_${e}`}getFragmentSource(){let e=this.getFilterWindow();return this.generateShader(e)}getTaps(){let e=this.lanczosCreate(this.lanczosLobes),t=this.tempScale,n=this.getFilterWindow(),r=Array(n);for(let i=1;i<=n;i++)r[i-1]=e(i*t);return r}generateShader(e){let t=Array(e);for(let n=1;n<=e;n++)t[n-1]=`${n}.0 * uDelta`;return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n uniform float uTaps[${e}];\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float sum = 1.0;\n ${t.map((e,t)=>`\n color += texture2D(uTexture, vTexCoord + ${e}) * uTaps[${t}] + texture2D(uTexture, vTexCoord - ${e}) * uTaps[${t}];\n sum += 2.0 * uTaps[${t}];\n `).join(`
410
+ `)}\n gl_FragColor = color / sum;\n }\n `}applyToForWebgl(e){e.passes++,this.width=e.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=e.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),e.destinationWidth=this.dW,super.applyTo(e),e.sourceWidth=e.destinationWidth,this.height=e.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),e.destinationHeight=this.dH,super.applyTo(e),e.sourceHeight=e.destinationHeight}applyTo(e){Xs(e)?this.applyToForWebgl(e):this.applyTo2d(e)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(e){return t=>{if(t>=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;let n=(t*=Math.PI)/e;return Math.sin(t)/t*Math.sin(n)/n}}applyTo2d(e){let t=e.imageData,n=this.scaleX,r=this.scaleY;this.rcpScaleX=1/n,this.rcpScaleY=1/r;let i=t.width,a=t.height,o=Math.round(i*n),s=Math.round(a*r),c;c=this.resizeType===`sliceHack`?this.sliceByTwo(e,i,a,o,s):this.resizeType===`hermite`?this.hermiteFastResize(e,i,a,o,s):this.resizeType===`bilinear`?this.bilinearFiltering(e,i,a,o,s):this.resizeType===`lanczos`?this.lanczosResize(e,i,a,o,s):new ImageData(o,s),e.imageData=c}sliceByTwo(e,t,n,r,i){let a=e.imageData,o=.5,s=!1,c=!1,l=t*o,u=n*o,d=e.filterBackend.resources,f=0,p=0,m=t,h=0;d.sliceByTwo||=Fe();let g=d.sliceByTwo;(g.width<1.5*t||g.height<n)&&(g.width=1.5*t,g.height=n);let _=g.getContext(`2d`);for(_.clearRect(0,0,1.5*t,n),_.putImageData(a,0,0),r=Math.floor(r),i=Math.floor(i);!s||!c;)t=l,n=u,r<Math.floor(l*o)?l=Math.floor(l*o):(l=r,s=!0),i<Math.floor(u*o)?u=Math.floor(u*o):(u=i,c=!0),_.drawImage(g,f,p,t,n,m,h,l,u),f=m,p=h,h+=u;return _.getImageData(f,p,r,i)}lanczosResize(e,t,n,r,i){let a=e.imageData.data,o=e.ctx.createImageData(r,i),s=o.data,c=this.lanczosCreate(this.lanczosLobes),l=this.rcpScaleX,u=this.rcpScaleY,d=2/this.rcpScaleX,f=2/this.rcpScaleY,p=Math.ceil(l*this.lanczosLobes/2),m=Math.ceil(u*this.lanczosLobes/2),h={},g={x:0,y:0},_={x:0,y:0};return function e(v){let y,b,x,S,C,w,T,E,D,O,k;for(g.x=(v+.5)*l,_.x=Math.floor(g.x),y=0;y<i;y++){for(g.y=(y+.5)*u,_.y=Math.floor(g.y),C=0,w=0,T=0,E=0,D=0,b=_.x-p;b<=_.x+p;b++)if(!(b<0||b>=t)){O=Math.floor(1e3*Math.abs(b-g.x)),h[O]||(h[O]={});for(let e=_.y-m;e<=_.y+m;e++)e<0||e>=n||(k=Math.floor(1e3*Math.abs(e-g.y)),h[O][k]||(h[O][k]=c(Math.sqrt((O*d)**2+(k*f)**2)/1e3)),x=h[O][k],x>0&&(S=4*(e*t+b),C+=x,w+=x*a[S],T+=x*a[S+1],E+=x*a[S+2],D+=x*a[S+3]))}S=4*(y*r+v),s[S]=w/C,s[S+1]=T/C,s[S+2]=E/C,s[S+3]=D/C}return++v<r?e(v):o}(0)}bilinearFiltering(e,t,n,r,i){let a,o,s,c,l,u,d,f,p,m,h,g,_,v=0,y=this.rcpScaleX,b=this.rcpScaleY,x=4*(t-1),S=e.imageData.data,C=e.ctx.createImageData(r,i),w=C.data;for(d=0;d<i;d++)for(f=0;f<r;f++)for(l=Math.floor(y*f),u=Math.floor(b*d),p=y*f-l,m=b*d-u,_=4*(u*t+l),h=0;h<4;h++)a=S[_+h],o=S[_+4+h],s=S[_+x+h],c=S[_+x+4+h],g=a*(1-p)*(1-m)+o*p*(1-m)+s*m*(1-p)+c*p*m,w[v++]=g;return C}hermiteFastResize(e,t,n,r,i){let a=this.rcpScaleX,o=this.rcpScaleY,s=Math.ceil(a/2),c=Math.ceil(o/2),l=e.imageData.data,u=e.ctx.createImageData(r,i),d=u.data;for(let e=0;e<i;e++)for(let n=0;n<r;n++){let i=4*(n+e*r),u,f=0,p=0,m=0,h=0,g=0,_=0,v=(e+.5)*o;for(let r=Math.floor(e*o);r<(e+1)*o;r++){let e=Math.abs(v-(r+.5))/c,i=(n+.5)*a,o=e*e;for(let e=Math.floor(n*a);e<(n+1)*a;e++){let n=Math.abs(i-(e+.5))/s,a=Math.sqrt(o+n*n);a>1&&a<-1||(u=2*a*a*a-3*a*a+1,u>0&&(n=4*(e+r*t),_+=u*l[n+3],p+=u,l[n+3]<255&&(u=u*l[n+3]/250),m+=u*l[n],h+=u*l[n+1],g+=u*l[n+2],f+=u))}}d[i]=m/f,d[i+1]=h/f,d[i+2]=g/f,d[i+3]=_/p}return u}};p(jc,`type`,`Resize`),p(jc,`defaults`,{resizeType:`hermite`,scaleX:1,scaleY:1,lanczosLobes:3}),p(jc,`uniformLocations`,[`uDelta`,`uTaps`]),L.setClass(jc);var Mc=class extends ec{getFragmentSource(){return`
481
411
  precision highp float;
482
412
  uniform sampler2D uTexture;
483
413
  uniform float uSaturation;
@@ -491,7 +421,7 @@ void main() {
491
421
  color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
492
422
  gl_FragColor = color;
493
423
  }
494
- `}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],l=Math.max(n,r,o);e[i]+=l!==n?(l-n)*s:0,e[i+1]+=l!==r?(l-r)*s:0,e[i+2]+=l!==o?(l-o)*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}x(An,"type","Saturation"),x(An,"defaults",{saturation:0}),x(An,"uniformLocations",["uSaturation"]),I.setClass(An);class Tn extends St{getFragmentSource(){return`
424
+ `}applyTo2d({imageData:{data:e}}){let t=-this.saturation;for(let n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2],o=Math.max(r,i,a);e[n]+=o===r?0:(o-r)*t,e[n+1]+=o===i?0:(o-i)*t,e[n+2]+=o===a?0:(o-a)*t}}sendUniformData(e,t){e.uniform1f(t.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}};p(Mc,`type`,`Saturation`),p(Mc,`defaults`,{saturation:0}),p(Mc,`uniformLocations`,[`uSaturation`]),L.setClass(Mc);var Nc=class extends ec{getFragmentSource(){return`
495
425
  precision highp float;
496
426
  uniform sampler2D uTexture;
497
427
  uniform float uVibrance;
@@ -506,15 +436,14 @@ void main() {
506
436
  color.b += max != color.b ? (max - color.b) * amt : 0.00;
507
437
  gl_FragColor = color;
508
438
  }
509
- `}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],l=Math.max(n,r,o),h=(n+r+o)/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!==o?(l-o)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}x(Tn,"type","Vibrance"),x(Tn,"defaults",{vibrance:0}),x(Tn,"uniformLocations",["uVibrance"]),I.setClass(Tn);var ui={};ui.d=(a,t)=>{for(var e in t)ui.o(t,e)&&!ui.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},ui.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var X=globalThis.pdfjsLib={};ui.d(X,{AbortException:()=>Ke,AnnotationEditorLayer:()=>ze,AnnotationEditorParamsType:()=>tt,AnnotationEditorType:()=>Y,AnnotationEditorUIManager:()=>Qe,AnnotationLayer:()=>Yf,AnnotationMode:()=>Ye,ColorPicker:()=>ae,DOMSVGFactory:()=>_o,DrawLayer:()=>zt,FeatureTest:()=>$t,GlobalWorkerOptions:()=>_i,ImageKind:()=>En,InvalidPDFException:()=>Zr,MissingPDFException:()=>fi,OPS:()=>ve,OutputScale:()=>ao,PDFDataRangeTransport:()=>dh,PDFDateString:()=>Il,PDFWorker:()=>$s,PasswordResponses:()=>sd,PermissionFlag:()=>ed,PixelsPerInch:()=>js,RenderingCancelledException:()=>no,TextLayer:()=>Ht,TouchManager:()=>In,UnexpectedResponseException:()=>On,Util:()=>H,VerbosityLevel:()=>kn,XfaLayer:()=>mh,build:()=>kf,createValidAbsoluteUrl:()=>od,fetchData:()=>Rn,getDocument:()=>yf,getFilenameFromUrl:()=>pd,getPdfFilenameFromUrl:()=>md,getXfaPageViewport:()=>bd,isDataScheme:()=>Ln,isPdfFile:()=>ro,noContextMenu:()=>ye,normalizeUnicode:()=>dd,setLayerDimensions:()=>ms,shadow:()=>Q,stopEvent:()=>ie,version:()=>Ef});const Ot=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Ol=[1,0,0,1,0,0],Kr=[.001,0,0,.001,0,0],Zu=1e7,Qr=1.35,se={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Ye={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},td="pdfjs_internal_editor_",Y={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},tt={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},ed={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Dt={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},En={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Ct={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},di={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},kn={ERRORS:0,WARNINGS:1,INFOS:5},ve={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},sd={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Mn=kn.WARNINGS;function id(a){Number.isInteger(a)&&(Mn=a)}function nd(){return Mn}function Pn(a){Mn>=kn.INFOS&&console.log(`Info: ${a}`)}function q(a){Mn>=kn.WARNINGS&&console.log(`Warning: ${a}`)}function at(a){throw new Error(a)}function _t(a,t){a||at(t)}function rd(a){switch(a?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function od(a,t=null,e=null){if(!a)return null;try{if(e&&typeof a=="string"&&(e.addDefaultProtocol&&a.startsWith("www.")&&a.match(/\./g)?.length>=2&&(a=`http://${a}`),e.tryConvertEncoding))try{a=ud(a)}catch{}const s=t?new URL(a,t):new URL(a);if(rd(s))return s}catch{}return null}function Q(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const qe=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class Dl extends qe{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Jr extends qe{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Zr extends qe{constructor(t){super(t,"InvalidPDFException")}}class fi extends qe{constructor(t){super(t,"MissingPDFException")}}class On extends qe{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class ad extends qe{constructor(t){super(t,"FormatError")}}class Ke extends qe{constructor(t){super(t,"AbortException")}}function Rl(a){(typeof a!="object"||a?.length===void 0)&&at("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 Dn(a){typeof a!="string"&&at("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 ld(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function to(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function hd(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function cd(){try{return new Function(""),!0}catch{return!1}}class $t{static get isLittleEndian(){return Q(this,"isLittleEndian",hd())}static get isEvalSupported(){return Q(this,"isEvalSupported",cd())}static get isOffscreenCanvasSupported(){return Q(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Q(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?Q(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):Q(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return Q(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const eo=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class H{static makeHexColor(t,e,s){return`#${eo[t]}${eo[e]}${eo[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,l=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,h=o+l||1,c=o-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,o,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*o)+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,o,l,h,c,u,d){if(Math.abs(h)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,o,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,o,l,(-c+g)/p,d),this.#t(t,e,s,i,n,r,o,l,(-c-g)/p,d)}static bezierBoundingBox(t,e,s,i,n,r,o,l,h){return h?(h[0]=Math.min(h[0],t,o),h[1]=Math.min(h[1],e,l),h[2]=Math.max(h[2],t,o),h[3]=Math.max(h[3],e,l)):h=[Math.min(t,o),Math.min(e,l),Math.max(t,o),Math.max(e,l)],this.#e(t,s,n,o,e,i,r,l,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),h),this.#e(t,s,n,o,e,i,r,l,3*(-e+3*(i-r)+l),6*(e-2*i+r),3*(i-e),h),h}}function ud(a){return decodeURIComponent(escape(a))}let so=null,Ll=null;function dd(a){return so||(so=/([\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,Ll=new Map([["ſt","ſt"]])),a.replaceAll(so,(t,e,s)=>e?e.normalize("NFKC"):Ll.get(s))}function fd(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const a=new Uint8Array(32);return crypto.getRandomValues(a),Rl(a)}const io="pdfjs_internal_id_";function gd(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(Rl(a))}typeof Promise.try!="function"&&(Promise.try=function(a,...t){return new Promise(e=>{e(a(...t))})});const He="http://www.w3.org/2000/svg";class js{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Rn(a,t="text"){if(pi(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 gi{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 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.")}o&&(d=-d,f=-f);let g,p,b,m;c===0?(g=Math.abs(h-t[1])*s+n,p=Math.abs(l-t[0])*s+r,b=(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,b=(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=b,this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return Q(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 gi({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return H.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=H.applyTransform([t[0],t[1]],this.transform),s=H.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return H.applyInverseTransform([t,e],this.transform)}}class no extends qe{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Ln(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function ro(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function pd(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function md(a,t="document.pdf"){if(typeof a!="string")return t;if(Ln(a))return q('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 Fl{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
510
- `);return t.join("")}}function pi(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function ye(a){a.preventDefault()}function ie(a){a.preventDefault(),a.stopPropagation()}class Il{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 o=parseInt(e[5],10);o=o>=0&&o<=59?o: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,o+=u):h==="+"&&(r-=c,o-=u),new Date(Date.UTC(s,i,n,r,o,l))}}function bd(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new gi({viewBox:n,userUnit:1,scale:t,rotation:e})}function oo(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):(q(`Not a valid color format: "${a}"`),[0,0,0])}function vd(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,oo(s))}t.remove()}function ht(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function Te(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 ms(a,t,e=!1,s=!0){if(t instanceof gi){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=$t.isCSSRoundSupported,l=`var(--scale-factor) * ${i}px`,h=`var(--scale-factor) * ${n}px`,c=o?`round(down, ${l}, var(--scale-round-x, 1px))`:`calc(${l})`,u=o?`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&&a.setAttribute("data-main-rotation",t.rotation)}class ao{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 mi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,mi.#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",ye,{signal:e}),t.addEventListener("pointerdown",mi.#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()}#a(t){this.#s._focusEventsAllowed=!1,ie(t)}#c(t){this.#s._focusEventsAllowed=!0,ie(t)}#h(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#a.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ye,{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",mi.#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 yd{#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",ye,{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 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]}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",ye,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function Fn(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class _d{#t=0;get id(){return`${td}${this.#t++}`}}class lo{#t=fd();#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 Q(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 Rn(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=lo._isSVGFittingCanvas,r=new FileReader,o=new Image,l=new Promise((h,c)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,h()},r.onload=async()=>{const u=s.svgUrl=r.result;o.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},o.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 wd{#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:o=!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){o&&(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 bi{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=$t.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)))}}#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:o=null}}=s;o&&!o(t,e)||(i.bind(t,...r,e)(),n||ie(e))}}class ho{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return vd(t),Q(this,"_colors",t)}convert(t){const e=oo(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 ho._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?H.makeHexColor(...e):t}}class Qe{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#l=null;#a=new wd;#c=null;#h=null;#d=0;#u=new Set;#f=null;#o=null;#g=new Set;_editorUndoBar=null;#m=!1;#p=!1;#b=!1;#_=null;#v=null;#w=null;#S=null;#A=!1;#E=null;#M=new _d;#x=!1;#k=!1;#T=null;#O=null;#L=null;#I=null;#C=Y.NONE;#y=new Set;#R=null;#H=null;#z=null;#G={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#j=[0,0];#F=null;#N=null;#W=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Qe.prototype,e=r=>r.#N.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:l}=o;return l!=="text"&&l!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return Q(this,"_keyboardManager",new bi([[["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)&&r.#N.contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o 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,o,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.#Y(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#H=r,this.#S=o||null,this.#m=l,this.#p=h,this.#b=c,this.#I=u||null,this.viewParameters={realScale:js.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.#a.destroy(),this.#r?.destroy(),this.#E?.hide(),this.#E=null,this.#v&&(clearTimeout(this.#v),this.#v=null),this.#F&&(clearTimeout(this.#F),this.#F=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.#b}get hcmFilter(){return Q(this,"hcmFilter",this.#H?this.#_.addHCMFilter(this.#H.foreground,this.#H.background):"none")}get direction(){return Q(this,"direction",getComputedStyle(this.#N).direction)}get highlightColors(){return Q(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return Q(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.#L=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}){t==="enableNewAltTextWhenAddingImage"&&(this.#b=e)}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:o}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+o)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*js.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}#U(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,o=e.toString(),h=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(h);if(!c)return;e.empty();const u=this.#U(h),d=this.#C===Y.NONE,f=()=>{u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:o}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(Y.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 yd(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.#P({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.#P({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=e,this.#P({hasSelectedText:!0}),!(this.#C!==Y.HIGHLIGHT&&this.#C!==Y.NONE)&&(this.#C===Y.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===Y.HIGHLIGHT?this.#U(i):null;n?.toggleDrawing();const r=new AbortController,o=this.combinedSignal(r),l=h=>{h.type==="pointerup"&&h.button!==0||(r.abort(),n?.toggleDrawing(!0),h.type==="pointerup"&&this.#X("main_toolbar"))};window.addEventListener("pointerup",l,{signal:o}),window.addEventListener("blur",l,{signal:o})}}#X(t=""){this.#C===Y.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.#X("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()}#Y(){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.#Y(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#o)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.#o)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.#o)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.#Q(l);this.#J(n)},o=()=>{for(const l of n)l.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){q(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==Y.NONE&&!this.isEditorHandlingKeyboard&&Qe._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#X("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}}#P(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===Y.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#$([[tt.HIGHLIGHT_FREE,!0]]))}#$(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#P({isEditing:this.#C!==Y.NONE,isEmpty:this.#V(),hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:this.#a.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#K(),this.#P({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#o){this.#o=t;for(const e of this.#o)this.#$(e.defaultPropertiesToUpdate)}}getId(){return this.#M.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===Y.NONE){this.setEditingState(!1),this.#at(),this._editorUndoBar?.hide(),this.#D.resolve();return}this.setEditingState(!0),await this.#ot(),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.#o){switch(t){case tt.CREATE:this.currentLayer.addNewEditor();return;case tt.HIGHLIGHT_DEFAULT_COLOR:this.#L?.updateColor(e);break;case tt.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#z||=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.#o)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#z?.get(tt.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#$([[tt.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#ot(){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()}}#at(){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.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.focusMainContainer(),this.#v=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}#Q(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.#$(t.propertiesToUpdate))}get#lt(){let t=null;for(t of this.#y);return t}updateUI(t){this.#lt===t&&this.#$(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#$(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#P({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#$(t.propertiesToUpdate),this.#P({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.#$(t.propertiesToUpdate),this.#P({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.#P({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#y.size!==0}get isEnterHandled(){return this.#y.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#a.undo(),this.#P({hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#V()}),this._editorUndoBar?.hide()}redo(){this.#a.redo(),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:this.#a.hasSomethingToRedo(),isEmpty:this.#V()})}addCommands(t){this.#a.add(t),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#V()})}cleanUndoStack(t){this.#a.cleanType(t)}#V(){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.#Q(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#J(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.#P({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#y)t.commit();this.#J(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==Y.NONE))&&!this.#h?.commitOrRemove()&&this.hasSelection){for(const t of this.#y)t.unselect();this.#y.clear(),this.#P({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],o=1e3;this.#F&&clearTimeout(this.#F),this.#F=setTimeout(()=>{this.#F=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})},o);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},o]of t)o.newX=i,o.newY=n,o.newPageIndex=r,e||=i!==o.savedX||n!==o.savedY||r!==o.savedPageIndex;if(!e)return!1;const s=(i,n,r,o)=>{if(this.#s.has(i.id)){const l=this.#i.get(o);l?i._setParentAndPosition(l,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(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 Q(this,"imageManager",new lo)}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 o;switch(t.getAttribute("data-main-rotation")){case"90":o=(h,c,u,d)=>({x:(c-i)/r,y:1-(h+u-s)/n,width:d/r,height:u/n});break;case"180":o=(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":o=(h,c,u,d)=>({x:1-(c+d-i)/r,y:(h-s)/n,width:d/r,height:u/n});break;default:o=(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(o(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===Y.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Ee{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#l=!1;#a=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,Ee.#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){Ee._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",Ee.#f.missing),e.setAttribute("data-l10n-id",Ee.#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",ye,{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.#o}})};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#o(){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 Ee._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.#a?.remove(),this.#a=null;return}if(!this.#a){const e=this.#a=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#a.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.#o}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#r=null,this.#a?.remove(),this.#a=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",Ee.#f[this.#o]),this.#i?.setAttribute("data-l10n-id",Ee.#f[`${this.#o}-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 In{#t;#e=!1;#s=null;#i;#r;#n;#l;#a;#c=null;#h;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:o}){this.#t=t,this.#s=s,this.#i=e,this.#r=i,this.#n=n,this.#l=r,this.#h=new AbortController,this.#a=AbortSignal.any([o,this.#h.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#a})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return Q(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.#a,this.#d.signal]),n=this.#t,r={signal:i,passive:!1};n.addEventListener("touchmove",this.#f.bind(this),r),n.addEventListener("touchend",this.#o.bind(this),r),n.addEventListener("touchcancel",this.#o.bind(this),r),this.#r?.()}if(ie(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:o}=s,l=this.#c,{touch0X:h,touch0Y:c,touch1X:u,touch1Y:d}=l,f=u-h,g=d-c,p=r-i,b=o-n,m=Math.hypot(p,b)||1,v=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(v-m)<=In.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(l.touch0X=i,l.touch0Y=n,l.touch1X=r,l.touch1Y=o,t.preventDefault(),!this.#e){this.#e=!0;return}const _=[(i+r)/2,(n+o)/2];this.#n?.(_,v,m)}#o(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;#a=null;#c=null;#h=null;#d=null;#u="";#f=!1;#o=null;#g=!1;#m=!1;#p=!1;#b=null;#_=0;#v=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 ho;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=G.prototype._resizeWithKeyboard,e=Qe.TRANSLATE_SMALL,s=Qe.TRANSLATE_BIG;return Q(this,"_resizerKeyboardManager",new bi([[["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[o,l]=this.parentDimensions;this.x=t.x/o,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 Q(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new xd({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){at("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()}#M([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.#M(this.parentDimensions,t,e)}translateInPage(t,e){this.#o||=[this.x,this.y,this.width,this.height],this.#M(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#o||=[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:o}=this;const[l,h]=this.getBaseTranslation();r+=l,o+=h;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#o&&(this.#o[0]!==this.x||this.#o[1]!==this.y)}get _hasBeenResized(){return!!this.#o&&(this.#o[2]!==this.width||this.#o[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:o,height:l}=this;if(o*=s,l*=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-l,r));break;case 90:n=Math.max(0,Math.min(s-l,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(l,r));break;case 270:n=Math.min(s,Math.max(l,n)),r=Math.max(0,Math.min(i-o,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,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#l&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#T(){if(this.#a)return;this.#a=document.createElement("div"),this.#a.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.#a.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",ye,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#a)}#O(t,e){e.preventDefault();const{isMac:s}=$t.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",ie,{passive:!1,signal:r}),window.addEventListener("contextmenu",ye,{signal:r}),this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=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=o,this.div.style.cursor=l,this.#I()};window.addEventListener("pointerup",h,{signal:r}),window.addEventListener("blur",h,{signal:r})}#L(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,o=this.width,l=this.height;n===t&&r===e&&o===s&&l===i||this.addCommands({cmd:this.#L.bind(this,n,r,o,l),undo:this.#L.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,o=this.width,l=this.height,h=G.MIN_SIZE/s,c=G.MIN_SIZE/i,u=this.#k(this.rotation),d=(M,D)=>[u[0]*M+u[2]*D,u[1]*M+u[3]*D],f=this.#k(360-this.rotation),g=(M,D)=>[f[0]*M+f[2]*D,f[1]*M+f[3]*D];let p,b,m=!1,v=!1;switch(t){case"topLeft":m=!0,p=(M,D)=>[0,0],b=(M,D)=>[M,D];break;case"topMiddle":p=(M,D)=>[M/2,0],b=(M,D)=>[M/2,D];break;case"topRight":m=!0,p=(M,D)=>[M,0],b=(M,D)=>[0,D];break;case"middleRight":v=!0,p=(M,D)=>[M,D/2],b=(M,D)=>[0,D/2];break;case"bottomRight":m=!0,p=(M,D)=>[M,D],b=(M,D)=>[0,0];break;case"bottomMiddle":p=(M,D)=>[M/2,D],b=(M,D)=>[M/2,0];break;case"bottomLeft":m=!0,p=(M,D)=>[0,D],b=(M,D)=>[M,0];break;case"middleLeft":v=!0,p=(M,D)=>[0,D/2],b=(M,D)=>[M,D/2];break}const _=p(o,l),y=b(o,l);let w=d(...y);const C=G._round(n+w[0]),A=G._round(r+w[1]);let T=1,k=1,L,R;if(e.fromKeyboard)({deltaX:L,deltaY:R}=e);else{const{screenX:M,screenY:D}=e,[V,lt]=this.#c;[L,R]=this.screenToPageTranslation(M-V,D-lt),this.#c[0]=M,this.#c[1]=D}if([L,R]=g(L/s,R/i),m){const M=Math.hypot(o,l);T=k=Math.max(Math.min(Math.hypot(y[0]-_[0]-L,y[1]-_[1]-R)/M,1/o,1/l),h/o,c/l)}else v?T=Math.max(h,Math.min(1,Math.abs(y[0]-_[0]-L)))/o:k=Math.max(c,Math.min(1,Math.abs(y[1]-_[1]-R)))/l;const F=G._round(o*T),P=G._round(l*k);w=d(...b(F,P));const O=C-w[0],$=A-w[1];this.#o||=[this.x,this.y,this.width,this.height],this.width=F,this.height=P,this.x=O,this.y=$,this.setDims(s*F,i*P),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new mi(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||(Ee.initialize(G._l10n),this.#s=new Ee(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),Fn(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new In({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#H.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),o=(C,A)=>[r[0]*C+r[2]*A,r[1]*C+r[3]*A],[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 b=G._round(d*n),m=G._round(f*n);if(b===d&&m===f)return;this.#o||=[c,u,d,f];const v=o(d/2,f/2),_=G._round(c+v[0]),y=G._round(u+v[1]),w=o(b/2,m/2);this.x=_-w[0],this.y=y-w[1],this.width=b,this.height=m,this.setDims(l*b,h*m),this.fixAndSetPosition(),this._onResizing()}#H(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=$t.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#G(t);return}this.#z(t)}get isSelected(){return this._uiManager.isSelected(this)}#z(t){const{isMac:e}=$t.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},o=h=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#z(h),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#v=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){ie(h);return}const[f,g]=this.screenToPageTranslation(c-this.#_,u-this.#v);this.#_=c,this.#v=u,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",ie,r),window.addEventListener("pointerdown",h=>{h.pointerType===this.#n&&(this.#S||h.isPrimary)&&o(h),ie(h)},r));const l=h=>{if(!this.#r||this.#r===h.pointerId){o(h);return}ie(h)};window.addEventListener("pointerup",l,{signal:n}),window.addEventListener("blur",l,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=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,[o,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+o,r-d-c-g+l,u+h+f+o,r-d-c+l];case 90:return[u+c+o,r-d+h+l,u+c+g+o,r-d+h+f+l];case 180:return[u-h-f+o,r-d+c+l,u-h+o,r-d+c+g+l];case 270:return[u-c-g+o,r-d-h-f+l,u-c+o,r-d-h+l];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,l=r-i;switch(this.rotation){case 0:return[s,e-r,o,l];case 90:return[s,e-i,l,o];case 180:return[n,e-i,o,l];case 270:return[n,e-r,l,o];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){at("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,[o,l,h,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/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.#b&&(clearTimeout(this.#b),this.#b=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.#a.classList.remove("hidden"),Fn(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.#a.children;if(!this.#e){this.#e=Array.from(e);const r=this.#F.bind(this),o=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",o,{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 o=0;o<i-n;o++)this.#a.append(this.#a.firstChild);else if(n>i)for(let o=0;o<n-i;o++)this.#a.firstChild.before(this.#a.lastChild);let r=0;for(const o of e){const h=this.#e[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",G._l10nResizer[h])}}this.#D(0),this.#p=!0,this.#a.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#F(t){G._resizerKeyboardManager.exec(this,t)}#N(t){this.#p&&t.relatedTarget?.parentNode!==this.#a&&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.#a?.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 xd extends G{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const jl=3285377520,oe=4294901760,ke=65535;class Nl{constructor(t){this.h1=t?t&4294967295:jl,this.h2=t?t&4294967295:jl}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,b=t.length;p<b;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 o=0,l=0,h=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&ke,g=d&ke;for(let p=0;p<i;p++)p&1?(o=r[p],o=o*u&oe|o*f&ke,o=o<<15|o>>>17,o=o*d&oe|o*g&ke,h^=o,h=h<<13|h>>>19,h=h*5+3864292196):(l=r[p],l=l*u&oe|l*f&ke,l=l<<15|l>>>17,l=l*d&oe|l*g&ke,c^=l,c=c<<13|c>>>19,c=c*5+3864292196);switch(o=0,n){case 3:o^=e[i*4+2]<<16;case 2:o^=e[i*4+1]<<8;case 1:o^=e[i*4],o=o*u&oe|o*f&ke,o=o<<15|o>>>17,o=o*d&oe|o*g&ke,i&1?h^=o:c^=o}this.h1=h,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&oe|t*36045&ke,e=e*4283543511&oe|((e<<16|t>>>16)*2950163797&oe)>>>16,t^=e>>>1,t=t*444984403&oe|t*60499&ke,e=e*3301882366&oe|((e<<16|t>>>16)*3120437893&oe)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const co=Object.freeze({map:null,hash:"",transfer:void 0});class uo{#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?to(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 Bl(this)}get serializable(){if(this.#s.size===0)return co;const t=new Map,e=new Nl,s=[],i=Object.create(null);let n=!1;for(const[r,o]of this.#s){const l=o instanceof G?o.serialize(!1,i):o;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}:co}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[o,l]of Object.entries(i)){if(o==="type")continue;let h=r.get(o);h||(h=new Map,r.set(o,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 Bl extends uo{#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(){at("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return Q(this,"modifiedIds",{ids:new Set,hash:""})}}class Sd{#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(_t(!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}at("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 Q(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Ot||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),Q(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(_t(!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 Q(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(y,w){return y.charCodeAt(w)<<24|y.charCodeAt(w+1)<<16|y.charCodeAt(w+2)<<8|y.charCodeAt(w+3)&255}function i(y,w,C,A){const T=y.substring(0,w),k=y.substring(w+C);return T+A+k}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const l=o.getContext("2d");let h=0;function c(y,w){if(++h>30){q("Load test font never loaded."),w();return}if(l.font="30px "+y,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){w();return}setTimeout(c.bind(null,y,w))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const g=16,p=1482184792;let b=s(d,g);for(n=0,r=u.length-3;n<r;n+=4)b=b-p+s(u,n)|0;n<u.length&&(b=b-p+s(u+"XXX",n)|0),d=i(d,g,4,ld(b));const m=`url(data:font/opentype;base64,${btoa(d)});`,v=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(v);const _=this._document.createElement("div");_.style.visibility="hidden",_.style.width=_.style.height="10px",_.style.position="absolute",_.style.top=_.style.left="0px";for(const y of[t.loadedName,u]){const w=this._document.createElement("span");w.textContent="Hi",w.style.fontFamily=y,_.append(w)}this._document.body.append(_),c(u,()=>{_.remove(),e.complete()})}}class Cd{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,${gd(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 jn={DATA:1,ERROR:2},wt={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function $l(){}function Yt(a){if(a instanceof Ke||a instanceof Zr||a instanceof fi||a instanceof Dl||a instanceof On||a instanceof Jr)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||at('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new Ke(a.message);case"InvalidPDFException":return new Zr(a.message);case"MissingPDFException":return new fi(a.message);case"PasswordException":return new Dl(a.message,a.code);case"UnexpectedResponseException":return new On(a.message,a.status);case"UnknownErrorException":return new Jr(a.message,a.details)}return new Jr(a.message,a.toString())}class vi{#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===jn.DATA)i.resolve(t.data);else if(t.callback===jn.ERROR)i.reject(Yt(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:jn.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:jn.ERROR,callbackId:t.callbackId,reason:Yt(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,o=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:o,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:o,stream:wt.PULL,streamId:n,desiredSize:h.desiredSize}),c.promise},cancel:h=>{_t(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:o,stream:wt.CANCEL,streamId:n,reason:Yt(h)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=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:wt.ENQUEUE,streamId:e,chunk:h},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:wt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(h){_t(h instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:wt.ERROR,streamId:e,reason:Yt(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(o,t.data,l).then(function(){n.postMessage({sourceName:s,targetName:i,stream:wt.START_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:wt.START_COMPLETE,streamId:e,reason:Yt(h)})})}#i(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 wt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Yt(t.reason));break;case wt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Yt(t.reason));break;case wt.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:wt.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||$l).then(function(){n.postMessage({sourceName:s,targetName:i,stream:wt.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:wt.PULL_COMPLETE,streamId:e,reason:Yt(h)})});break;case wt.ENQUEUE:if(_t(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case wt.CLOSE:if(_t(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case wt.ERROR:_t(r,"error should have stream controller"),r.controller.error(Yt(t.reason)),this.#r(r,e);break;case wt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Yt(t.reason)),this.#r(r,e);break;case wt.CANCEL:if(!o)break;const l=Yt(t.reason);Promise.try(o.onCancel||$l,l).then(function(){n.postMessage({sourceName:s,targetName:i,stream:wt.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:wt.CANCEL_COMPLETE,streamId:e,reason:Yt(h)})}),o.sinkCapability.reject(l),o.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 Hl{#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){at("Abstract method `_createCanvas` called.")}}class Ad extends Hl{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 zl{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){at("Abstract method `_fetch` called.")}}class Gl extends zl{async _fetch(t){const e=await Rn(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):Dn(e)}}class Wl{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 Td extends Wl{#t;#e;#s;#i;#r;#n;#l=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#a(){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(He,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(He,"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),o=new Array(256);for(let l=0;l<256;l++)n[l]=e[l]/255,r[l]=s[l]/255,o[l]=i[l]/255;return[n.join(","),r.join(","),o.join(",")]}#u(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Ln(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.#a.get(t);if(e)return e;const[s,i,n]=this.#d(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#a.get(r),e)return this.#a.set(t,e),e;const o=`g_${this.#i}_transfer_map_${this.#l++}`,l=this.#u(o);this.#a.set(t,l),this.#a.set(r,l);const h=this.#g(o);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=H.makeHexColor(...r);const o=this.#_(e);if(e=H.makeHexColor(...o),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.#o(u);const d=(f,g)=>{const p=r[f]/255,b=o[f]/255,m=new Array(g+1);for(let v=0;v<=g;v++)m[v]=p+v/g*(b-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.#a.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#l++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#b(s,o),r}addLuminosityFilter(t){let e=this.#a.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#l++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#f(o),t&&this.#b(s,o),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let o=this.#c.get(t);if(o?.key===r||(o?(o.filter?.remove(),o.key=r,o.url="none",o.filter=null):(o={key:r,url:"none",filter:null},this.#c.set(t,o)),!e||!s))return o.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,v,_)=>{const y=new Array(256),w=(u-c)/_,C=m/255,A=(v-m)/(255*_);let T=0;for(let k=0;k<=_;k++){const L=Math.round(c+k*w),R=C+k*A;for(let F=T;F<=L;F++)y[F]=R;T=L+1}for(let k=T;k<256;k++)y[k]=y[T-1];return y.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,b=o.filter=this.#g(p);return this.#o(b),this.#p(g(d[0],f[0],5),g(d[1],f[1],5),g(d[2],f[2],5),b),o.url=this.#u(p),o.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(He,"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)}#o(t){const e=this.#r.createElementNS(He,"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(He,"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(He,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(He,"feComponentTransfer");i.append(n),this.#m(n,"feFuncR",t),this.#m(n,"feFuncG",e),this.#m(n,"feFuncB",s)}#b(t,e){const s=this.#r.createElementNS(He,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#h.style.color=t,oo(getComputedStyle(this.#h).getPropertyValue("color"))}}class Vl{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){at("Abstract method `_fetch` called.")}}class Xl extends Vl{async _fetch(t){const e=await Rn(t,"arraybuffer");return new Uint8Array(e)}}Ot&&q("Please use the `legacy` build in Node.js environments.");async function Ul(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class Ed extends Wl{}class kd extends Hl{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:pt&&pt.tagName.toUpperCase()==="SCRIPT"&&pt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class Md extends zl{async _fetch(t){return Ul(t)}}class Pd extends Vl{async _fetch(t){return Ul(t)}}const Rt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function fo(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 go{getPattern(){at("Abstract method `getPattern` called.")}}class Od extends go{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===Rt.STROKE||i===Rt.FILL){const r=e.current.getClippedPathBoundingBox(i,ht(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,l=Math.ceil(r[3]-r[1])||1,h=e.cachedCanvases.getCanvas("pattern",o,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=H.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),fo(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 fo(t,this._bbox),n=this._createGradient(t);return n}}function po(a,t,e,s,i,n,r,o){const l=t.coords,h=t.colors,c=a.data,u=a.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=o,o=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,b=(l[s+1]+t.offsetY)*t.scaleY,m=(l[i]+t.offsetX)*t.scaleX,v=(l[i+1]+t.offsetY)*t.scaleY;if(g>=v)return;const _=h[n],y=h[n+1],w=h[n+2],C=h[r],A=h[r+1],T=h[r+2],k=h[o],L=h[o+1],R=h[o+2],F=Math.round(g),P=Math.round(v);let O,$,M,D,V,lt,ut,E;for(let B=F;B<=P;B++){if(B<b){const j=B<g?0:(g-B)/(g-b);O=f-(f-p)*j,$=_-(_-C)*j,M=y-(y-A)*j,D=w-(w-T)*j}else{let j;B>v?j=1:b===v?j=0:j=(b-B)/(b-v),O=p-(p-m)*j,$=C-(C-k)*j,M=A-(A-L)*j,D=T-(T-R)*j}let z;B<g?z=0:B>v?z=1:z=(g-B)/(g-v),V=f-(f-m)*z,lt=_-(_-k)*z,ut=y-(y-L)*z,E=w-(w-R)*z;const J=Math.round(Math.min(O,V)),Et=Math.round(Math.max(O,V));let nt=u*B+J*4;for(let j=J;j<=Et;j++)z=(O-j)/(O-V),z<0?z=0:z>1&&(z=1),c[nt++]=$-($-lt)*z|0,c[nt++]=M-(M-ut)*z|0,c[nt++]=D-(D-E)*z|0,c[nt++]=255}}function Dd(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(n=0;n<l;n++){let c=n*o;for(let u=0;u<h;u++,c++)po(a,e,s[c],s[c+1],s[c+o],i[c],i[c+1],i[c+o]),po(a,e,s[c+o+1],s[c+1],s[c+o],i[c+o+1],i[c+1],i[c+o])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)po(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 Rd extends go{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]),l=Math.floor(this._bounds[1]),h=Math.ceil(this._bounds[2])-o,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:-o,offsetY:-l,scaleX:1/f,scaleY:1/g},b=u+4,m=d+4,v=s.getCanvas("mesh",b,m),_=v.context,y=_.createImageData(u,d);if(e){const C=y.data;for(let A=0,T=C.length;A<T;A+=4)C[A]=e[0],C[A+1]=e[1],C[A+2]=e[2],C[A+3]=255}for(const C of this._figures)Dd(y,C,p);return _.putImageData(y,2,2),{canvas:v.canvas,offsetX:o-2*f,offsetY:l-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){fo(t,this._bbox);let n;if(i===Rt.SHADING)n=H.singularValueDecompose2dScale(ht(t));else if(n=H.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=H.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Rt.SHADING?null:this._background,e.cachedCanvases);return i!==Rt.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 Ld extends go{getPattern(){return"hotpink"}}function Fd(a){switch(a[0]){case"RadialAxial":return new Od(a);case"Mesh":return new Rd(a);case"Dummy":return new Ld}throw new Error(`Unknown IR type: ${a[0]}`)}const Yl={COLORED:1,UNCOLORED:2};class mo{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:o}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),Pn("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,b=H.singularValueDecompose2dScale(this.matrix),m=H.singularValueDecompose2dScale(this.baseTransform),v=b[0]*m[0],_=b[1]*m[1];let y=g,w=p,C=!1,A=!1;const T=Math.ceil(l*v),k=Math.ceil(h*_),L=Math.ceil(g*v),R=Math.ceil(p*_);T>=L?y=l:C=!0,k>=R?w=h:A=!0;const F=this.getSizeAndScale(y,this.ctx.canvas.width,v),P=this.getSizeAndScale(w,this.ctx.canvas.height,_),O=t.cachedCanvases.getCanvas("pattern",F.size,P.size),$=O.context,M=o.createCanvasGraphics($);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,i,r),$.translate(-F.scale*c,-P.scale*u),M.transform(F.scale,0,0,P.scale,0,0),$.save(),this.clipBbox(M,c,u,d,f),M.baseTransform=ht(M.ctx),M.executeOperatorList(s),M.endDrawing(),$.restore(),C||A){const D=O.canvas;C&&(y=l),A&&(w=h);const V=this.getSizeAndScale(y,this.ctx.canvas.width,v),lt=this.getSizeAndScale(w,this.ctx.canvas.height,_),ut=V.size,E=lt.size,B=t.cachedCanvases.getCanvas("pattern-workaround",ut,E),z=B.context,J=C?Math.floor(g/l):0,Et=A?Math.floor(p/h):0;for(let nt=0;nt<=J;nt++)for(let j=0;j<=Et;j++)z.drawImage(D,ut*nt,E*j,ut,E,0,0,ut,E);return{canvas:B.canvas,scaleX:V.scale,scaleY:lt.scale,offsetX:c,offsetY:u}}return{canvas:O.canvas,scaleX:F.scale,scaleY:P.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(mo.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(ht(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case Yl.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case Yl.UNCOLORED:const o=H.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new ad(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Rt.SHADING&&(n=H.transform(n,e.baseTransform),this.matrix&&(n=H.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 l=t.createPattern(r.canvas,"repeat");return l.setTransform(o),l}}function Id({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=$t.isLittleEndian?4278190080:255,[l,h]=r?[n,o]:[o,n],c=s>>3,u=s&7,d=a.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const b=t+c;t<b;t++){const m=t<d?a[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?a[t++]:255;for(let b=0;b<u;b++)e[f++]=p&1<<7-b?h:l}return{srcPos:t,destPos:f}}const ql=16,Kl=100,jd=15,Ql=10,Jl=1e3,qt=16;function Nd(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,l){t.transform(s,i,n,r,o,l),this.__originalTransform(s,i,n,r,o,l)},a.setTransform=function(s,i,n,r,o,l){t.setTransform(s,i,n,r,o,l),this.__originalSetTransform(s,i,n,r,o,l)},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 Bd{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 Nn(a,t,e,s,i,n,r,o,l,h){const[c,u,d,f,g,p]=ht(a);if(u===0&&d===0){const v=r*c+g,_=Math.round(v),y=o*f+p,w=Math.round(y),C=(r+l)*c+g,A=Math.abs(Math.round(C)-_)||1,T=(o+h)*f+p,k=Math.abs(Math.round(T)-w)||1;return a.setTransform(Math.sign(c),0,0,Math.sign(f),_,w),a.drawImage(t,e,s,i,n,0,0,A,k),a.setTransform(c,u,d,f,g,p),[A,k]}if(c===0&&f===0){const v=o*d+g,_=Math.round(v),y=r*u+p,w=Math.round(y),C=(o+h)*d+g,A=Math.abs(Math.round(C)-_)||1,T=(r+l)*u+p,k=Math.abs(Math.round(T)-w)||1;return a.setTransform(0,Math.sign(u),Math.sign(d),0,_,w),a.drawImage(t,e,s,i,n,0,0,k,A),a.setTransform(c,u,d,f,g,p),[k,A]}a.drawImage(t,e,s,i,n,r,o,l,h);const b=Math.hypot(c,u),m=Math.hypot(d,f);return[b*l,m*h]}function $d(a){const{width:t,height:e}=a;if(t>Jl||e>Jl)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,l,h;const c=t+7&-8;let u=new Uint8Array(c*e),d=0;for(const m of a.data){let v=128;for(;v>0;)u[d++]=m&v?0:255,v>>=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),o=1;o<e;o++){d=o*c,h=o*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=o*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(o=0;f&&o<=e;o++){let m=o*n;const v=m+t;for(;m<v&&!r[m];)m++;if(m===v)continue;p.moveTo(m%n,o);const _=m;let y=r[m];do{const w=g[y];do m+=w;while(!r[m]);const C=r[m];C!==5&&C!==10?(y=C,r[m]=0):(y=C&51*y>>4,r[m]&=y>>2|y<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(_!==m);--o}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 Zl{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Ol,this.textMatrixScale=1,this.fontMatrix=Kr,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=Dt.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]=H.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=H.applyTransform(e,t),i=H.applyTransform(e.slice(2),t),n=H.applyTransform([e[0],e[3]],t),r=H.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){H.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,l,h,c){const u=H.bezierBoundingBox(e,s,i,n,r,o,l,h,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Rt.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Rt.STROKE){e||at("Stroke bounding box must include transform.");const i=H.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=H.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=Rt.FILL,e=null){return H.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function th(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%qt,n=(e-i)/qt,r=i===0?n:n+1,o=a.createImageData(s,qt);let l=0,h;const c=t.data,u=o.data;let d,f,g,p;if(t.kind===En.GRAYSCALE_1BPP){const b=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),v=m.length,_=s+7>>3,y=4294967295,w=$t.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?qt:i,h=0,f=0;f<g;f++){const C=b-l;let A=0;const T=C>_?s:C*8-7,k=T&-8;let L=0,R=0;for(;A<k;A+=8)R=c[l++],m[h++]=R&128?y:w,m[h++]=R&64?y:w,m[h++]=R&32?y:w,m[h++]=R&16?y:w,m[h++]=R&8?y:w,m[h++]=R&4?y:w,m[h++]=R&2?y:w,m[h++]=R&1?y:w;for(;A<T;A++)L===0&&(R=c[l++],L=128),m[h++]=R&L?y:w,L>>=1}for(;h<v;)m[h++]=0;a.putImageData(o,0,d*qt)}}else if(t.kind===En.RGBA_32BPP){for(f=0,p=s*qt*4,d=0;d<n;d++)u.set(c.subarray(l,l+p)),l+=p,a.putImageData(o,0,f),f+=qt;d<r&&(p=s*i*4,u.set(c.subarray(l,l+p)),a.putImageData(o,0,f))}else if(t.kind===En.RGB_24BPP)for(g=qt,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;a.putImageData(o,0,d*qt)}else throw new Error(`bad image kind: ${t.kind}`)}function eh(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%qt,n=(e-i)/qt,r=i===0?n:n+1,o=a.createImageData(s,qt);let l=0;const h=t.data,c=o.data;for(let u=0;u<r;u++){const d=u<n?qt:i;({srcPos:l}=Id({src:h,srcPos:l,dest:c,width:s,height:d,nonBlackColor:0})),a.putImageData(o,0,u*qt)}}function yi(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 Bn(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),!Ot){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function sh(a,t){if(t)return!0;const e=H.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*js.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const Hd=["butt","round","square"],zd=["miter","round","bevel"],Gd={},ih={};class Ns{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},l,h){this.ctx=t,this.current=new Zl(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 Bd(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,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,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(...ht(this.compositeCtx))}this.ctx.save(),Bn(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=ht(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const l=n.length;if(l===o)return o;const h=l-o>Ql&&typeof s=="function",c=h?Date.now()+jd:0;let u=0;const d=this.commonObjs,f=this.objs;let g;for(;;){if(i!==void 0&&o===i.nextBreakPoint)return i.breakIt(o,s),o;if(g=r[o],g!==ve.dependency)this[g].apply(this,n[o]);else for(const p of n[o]){const b=p.startsWith("g_")?d:f;if(!b.has(p))return b.get(p,s),o}if(o++,o===l)return o;if(h&&++u>Ql){if(Date.now()>c)return s(),o;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),o=s,l=i,h="prescale1",c,u;for(;n>2&&o>1||r>2&&l>1;){let d=o,f=l;n>2&&o>1&&(d=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/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,o,l,0,0,d,f),t=c.canvas,o=d,l=f,h=h==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:l}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=ht(e);let l,h,c,u;if((t.bitmap||t.data)&&t.count>1){const T=t.bitmap||t.data.buffer;h=JSON.stringify(r?o:[o.slice(0,4),n]),l=this._cachedBitmapsMap.get(T),l||(l=new Map,this._cachedBitmapsMap.set(T,l));const k=l.get(h);if(k&&!r){const L=Math.round(Math.min(o[0],o[2])+o[4]),R=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:k,offsetX:L,offsetY:R}}c=k}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),eh(u.context,t));let d=H.transform(o,[1/s,0,0,-1/i,0,0]);d=H.transform(d,[1,0,0,1,0,-i]);const[f,g,p,b]=H.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,v=Math.round(b-g)||1,_=this.cachedCanvases.getCanvas("fillCanvas",m,v),y=_.context,w=f,C=g;y.translate(-w,-C),y.transform(...d),c||(c=this._scaleImage(u.canvas,Te(y)),c=c.img,l&&r&&l.set(h,c)),y.imageSmoothingEnabled=sh(ht(y),t.interpolate),Nn(y,c,0,0,c.width,c.height,0,0,s,i),y.globalCompositeOperation="source-in";const A=H.transform(Te(y),[1,0,0,1,-w,-C]);return y.fillStyle=r?n.getPattern(e,this,A,Rt.FILL):n,y.fillRect(0,0,s,i),l&&!r&&(this.cachedCanvases.delete("fillCanvas"),l.set(h,_.canvas)),{canvas:_.canvas,offsetX:Math.round(w),offsetY:Math.round(C)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Hd[t]}setLineJoin(t){this.ctx.lineJoin=zd[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(...ht(this.suspendedCtx)),yi(this.suspendedCtx,n),Nd(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(),yi(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,l=i[3]-r;o===0||l===0||(this.genericComposeSMask(e.context,s,o,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,o,l,h,c,u){let d=t.canvas,f=l-c,g=h-u;if(r){const b=H.makeHexColor(...r);if(f<0||g<0||f+s>d.width||g+i>d.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),v=m.context;v.drawImage(d,-f,-g),v.globalCompositeOperation="destination-atop",v.fillStyle=b,v.fillRect(0,0,s,i),v.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=b,t.fillRect(f,g,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 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?(yi(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(),yi(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,l,h;const c=ht(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 ve.rectangle:r=e[g++],o=e[g++];const b=e[g++],m=e[g++],v=r+b,_=o+m;i.moveTo(r,o),b===0||m===0?i.lineTo(v,_):(i.lineTo(v,o),i.lineTo(v,_),i.lineTo(r,_)),u||n.updateRectMinMax(c,[r,o,v,_]),i.closePath();break;case ve.moveTo:r=e[g++],o=e[g++],i.moveTo(r,o),u||n.updatePathMinMax(c,r,o);break;case ve.lineTo:r=e[g++],o=e[g++],i.lineTo(r,o),u||n.updatePathMinMax(c,r,o);break;case ve.curveTo:l=r,h=o,r=e[g+4],o=e[g+5],i.bezierCurveTo(e[g],e[g+1],e[g+2],e[g+3],r,o),n.updateCurvePathMinMax(c,l,h,e[g],e[g+1],e[g+2],e[g+3],r,o,d),g+=6;break;case ve.curveTo2:l=r,h=o,i.bezierCurveTo(r,o,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,l,h,r,o,e[g],e[g+1],e[g+2],e[g+3],d),r=e[g+2],o=e[g+3],g+=4;break;case ve.curveTo3:l=r,h=o,r=e[g+2],o=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,o,r,o),n.updateCurvePathMinMax(c,l,h,e[g],e[g+1],r,o,r,o,d),g+=4;break;case ve.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(c,d),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?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,Te(e),Rt.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,Te(e),Rt.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=Gd}eoClip(){this.pendingClip=ih}beginText(){this.current.textMatrix=Ol,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:l,path:h}of t)s.addPath(h,new DOMMatrix(n).preMultiplySelf(i).translate(r,o).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||Kr,(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 o="normal";s.black?o="900":s.bold&&(o="bold");const l=s.italic?"italic":"normal";let h=e;e<ql?h=ql:e>Kl&&(h=Kl),this.current.fontSizeScale=e/h,this.ctx.font=`${l} ${o} ${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,o=this.current,l=o.font,h=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,u=h&Dt.FILL_STROKE_MASK,d=!!(h&Dt.ADD_TO_PATH_FLAG),f=o.patternFill&&!l.missingFile,g=o.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===Dt.FILL||u===Dt.FILL_STROKE)if(i){const b=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,b,i))}else r.fill(p);if(u===Dt.STROKE||u===Dt.FILL_STROKE)if(n){const b=r.getTransform();r.setTransform(...n),r.stroke(this.#s(p,b,n))}else r.lineWidth/=c,r.stroke(p);r.restore()}else(u===Dt.FILL||u===Dt.FILL_STROKE)&&r.fillText(t,e,s),(u===Dt.STROKE||u===Dt.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:ht(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 Q(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,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],b=e.textRenderingMode===Dt.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,v;if(e.patternFill){n.save();const A=e.fillColor.getPattern(n,this,Te(n),Rt.FILL);m=ht(n),n.restore(),n.fillStyle=A}if(e.patternStroke){n.save();const A=e.strokeColor.getPattern(n,this,Te(n),Rt.STROKE);v=ht(n),n.restore(),n.strokeStyle=A}let _=e.lineWidth;const y=e.textMatrixScale;if(y===0||_===0){const A=e.textRenderingMode&Dt.FILL_STROKE_MASK;(A===Dt.STROKE||A===Dt.FILL_STROKE)&&(_=this.getSinglePixelWidth())}else _/=y;if(r!==1&&(n.scale(r,r),_/=r),n.lineWidth=_,s.isInvalidPDFjsFont){const A=[];let T=0;for(const k of t)A.push(k.unicode),T+=k.width;n.fillText(A.join(""),0,0),e.x+=T*p*c,n.restore(),this.compose();return}let w=0,C;for(C=0;C<u;++C){const A=t[C];if(typeof A=="number"){w+=f*A*i/1e3;continue}let T=!1;const k=(A.isSpace?l:0)+o,L=A.fontChar,R=A.accent;let F,P,O=A.width;if(d){const M=A.vmetric||g,D=-(A.vmetric?M[1]:O*.5)*p,V=M[2]*p;O=M?-M[0]:O,F=D/r,P=(w+V)/r}else F=w/r,P=0;if(s.remeasure&&O>0){const M=n.measureText(L).width*1e3/i*r;if(O<M&&this.isFontSubpixelAAEnabled){const D=O/M;T=!0,n.save(),n.scale(D,1),F/=D}else O!==M&&(F+=(O-M)/2e3*i/r)}if(this.contentVisible&&(A.isInFont||s.missingFile)){if(b&&!R)n.fillText(L,F,P);else if(this.paintChar(L,F,P,m,v),R){const M=F+i*R.offset.x/r,D=P-i*R.offset.y/r;this.paintChar(R.fontChar,M,D,m,v)}}const $=d?O*p-k*h:O*p+k*h;w+=$,T&&n.restore()}d?e.y-=w:e.x+=w*c,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,l=s.charSpacing,h=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||Kr,d=t.length,f=s.textRenderingMode===Dt.INVISIBLE;let g,p,b,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=o*p*n/1e3,this.ctx.translate(m,0),s.x+=m*c;continue}const v=(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()),b=H.applyTransform([p.width,0],u)[0]*n+v,e.translate(b,0),s.x+=b*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||ht(this.ctx),n={createCanvasGraphics:r=>new Ns(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new mo(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=H.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=H.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=Fd(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,Te(e),Rt.SHADING);const i=Te(e);if(i){const{width:n,height:r}=e.canvas,[o,l,h,c]=H.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,l,h-o,c-l)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){at("Should not call beginInlineImage")}beginImageData(){at("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=ht(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(ht(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||Pn("TODO: Support non-isolated groups."),t.knockout&&q("Knockout groups not supported.");const s=ht(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=H.getAxialAlignedBoundingBox(t.bbox,ht(e));const n=[0,0,e.canvas.width,e.canvas.height];i=H.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),o=Math.floor(i[1]),l=Math.max(Math.ceil(i[2])-r,1),h=Math.max(Math.ceil(i[3])-o,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,-o),d.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:d,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()),yi(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=ht(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=H.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(),Bn(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[l,h]=H.singularValueDecompose2dScale(ht(this.ctx)),{viewportScale:c}=this,u=Math.ceil(r*this.outputScaleX*c),d=Math.ceil(o*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,o*h),Bn(this.ctx)}else Bn(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new Zl(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=$d(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 l=ht(o);o.transform(e,s,i,n,0,0);const h=this._createMaskCanvas(t);o.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=H.transform(l,[e,s,i,n,r[c],r[c+1]]),[f,g]=H.applyTransform([0,0],d);o.drawImage(h.canvas,f,g)}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:l,transform:h}=n,c=this.cachedCanvases.getCanvas("maskCanvas",o,l),u=c.context;u.save();const d=this.getObject(r,n);eh(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,Te(e),Rt.FILL):s,u.fillRect(0,0,o,l),u.restore(),e.save(),e.transform(...h),e.scale(1,-1),Nn(e,c.canvas,0,0,o,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,o=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:o});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(),!Ot){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 l=this.cachedCanvases.getCanvas("inlineImage",e,s).context;th(l,t),n=this.applyTransferMapsToCanvas(l)}const r=this._scaleImage(n,Te(i));i.imageSmoothingEnabled=sh(ht(i),t.interpolate),Nn(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;th(l,t),i=this.applyTransferMapsToCanvas(l)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),Nn(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===ih?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=ht(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 l=Math.abs(e),h=Math.abs(n);if(l===h)if(t===0)r=o=1/l;else{const c=l*t;r=o=c<1?1/c:1}else if(t===0)r=1/l,o=1/h;else{const c=l*t,u=h*t;r=c<1?1/c:1,o=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,o=h/l;else{const u=t*l;r=c>u?c/u:1,o=h>u?h/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(l=>l/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}}for(const a in ve)Ns.prototype[a]!==void 0&&(Ns.prototype[ve[a]]=Ns.prototype[a]);class _i{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 Wd{#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 to(this.#t)}has(t){return this.#t.has(t)}}const Bs=Symbol("INTERNAL");class Vd{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&se.DISPLAY),this.#e=!!(t&se.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!==Bs&&at("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class Xd{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=se.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 Vd(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(Bs,!1);for(const s of t.on)this.#e.get(s)._setVisible(Bs,!0);for(const s of t.off)this.#e.get(s)._setVisible(Bs,!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 Pn("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(Bs,!1,!0);i._setVisible(Bs,!!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?to(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Nl;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class Ud{constructor(t,{disableRange:e=!1,disableStream:s=!1}){_t(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?.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)});_t(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(){_t(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Yd(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new qd(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 Yd{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=ro(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 qd{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 Kd(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let c=o(e);return c=unescape(c),c=l(c),c=h(c),n(c)}if(e=r(a),e){const c=h(e);return n(c)}if(e=s("filename","i").exec(a),e){e=e[1];let c=o(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=Dn(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,b,m]=d;if(p=parseInt(p,10),p in u){if(p===0)break;continue}u[p]=[b,m]}const g=[];for(let p=0;p<u.length&&p in u;++p){let[b,m]=u[p];m=o(m),b&&(m=unescape(m),p===0&&(m=l(m))),g.push(m)}return g.join("")}function o(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,b){return String.fromCharCode(parseInt(b,16))}),i(d,g);try{g=atob(g)}catch{}return i(d,g)})}return""}function nh(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 $n(a){try{return new URL(a).origin}catch{}return null}function rh({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 oh(a){const t=a.get("Content-Disposition");if(t){let e=Kd(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(ro(e))return e}return null}function Hn(a,t){return a===404||a===0&&t.startsWith("file:")?new fi('Missing PDF "'+t+'".'):new On(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function ah(a){return a===200||a===206}function lh(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function hh(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(q(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class ch{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=nh(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return _t(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new Qd(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Jd(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 Qd{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,lh(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=$n(n.url),!ah(n.status))throw Hn(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:l}=rh({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=l||this._contentLength,this._filename=oh(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Ke("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:hh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Jd{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,lh(n,this._withCredentials,this._abortController)).then(o=>{const l=$n(o.url);if(l!==t._responseOrigin)throw new Error(`Expected range response-origin "${l}" to match "${t._responseOrigin}".`);if(!ah(o.status))throw Hn(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(){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:hh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const bo=200,vo=206;function Zd(a){const t=a.response;return typeof t!="string"?t:Dn(t).buffer}class tf{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=nh(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=vo):i.expectedStatus=bo,e.responseType="arraybuffer",_t(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||bo;if(!(n===bo&&s.expectedStatus===vo)&&n!==s.expectedStatus){s.onError(i.status);return}const o=Zd(i);if(n===vo){const l=i.getResponseHeader("Content-Range"),h=/bytes (\d+)-(\d+)\/(\d+)/.exec(l);h?s.onDone({begin:parseInt(h[1],10),chunk:o}):(q('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 ef{constructor(t){this._source=t,this._manager=new tf(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 _t(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new sf(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new nf(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 sf{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=$n(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[l,...h]=o.split(": ");return[l,h.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=rh({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=oh(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=Hn(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 nf{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=$n(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??=Hn(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 rf=/^[a-z][a-z0-9\-+.]+:/i;function of(a){if(rf.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class af{constructor(t){this.source=t,this.url=of(t.url),_t(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return _t(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new lf(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new hf(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 lf{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 fi(`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 Ke("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class hf{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 cf=1e5,Kt=30,uf=.8;class Ht{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#l=0;#a=0;#c=null;#h=null;#d=0;#u=0;#f=Object.create(null);#o=[];#g=null;#m=[];#p=new WeakMap;#b=null;static#_=new Map;static#v=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:o}=s.rawDims;this.#b=[1,0,0,-1,-r,o+n],this.#a=i,this.#l=n,Ht.#O(),ms(e,s),this.#t.promise.finally(()=>{Ht.#A.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=$t.platform;return Q(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(),Ht.#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:Ht.#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 Ke("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#o}#E(t){if(this.#s)return;this.#n.ctx??=Ht.#k(this.#r);const e=this.#m,s=this.#o;for(const i of t){if(e.length>cf){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.#M(i)}}#M(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=H.transform(this.#b,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let o=this.#i&&r.fontSubstitution||r.fontFamily;o=Ht.fontFamilyMap.get(o)||o;const l=Math.hypot(i[2],i[3]),h=l*Ht.#L(o,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.#a).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}${(Ht.#S*l).toFixed(2)}px)`,f.fontFamily=o,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]),b=Math.abs(t.transform[3]);p!==b&&Math.max(p,b)/Math.min(p,b)>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(Ht.#S>1&&(r=`scale(${1/Ht.#S})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:o}=n,{canvasWidth:l,fontSize:h}=s;Ht.#T(i,h*this.#u,o);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.#v.values())t.remove();this.#v.clear()}}static#k(t=null){let e=this.#v.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.#v.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#L(t,e){const s=this.#_.get(t);if(s)return s;const i=this.#k(e);i.canvas.width=i.canvas.height=Kt,this.#T(i,Kt,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const c=r/(r+o);return this.#_.set(t,c),i.canvas.width=i.canvas.height=0,c}i.strokeStyle="red",i.clearRect(0,0,Kt,Kt),i.strokeText("g",0,0);let l=i.getImageData(0,0,Kt,Kt).data;o=0;for(let c=l.length-1-3;c>=0;c-=4)if(l[c]>0){o=Math.ceil(c/4/Kt);break}i.clearRect(0,0,Kt,Kt),i.strokeText("A",0,Kt),l=i.getImageData(0,0,Kt,Kt).data,r=0;for(let c=0,u=l.length;c<u;c+=4)if(l[c]>0){r=Kt-Math.floor(c/4/Kt);break}i.canvas.width=i.canvas.height=0;const h=r?r/(r+o):uf;return this.#_.set(t,h),h}}class wi{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const o=n.name;if(o==="#text")r=n.value;else if(wi.shouldBuildText(o))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 df=65536,ff=100,gf=5e3,pf=Ot?kd:Ad,mf=Ot?Md:Gl,bf=Ot?Ed:Td,vf=Ot?Pd:Xl;function yf(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new yo,{docId:e}=t,s=a.url?_f(a.url):null,i=a.data?wf(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,l=a.range instanceof dh?a.range:null,h=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:df;let c=a.worker instanceof $s?a.worker:null;const u=a.verbosity,d=typeof a.docBaseUrl=="string"&&!Ln(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,g=a.cMapPacked!==!1,p=a.CMapReaderFactory||mf,b=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,m=a.StandardFontDataFactory||vf,v=a.stopAtErrors!==!0,_=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,y=a.isEvalSupported!==!1,w=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Ot,C=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Ot&&($t.platform.isFirefox||!globalThis.chrome),A=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,T=typeof a.disableFontFace=="boolean"?a.disableFontFace:Ot,k=a.fontExtraProperties===!0,L=a.enableXfa===!0,R=a.ownerDocument||globalThis.document,F=a.disableRange===!0,P=a.disableStream===!0,O=a.disableAutoFetch===!0,$=a.pdfBug===!0,M=a.CanvasFactory||pf,D=a.FilterFactory||bf,V=a.enableHWA===!0,lt=l?l.length:a.length??NaN,ut=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Ot&&!T,E=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:p===Gl&&m===Xl&&f&&b&&pi(f,document.baseURI)&&pi(b,document.baseURI),B=null;id(u);const z={canvasFactory:new M({ownerDocument:R,enableHWA:V}),filterFactory:new D({docId:e,ownerDocument:R}),cMapReaderFactory:E?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:E?null:new m({baseUrl:b})};if(!c){const nt={verbosity:u,port:_i.workerPort};c=nt.port?$s.fromPort(nt):new $s(nt),t._worker=c}const J={docId:e,apiVersion:"4.10.38",data:i,password:o,disableAutoFetch:O,rangeChunkSize:h,length:lt,docBaseUrl:d,enableXfa:L,evaluatorOptions:{maxImageSize:_,disableFontFace:T,ignoreErrors:v,isEvalSupported:y,isOffscreenCanvasSupported:w,isImageDecoderSupported:C,canvasMaxAreaInBytes:A,fontExtraProperties:k,useSystemFonts:ut,cMapUrl:E?f:null,standardFontDataUrl:E?b:null}},Et={disableFontFace:T,fontExtraProperties:k,ownerDocument:R,pdfBug:$,styleElement:B,loadingParams:{disableAutoFetch:O,enableXfa:L}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const nt=c.messageHandler.sendWithPromise("GetDocRequest",J,i?[i.buffer]:null);let j;if(l)j=new Ud(l,{disableRange:F,disableStream:P});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let dt;if(Ot)if(pi(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`.");dt=ch}else dt=af;else dt=pi(s)?ch:ef;j=new dt({url:s,length:lt,httpHeaders:n,withCredentials:r,rangeChunkSize:h,disableRange:F,disableStream:P})}return nt.then(dt=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const Tt=new vi(e,dt,c.port),Qt=new Af(Tt,t,j,Et,z);t._transport=Qt,Tt.send("Ready",null)})}).catch(t._capability.reject),t}function _f(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(Ot&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function wf(a){if(Ot&&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 Dn(a);if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)||typeof a=="object"&&!isNaN(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 uh(a){return typeof a=="object"&&Number.isInteger(a?.num)&&a.num>=0&&Number.isInteger(a?.gen)&&a.gen>=0}class yo{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${yo.#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 dh{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){at("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class xf{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 Q(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 Sf{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new Fl:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new fh,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 gi({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 Q(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=Ye.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=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(),o||=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 b=!!(f&se.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=y=>{p.renderTasks.delete(v),(this._maybeCleanupAfterRender||b)&&(this.#e=!0),this.#s(!b),y?(v.capability.reject(y),this._abortOperatorList({intentState:p,reason:y instanceof Error?y:new Error(y)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new Hs({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:!b,pdfBug:this._pdfBug,pageColors:h});(p.renderTasks||=new Set).add(v);const _=v.task;return Promise.all([p.displayReadyCapability.promise,o]).then(([y,w])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(w.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:y,optionalContentConfig:w}),v.operatorListChanged()}).catch(m),_}getOperatorList({intent:t="display",annotationMode:e=Ye.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(l))}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 l;return o.opListReadCapability||(l=Object.create(null),l.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(l),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.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=>wi.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(o);return}o.lang??=l.lang,Object.assign(o.styles,l.styles),o.items.push(...l.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(),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 Fl),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)},gf),!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 no){let i=ff;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 Ke(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 Cf{#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 ct=class ct{constructor({name:t=null,port:e=null,verbosity:s=nd()}={}){Ws(this,zs);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(_e(ct,ws)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(_e(ct,ws)||Ai(ct,ws,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 vi("main","worker",t),this._messageHandler.on("ready",function(){}),Vn(this,zs,Un).call(this)}_initialize(){if(_e(ct,_s)||_e(ct,Gs,Yn)){this._setupFakeWorker();return}let{workerSrc:t}=ct;try{ct._isSameOrigin(window.location.href,t)||(t=ct._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new vi("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,Vn(this,zs,Un).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{Pn("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){_e(ct,_s)||(q("Setting up fake worker."),Ai(ct,_s,!0)),ct._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Cf;this._port=e;const s=`fake${Bh(ct,Wn)._++}`,i=new vi(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new vi(s,s+"_worker",e),Vn(this,zs,Un).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,_e(ct,ws)?.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=_e(this,ws)?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new ct(t)}static get workerSrc(){if(_i.workerSrc)return _i.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Q(this,"_setupFakeWorkerGlobal",(async()=>_e(this,Gs,Yn)?_e(this,Gs,Yn):(await import(this.workerSrc)).WorkerMessageHandler)())}};Wn=new WeakMap,_s=new WeakMap,ws=new WeakMap,zs=new WeakSet,Un=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Gs=new WeakSet,Yn=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},Ws(ct,Gs),Ws(ct,Wn,0),Ws(ct,_s,!1),Ws(ct,ws),Ot&&(Ai(ct,_s,!0),_i.workerSrc||="./pdf.worker.mjs"),ct._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},ct._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let $s=ct;class Af{#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 fh,this.fontLoader=new Sd({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 Q(this,"annotationStorage",new uo)}getRenderingIntent(t,e=Ye.ENABLE,s=null,i=!1,n=!1){let r=se.DISPLAY,o=co;switch(t){case"any":r=se.ANY;break;case"display":break;case"print":r=se.PRINT;break;default:q(`getRenderingIntent - invalid intent: ${t}`)}const l=r&se.PRINT&&s instanceof Bl?s:this.annotationStorage;switch(e){case Ye.DISABLE:r+=se.ANNOTATIONS_DISABLE;break;case Ye.ENABLE:break;case Ye.ENABLE_FORMS:r+=se.ANNOTATIONS_FORMS;break;case Ye.ENABLE_STORAGE:r+=se.ANNOTATIONS_STORAGE,o=l.serializable;break;default:q(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=se.IS_EDITING),n&&(r+=se.OPLIST);const{ids:h,hash:c}=l.modifiedIds,u=[r,o.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,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(),Ht.cleanup(),this._networkStream?.cancelAllRequests(new Ke("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)=>{_t(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}_t(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=o=>{e.onProgress?.({loaded:o.loaded,total:o.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{_t(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}_t(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 xf(s,this))}),t.on("DocException",s=>{e._capability.reject(Yt(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw Yt(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:o,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 Cd(n,{disableFontFace:r,fontExtraProperties:o,inspectFont:h});this.fontLoader.bind(c).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!o&&c.data&&(c.data=null),this.commonObjs.resolve(s,c)});break;case"CopyLocalImage":const{imageRef:u}=n;_t(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 o=this.#e.get(i);if(!o.objs.has(s)){if(o._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":o.objs.resolve(s,r),r?.dataLen>Zu&&(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=>{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 Sf(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return uh(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 Xd(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 Wd(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),Ht.cleanup()}}cachedPageNumber(t){if(!uh(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const xi=Symbol("INITIAL_DATA");class fh{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:xi}}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===xi)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!==xi}delete(t){const e=this.#t[t];return!e||e.data===xi?!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!==xi&&(yield[t,e])}}}class Tf{#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 Hs{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,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=o,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 Tf(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(Hs.#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.");Hs.#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 Ns(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),Hs.#e.delete(this._canvas),this.callback(t||new no(`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(),Hs.#e.delete(this._canvas),this.callback())))}}const Ef="4.10.38",kf="f9bea397f";function gh(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function Si(a){return Math.max(0,Math.min(255,255*a))}class ph{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=Si(t),[t,t,t]}static G_HTML([t]){const e=gh(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(Si)}static RGB_HTML(t){return`#${t.map(gh).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[Si(1-Math.min(1,t+i)),Si(1-Math.min(1,s+i)),Si(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 Mf{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){at("Abstract method `_createSVG` called.")}}class _o extends Mf{_createSVG(t){return document.createElementNS(He,t)}}class mh{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 l=o.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,o=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:(!o||l!=="href"&&l!=="newWindow")&&t.setAttribute(l,h)}o&&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 o=n!=="richText",l=t.div;if(l.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;l.style.transform=u}o&&l.setAttribute("class","xfaLayer xfaFont");const h=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),o&&wi.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 b=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(b),g.attributes&&this.setAttributes({html:b,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,b]);else if(g.value){const m=document.createTextNode(g.value);o&&wi.shouldBuildText(p)&&h.push(m),b.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 Ci=1e3,Pf=9,bs=new WeakSet;function Je(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class Of{static create(t){switch(t.data.annotationType){case Ct.LINK:return new bh(t);case Ct.TEXT:return new Df(t);case Ct.WIDGET:switch(t.data.fieldType){case"Tx":return new Rf(t);case"Btn":return t.data.radioButton?new vh(t):t.data.checkBox?new Ff(t):new If(t);case"Ch":return new jf(t);case"Sig":return new Lf(t)}return new vs(t);case Ct.POPUP:return new wo(t);case Ct.FREETEXT:return new yh(t);case Ct.LINE:return new Bf(t);case Ct.SQUARE:return new $f(t);case Ct.CIRCLE:return new Hf(t);case Ct.POLYLINE:return new _h(t);case Ct.CARET:return new Gf(t);case Ct.INK:return new xo(t);case Ct.POLYGON:return new zf(t);case Ct.HIGHLIGHT:return new wh(t);case Ct.UNDERLINE:return new Wf(t);case Ct.SQUIGGLY:return new Vf(t);case Ct.STRIKEOUT:return new Xf(t);case Ct.STAMP:return new xh(t);case Ct.FILEATTACHMENT:return new Uf(t);default:return new vt(t)}}}class vt{#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 vt._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:o,pageY:l}}}}=this;s?.splice(0,4,...t);const{width:h,height:c}=Je(t);e.left=`${100*(t[0]-o)/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 vs||(n.tabIndex=Ci);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 wo){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:o,height:l}=Je(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,b=e.borderStyle.verticalCornerRadius;if(p>0||b>0){const v=`calc(${p}px * var(--scale-factor)) / calc(${b}px * var(--scale-factor))`;r.borderRadius=v}else if(this instanceof vh){const v=`calc(${o}px * var(--scale-factor)) / calc(${l}px * var(--scale-factor))`;r.borderRadius=v}switch(e.borderStyle.style){case di.SOLID:r.borderStyle="solid";break;case di.DASHED:r.borderStyle="dashed";break;case di.BEVELED:q("Unimplemented border style: beveled");break;case di.INSET:q("Unimplemented border style: inset");break;case di.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=H.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const h=H.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*o/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}=Je(this.data.rect);let o,l;t%180===0?(o=100*n/s,l=100*r/i):(o=100*r/s,l=100*n/i),e.style.width=`${o}%`,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],o=n.slice(1);i.target.style[s]=ph[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:ph[`${r}_rgb`](o)})};return Q(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 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(p=>Math.fround(p));if(t.length===8){const[p,b,m,v]=t.subarray(2,6);if(i===p&&n===b&&e===m&&s===v)return}const{style:r}=this.container;let o;if(this.#e){const{borderColor:p,borderWidth:b}=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="${p}" stroke-width="${b}">`],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,b=t.length;p<b;p+=8){const m=t[p],v=t[p+1],_=t[p+2],y=t[p+3],w=c.createElement("rect"),C=(_-e)/l,A=(n-v)/h,T=(m-_)/l,k=(v-y)/h;w.setAttribute("x",C),w.setAttribute("y",A),w.setAttribute("width",T),w.setAttribute("height",k),f.append(w),o?.push(`<rect vector-effect="non-scaling-stroke" x="${C}" y="${A}" width="${T}" height="${k}"/>`)}this.#e&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,e=this.#s=new wo({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(){at("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 l=typeof o=="string"?o:null,h=document.querySelector(`[data-element-id="${r}"]`);if(h&&!bs.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&&bs.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 bh extends vt{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,o=[];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&&o.push(d)}else for(const c of Object.values(this._fieldObjects))o.push(...c);const l=this.annotationStorage,h=[];for(const c of o){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(!bs.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 Df extends vt{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 vs extends vt{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return $t.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":H.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Pf,n=t.style;let r;const o=2,l=h=>Math.round(10*h)/10;if(this.data.multiLine){const h=Math.abs(this.data.rect[3]-this.data.rect[1]-o),c=Math.round(h/(Qr*i))||1,u=h/c;r=Math.min(i,l(u/Qr))}else{const h=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,l(h/Qr))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=H.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 Rf extends vs{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 o=i.formattedValue||this.data.textContent?.join(`
511
- `)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,""));const l={userValue:n,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=o??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",o??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),bs.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=Ci,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 b=l.userValue;!b||b.length<=g||(b=b.slice(0,g),p.value=l.userValue=b,t.setValue(e,{value:b}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:b,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:b}=f;let m=p,v=b;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*/);_&&(v+=_[0].length);break}case"deleteContentBackward":p===b&&(m-=1);break;case"deleteContentForward":p===b&&(v+=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:v}})}),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 Lf extends vs{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Ff extends vs{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 bs.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=Ci,n.addEventListener("change",r=>{const{name:o,checked:l}=r.target;for(const h of this._getElementsByName(o,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 o=e.defaultFieldValue||"Off";r.target.checked=o===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const o={value(l){l.target.checked=l.detail.value!=="Off",t.setValue(s,{value:l.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 vh extends vs{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(bs.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=Ci,n.addEventListener("change",r=>{const{name:o,checked:l}=r.target;for(const h of this._getElementsByName(o,s))t.setValue(h.id,{value:!1});t.setValue(s,{value:l})}),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 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,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 If extends bh{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 jf extends vs{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");bs.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=Ci;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 o=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=o(!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:o(!0)}),l=o(!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,b=>b.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:o(!0),items:h(d)}),l=o(!1)},clear(d){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),l=o(!1)},insert(d){const{index:f,displayValue:g,exportValue:p}=d.detail.insert,b=i.children[f],m=document.createElement("option");m.textContent=g,m.value=p,b?b.before(m):i.append(m),t.setValue(e,{value:o(!0),items:h(d)}),l=o(!1)},items(d){const{items:f}=d.detail;for(;i.length!==0;)i.remove(0);for(const g of f){const{displayValue:p,exportValue:b}=g,m=document.createElement("option");m.textContent=p,m.value=b,i.append(m)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:o(!0),items:h(d)}),l=o(!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:o(!0)}),l=o(!1)},editable(d){d.target.disabled=!d.detail.editable}};this._dispatchEventFromSandbox(u,c)}),i.addEventListener("input",c=>{const u=o(!0),d=o(!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:o(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class wo extends vt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:vt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new Nf({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=>`${io}${s}`).join(",")),this.container}}class Nf{#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;#a=null;#c=null;#h=null;#d=null;#u=!1;#f=null;#o=null;#g=null;#m=null;#p=null;#b=null;#_=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:o,parent:l,rect:h,parentRect:c,open:u}){this.#n=t,this.#p=i,this.#l=r,this.#m=o,this.#h=l,this.#r=e,this.#g=h,this.#d=c,this.#c=s,this.#a=Il.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=H.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=H.makeHexColor(...this.#r.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}=this.#p,t.append(e),this.#a){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.#a.valueOf()})),e.append(n)}const i=this.#v;if(i)mh.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#v(){const t=this.#m,e=this.#l;return t?.str&&(!e?.str||e.str===t.str)&&this.#m.html||null}get#w(){return this.#v?.attributes?.style?.fontSize||0}get#S(){return this.#v?.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(`
512
- `))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 o=i[n];s.append(document.createTextNode(o)),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.#b||={contentsObj:this.#l,richText:this.#m},t&&(this.#o=null),e&&(this.#m=this.#A(e),this.#l=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#b&&({contentsObj:this.#l,richText:this.#m}=this.#b,this.#b=null,this.#f?.remove(),this.#f=null,this.#o=null)}#M(){if(this.#o!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#h;let r=!!this.#d,o=r?this.#d:this.#g;for(const g of this.#c)if(!o||H.intersect(g.data.rect,o)!==null){o=g.data.rect,r=!0;break}const l=H.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]),c=r?o[2]-o[0]+5:0,u=l[0]+c,d=l[1];this.#o=[100*(u-i)/e,100*(d-n)/s];const{style:f}=this.#n;f.left=`${this.#o[0]}%`,f.top=`${this.#o[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.#M(),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 yh extends vt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=Y.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 Bf extends vt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=Je(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 $f extends vt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=Je(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 Hf extends vt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=Je(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 _h extends vt{#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}=Je(t),o=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"),o.append(h),this.container.append(o),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class zf extends _h{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Gf extends vt{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 xo extends vt{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?Y.HIGHLIGHT:Y.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:o,height:l}=this.#s(e,t),h=this.svgFactory.create(o,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,o=this.#e.length;r<o;r++)this.#e[r].setAttribute("points",s[r].join(","));if(i){const{transform:r,width:o,height:l}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${o} ${l}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class wh extends vt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=Y.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class Wf extends vt{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 Vf extends vt{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 Xf extends vt{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 xh extends vt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=Y.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 Uf extends vt{#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}=$t.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 Yf{#t=null;#e=null;#s=new Map;#i=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){this.div=t,this.#t=e,this.#e=s,this.#i=o||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=`${io}${e}`,n=await this.#i?.getAriaAttributes(i);if(n)for(const[r,o]of n)s.setAttribute(r,o);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 _o,annotationStorage:t.annotationStorage||new uo,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const r of e){if(r.noHTML)continue;const o=r.annotationType===Ct.POPUP;if(o){const c=i.get(r.id);if(!c)continue;n.elements=c}else{const{width:c,height:u}=Je(r.rect);if(c<=0||u<=0)continue}n.data=r;const l=Of.create(n);if(!l.isRenderable)continue;if(!o&&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 zn=/\r\n?|\n/g;class At 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=At.prototype,e=n=>n.isEmpty(),s=Qe.TRANSLATE_SMALL,i=Qe.TRANSLATE_BIG;return Q(this,"_keyboardManager",new bi([[["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=Y.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||At._defaultColor||G._defaultLineColor,this.#r=t.fontSize||At._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 tt.FREETEXT_SIZE:At._defaultFontSize=e;break;case tt.FREETEXT_COLOR:At._defaultColor=e;break}}updateParams(t,e){switch(t){case tt.FREETEXT_SIZE:this.#n(e);break;case tt.FREETEXT_COLOR:this.#l(e);break}}static get defaultPropertiesToUpdate(){return[[tt.FREETEXT_SIZE,At._defaultFontSize],[tt.FREETEXT_COLOR,At._defaultColor||G._defaultLineColor]]}get propertiesToUpdate(){return[[tt.FREETEXT_SIZE,this.#r],[tt.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:tt.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:tt.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-At._internalPadding*t,-(At._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(Y.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()}#a(){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(At.#h(s)),e=s);return t.join(`
513
- `)}#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,o=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",o)}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.#a().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){At._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),Fn(this,this.div,["dblclick","keydown"]),this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:r}=this._initialData;let[o,l]=this.getInitialTranslation();[o,l]=this.pageTranslationToScreen(o,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,[o,l]=[l,-o];break;case 180:f=t-this.width+(r[0]-u)/h,g=e-(r[1]-d)/c,[o,l]=[-o,-l];break;case 270:f=t+(r[0]-u-this.height*c)/h,g=e+(r[1]-d-this.width*h)/c,[o,l]=[-l,o];break}this.setAt(f*i,g*n,o,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(zn,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=At.#f(e.getData("text")||"").replaceAll(zn,`
514
- `);if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes(`
515
- `)){r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:o,startOffset:l}=r,h=[],c=[];if(o.nodeType===Node.TEXT_NODE){const f=o.parentElement;if(c.push(o.nodeValue.slice(l).replaceAll(zn,"")),f!==this.editorDiv){let g=h;for(const p of this.editorDiv.childNodes){if(p===f){g=c;continue}g.push(At.#h(p))}}h.push(o.nodeValue.slice(0,l).replaceAll(zn,""))}else if(o===this.editorDiv){let f=h,g=0;for(const p of this.editorDiv.childNodes)g++===l&&(f=c),f.push(At.#h(p))}this.#e=`${h.join(`
516
- `)}${i}${c.join(`
517
- `)}`,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(`
518
- `)){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 yh){const{data:{defaultAppearanceData:{fontSize:r,fontColor:o},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:Y.FREETEXT,color:Array.from(o),fontSize:r,value:d.join(`
519
- `),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=H.makeHexColor(...t.color),n.#e=At.#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=At._internalPadding*this.parentScale,s=this.getRect(e,e),i=G._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#t),n={annotationType:Y.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.#o(n)?null:(n.id=this.annotationElementId,n)}#o(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,o)=>r!==i[o])||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(`
520
- `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=At._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class N{static PRECISION=1e-4;toSVGPath(){at("Abstract method `toSVGPath` must be implemented.")}get box(){at("Abstract getter `box` must be implemented.")}serialize(t,e){at("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,l=t.length;o<l;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||=new Float32Array(t.length);for(let o=0,l=t.length;o<l;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||=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 ys{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#l;#a;#c;#h;#d;#u;#f=[];static#o=8;static#g=2;static#m=ys.#o+ys.#g;constructor({x:t,y:e},s,i,n,r,o=0){this.#t=s,this.#u=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=o,this.#h=ys.#o*i,this.#c=ys.#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.#a+(t[1]-e[1])/2-i)/r,(this.#l+(e[0]-t[0])/2-s)/n,(this.#a+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#l=t,this.#a=e;const[s,i,n,r]=this.#t;let[o,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,b=p*u,m=p*d;let v=o,_=l;o=h,l=c,h+=b,c+=m,this.#f?.push(t,e);const y=-m/g,w=b/g,C=y*this.#u,A=w*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([h+C,c+A],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([h-C,c-A],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([o+C,l+A],2),this.#r.push(NaN,NaN,NaN,NaN,(o+C-s)/n,(l+A-i)/r),this.#n.set([o-C,l-A],14),this.#e.push(NaN,NaN,NaN,NaN,(o-C-s)/n,(l-A-i)/r)),this.#n.set([v,_,o,l,h,c],6),!this.isEmpty()):(this.#n.set([v,_,o,l,h,c],6),Math.abs(Math.atan2(_-l,v-o)-Math.atan2(m,b))<Math.PI/2?([o,l,h,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((o+h)/2-s)/n,((l+c)/2-i)/r),[o,l,v,_]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((v+o)/2-s)/n,((_+l)/2-i)/r),!0):([v,_,o,l,h,c]=this.#n.subarray(0,6),this.#r.push(((v+5*o)/6-s)/n,((_+5*l)/6-i)/r,((5*o+h)/6-s)/n,((5*l+c)/6-i)/r,((o+h)/2-s)/n,((l+c)/2-i)/r),[h,c,o,l,v,_]=this.#n.subarray(12,18),this.#e.push(((v+5*o)/6-s)/n,((_+5*l)/6-i)/r,((5*o+h)/6-s)/n,((5*l+c)/6-i)/r,((o+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.#b();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.#v(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(" ")}#b(){const[t,e,s,i]=this.#t,[n,r,o,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${o} ${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`)}#v(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),o=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${(o[0]-e)/i} ${(o[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Sh(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,o]=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)/o;if(l[l.length-2]=(this.#l-i)/r,l[l.length-1]=(this.#a-n)/o,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,[o,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,o,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,o,l]=this.#t,[h,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/l,NaN,NaN,NaN,NaN,h,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/l],e),e+=24}}class Sh extends N{#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.#a(r);const[o,l,h,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-o)/h,t[u+1]=(t[u+1]-l)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-o)/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,o=i-e;let l,h;switch(n){case 0:l=N._rescale(this.#l,t,i,r,-o),h=N._rescale(this.#r,t,i,r,-o);break;case 90:l=N._rescaleAndSwap(this.#l,t,e,r,o),h=N._rescaleAndSwap(this.#r,t,e,r,o);break;case 180:l=N._rescale(this.#l,s,e,-r,o),h=N._rescale(this.#r,s,e,-r,o);break;case 270:l=N._rescaleAndSwap(this.#l,s,i,-r,-o),h=N._rescaleAndSwap(this.#r,s,i,-r,-o);break}return{outline:Array.from(l),points:[Array.from(h)]}}#a(t){const e=this.#l;let s=e[4],i=e[5],n=s,r=i,o=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]),o=Math.max(o,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=H.bezierBoundingBox(s,i,...e.slice(f,f+6));n=Math.min(n,p[0]),r=Math.min(r,p[1]),o=Math.max(o,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]=o-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 ys(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[o,l,h,c]=this.#t,u=n*h,d=r*c,f=s*h+o,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 b=2;b<this.#r.length;b+=2)p.add({x:this.#r[b]*u+f,y:this.#r[b+1]*d+g});return p.getOutlines()}}class So{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,o=1/0,l=-1/0;const h=10**-4;for(const{x:b,y:m,width:v,height:_}of t){const y=Math.floor((b-e)/h)*h,w=Math.ceil((b+v+e)/h)*h,C=Math.floor((m-e)/h)*h,A=Math.ceil((m+_+e)/h)*h,T=[y,C,A,!0],k=[w,C,A,!1];this.#s.push(T,k),n=Math.min(n,y),r=Math.max(r,w),o=Math.min(o,C),l=Math.max(l,A)}const c=r-n+2*s,u=l-o+2*s,d=n-s,f=o-s,g=this.#s.at(i?-1:-2),p=[g[0],g[2]];for(const b of this.#s){const[m,v,_]=b;b[0]=(m-d)/c,b[1]=(v-f)/u,b[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.#a(e),t.push(...this.#c(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[o,l,h]=r;e.push([o,l,r],[o,h,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 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[o,l,h,c,u]=r;s.delete(r);let d=o,f=l;for(n=[o,h],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[o,l,h,c,u]=g,d!==o&&(n.push(d,f,o,f===l?l:h),d=o),f=f===l?h:l}n.push(d,f)}return new qf(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])}#a([,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 o=0;o<r;o++){const[l,h]=this.#i[o];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 qf extends N{#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],o=e[n+1];r===s?(t.push(`V${o}`),i=o):o===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],o=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]*o,c[u+1]=i-h[u+1]*l;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class Co extends ys{newFreeDrawOutline(t,e,s,i,n,r){return new Kf(t,e,s,i,n,r)}}class Kf extends Sh{newOutliner(t,e,s,i,n,r=0){return new Co(t,e,s,i,n,r)}}class ae{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#l=null;#a;#c=null;#h=null;#d;static#u=null;static get _keyboardManager(){return Q(this,"_keyboardManager",new bi([[["Escape","mac+Escape"],ae.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ae.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ae.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ae.prototype._moveToPrevious],[["Home","mac+Home"],ae.prototype._moveToBeginning],[["End","mac+End"],ae.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=tt.HIGHLIGHT_COLOR,this.#l=t):(this.#n=!0,this.#d=tt.HIGHLIGHT_DEFAULT_COLOR),this.#h=t?._uiManager||e,this.#a=this.#h._eventBus,this.#s=t?.color||this.#h?.highlightColors.values().next().value||"#FFFF98",ae.#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",ye,{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",ae.#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.#o.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#g.bind(this),{signal:e}),t}#o(t,e){e.stopPropagation(),this.#a.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.#o(e,t)}_moveToNext(t){if(!this.#b){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.#b&&this._hideDropdownFromKeyboard();return}this.#b||this.#m(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#b){this.#m(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#b){this.#m(t);return}this.#i.lastChild?.focus()}#g(t){ae._keyboardManager.exec(this,t)}#m(t){if(this.#b){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#b(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#b){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 yt extends G{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#l=null;#a=0;#c=null;#h=null;#d=null;#u=!1;#f=null;#o;#g=null;#m="";#p;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=Y.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=yt.prototype;return Q(this,"_keyboardManager",new bi([[["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||yt._defaultColor,this.#p=t.thickness||yt._defaultThickness,this.#o=t.opacity||yt._defaultOpacity,this.#s=t.boxes||null,this.#b=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#u=!0,this.#v(t),this.#M()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#l=t.focusNode,this.#a=t.focusOffset,this.#_(),this.#M(),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.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_(){const t=new So(this.#s,.001);this.#h=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#h.box;const e=new So(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]}#v({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:yt.#x(this.#h.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:yt.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,o,l]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=o,this.height=l;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=o*u/c,this.height=l*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=o,this.height=l;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=o*u/c,this.height=l*c/u;break}}const{lastPoint:h}=this.#n;this.#f=[(h[0]-n)/o,(h[1]-r)/l]}static initialize(t,e){G.initialize(t,e),yt._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case tt.HIGHLIGHT_DEFAULT_COLOR:yt._defaultColor=e;break;case tt.HIGHLIGHT_THICKNESS:yt._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case tt.HIGHLIGHT_COLOR:this.#w(e);break;case tt.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[tt.HIGHLIGHT_DEFAULT_COLOR,yt._defaultColor],[tt.HIGHLIGHT_THICKNESS,yt._defaultThickness]]}get propertiesToUpdate(){return[[tt.HIGHLIGHT_COLOR,this.color||yt._defaultColor],[tt.HIGHLIGHT_THICKNESS,this.#p||yt._defaultThickness],[tt.HIGHLIGHT_FREE,this.#u]]}#w(t){const e=(n,r)=>{this.color=n,this.#o=r,this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#o;this.addCommands({cmd:e.bind(this,t,yt._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.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:tt.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 ae({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.#M(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#M(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.#v({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)}#M(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.#o},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=yt.#x(this.#h.box,t)):s=yt.#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:yt.#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),Fn(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){yt._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.#a)}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}#L(){if(this.#u)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let o=0;for(const{x:l,y:h,width:c,height:u}of n){const d=l*t+s,f=(1-h)*e+i;r[o]=r[o+4]=d,r[o+1]=r[o+3]=f,r[o+2]=r[o+6]=d+c*t,r[o+5]=r[o+7]=f-u*e,o+=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:o,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",ie,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",ye,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new Co({x:i,y:n},[r,o,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 wh){const{data:{quadPoints:g,rect:p,rotation:b,id:m,color:v,opacity:_,popupRef:y},parent:{page:{pageNumber:w}}}=t;i=t={annotationType:Y.HIGHLIGHT,color:Array.from(v),opacity:_,quadPoints:g,boxes:null,pageIndex:w-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:y}}else if(t instanceof xo){const{data:{inkLists:g,rect:p,rotation:b,id:m,color:v,borderStyle:{rawWidth:_},popupRef:y},parent:{page:{pageNumber:w}}}=t;i=t={annotationType:Y.HIGHLIGHT,color:Array.from(v),thickness:_,inkLists:g,boxes:null,pageIndex:w-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:y}}const{color:n,quadPoints:r,inkLists:o,opacity:l}=t,h=await super.deserialize(t,e,s);h.color=H.makeHexColor(...n),h.#o=l||1,o&&(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.#M(),h.rotate(h.rotation)}else if(o){h.#u=!0;const g=o[0],p={x:g[0]-d,y:u-(g[1]-f)},b=new Co(p,[0,0,c,u],1,h.#p/2,!0,.001);for(let _=0,y=g.length;_<y;_+=2)p.x=g[_]-d,p.y=u-(g[_+1]-f),b.add(p);const{id:m,clipPathId:v}=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:b.toSVGPath()}},!0,!0);h.#v({highlightOutlines:b.getOutlines(),highlightId:m,clipPathId:v}),h.#M()}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:Y.HIGHLIGHT,color:s,opacity:this.#o,thickness:this.#p,quadPoints:this.#L(),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 Qf{#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(){at("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#a=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){at("Not implemented")}static get typesMap(){at("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=o=>{i.updateProperty(e,o);const l=this.#t.updateProperty(e,o);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)}}#o([t,e,s,i]){const{parentDimensions:[n,r],rotation:o}=this;switch(o){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:o}=this;switch(o){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.#o(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:[o,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*(o/l),i*(l/o),s*(o/l)];case 5:return[1-e,t,s*(o/l),i*(l/o)];case 6:return[1-t-i*(l/o),1-e,i*(l/o),s*(o/l)];case 7:return[e-s*(o/l),1-t-i*(l/o),s*(o/l),i*(l/o)];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/o),e,i*(l/o),s*(o/l)];case 13:return[1-e-s*(o/l),t-i*(l/o),s*(o/l),i*(l/o)];case 14:return[1-t,1-e-s*(o/l),i*(l/o),s*(o/l)];case 15:return[e,1-t,s*(o/l),i*(l/o)];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){at("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:o,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.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{W.#n===p.pointerId?this._currentParent.endDrawingSession():W.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{W.#l===p.pointerType&&((W.#a||=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",ye,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===W.#c&&ie(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),W.#s){t.drawLayer.updateProperties(this._currentDrawId,W.#s.startNew(r,o,u,d,c));return}e.updateUIForDefaultProperties(this),W.#s=this.createDrawerInstance(r,o,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.#a?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,W.#s.add(e,s)),W.#c=t.timeStamp,ie(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.#a=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:tt.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(tt.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){at("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=e.viewport,l=this.deserializeDraw(r,o,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 Jf{#t=new Float64Array(6);#e;#s;#i;#r;#n;#l="";#a=0;#c=new Gn;#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 o=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#s=[{line:o,points:this.#n}],this.#t.set(o,0)}updateProperty(t,e){t==="stroke-width"&&(this.#r=e)}#u(t,e){return N._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),o=t-n,l=e-r;return Math.hypot(this.#h*o,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(...N.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 o=this.#s.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#s.push({line:r,points:this.#n}),this.#t.set(r,0),this.#a=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.#a=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.#a=0,this.toSVGPath()}return{path:{d:this.#l}}}toSVGPath(){const t=N.svgRound(this.#e[4]),e=N.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.#a=6}if(this.#n.length===4){const i=N.svgRound(this.#e[10]),n=N.svgRound(this.#e[11]);return this.#l=`${this.#l} L ${i} ${n}`,this.#a=12,this.#l}const s=[];this.#a===0&&(s.push(`M ${t} ${e}`),this.#a=6);for(let i=this.#a,n=this.#e.length;i<n;i+=6){const[r,o,l,h,c,u]=this.#e.slice(i,i+6).map(N.svgRound);s.push(`C${r} ${o} ${l} ${h} ${c} ${u}`)}return this.#l+=s.join(" "),this.#a=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 Gn extends N{#t;#e=0;#s;#i;#r;#n;#l;#a;#c;build(t,e,s,i,n,r,o){this.#r=e,this.#n=s,this.#l=i,this.#a=n,this.#c=r,this.#s=o??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${N.svgRound(e[4])} ${N.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${N.svgRound(e[10])} ${N.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,o,l,h,c]=e.subarray(s,s+6).map(N.svgRound);t.push(`C${n} ${r} ${o} ${l} ${h} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],o=[],[l,h,c,u]=this.#d();let d,f,g,p,b,m,v,_,y;switch(this.#a){case 0:y=N._rescale,d=t,f=e+i,g=s,p=-i,b=t+l*s,m=e+(1-h-u)*i,v=t+(l+c)*s,_=e+(1-h)*i;break;case 90:y=N._rescaleAndSwap,d=t,f=e,g=s,p=i,b=t+h*s,m=e+l*i,v=t+(h+u)*s,_=e+(l+c)*i;break;case 180:y=N._rescale,d=t+s,f=e,g=-s,p=i,b=t+(1-l-c)*s,m=e+h*i,v=t+(1-l)*s,_=e+(h+u)*i;break;case 270:y=N._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,b=t+(1-h-u)*s,m=e+(1-l-c)*i,v=t+(1-h)*s,_=e+(1-l)*i;break}for(const{line:w,points:C}of this.#i)r.push(y(w,d,f,g,p,n?new Array(w.length):null)),o.push(y(C,d,f,g,p,n?new Array(C.length):null));return{lines:r,points:o,rect:[b,m,v,_]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:o},rotation:l,thickness:h}){const c=[];let u,d,f,g,p;switch(l){case 0:p=N._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=N._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=N._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=N._rescaleAndSwap,u=e/i+1,d=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of o){const v=m.length;if(v===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(v===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*(v-2));r.push(_);let[y,w,C,A]=m.subarray(0,4);_.set([NaN,NaN,NaN,NaN,y,w],0);for(let T=4;T<v;T+=2){const k=m[T],L=m[T+1];_.set(N.createBezierPoints(y,w,C,A,k,L),(T-2)*3),[y,w,C,A]=[C,A,k,L]}}}for(let m=0,v=r.length;m<v;m++)c.push({line:p(r[m].map(_=>_??NaN),u,d,f,g),points:p(o[m].map(_=>_??NaN),u,d,f,g)});const b=new Gn;return b.build(c,s,i,1,l,h,n),b}#h(t=this.#c){const e=this.#s+t/2*this.#l;return this.#a%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 o=4,l=i.length;o<l;o+=6){const[h,c]=i.subarray(o,o+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 o=6,l=i.length;o<l;o+=6){const[h,c,u,d,f,g]=i.subarray(o,o+6);H.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,o]=[i-e,n-s],l=this.#t;return l[0]-=r,l[1]-=o,l[2]+=2*r,l[3]+=2*o,l}updateParentDimensions([t,e],s){const[i,n]=this.#h();this.#r=t,this.#n=e,this.#l=s;const[r,o]=this.#h(),l=r-i,h=o-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(N.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${N.svgRound(t)} ${N.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,o=0,l=0;switch(this.#e){case 90:i=e/t,n=-t/e,o=t;break;case 180:s=-1,r=-1,o=t,l=e;break;case 270:i=-e/t,n=t/e,l=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${N.svgRound(o)} ${N.svgRound(l)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#h(),[o,l,h,c]=this.#t;if(Math.abs(h-n)<=N.PRECISION||Math.abs(c-r)<=N.PRECISION){const p=t+s/2-(o+h/2),b=e+i/2-(l+c/2);return{path:{"transform-origin":`${N.svgRound(t)} ${N.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${b})`}}}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":`${N.svgRound(o)} ${N.svgRound(l)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${N.svgRound(n)} ${N.svgRound(r)}) scale(${u} ${d}) translate(${N.svgRound(-n)} ${N.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#h(),o=this.#t,[l,h,c,u]=o;if(o[0]=t,o[1]=e,o[2]=s,o[3]=i,Math.abs(c-n)<=N.PRECISION||Math.abs(u-r)<=N.PRECISION){const b=t+s/2-(l+c/2),m=e+i/2-(h+u/2);for(const{line:v,points:_}of this.#i)N._translate(v,b,m,v),N._translate(_,b,m,_);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${N.svgRound(t)} ${N.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:b,points:m}of this.#i)N._rescale(b,g,p,d,f,b),N._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${N.svgRound(t)} ${N.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,o=t-r[0],l=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:h,points:c}of this.#i)N._translate(h,o,l,h),N._translate(c,o,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)N._rescale(u,o,l,h,c,u),N._rescale(d,o,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":`${N.svgRound(t)} ${N.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${N.svgRound(t[0])} ${N.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Ao extends Qf{#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 Ao(this.#t);return t.updateAll(this),t}}class To extends W{static _type="ink";static _editorType=Y.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){G.initialize(t,e),this._defaultDrawingOptions=new Ao(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return Q(this,"typesMap",new Map([[tt.INK_THICKNESS,"stroke-width"],[tt.INK_COLOR,"stroke"],[tt.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new Jf(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return Gn.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof xo){const{data:{inkLists:r,rect:o,rotation:l,id:h,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:Y.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:o.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=To.getDefaultDrawingOptions({stroke:H.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":o}}=this,l={annotationType:Y.INK,color:G._colorManager.convert(n),opacity:r,thickness:o,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,o)=>r!==e[o])||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 Eo extends G{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#l=null;#a=null;#c=!1;#h=!1;static _type="stamp";static _editorType=Y.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 Q(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return Q(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(Y.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.#o()}#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,o=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!o)throw new Error("No response from the AI service.");if(o.error)throw new Error("Error from the AI service.");if(o.cancel)return null;if(!o.output)throw new Error("No valid response from the AI service.");const l=o.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=Eo.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.#a&&(clearTimeout(this.#a),this.#a=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.#o():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.#a!==null&&clearTimeout(this.#a);const t=200;this.#a=setTimeout(()=>{this.#a=null,this.#m()},t)}#o(){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[o,l]=this.parentDimensions;this.setDims(e*o/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 ao;let o=this.#t,l=i,h=n,c=null;if(e){if(i>e||n>e){const C=Math.min(e/i,e/n);l=Math.floor(i*C),h=Math.floor(n*C)}c=document.createElement("canvas");const d=c.width=Math.ceil(l*r.sx),f=c.height=Math.ceil(h*r.sy);this.#c||(o=this.#g(d,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",b="#42414d");const m=15,v=m*r.sx,_=m*r.sy,y=new OffscreenCanvas(v*2,_*2),w=y.getContext("2d");w.fillStyle=p,w.fillRect(0,0,v*2,_*2),w.fillStyle=b,w.fillRect(0,0,v,_),w.fillRect(v,_,v,_),g.fillStyle=g.createPattern(y,"repeat"),g.fillRect(0,0,d,f),g.drawImage(o,0,0,o.width,o.height,0,0,d,f)}let u=null;if(s){let d,f;if(r.symmetric&&o.width<t&&o.height<t)d=o.width,f=o.height;else if(o=this.#t,i>t||n>t){const b=Math.min(t/i,t/n);d=Math.floor(i*b),f=Math.floor(n*b),this.#c||(o=this.#g(d,f))}const p=new OffscreenCanvas(d,f).getContext("2d",{willReadFrequently:!0});p.drawImage(o,0,0,o.width,o.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,o=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(o,0,0,l,h,0,0,n,r),o=c.transferToImageBitmap()}return o}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new ao,r=Math.ceil(s*t*n.sx),o=Math.ceil(i*e*n.sy),l=this.#l;if(!l||l.width===r&&l.height===o)return;l.width=r,l.height=o;const h=this.#c?this.#t:this.#g(r,o),c=l.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(h,0,0,h.width,h.height,0,0,r,o)}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*js.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*js.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 xh){const{data:{rect:g,rotation:p,id:b,structParent:m,popupRef:v},container:_,parent:{page:{pageNumber:y}}}=t,w=_.querySelector("canvas"),C=s.imageManager.getFromCanvas(_.id,w);w.remove();const A=(await e._structTree.getAriaAttributes(`${io}${b}`))?.get("aria-label")||"";i=t={annotationType:Y.STAMP,bitmapId:C.id,bitmap:C.bitmap,pageIndex:y-1,rect:g.slice(0),rotation:p,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:A},isSvg:!1,structParent:m,popupRef:v}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:u}=t;h&&s.imageManager.isValidId(h)?(n.#e=h,o&&(n.#t=o)):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:Y.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 o=this.#b(s);if(o.isSame)return null;o.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 o=e.stamps.get(this.#e);r>o.area&&(o.area=r,o.serialized.bitmap.close(),o.serialized.bitmap=this.#p(!1))}return s}#b(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 ze{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#l=!1;#a=!1;#c=!1;#h=null;#d=null;#u=null;#f=null;#o;static _initialized=!1;static#g=new Map([At,To,Eo,yt].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:l,viewport:h,l10n:c}){const u=[...ze.#g.values()];if(!ze._initialized){ze._initialized=!0;for(const d of u)d.initialize(c,t)}t.registerEditorTypes(u),this.#o=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=h,this.#u=l,this.drawLayer=o,this._structTree=i,this.#o.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#o.getMode()===Y.NONE}updateToolbar(t){this.#o.updateToolbar(t)}updateMode(t=this.#o.getMode()){switch(this.#v(),t){case Y.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Y.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case Y.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 ze.#g.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#u?.div}setEditingState(t){this.#o.setEditingState(t)}addCommands(t){this.#o.addCommands(t)}cleanUndoStack(t){this.#o.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.#o.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.#o.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.#a=!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.#o.isDeletedAnnotationElement(r))continue;let o=e.get(r);if(o){o.resetAnnotationElement(n),o.show(!1),n.show();continue}o=t.get(r),o&&(this.#o.addChangedExistingAnnotation(o),o.renderAnnotationElement(n)&&o.show(!1)),n.show()}}this.#v(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of ze.#g.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#a=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#o.getActive()!==t&&this.#o.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#u?.div&&!this.#f){this.#f=new AbortController;const t=this.#o.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.#o.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}=$t.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#o.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),yt.startHighlighting(this,this.#o.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.#o._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#o.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.#o.isDeletedAnnotationElement(e)&&this.#o.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#a&&t.annotationElementId&&this.#o.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#o.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#o.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.#o.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.#o.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.#o._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.#o.getId()}get#p(){return ze.#g.get(this.#o.getMode())}combinedSignal(t){return this.#o.combinedSignal(t)}#b(t){const e=this.#p;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#o.updateToolbar(t),this.#o.updateMode(t);const{offsetX:s,offsetY:i}=this.#_(),n=this.getNextId(),r=this.#b({parent:this,id:n,x:s,y:i,uiManager:this.#o,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await ze.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#o)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#b({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#o,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),o=Math.min(window.innerWidth,t+s),l=Math.min(window.innerHeight,e+i),h=(n+o)/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.#o.setSelected(t)}toggleSelected(t){this.#o.toggleSelected(t)}unselect(t){this.#o.unselect(t)}pointerup(t){const{isMac:e}=$t.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.#o.getMode()===Y.STAMP){this.#o.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#o.getMode()===Y.HIGHLIGHT&&this.enableTextSelection(),this.#l){this.#l=!1;return}const{isMac:e}=$t.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.#o.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus(),this.#h){this.#p.startDrawing(this,this.#o,!1,t);return}this.#o.setCurrentDrawingSession(this),this.#h=new AbortController;const e=this.#o.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.#o,!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.#o.setCurrentDrawingSession(null),this.#h.abort(),this.#h=null,this.#d=null,this.#p.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#o.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.#o.getActive()?.parent===this&&(this.#o.commitOrRemove(),this.#o.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.#o.removeLayer(this)}#v(){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.#o.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#o.commitOrRemove(),this.#v();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.#o.viewParameters.realScale}}class zt{#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 Q(this,"_svgFactory",new _o)}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=zt._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#l(t,e){const s=zt._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=zt._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#a(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=zt._svgFactory.createElement("defs");n.append(r);const o=zt._svgFactory.createElement("path");r.append(o);const l=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",l),o.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,o);const h=s?this.#l(r,l):null,c=zt._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=zt._svgFactory.createElement("defs");i.append(n);const r=zt._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 l;if(e){const u=zt._svgFactory.createElement("mask");n.append(u),l=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",l),u.setAttribute("maskUnits","objectBoundingBox");const d=zt._svgFactory.createElement("rect");u.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const f=zt._svgFactory.createElement("use");u.append(f),f.setAttribute("href",`#${o}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const h=zt._svgFactory.createElement("use");i.append(h),h.setAttribute("href",`#${o}`),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,o=typeof t=="number"?this.#s.get(t):t;if(o){if(s&&this.#a(o,s),i&&zt.#r(o,i),n){const{classList:l}=o;for(const[h,c]of Object.entries(n))l.toggle(h,c)}if(r){const h=o.firstChild.firstChild;this.#a(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:So},X.AbortException,X.AnnotationEditorLayer,X.AnnotationEditorParamsType,X.AnnotationEditorType,X.AnnotationEditorUIManager,X.AnnotationLayer,X.AnnotationMode,X.ColorPicker,X.DOMSVGFactory,X.DrawLayer,X.FeatureTest;var Zf=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 tg=X.getDocument;X.getFilenameFromUrl,X.getPdfFilenameFromUrl,X.getXfaPageViewport,X.isDataScheme,X.isPdfFile,X.noContextMenu,X.normalizeUnicode,X.setLayerDimensions,X.shadow,X.stopEvent;var eg=X.version;let Ch=null;function sg(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function ig(){const a=Ch??sg();return Ch=a,a/72}function ng(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 rg(a){return a.arrayBuffer?a.arrayBuffer():new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>{const i=s.result;if(!(i instanceof ArrayBuffer)){e(new Error("Failed to read file as ArrayBuffer."));return}t(i)}),s.addEventListener("error",e),s.readAsArrayBuffer(a)})}Ah()||(Zf.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${eg}/pdf.worker.min.mjs`);function Ah(){try{return typeof OffscreenCanvas<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function"&&globalThis.self===window.top}catch{return!1}}function og(a,t){const e=ig()/window.devicePixelRatio,s={...a,id:t,units:e};return Ah()?ag(s):lg(s)}async function ag({data:a,password:t,id:e,page:s,units:i,scale:n}){const r=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/pdfjs.worker-C52Du2jb.js").href:new URL("assets/pdfjs.worker-C52Du2jb.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:pt&&pt.tagName.toUpperCase()==="SCRIPT"&&pt.src||new URL("pdf-canvas.umd.js",document.baseURI).href),{type:"module"});try{return r.postMessage({data:a,password:t,id:e,page:s,units:i,scale:n}),await new Promise((l,h)=>{const c=d=>{if(d.data.status){if(d.data.status==="success"){const{bitmap:f,width:g,height:p,pages:b}=d.data;if(f&&e){const m=document.createElement("canvas"),v=m.getContext("2d");m.width=g,m.height=p,v?.drawImage(f,0,0),f.close(),l({pages:b,canvas:m})}else l({pages:b,canvas:null})}d.data.status==="error"&&h(d.data.error),r.removeEventListener("message",c)}},u=d=>{h(new Error(`Worker error: ${d.message}`))};r.addEventListener("message",c),r.addEventListener("error",u,{once:!0})})}finally{r.terminate()}}async function lg({data:a,password:t,id:e,page:s,scale:i,units:n}){const r=await rg(a),o=await tg({data:r,password:t}).promise;try{const l=o.numPages;if(!e)return{canvas:null,pages:l};const h=await o.getPage(s),c=h.getViewport({scale:i}),u=document.createElement("canvas"),d=u.getContext("2d");if(!d)throw new Error("Failed to get 2d context");const f={canvasContext:d,viewport:c,transform:[n,0,0,n,0,0]};return u.width=Math.floor(c.width*n),u.height=Math.floor(c.height*n),await h.render(f).promise,{canvas:u,pages:l}}finally{o.destroy()}}const Gt=new Map;function hg(a){const t=new Br(a);return Gt.set(a,t),t}function cg(a){const t=Date.now();return{PDFId:`${a.name}-${t}`,name:a.name.replace(/.pdf/,""),updateDate:t,data:a}}async function ug({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await Vu(a),n=s.filter(o=>o!==null),r=vu.groupSVGElements(n,i);return n.forEach(o=>{o.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function dg(a,t){if(!Gt.get(a))return;const s=1/3,i=yg(t,s);Eh(a,i)}async function fg(a,t){const e=Date.now(),i={PDFId:`${a.name}-${e}`,name:a.name.replace(/.png|.jpg|.jpeg/,""),updateDate:e,data:a};return t&&Th(t,{data:a}),{...i,pages:1}}async function Th(a,{data:t,scale:e=.5}){if(!Gt.get(a))return;const i=URL.createObjectURL(t),n=await Ut.fromURL(i);n.scale(e),Eh(a,n),URL.revokeObjectURL(i)}function Eh(a,t){const e=Gt.get(a);e&&(e.setDimensions({width:t.getScaledWidth(),height:t.getScaledHeight()}),t.set({originX:"left",originY:"top",left:0,top:0}),e.backgroundImage=t,e.renderAll())}function gg(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:l}=t;t.top=i-n*o/2,t.left=s-r*l/2,t.setCoords()}function pg(a,t,e){!e||!a||(e.scale(1/t),gg(a,e))}function mg(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 bg(a){const t=Gt.get(a);t&&(t.discardActiveObject(),t.renderAll())}function vg(a){const t=Gt.get(a);t&&(t.clear(),Gt.delete(a))}function yg(a,t){return new Ut(a,{scaleX:t,scaleY:t})}function ko(a,t){if(!t)return;const{left:e,top:s}=a,i=t.x*a.getScaledWidth(),n=t.y*a.getScaledHeight();a.set({left:e-i,top:s-n,originX:"left",originY:"top"})}function kh(a,t,e){const s=a.type;return{"application/pdf":_g,"image/png":Ph,"image/jpeg":Ph}[s]?.(a,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function _g(a,t,e){const s=cg(a),i=await Mh({page:1,data:a,scale:.8,password:t},e);return{...s,pages:i}}function Mh(a,t){return og(a,t).then(({canvas:e,pages:s})=>(e&&t&&dg(t,e),s))}async function Ph(a,t,e){return await fg(a,e)}function wg(a,t){const e=Gt.get(a);if(!e)return;const s=e.getActiveObject();s&&(s instanceof te?s.forEachObject(i=>{i.set(t)}):s.set(t),e.renderAll())}async function xg(a,t){const e=Gt.get(a);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(Yh);i instanceof te?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),ko(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function Sg(a){const t=Gt.get(a);if(!t)return;const e=t.getActiveObject();e&&(e instanceof te?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Oh(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{},l=K.useRef(null),h=K.useRef(null),c=K.useRef(1),u=K.useRef({...Uh});function d(){if(!t||Gt.has(t))return;const P=hg(t);return P.on("selection:created",O=>{if(r?.(O),O.selected.length<=1)return;const $=P.getActiveObject();$&&(h.current=$,e?.value&&h.current.set(e.value),h.current._cornerSize=h.current.cornerSize,w(c.current))}),P.on("selection:cleared",O=>{o?.(O),A(P)}),s&&P.on("mouse:down",s),i&&P.on("mouse:move",i),n&&P.on("mouse:up",n),P}function f(P,O){return kh(P,O,t)}function g(P){return Mh(P,t)}function p({data:P,scale:O=.5}){return Th(t,{data:P,scale:O})}async function b(P,O,$){const M=Gt.get(t);if(!M)return;const D=await Ut.fromURL(P,{},{...Wh,...O});ko(D,$),M.add(D),v(M,D),M.setActiveObject(D)}function m(P,O,$){const M=Gt.get(t);if(!M)return;const D=new Pt(P,{...Vh,...O});ko(D,$),M.add(D),v(M,D),M.setActiveObject(D)}function v(P,O){O.on("selected",$=>_({canvas:P,target:$.target})),O.on("modified",$=>_({canvas:P,target:$.target})),O.on("scaling",()=>A(P)),O.on("moving",()=>A(P)),O.on("rotating",()=>A(P)),O._cornerSize=O._cornerSize??O.cornerSize}async function _({canvas:P,target:O,stroke:$=u.current.stroke,uuid:M=Date.now()}){if(P.getActiveObjects().length>1||l.current?.stroke===`${$}-${M}`)return;const V=await ug(u.current,M,$);A(P),l.current=V,h.current=O,y(P,O,M),w(c.current,!0),V&&P.add(V)}function y(P,O,$){l.current&&(l.current.on("selected",()=>{P.remove(O),A(P)}),l.current.on("mouseover",()=>{_({canvas:P,target:O,stroke:u.current.hoverStroke,uuid:$})}),l.current.on("mouseout",()=>{_({canvas:P,target:O,stroke:u.current.stroke,uuid:$})}))}function w(P,O=!1){const $=Gt.get(t);c.current=P,$&&(mg(h.current,P),pg(h.current,P,l.current),!O&&$.renderAll())}function C(P){if(!P)return;u.current={...u.current,...P};const O=Gt.get(t);!l||!h.current||!O||_({target:h.current,canvas:O})}function A(P){h.current=null,l.current&&(P.remove(l.current),l.current=null)}function T(){bg(t)}function k(){vg(t)}function L(P){wg(t,P)}function R(){return xg(t,v)}function F(){Sg(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:b,addTextFabric:m,clearActive:T,deleteCanvas:k,scaleFabric:w,setCloseSvgOptions:C,setActiveFabric:L,copyActiveFabric:R,deleteActiveFabric:F}}function Cg(a){const t=K.useRef(0);return K.useEffect(()=>{const e=ng(()=>{const{innerWidth:s}=globalThis;s!==t.current&&(t.current=s,a())});return t.current=window.innerWidth,window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),null}const Ag=K.forwardRef(Tg);function Tg({file:a,page:t=1,canvasId:e="PDF-canvas",fileZoom:s=1,fileScale:i=1,canvasScale:n=1,canvasClass:r="",isDrop:o=!1,password:l,dropTextOptions:h,dropImageOptions:c,closeSvgOptions:u,selectionOptions:d,manualReload:f,onLoaded:g,onReload:p,onPointerDown:b,onPointerMove:m,onPointerUp:v,onSelectionCreated:_,onSelectionCleared:y},w){const C=K.useRef(null),A=`${e}-${t-1}`,T=K.useMemo(()=>s*n,[s,n]),k=K.useMemo(()=>({...Xh,...d}),[d]),{createCanvas:L,specifyPage:R,addFabric:F,addTextFabric:P,renderImage:O,clearActive:$,deleteCanvas:M,scaleFabric:D,setActiveFabric:V,setCloseSvgOptions:lt,copyActiveFabric:ut,deleteActiveFabric:E}=Oh({id:A,selectionOptions:k,pointerDown:b,pointerMove:m,pointerUp:v,selectionCreated:_,selectionCleared:y});Cg(nt);async function B(){globalThis.requestAnimationFrame(async()=>{if(L(),a.data?.type.startsWith("image/")){const Tt=a.data;Tt&&O({data:Tt,scale:i/3}),g?.();return}const j=a.data;j&&await R({page:t,data:j,scale:i,password:l}),g?.()})}function z(j){if(j.preventDefault(),j.stopPropagation(),!o||!j.dataTransfer)return;const{dataTransfer:dt,nativeEvent:Tt}=j,{offsetX:Qt,offsetY:Eg}=Tt,Dh=dt.getData("text/plain"),Rh=dt.getData("text/uri-list"),Lh=dt.getData("custom/offset"),Fh=Lh?JSON.parse(Lh):null,Ih={top:Eg,left:Qt},jh={x:Fh?.offsetX??0,y:Fh?.offsetY??0};Rh?J(Rh,Ih,jh):Dh&&Et(Dh,Ih,jh)}function J(j,dt,Tt){F(j,{...c,...dt},Tt)}function Et(j,dt,Tt){P(j,{...h,...dt},Tt)}function nt(){f||B(),p?.()}return K.useImperativeHandle(w,()=>({reload:B,addImage:J,addText:Et,clearActive:$,deleteCanvas:M,setActiveFabric:V,copyActiveFabric:ut,deleteActiveFabric:E,canvasRef:C})),K.useEffect(()=>{nt()},[i,t,a,l]),K.useEffect(()=>{D(T)},[T]),K.useEffect(()=>{lt(u)},[u]),K.useEffect(()=>()=>M(),[]),Ro.jsx("div",{style:{transform:`scale(${T})`},onDragOver:j=>j.preventDefault(),onDragEnter:j=>j.preventDefault(),onDrop:z,children:Ro.jsx("canvas",{id:A,ref:C,className:r})})}et.default=Ag,et.loadFile=kh,et.useFabric=Oh,Object.defineProperties(et,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
439
+ `}applyTo2d({imageData:{data:e}}){let t=-this.vibrance;for(let n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2],o=Math.max(r,i,a),s=(r+i+a)/3,c=2*Math.abs(o-s)/255*t;e[n]+=o===r?0:(o-r)*c,e[n+1]+=o===i?0:(o-i)*c,e[n+2]+=o===a?0:(o-a)*c}}sendUniformData(e,t){e.uniform1f(t.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}};p(Nc,`type`,`Vibrance`),p(Nc,`defaults`,{vibrance:0}),p(Nc,`uniformLocations`,[`uVibrance`]),L.setClass(Nc),u({BaseFilter:()=>ec,BlackWhite:()=>gc,BlendColor:()=>nc,BlendImage:()=>ic,Blur:()=>ac,Brightness:()=>oc,Brownie:()=>uc,ColorMatrix:()=>cc,Composed:()=>_c,Contrast:()=>vc,Convolute:()=>bc,Gamma:()=>Sc,Grayscale:()=>wc,HueRotation:()=>Ec,Invert:()=>Dc,Kodachrome:()=>fc,Noise:()=>Oc,Pixelate:()=>kc,Polaroid:()=>mc,RemoveColor:()=>Ac,Resize:()=>jc,Saturation:()=>Mc,Sepia:()=>hc,Technicolor:()=>pc,Vibrance:()=>Nc,Vintage:()=>dc});var Pc={};Pc.d=(e,t)=>{for(var n in t)Pc.o(t,n)&&!Pc.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Pc.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var U=globalThis.pdfjsLib={};Pc.d(U,{AbortException:()=>ul,AnnotationEditorLayer:()=>yp,AnnotationEditorParamsType:()=>G,AnnotationEditorType:()=>W,AnnotationEditorUIManager:()=>eu,AnnotationLayer:()=>tp,AnnotationMode:()=>Vc,ColorPicker:()=>up,DOMSVGFactory:()=>Sf,DrawLayer:()=>bp,FeatureTest:()=>_l,GlobalWorkerOptions:()=>ud,ImageKind:()=>Gc,InvalidPDFException:()=>ol,MissingPDFException:()=>sl,OPS:()=>Yc,OutputScale:()=>Gl,PDFDataRangeTransport:()=>of,PDFDateString:()=>zl,PDFWorker:()=>uf,PasswordResponses:()=>Xc,PermissionFlag:()=>Uc,PixelsPerInch:()=>Dl,RenderingCancelledException:()=>Al,TextLayer:()=>Gd,TouchManager:()=>nu,UnexpectedResponseException:()=>cl,Util:()=>X,VerbosityLevel:()=>Jc,XfaLayer:()=>Cf,build:()=>_f,createValidAbsoluteUrl:()=>nl,fetchData:()=>Ol,getDocument:()=>ef,getFilenameFromUrl:()=>Nl,getPdfFilenameFromUrl:()=>Pl,getXfaPageViewport:()=>Bl,isDataScheme:()=>jl,isPdfFile:()=>Ml,noContextMenu:()=>Ll,normalizeUnicode:()=>Sl,setLayerDimensions:()=>Wl,shadow:()=>Y,stopEvent:()=>Rl,version:()=>gf});var Fc=typeof process==`object`&&process+``==`[object process]`&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!==`browser`),Ic=[1,0,0,1,0,0],Lc=[.001,0,0,.001,0,0],Rc=1e7,zc=1.35,Bc={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Vc={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Hc=`pdfjs_internal_editor_`,W={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},G={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},Uc={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Wc={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Gc={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Kc={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},qc={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Jc={ERRORS:0,WARNINGS:1,INFOS:5},Yc={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},Xc={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},Zc=Jc.WARNINGS;function Qc(e){Number.isInteger(e)&&(Zc=e)}function $c(){return Zc}function el(e){Zc>=Jc.INFOS&&console.log(`Info: ${e}`)}function K(e){Zc>=Jc.WARNINGS&&console.log(`Warning: ${e}`)}function q(e){throw Error(e)}function J(e,t){e||q(t)}function tl(e){switch(e?.protocol){case`http:`:case`https:`:case`ftp:`:case`mailto:`:case`tel:`:return!0;default:return!1}}function nl(e,t=null,n=null){if(!e)return null;try{if(n&&typeof e==`string`&&(n.addDefaultProtocol&&e.startsWith(`www.`)&&e.match(/\./g)?.length>=2&&(e=`http://${e}`),n.tryConvertEncoding))try{e=yl(e)}catch{}let r=t?new URL(e,t):new URL(e);if(tl(r))return r}catch{}return null}function Y(e,t,n,r=!1){return Object.defineProperty(e,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var rl=function(){function e(e,t){this.message=e,this.name=t}return e.prototype=Error(),e.constructor=e,e}(),il=class extends rl{constructor(e,t){super(e,`PasswordException`),this.code=t}},al=class extends rl{constructor(e,t){super(e,`UnknownErrorException`),this.details=t}},ol=class extends rl{constructor(e){super(e,`InvalidPDFException`)}},sl=class extends rl{constructor(e){super(e,`MissingPDFException`)}},cl=class extends rl{constructor(e,t){super(e,`UnexpectedResponseException`),this.status=t}},ll=class extends rl{constructor(e){super(e,`FormatError`)}},ul=class extends rl{constructor(e){super(e,`AbortException`)}};function dl(e){(typeof e!=`object`||e?.length===void 0)&&q(`Invalid argument for bytesToString`);let t=e.length,n=8192;if(t<n)return String.fromCharCode.apply(null,e);let r=[];for(let i=0;i<t;i+=n){let a=Math.min(i+n,t),o=e.subarray(i,a);r.push(String.fromCharCode.apply(null,o))}return r.join(``)}function fl(e){typeof e!=`string`&&q(`Invalid argument for stringToBytes`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;++r)n[r]=e.charCodeAt(r)&255;return n}function pl(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,e&255)}function ml(e){let t=Object.create(null);for(let[n,r]of e)t[n]=r;return t}function hl(){let e=new Uint8Array(4);return e[0]=1,new Uint32Array(e.buffer,0,1)[0]===1}function gl(){try{return Function(``),!0}catch{return!1}}var _l=class{static get isLittleEndian(){return Y(this,`isLittleEndian`,hl())}static get isEvalSupported(){return Y(this,`isEvalSupported`,gl())}static get isOffscreenCanvasSupported(){return Y(this,`isOffscreenCanvasSupported`,typeof OffscreenCanvas<`u`)}static get isImageDecoderSupported(){return Y(this,`isImageDecoderSupported`,typeof ImageDecoder<`u`)}static get platform(){return typeof navigator<`u`&&typeof navigator?.platform==`string`?Y(this,`platform`,{isMac:navigator.platform.includes(`Mac`),isWindows:navigator.platform.includes(`Win`),isFirefox:typeof navigator?.userAgent==`string`&&navigator.userAgent.includes(`Firefox`)}):Y(this,`platform`,{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return Y(this,`isCSSRoundSupported`,globalThis.CSS?.supports?.(`width: round(1.5px, 1px)`))}},vl=Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,`0`)),X=class{static makeHexColor(e,t,n){return`#${vl[e]}${vl[t]}${vl[n]}`}static scaleMinMax(e,t){let n;e[0]?(e[0]<0&&(n=t[0],t[0]=t[2],t[2]=n),t[0]*=e[0],t[2]*=e[0],e[3]<0&&(n=t[1],t[1]=t[3],t[3]=n),t[1]*=e[3],t[3]*=e[3]):(n=t[0],t[0]=t[1],t[1]=n,n=t[2],t[2]=t[3],t[3]=n,e[1]<0&&(n=t[1],t[1]=t[3],t[3]=n),t[1]*=e[1],t[3]*=e[1],e[2]<0&&(n=t[0],t[0]=t[2],t[2]=n),t[0]*=e[2],t[2]*=e[2]),t[0]+=e[4],t[1]+=e[5],t[2]+=e[4],t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){let n=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/n,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/n]}static getAxialAlignedBoundingBox(e,t){let n=this.applyTransform(e,t),r=this.applyTransform(e.slice(2,4),t),i=this.applyTransform([e[0],e[3]],t),a=this.applyTransform([e[2],e[1]],t);return[Math.min(n[0],r[0],i[0],a[0]),Math.min(n[1],r[1],i[1],a[1]),Math.max(n[0],r[0],i[0],a[0]),Math.max(n[1],r[1],i[1],a[1])]}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){let t=[e[0],e[2],e[1],e[3]],n=e[0]*t[0]+e[1]*t[2],r=e[0]*t[1]+e[1]*t[3],i=e[2]*t[0]+e[3]*t[2],a=e[2]*t[1]+e[3]*t[3],o=(n+a)/2,s=Math.sqrt((n+a)**2-4*(n*a-i*r))/2,c=o+s||1,l=o-s||1;return[Math.sqrt(c),Math.sqrt(l)]}static normalizeRect(e){let t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>r)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>a?null:[n,i,r,a]}static#e(e,t,n,r,i,a,o,s,c,l){if(c<=0||c>=1)return;let u=1-c,d=c*c,f=d*c,p=u*(u*(u*e+3*c*t)+3*d*n)+f*r,m=u*(u*(u*i+3*c*a)+3*d*o)+f*s;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],m),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],m)}static#t(e,t,n,r,i,a,o,s,c,l,u,d){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,n,r,i,a,o,s,-u/l,d);return}let f=l**2-4*u*c;if(f<0)return;let p=Math.sqrt(f),m=2*c;this.#e(e,t,n,r,i,a,o,s,(-l+p)/m,d),this.#e(e,t,n,r,i,a,o,s,(-l-p)/m,d)}static bezierBoundingBox(e,t,n,r,i,a,o,s,c){return c?(c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,s),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,s)):c=[Math.min(e,o),Math.min(t,s),Math.max(e,o),Math.max(t,s)],this.#t(e,n,i,o,t,r,a,s,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,r,a,s,3*(-t+3*(r-a)+s),6*(t-2*r+a),3*(r-t),c),c}};function yl(e){return decodeURIComponent(escape(e))}var bl=null,xl=null;function Sl(e){return bl||(bl=/([\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,xl=new Map([[`ſt`,`ſt`]])),e.replaceAll(bl,(e,t,n)=>t?t.normalize(`NFKC`):xl.get(n))}function Cl(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),dl(e)}var wl=`pdfjs_internal_id_`;function Tl(e){return Uint8Array.prototype.toBase64?e.toBase64():btoa(dl(e))}typeof Promise.try!=`function`&&(Promise.try=function(e,...t){return new Promise(n=>{n(e(...t))})});var El=`http://www.w3.org/2000/svg`,Dl=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function Ol(e,t=`text`){if(Il(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case`arraybuffer`:return n.arrayBuffer();case`blob`:return n.blob();case`json`:return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(`GET`,e,!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`:n(i.response);return}n(i.responseText);return}r(Error(i.statusText))}},i.send(null)})}var kl=class e{constructor({viewBox:e,userUnit:t,scale:n,rotation:r,offsetX:i=0,offsetY:a=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=r,this.offsetX=i,this.offsetY=a,n*=t;let s=(e[2]+e[0])/2,c=(e[3]+e[1])/2,l,u,d,f;switch(r%=360,r<0&&(r+=360),r){case 180:l=-1,u=0,d=0,f=1;break;case 90:l=0,u=1,d=1,f=0;break;case 270:l=0,u=-1,d=-1,f=0;break;case 0:l=1,u=0,d=0,f=-1;break;default:throw Error(`PageViewport: Invalid rotation, must be a multiple of 90 degrees.`)}o&&(d=-d,f=-f);let p,m,h,g;l===0?(p=Math.abs(c-e[1])*n+i,m=Math.abs(s-e[0])*n+a,h=(e[3]-e[1])*n,g=(e[2]-e[0])*n):(p=Math.abs(s-e[0])*n+i,m=Math.abs(c-e[1])*n+a,h=(e[2]-e[0])*n,g=(e[3]-e[1])*n),this.transform=[l*n,u*n,d*n,f*n,p-l*n*s-d*n*c,m-u*n*s-f*n*c],this.width=h,this.height=g}get rawDims(){let{userUnit:e,viewBox:t}=this,n=t.map(t=>t*e);return Y(this,`rawDims`,{pageWidth:n[2]-n[0],pageHeight:n[3]-n[1],pageX:n[0],pageY:n[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:a=!1}={}){return new e({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:n,offsetX:r,offsetY:i,dontFlip:a})}convertToViewportPoint(e,t){return X.applyTransform([e,t],this.transform)}convertToViewportRectangle(e){let t=X.applyTransform([e[0],e[1]],this.transform),n=X.applyTransform([e[2],e[3]],this.transform);return[t[0],t[1],n[0],n[1]]}convertToPdfPoint(e,t){return X.applyInverseTransform([e,t],this.transform)}},Al=class extends rl{constructor(e,t=0){super(e,`RenderingCancelledException`),this.extraDelay=t}};function jl(e){let t=e.length,n=0;for(;n<t&&e[n].trim()===``;)n++;return e.substring(n,n+5).toLowerCase()===`data:`}function Ml(e){return typeof e==`string`&&/\.pdf$/i.test(e)}function Nl(e){return[e]=e.split(/[#?]/,1),e.substring(e.lastIndexOf(`/`)+1)}function Pl(e,t=`document.pdf`){if(typeof e!=`string`)return t;if(jl(e))return K(`getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.`),t;let n=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,r=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=n.exec(e),a=r.exec(i[1])||r.exec(i[2])||r.exec(i[3]);if(a&&(a=a[0],a.includes(`%`)))try{a=r.exec(decodeURIComponent(a))[0]}catch{}return a||t}var Fl=class{started=Object.create(null);times=[];time(e){e in this.started&&K(`Timer is already running for ${e}`),this.started[e]=Date.now()}timeEnd(e){e in this.started||K(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e]}toString(){let e=[],t=0;for(let{name:e}of this.times)t=Math.max(e.length,t);for(let{name:n,start:r,end:i}of this.times)e.push(`${n.padEnd(t)} ${i-r}ms\n`);return e.join(``)}};function Il(e,t){try{let{protocol:n}=t?new URL(e,t):new URL(e);return n===`http:`||n===`https:`}catch{return!1}}function Ll(e){e.preventDefault()}function Rl(e){e.preventDefault(),e.stopPropagation()}var zl=class{static#e;static toDateObject(e){if(!e||typeof e!=`string`)return null;this.#e||=RegExp(`^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?`);let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),r=parseInt(t[2],10);r=r>=1&&r<=12?r-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let s=parseInt(t[6],10);s=s>=0&&s<=59?s:0;let c=t[7]||`Z`,l=parseInt(t[8],10);l=l>=0&&l<=23?l:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c===`-`?(a+=l,o+=u):c===`+`&&(a-=l,o-=u),new Date(Date.UTC(n,r,i,a,o,s))}};function Bl(e,{scale:t=1,rotation:n=0}){let{width:r,height:i}=e.attributes.style;return new kl({viewBox:[0,0,parseInt(r),parseInt(i)],userUnit:1,scale:t,rotation:n})}function Vl(e){if(e.startsWith(`#`)){let t=parseInt(e.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return e.startsWith(`rgb(`)?e.slice(4,-1).split(`,`).map(e=>parseInt(e)):e.startsWith(`rgba(`)?e.slice(5,-1).split(`,`).map(e=>parseInt(e)).slice(0,3):(K(`Not a valid color format: "${e}"`),[0,0,0])}function Hl(e){let t=document.createElement(`span`);t.style.visibility=`hidden`,document.body.append(t);for(let n of e.keys()){t.style.color=n;let r=window.getComputedStyle(t).color;e.set(n,Vl(r))}t.remove()}function Z(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform();return[t,n,r,i,a,o]}function Ul(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform().invertSelf();return[t,n,r,i,a,o]}function Wl(e,t,n=!1,r=!0){if(t instanceof kl){let{pageWidth:r,pageHeight:i}=t.rawDims,{style:a}=e,o=_l.isCSSRoundSupported,s=`var(--scale-factor) * ${r}px`,c=`var(--scale-factor) * ${i}px`,l=o?`round(down, ${s}, var(--scale-round-x, 1px))`:`calc(${s})`,u=o?`round(down, ${c}, var(--scale-round-y, 1px))`:`calc(${c})`;!n||t.rotation%180==0?(a.width=l,a.height=u):(a.width=u,a.height=l)}r&&e.setAttribute(`data-main-rotation`,t.rotation)}var Gl=class{constructor(){let e=window.devicePixelRatio||1;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}},Kl=class e{#e=null;#t=null;#n;#r=null;#i=null;static#a=null;constructor(t){this.#n=t,e.#a||=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(){let t=this.#e=document.createElement(`div`);t.classList.add(`editToolbar`,`hidden`),t.setAttribute(`role`,`toolbar`);let n=this.#n._uiManager._signal;t.addEventListener(`contextmenu`,Ll,{signal:n}),t.addEventListener(`pointerdown`,e.#o,{signal:n});let r=this.#r=document.createElement(`div`);r.className=`buttons`,t.append(r);let i=this.#n.toolbarPosition;if(i){let{style:e}=t;e.insetInlineEnd=`${100*(this.#n._uiManager.direction===`ltr`?1-i[0]:i[0])}%`,e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#u(),t}get div(){return this.#e}static#o(e){e.stopPropagation()}#s(e){this.#n._focusEventsAllowed=!1,Rl(e)}#c(e){this.#n._focusEventsAllowed=!0,Rl(e)}#l(e){let t=this.#n._uiManager._signal;e.addEventListener(`focusin`,this.#s.bind(this),{capture:!0,signal:t}),e.addEventListener(`focusout`,this.#c.bind(this),{capture:!0,signal:t}),e.addEventListener(`contextmenu`,Ll,{signal:t})}hide(){this.#e.classList.add(`hidden`),this.#t?.hideDropdown()}show(){this.#e.classList.remove(`hidden`),this.#i?.shown()}#u(){let{editorType:t,_uiManager:n}=this.#n,r=document.createElement(`button`);r.className=`delete`,r.tabIndex=0,r.setAttribute(`data-l10n-id`,e.#a[t]),this.#l(r),r.addEventListener(`click`,e=>{n.delete()},{signal:n._signal}),this.#r.append(r)}get#d(){let e=document.createElement(`div`);return e.className=`divider`,e}async addAltText(e){let t=await e.render();this.#l(t),this.#r.prepend(t,this.#d),this.#i=e}addColorPicker(e){this.#t=e;let t=e.renderButton();this.#l(t),this.#r.prepend(t,this.#d)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},ql=class{#e=null;#t=null;#n;constructor(e){this.#n=e}#r(){let e=this.#t=document.createElement(`div`);e.className=`editToolbar`,e.setAttribute(`role`,`toolbar`),e.addEventListener(`contextmenu`,Ll,{signal:this.#n._signal});let t=this.#e=document.createElement(`div`);return t.className=`buttons`,e.append(t),this.#a(),e}#i(e,t){let n=0,r=0;for(let i of e){let e=i.y+i.height;if(e<n)continue;let a=i.x+(t?i.width:0);if(e>n){r=a,n=e;continue}t?a>r&&(r=a):a<r&&(r=a)}return[t?1-r:r,n]}show(e,t,n){let[r,i]=this.#i(t,n),{style:a}=this.#t||=this.#r();e.append(this.#t),a.insetInlineEnd=`${100*r}%`,a.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){this.#t.remove()}#a(){let e=document.createElement(`button`);e.className=`highlightButton`,e.tabIndex=0,e.setAttribute(`data-l10n-id`,`pdfjs-highlight-floating-button1`);let t=document.createElement(`span`);e.append(t),t.className=`visuallyHidden`,t.setAttribute(`data-l10n-id`,`pdfjs-highlight-floating-button-label`);let n=this.#n._signal;e.addEventListener(`contextmenu`,Ll,{signal:n}),e.addEventListener(`click`,()=>{this.#n.highlightSelection(`floating_button`)},{signal:n}),this.#e.append(e)}};function Jl(e,t,n){for(let r of n)t.addEventListener(r,e[r].bind(e))}var Yl=class{#e=0;get id(){return`${Hc}${this.#e++}`}},Xl=class e{#e=Cl();#t=0;#n=null;static get _isSVGFittingCanvas(){let e=new OffscreenCanvas(1,3).getContext(`2d`,{willReadFrequently:!0}),t=new Image;t.src=`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>`;let n=t.decode().then(()=>(e.drawImage(t,0,0,1,1,0,0,1,3),new Uint32Array(e.getImageData(0,0,1,1).data.buffer)[0]===0));return Y(this,`_isSVGFittingCanvas`,n)}async#r(t,n){this.#n||=new Map;let r=this.#n.get(t);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let t;if(typeof n==`string`?(r.url=n,t=await Ol(n,`blob`)):n instanceof File?t=r.file=n:n instanceof Blob&&(t=n),t.type===`image/svg+xml`){let n=e._isSVGFittingCanvas,i=new FileReader,a=new Image,o=new Promise((e,t)=>{a.onload=()=>{r.bitmap=a,r.isSvg=!0,e()},i.onload=async()=>{let e=r.svgUrl=i.result;a.src=await n?`${e}#svgView(preserveAspectRatio(none))`:e},a.onerror=i.onerror=t});i.readAsDataURL(t),await o}else r.bitmap=await createImageBitmap(t);r.refCounter=1}catch(e){K(e),r=null}return this.#n.set(t,r),r&&this.#n.set(r.id,r),r}async getFromFile(e){let{lastModified:t,name:n,size:r,type:i}=e;return this.#r(`${t}_${n}_${r}_${i}`,e)}async getFromUrl(e){return this.#r(e,e)}async getFromBlob(e,t){let n=await t;return this.#r(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:e}=t;return delete t.blobPromise,this.getFromBlob(t.id,e)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let r=new OffscreenCanvas(t.width,t.height);return r.getContext(`2d`).drawImage(t,0,0),n={bitmap:r.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);return t?.isSvg?t.svgUrl:null}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t||(--t.refCounter,t.refCounter!==0))return;let{bitmap:n}=t;if(!t.url&&!t.file){let e=new OffscreenCanvas(n.width,n.height);e.getContext(`bitmaprenderer`).transferFromImageBitmap(n),t.blobPromise=e.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},Zl=class{#e=[];#t=!1;#n;#r=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:r,type:i=NaN,overwriteIfSameType:a=!1,keepUndo:o=!1}){if(r&&e(),this.#t)return;let s={cmd:e,undo:t,post:n,type:i};if(this.#r===-1){this.#e.length>0&&(this.#e.length=0),this.#r=0,this.#e.push(s);return}if(a&&this.#e[this.#r].type===i){o&&(s.undo=this.#e[this.#r].undo),this.#e[this.#r]=s;return}let c=this.#r+1;c===this.#n?this.#e.splice(0,1):(this.#r=c,c<this.#e.length&&this.#e.splice(c)),this.#e.push(s)}undo(){if(this.#r===-1)return;this.#t=!0;let{undo:e,post:t}=this.#e[this.#r];e(),t?.(),this.#t=!1,--this.#r}redo(){if(this.#r<this.#e.length-1){this.#r+=1,this.#t=!0;let{cmd:e,post:t}=this.#e[this.#r];e(),t?.(),this.#t=!1}}hasSomethingToUndo(){return this.#r!==-1}hasSomethingToRedo(){return this.#r<this.#e.length-1}cleanType(e){if(this.#r!==-1){for(let t=this.#r;t>=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#r-t),this.#r=t;return}this.#e.length=0,this.#r=-1}}destroy(){this.#e=null}},Ql=class{constructor(e){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:t}=_l.platform;for(let[n,r,i={}]of e)for(let e of n){let n=e.startsWith(`mac+`);t&&n?(this.callbacks.set(e.slice(4),{callback:r,options:i}),this.allKeys.add(e.split(`+`).at(-1))):!t&&!n&&(this.callbacks.set(e,{callback:r,options:i}),this.allKeys.add(e.split(`+`).at(-1)))}}#e(e){e.altKey&&this.buffer.push(`alt`),e.ctrlKey&&this.buffer.push(`ctrl`),e.metaKey&&this.buffer.push(`meta`),e.shiftKey&&this.buffer.push(`shift`),this.buffer.push(e.key);let t=this.buffer.join(`+`);return this.buffer.length=0,t}exec(e,t){if(!this.allKeys.has(t.key))return;let n=this.callbacks.get(this.#e(t));if(!n)return;let{callback:r,options:{bubbles:i=!1,args:a=[],checker:o=null}}=n;o&&!o(e,t)||(r.bind(e,...a,t)(),i||Rl(t))}},$l=class e{static _colorsMapping=new Map([[`CanvasText`,[0,0,0]],[`Canvas`,[255,255,255]]]);get _colors(){let e=new Map([[`CanvasText`,null],[`Canvas`,null]]);return Hl(e),Y(this,`_colors`,e)}convert(t){let n=Vl(t);if(!window.matchMedia(`(forced-colors: active)`).matches)return n;for(let[t,r]of this._colors)if(r.every((e,t)=>e===n[t]))return e._colorsMapping.get(t);return n}getHexCode(e){let t=this._colors.get(e);return t?X.makeHexColor(...t):e}},eu=class e{#e=new AbortController;#t=null;#n=new Map;#r=new Map;#i=null;#a=null;#o=null;#s=new Zl;#c=null;#l=null;#u=0;#d=new Set;#f=null;#p=null;#m=new Set;_editorUndoBar=null;#h=!1;#g=!1;#_=!1;#v=null;#y=null;#b=null;#x=null;#S=!1;#C=null;#w=new Yl;#T=!1;#E=!1;#D=null;#O=null;#k=null;#A=null;#j=W.NONE;#M=new Set;#N=null;#P=null;#F=null;#I={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#L=[0,0];#R=null;#z=null;#B=null;#V=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.#z.contains(document.activeElement)&&document.activeElement.tagName!==`BUTTON`&&e.hasSomethingToControl(),r=(e,{target:t})=>{if(t instanceof HTMLInputElement){let{type:e}=t;return e!==`text`&&e!==`number`}return!0},i=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return Y(this,`_keyboardManager`,new Ql([[[`ctrl+a`,`mac+meta+a`],t.selectAll,{checker:r}],[[`ctrl+z`,`mac+meta+z`],t.undo,{checker:r}],[[`ctrl+y`,`ctrl+shift+z`,`mac+meta+shift+z`,`ctrl+shift+Z`,`mac+meta+shift+Z`],t.redo,{checker:r}],[[`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:r}],[[`Enter`,`mac+Enter`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#z.contains(t)&&!e.isEnterHandled}],[[` `,`mac+ `],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#z.contains(document.activeElement)}],[[`Escape`,`mac+Escape`],t.unselectAll],[[`ArrowLeft`,`mac+ArrowLeft`],t.translateSelectedEditors,{args:[-i,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t.translateSelectedEditors,{args:[-a,0],checker:n}],[[`ArrowRight`,`mac+ArrowRight`],t.translateSelectedEditors,{args:[i,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t.translateSelectedEditors,{args:[a,0],checker:n}],[[`ArrowUp`,`mac+ArrowUp`],t.translateSelectedEditors,{args:[0,-i],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t.translateSelectedEditors,{args:[0,-a],checker:n}],[[`ArrowDown`,`mac+ArrowDown`],t.translateSelectedEditors,{args:[0,i],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t.translateSelectedEditors,{args:[0,a],checker:n}]]))}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=this._signal=this.#e.signal;this.#z=e,this.#B=t,this.#i=n,this._eventBus=r,r._on(`editingaction`,this.onEditingAction.bind(this),{signal:p}),r._on(`pagechanging`,this.onPageChanging.bind(this),{signal:p}),r._on(`scalechanging`,this.onScaleChanging.bind(this),{signal:p}),r._on(`rotationchanging`,this.onRotationChanging.bind(this),{signal:p}),r._on(`setpreference`,this.onSetPreference.bind(this),{signal:p}),r._on(`switchannotationeditorparams`,e=>this.updateParams(e.type,e.value),{signal:p}),this.#q(),this.#ee(),this.#X(),this.#a=i.annotationStorage,this.#v=i.filterFactory,this.#P=a,this.#x=o||null,this.#h=s,this.#g=c,this.#_=l,this.#A=u||null,this.viewParameters={realScale:Dl.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#V?.resolve(),this.#V=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#r.values())e.destroy();this.#r.clear(),this.#n.clear(),this.#m.clear(),this.#t=null,this.#M.clear(),this.#s.destroy(),this.#i?.destroy(),this.#C?.hide(),this.#C=null,this.#y&&=(clearTimeout(this.#y),null),this.#R&&=(clearTimeout(this.#R),null),this._editorUndoBar?.destroy()}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#A}get useNewAltTextFlow(){return this.#g}get useNewAltTextWhenAddingImage(){return this.#_}get hcmFilter(){return Y(this,`hcmFilter`,this.#P?this.#v.addHCMFilter(this.#P.foreground,this.#P.background):`none`)}get direction(){return Y(this,`direction`,getComputedStyle(this.#z).direction)}get highlightColors(){return Y(this,`highlightColors`,this.#x?new Map(this.#x.split(`,`).map(e=>e.split(`=`).map(e=>e.trim()))):null)}get highlightColorNames(){return Y(this,`highlightColorNames`,this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#l=e}setMainHighlightColorPicker(e){this.#k=e}editAltText(e,t=!1){this.#i?.editAltText(this,e,t)}switchToMode(e,t){this._eventBus.on(`annotationeditormodechanged`,t,{once:!0,signal:this._signal}),this._eventBus.dispatch(`showannotationeditorui`,{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch(`setpreference`,{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){e===`enableNewAltTextWhenAddingImage`&&(this.#_=t)}onPageChanging({pageNumber:e}){this.#u=e-1}focusMainContainer(){this.#z.focus()}findParent(e,t){for(let n of this.#r.values()){let{x:r,y:i,width:a,height:o}=n.div.getBoundingClientRect();if(e>=r&&e<=r+a&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#B.classList.toggle(`noUserSelect`,e)}addShouldRescale(e){this.#m.add(e)}removeShouldRescale(e){this.#m.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Dl.PDF_TO_CSS_UNITS;for(let e of this.#m)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#H({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#U(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let t of this.#r.values())if(t.hasTextLayer(e))return t;return null}highlightSelection(e=``){let t=document.getSelection();if(!t||t.isCollapsed)return;let{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a}=t,o=t.toString(),s=this.#H(t).closest(`.textLayer`),c=this.getSelectionBoxes(s);if(!c)return;t.empty();let l=this.#U(s),u=this.#j===W.NONE,d=()=>{l?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:c,anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a,text:o}),u&&this.showAllEditors(`highlight`,!0,!0)};if(u){this.switchToMode(W.HIGHLIGHT,d);return}d()}#W(){let e=document.getSelection();if(!e||e.isCollapsed)return;let t=this.#H(e).closest(`.textLayer`),n=this.getSelectionBoxes(t);n&&(this.#C||=new ql(this),this.#C.show(t,n,this.direction===`ltr`))}addToAnnotationStorage(e){!e.isEmpty()&&this.#a&&!this.#a.has(e.id)&&this.#a.setValue(e.id,e)}#G(){let e=document.getSelection();if(!e||e.isCollapsed){this.#N&&(this.#C?.hide(),this.#N=null,this.#te({hasSelectedText:!1}));return}let{anchorNode:t}=e;if(t===this.#N)return;let n=this.#H(e).closest(`.textLayer`);if(!n){this.#N&&(this.#C?.hide(),this.#N=null,this.#te({hasSelectedText:!1}));return}if(this.#C?.hide(),this.#N=t,this.#te({hasSelectedText:!0}),(this.#j===W.HIGHLIGHT||this.#j===W.NONE)&&(this.#j===W.HIGHLIGHT&&this.showAllEditors(`highlight`,!0,!0),this.#S=this.isShiftKeyDown,!this.isShiftKeyDown)){let e=this.#j===W.HIGHLIGHT?this.#U(n):null;e?.toggleDrawing();let t=new AbortController,r=this.combinedSignal(t),i=n=>{(n.type!==`pointerup`||n.button===0)&&(t.abort(),e?.toggleDrawing(!0),n.type===`pointerup`&&this.#K(`main_toolbar`))};window.addEventListener(`pointerup`,i,{signal:r}),window.addEventListener(`blur`,i,{signal:r})}}#K(e=``){this.#j===W.HIGHLIGHT?this.highlightSelection(e):this.#h&&this.#W()}#q(){document.addEventListener(`selectionchange`,this.#G.bind(this),{signal:this._signal})}#J(){if(this.#b)return;this.#b=new AbortController;let e=this.combinedSignal(this.#b);window.addEventListener(`focus`,this.focus.bind(this),{signal:e}),window.addEventListener(`blur`,this.blur.bind(this),{signal:e})}#Y(){this.#b?.abort(),this.#b=null}blur(){if(this.isShiftKeyDown=!1,this.#S&&(this.#S=!1,this.#K(`main_toolbar`)),!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#M)if(t.div.contains(e)){this.#O=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;let[e,t]=this.#O;this.#O=null,t.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#X(){if(this.#D)return;this.#D=new AbortController;let e=this.combinedSignal(this.#D);window.addEventListener(`keydown`,this.keydown.bind(this),{signal:e}),window.addEventListener(`keyup`,this.keyup.bind(this),{signal:e})}#Z(){this.#D?.abort(),this.#D=null}#Q(){if(this.#c)return;this.#c=new AbortController;let e=this.combinedSignal(this.#c);document.addEventListener(`copy`,this.copy.bind(this),{signal:e}),document.addEventListener(`cut`,this.cut.bind(this),{signal:e}),document.addEventListener(`paste`,this.paste.bind(this),{signal:e})}#$(){this.#c?.abort(),this.#c=null}#ee(){let e=this._signal;document.addEventListener(`dragover`,this.dragOver.bind(this),{signal:e}),document.addEventListener(`drop`,this.drop.bind(this),{signal:e})}addEditListeners(){this.#X(),this.#Q()}removeEditListeners(){this.#Z(),this.#$()}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#p)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect=`copy`,e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#p)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let e of this.#M){let n=e.serialize(!0);n&&t.push(n)}t.length!==0&&e.clipboardData.setData(`application/pdfjs`,JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let e of t.items)for(let t of this.#p)if(t.isHandlingMimeForPasting(e.type)){t.paste(e,this.currentLayer);return}let n=t.getData(`application/pdfjs`);if(!n)return;try{n=JSON.parse(n)}catch(e){K(`paste: "${e.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let r=this.currentLayer;try{let e=[];for(let t of n){let n=await r.deserialize(t);if(!n)return;e.push(n)}this.addCommands({cmd:()=>{for(let t of e)this.#ae(t);this.#ce(e)},undo:()=>{for(let t of e)t.remove()},mustExec:!0})}catch(e){K(`paste: "${e.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key===`Shift`&&(this.isShiftKeyDown=!0),this.#j!==W.NONE&&!this.isEditorHandlingKeyboard&&e._keyboardManager.exec(this,t)}keyup(e){this.isShiftKeyDown&&e.key===`Shift`&&(this.isShiftKeyDown=!1,this.#S&&(this.#S=!1,this.#K(`main_toolbar`)))}onEditingAction({name:e}){switch(e){case`undo`:case`redo`:case`delete`:case`selectAll`:this[e]();break;case`highlightSelection`:this.highlightSelection(`context_menu`)}}#te(e){Object.entries(e).some(([e,t])=>this.#I[e]!==t)&&(this._eventBus.dispatch(`annotationeditorstateschanged`,{source:this,details:Object.assign(this.#I,e)}),this.#j===W.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#ne([[G.HIGHLIGHT_FREE,!0]]))}#ne(e){this._eventBus.dispatch(`annotationeditorparamschanged`,{source:this,details:e})}setEditingState(e){e?(this.#J(),this.#Q(),this.#te({isEditing:this.#j!==W.NONE,isEmpty:this.#se(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#$(),this.#te({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#p){this.#p=e;for(let e of this.#p)this.#ne(e.defaultPropertiesToUpdate)}}getId(){return this.#w.id}get currentLayer(){return this.#r.get(this.#u)}getLayer(e){return this.#r.get(e)}get currentPageIndex(){return this.#u}addLayer(e){this.#r.set(e.pageIndex,e),this.#T?e.enable():e.disable()}removeLayer(e){this.#r.delete(e.pageIndex)}async updateMode(e,t=null,n=!1){if(this.#j!==e&&!(this.#V&&(await this.#V.promise,!this.#V))){if(this.#V=Promise.withResolvers(),this.#j=e,e===W.NONE){this.setEditingState(!1),this.#ie(),this._editorUndoBar?.hide(),this.#V.resolve();return}this.setEditingState(!0),await this.#re(),this.unselectAll();for(let t of this.#r.values())t.updateMode(e);if(!t){n&&this.addNewEditorFromKeyboard(),this.#V.resolve();return}for(let e of this.#n.values())e.annotationElementId===t?(this.setSelected(e),e.enterInEditMode()):e.unselect();this.#V.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e!==this.#j&&this._eventBus.dispatch(`switchannotationeditormode`,{source:this,mode:e})}updateParams(e,t){if(this.#p){switch(e){case G.CREATE:this.currentLayer.addNewEditor();return;case G.HIGHLIGHT_DEFAULT_COLOR:this.#k?.updateColor(t);break;case G.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:{type:`highlight`,action:`toggle_visibility`}}}),(this.#F||=new Map).set(e,t),this.showAllEditors(`highlight`,t)}for(let n of this.#M)n.updateParams(e,t);for(let n of this.#p)n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){for(let n of this.#n.values())n.editorType===e&&n.show(t);(this.#F?.get(G.HIGHLIGHT_SHOW_ALL)??!0)!==t&&this.#ne([[G.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#E!==e){this.#E=e;for(let t of this.#r.values())e?t.disableClick():t.enableClick(),t.div.classList.toggle(`waiting`,e)}}async#re(){if(!this.#T){this.#T=!0;let e=[];for(let t of this.#r.values())e.push(t.enable());await Promise.all(e);for(let e of this.#n.values())e.enable()}}#ie(){if(this.unselectAll(),this.#T){this.#T=!1;for(let e of this.#r.values())e.disable();for(let e of this.#n.values())e.disable()}}getEditors(e){let t=[];for(let n of this.#n.values())n.pageIndex===e&&t.push(n);return t}getEditor(e){return this.#n.get(e)}addEditor(e){this.#n.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.focusMainContainer(),this.#y=null},0)),this.#n.delete(e.id),this.unselect(e),(!e.annotationElementId||!this.#d.has(e.annotationElementId))&&this.#a?.remove(e.id)}addDeletedAnnotationElement(e){this.#d.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#d.has(e)}removeDeletedAnnotationElement(e){this.#d.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#ae(e){let t=this.#r.get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#ne(e.propertiesToUpdate))}get#oe(){let e=null;for(e of this.#M);return e}updateUI(e){this.#oe===e&&this.#ne(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#ne(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#M.has(e)){this.#M.delete(e),e.unselect(),this.#te({hasSelectedEditor:this.hasSelection});return}this.#M.add(e),e.select(),this.#ne(e.propertiesToUpdate),this.#te({hasSelectedEditor:!0})}setSelected(e){this.#l?.commitOrRemove();for(let t of this.#M)t!==e&&t.unselect();this.#M.clear(),this.#M.add(e),e.select(),this.#ne(e.propertiesToUpdate),this.#te({hasSelectedEditor:!0})}isSelected(e){return this.#M.has(e)}get firstSelectedEditor(){return this.#M.values().next().value}unselect(e){e.unselect(),this.#M.delete(e),this.#te({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#M.size!==0}get isEnterHandled(){return this.#M.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#s.undo(),this.#te({hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#se()}),this._editorUndoBar?.hide()}redo(){this.#s.redo(),this.#te({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#se()})}addCommands(e){this.#s.add(e),this.#te({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#se()})}cleanUndoStack(e){this.#s.cleanType(e)}#se(){if(this.#n.size===0)return!0;if(this.#n.size===1)for(let e of this.#n.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#M],n=()=>{this._editorUndoBar?.show(r,t.length===1?t[0].editorType:t.length);for(let e of t)e.remove()},r=()=>{for(let e of t)this.#ae(e)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#ce(e){for(let e of this.#M)e.unselect();this.#M.clear();for(let t of e)t.isEmpty()||(this.#M.add(t),t.select());this.#te({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#M)e.commit();this.#ce(this.#n.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#j!==W.NONE))&&!this.#l?.commitOrRemove()&&this.hasSelection){for(let e of this.#M)e.unselect();this.#M.clear(),this.#te({hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#L[0]+=e,this.#L[1]+=t;let[r,i]=this.#L,a=[...this.#M];this.#R&&clearTimeout(this.#R),this.#R=setTimeout(()=>{this.#R=null,this.#L[0]=this.#L[1]=0,this.addCommands({cmd:()=>{for(let e of a)this.#n.has(e.id)&&e.translateInPage(r,i)},undo:()=>{for(let e of a)this.#n.has(e.id)&&e.translateInPage(-r,-i)},mustExec:!1})},1e3);for(let n of a)n.translateInPage(e,t)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(let e of this.#M)this.#f.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);let e=this.#f;this.#f=null;let t=!1;for(let[{x:n,y:r,pageIndex:i},a]of e)a.newX=n,a.newY=r,a.newPageIndex=i,t||=n!==a.savedX||r!==a.savedY||i!==a.savedPageIndex;if(!t)return!1;let n=(e,t,n,r)=>{if(this.#n.has(e.id)){let i=this.#r.get(r);i?e._setParentAndPosition(i,t,n):(e.pageIndex=r,e.x=t,e.y=n)}};return this.addCommands({cmd:()=>{for(let[t,{newX:r,newY:i,newPageIndex:a}]of e)n(t,r,i,a)},undo:()=>{for(let[t,{savedX:r,savedY:i,savedPageIndex:a}]of e)n(t,r,i,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(this.#f)for(let n of this.#f.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#M.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#j}get imageManager(){return Y(this,`imageManager`,new Xl)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let n=0,r=t.rangeCount;n<r;n++)if(!e.contains(t.getRangeAt(n).commonAncestorContainer))return null;let{x:n,y:r,width:i,height:a}=e.getBoundingClientRect(),o;switch(e.getAttribute(`data-main-rotation`)){case`90`:o=(e,t,o,s)=>({x:(t-r)/a,y:1-(e+o-n)/i,width:s/a,height:o/i});break;case`180`:o=(e,t,o,s)=>({x:1-(e+o-n)/i,y:1-(t+s-r)/a,width:o/i,height:s/a});break;case`270`:o=(e,t,o,s)=>({x:1-(t+s-r)/a,y:(e-n)/i,width:s/a,height:o/i});break;default:o=(e,t,o,s)=>({x:(e-n)/i,y:(t-r)/a,width:o/i,height:s/a})}let s=[];for(let e=0,n=t.rangeCount;e<n;e++){let n=t.getRangeAt(e);if(!n.collapsed)for(let{x:e,y:t,width:r,height:i}of n.getClientRects())r!==0&&i!==0&&s.push(o(e,t,r,i))}return s.length===0?null:s}addChangedExistingAnnotation({annotationElementId:e,id:t}){(this.#o||=new Map).set(e,t)}removeChangedExistingAnnotation({annotationElementId:e}){this.#o?.delete(e)}renderAnnotationElement(e){let t=this.#o?.get(e.data.id);if(!t)return;let n=this.#a.getRawValue(t);n&&(this.#j===W.NONE&&!n.hasBeenModified||n.renderAnnotationElement(e))}},tu=class e{#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=!1;#s=null;#c=null;#l=null;#u=null;#d=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#d=t._uiManager.useNewAltTextFlow,e.#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){e._l10n??=t}async render(){let t=this.#n=document.createElement(`button`);t.className=`altText`,t.tabIndex=`0`;let n=this.#r=document.createElement(`span`);t.append(n),this.#d?(t.classList.add(`new`),t.setAttribute(`data-l10n-id`,e.#f.missing),n.setAttribute(`data-l10n-id`,e.#f[`missing-label`])):(t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-button`),n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-button-label`));let r=this.#c._uiManager._signal;t.addEventListener(`contextmenu`,Ll,{signal:r}),t.addEventListener(`pointerdown`,e=>e.stopPropagation(),{signal:r});let i=e=>{e.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_clicked`,data:{label:this.#p}})};return t.addEventListener(`click`,i,{capture:!0,signal:r}),t.addEventListener(`keydown`,e=>{e.target===t&&e.key===`Enter`&&(this.#o=!0,i(e))},{signal:r}),await this.#m(),t}get#p(){return this.#e&&`added`||this.#e===null&&this.guessedText&&`review`||`missing`}finish(){this.#n&&(this.#n.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#e===null&&(this.#l=t,this.#u=await e._l10n.get(`pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer`,{generatedAltText:t}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let e=this.#s=document.createElement(`div`);e.className=`noAltTextBadge`,this.#c.div.append(e)}this.#s.classList.toggle(`hidden`,!e)}serialize(e){let t=this.#e;return!e&&this.#l===t&&(t=this.#u),{altText:t,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:r,cancel:i=!1}){n&&(this.#l=n,this.#u=r),(this.#e!==e||this.#t!==t)&&(i||(this.#e=e,this.#t=t),this.#m())}toggle(e=!1){this.#n&&(!e&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n.disabled=!e)}shown(){this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_displayed`,data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#r=null,this.#i=null,this.#s?.remove(),this.#s=null}async#m(){let t=this.#n;if(!t)return;if(this.#d){if(t.classList.toggle(`done`,!!this.#e),t.setAttribute(`data-l10n-id`,e.#f[this.#p]),this.#r?.setAttribute(`data-l10n-id`,e.#f[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){t.classList.remove(`done`),this.#i?.remove();return}t.classList.add(`done`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-edit-button`)}let n=this.#i;if(!n){this.#i=n=document.createElement(`span`),n.className=`tooltip`,n.setAttribute(`role`,`tooltip`),n.id=`alt-text-tooltip-${this.#c.id}`;let e=this.#c._uiManager._signal;e.addEventListener(`abort`,()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener(`mouseenter`,()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add(`show`),this.#c._reportTelemetry({action:`alt_text_tooltip`})},100)},{signal:e}),t.addEventListener(`mouseleave`,()=>{this.#a&&=(clearTimeout(this.#a),null),this.#i?.classList.remove(`show`)},{signal:e})}this.#t?n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-decorative-tooltip`):(n.removeAttribute(`data-l10n-id`),n.textContent=this.#e),n.parentNode||t.append(n),this.#c.getImageForAltText()?.setAttribute(`aria-describedby`,n.id)}},nu=class e{#e;#t=!1;#n=null;#r;#i;#a;#o;#s;#c=null;#l;#u=null;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:r=null,onPinching:i=null,onPinchEnd:a=null,signal:o}){this.#e=e,this.#n=n,this.#r=t,this.#i=r,this.#a=i,this.#o=a,this.#l=new AbortController,this.#s=AbortSignal.any([o,this.#l.signal]),e.addEventListener(`touchstart`,this.#d.bind(this),{passive:!1,signal:this.#s})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return Y(this,`MIN_TOUCH_DISTANCE_TO_PINCH`,35/(window.devicePixelRatio||1))}#d(e){if(this.#r?.()||e.touches.length<2)return;if(!this.#u){this.#u=new AbortController;let e=AbortSignal.any([this.#s,this.#u.signal]),t=this.#e,n={signal:e,passive:!1};t.addEventListener(`touchmove`,this.#f.bind(this),n),t.addEventListener(`touchend`,this.#p.bind(this),n),t.addEventListener(`touchcancel`,this.#p.bind(this),n),this.#i?.()}if(Rl(e),e.touches.length!==2||this.#n?.()){this.#c=null;return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),this.#c={touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[n,r]=t.touches;n.identifier>r.identifier&&([n,r]=[r,n]);let{screenX:i,screenY:a}=n,{screenX:o,screenY:s}=r,c=this.#c,{touch0X:l,touch0Y:u,touch1X:d,touch1Y:f}=c,p=d-l,m=f-u,h=o-i,g=s-a,_=Math.hypot(h,g)||1,v=Math.hypot(p,m)||1;if(!this.#t&&Math.abs(v-_)<=e.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=a,c.touch1X=o,c.touch1Y=s,t.preventDefault(),!this.#t){this.#t=!0;return}let y=[(i+o)/2,(a+s)/2];this.#a?.(y,v,_)}#p(e){this.#u.abort(),this.#u=null,this.#o?.(),this.#c&&(e.preventDefault(),this.#c=null,this.#t=!1)}destroy(){this.#l?.abort(),this.#l=null}},Q=class e{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=``;#o=!1;#s=null;#c=null;#l=null;#u=null;#d=``;#f=!1;#p=null;#m=!1;#h=!1;#g=!1;#_=null;#v=0;#y=0;#b=null;#x=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#S=!1;#C=e._zIndex++;static _borderLineWidth=-1;static _colorManager=new $l;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=e.prototype._resizeWithKeyboard,n=eu.TRANSLATE_SMALL,r=eu.TRANSLATE_BIG;return Y(this,`_resizerKeyboardManager`,new Ql([[[`ArrowLeft`,`mac+ArrowLeft`],t,{args:[-n,0]}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t,{args:[-r,0]}],[[`ArrowRight`,`mac+ArrowRight`],t,{args:[n,0]}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t,{args:[r,0]}],[[`ArrowUp`,`mac+ArrowUp`],t,{args:[0,-n]}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t,{args:[0,-r]}],[[`ArrowDown`,`mac+ArrowDown`],t,{args:[0,n]}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t,{args:[0,r]}],[[`Escape`,`mac+Escape`],e.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null;let{rotation:t,rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,r],this.pageTranslation=[i,a];let[o,s]=this.parentDimensions;this.x=e.x/o,this.y=e.y/s,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return Y(this,`_defaultLineColor`,this._colorManager.getHexCode(`CanvasText`))}static deleteAnnotationElement(e){let t=new ru({id:e.parent.getNextId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(t,n){if(e._l10n??=t,e._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`}),e._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);e._borderLineWidth=parseFloat(r.getPropertyValue(`--outline-width`))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){q(`Not implemented`)}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(e){this.#S=e,this.div?.classList.toggle(`draggable`,e)}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#C}setParent(e){e===null?this.#H():(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(e){this._focusEventsAllowed&&this.isAttachedToDOM&&(e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,r){let[i,a]=this.parentDimensions;[n,r]=this.screenToPageTranslation(n,r),this.x=(e+n)/i,this.y=(t+r)/a,this.fixAndSetPosition()}#w([e,t],n,r){[n,r]=this.screenToPageTranslation(n,r),this.x+=n/e,this.y+=r/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#w(this.parentDimensions,e,t)}translateInPage(e,t){this.#p||=[this.x,this.y,this.width,this.height],this.#w(this.pageDimensions,e,t),this.div.scrollIntoView({block:`nearest`})}drag(e,t){this.#p||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[r,i]}=this;if(this.x+=e/r,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:e,y:t}=this.div.getBoundingClientRect();this.parent.findNewParent(this,e,t)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:o}=this,[s,c]=this.getBaseTranslation();a+=s,o+=c;let{style:l}=n;l.left=`${(100*a).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(a,o),n.scrollIntoView({block:`nearest`})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#p&&(this.#p[0]!==this.x||this.#p[1]!==this.y)}get _hasBeenResized(){return!!this.#p&&(this.#p[2]!==this.width||this.#p[3]!==this.height)}getBaseTranslation(){let[t,n]=this.parentDimensions,{_borderLineWidth:r}=e,i=r/t,a=r/n;switch(this.rotation){case 90:return[-i,a];case 180:return[i,a];case 270:return[i,-a];default:return[-i,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,r]}=this,{x:i,y:a,width:o,height:s}=this;if(o*=n,s*=r,i*=n,a*=r,this._mustFixPosition)switch(e){case 0:i=Math.max(0,Math.min(n-o,i)),a=Math.max(0,Math.min(r-s,a));break;case 90:i=Math.max(0,Math.min(n-s,i)),a=Math.min(r,Math.max(o,a));break;case 180:i=Math.min(n,Math.max(o,i)),a=Math.min(r,Math.max(s,a));break;case 270:i=Math.min(n,Math.max(s,i)),a=Math.max(0,Math.min(r-o,a))}this.x=i/=n,this.y=a/=r;let[c,l]=this.getBaseTranslation();i+=c,a+=l,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#T(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(t,n){return e.#T(t,n,this.parentRotation)}pageTranslationToScreen(t,n){return e.#T(t,n,360-this.parentRotation)}#E(e){switch(e){case 90:{let[e,t]=this.pageDimensions;return[0,-e/t,t/e,0]}case 180:return[-1,0,0,-1];case 270:{let[e,t]=this.pageDimensions;return[0,e/t,-t/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(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(e,t){let[n,r]=this.parentDimensions,{style:i}=this.div;i.width=`${(100*e/n).toFixed(2)}%`,this.#o||(i.height=`${(100*t/r).toFixed(2)}%`)}fixDims(){let{style:e}=this.div,{height:t,width:n}=e,r=n.endsWith(`%`),i=!this.#o&&t.endsWith(`%`);if(r&&i)return;let[a,o]=this.parentDimensions;r||(e.width=`${(100*parseFloat(n)/a).toFixed(2)}%`),!this.#o&&!i&&(e.height=`${(100*parseFloat(t)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#D(){if(this.#s)return;this.#s=document.createElement(`div`),this.#s.classList.add(`resizers`);let e=this._willKeepAspectRatio?[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`]:[`topLeft`,`topMiddle`,`topRight`,`middleRight`,`bottomRight`,`bottomMiddle`,`bottomLeft`,`middleLeft`],t=this._uiManager._signal;for(let n of e){let e=document.createElement(`div`);this.#s.append(e),e.classList.add(`resizer`,n),e.setAttribute(`data-resizer-name`,n),e.addEventListener(`pointerdown`,this.#O.bind(this,n),{signal:t}),e.addEventListener(`contextmenu`,Ll,{signal:t}),e.tabIndex=-1}this.div.prepend(this.#s)}#O(e,t){t.preventDefault();let{isMac:n}=_l.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let r=this._isDraggable;this._isDraggable=!1,this.#c=[t.screenX,t.screenY];let i=new AbortController,a=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener(`pointermove`,this.#j.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener(`touchmove`,Rl,{passive:!1,signal:a}),window.addEventListener(`contextmenu`,Ll,{signal:a}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,s=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=r,this.parent.div.style.cursor=o,this.div.style.cursor=s,this.#A()};window.addEventListener(`pointerup`,c,{signal:a}),window.addEventListener(`blur`,c,{signal:a})}#k(e,t,n,r){this.width=n,this.height=r,this.x=e,this.y=t;let[i,a]=this.parentDimensions;this.setDims(i*n,a*r),this.fixAndSetPosition(),this._onResized()}_onResized(){}#A(){if(!this.#l)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:r}=this.#l;this.#l=null;let i=this.x,a=this.y,o=this.width,s=this.height;(i!==e||a!==t||o!==n||s!==r)&&this.addCommands({cmd:this.#k.bind(this,i,a,o,s),undo:this.#k.bind(this,e,t,n,r),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#j(t,n){let[r,i]=this.parentDimensions,a=this.x,o=this.y,s=this.width,c=this.height,l=e.MIN_SIZE/r,u=e.MIN_SIZE/i,d=this.#E(this.rotation),f=(e,t)=>[d[0]*e+d[2]*t,d[1]*e+d[3]*t],p=this.#E(360-this.rotation),m=(e,t)=>[p[0]*e+p[2]*t,p[1]*e+p[3]*t],h,g,_=!1,v=!1;switch(t){case`topLeft`:_=!0,h=(e,t)=>[0,0],g=(e,t)=>[e,t];break;case`topMiddle`:h=(e,t)=>[e/2,0],g=(e,t)=>[e/2,t];break;case`topRight`:_=!0,h=(e,t)=>[e,0],g=(e,t)=>[0,t];break;case`middleRight`:v=!0,h=(e,t)=>[e,t/2],g=(e,t)=>[0,t/2];break;case`bottomRight`:_=!0,h=(e,t)=>[e,t],g=(e,t)=>[0,0];break;case`bottomMiddle`:h=(e,t)=>[e/2,t],g=(e,t)=>[e/2,0];break;case`bottomLeft`:_=!0,h=(e,t)=>[0,t],g=(e,t)=>[e,0];break;case`middleLeft`:v=!0,h=(e,t)=>[0,t/2],g=(e,t)=>[e,t/2]}let y=h(s,c),b=g(s,c),x=f(...b),S=e._round(a+x[0]),C=e._round(o+x[1]),w=1,T=1,E,D;if(n.fromKeyboard)({deltaX:E,deltaY:D}=n);else{let{screenX:e,screenY:t}=n,[r,i]=this.#c;[E,D]=this.screenToPageTranslation(e-r,t-i),this.#c[0]=e,this.#c[1]=t}if([E,D]=m(E/r,D/i),_){let e=Math.hypot(s,c);w=T=Math.max(Math.min(Math.hypot(b[0]-y[0]-E,b[1]-y[1]-D)/e,1/s,1/c),l/s,u/c)}else v?w=Math.max(l,Math.min(1,Math.abs(b[0]-y[0]-E)))/s:T=Math.max(u,Math.min(1,Math.abs(b[1]-y[1]-D)))/c;let O=e._round(s*w),k=e._round(c*T);x=f(...g(O,k));let A=S-x[0],j=C-x[1];this.#p||=[this.x,this.y,this.width,this.height],this.width=O,this.height=k,this.x=A,this.y=j,this.setDims(r*O,i*k),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}async addEditToolbar(){return this._editToolbar||this.#h?this._editToolbar:(this._editToolbar=new Kl(this),this.div.append(this._editToolbar.render()),this.#n&&await this._editToolbar.addAltText(this.#n),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#n?.destroy())}addContainer(e){let t=this._editToolbar?.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#n||(tu.initialize(e._l10n),this.#n=new tu(this),this.#e&&=(this.#n.data=this.#e,null),await this.addEditToolbar())}get altTextData(){return this.#n?.data}set altTextData(e){this.#n&&(this.#n.data=e)}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.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.#r?-1:0,this._isVisible||this.div.classList.add(`hidden`),this.setInForeground(),this.#L();let[e,t]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*t/e).toFixed(2)}%`,this.div.style.maxHeight=`${(100*e/t).toFixed(2)}%`);let[n,r]=this.getInitialTranslation();return this.translate(n,r),Jl(this,this.div,[`pointerdown`]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#x||=new nu({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#M.bind(this),onPinching:this.#N.bind(this),onPinchEnd:this.#P.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#M(){this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#N(t,n,r){let i=.7,a=r/n*i+1-i;if(a===1)return;let o=this.#E(this.rotation),s=(e,t)=>[o[0]*e+o[2]*t,o[1]*e+o[3]*t],[c,l]=this.parentDimensions,u=this.x,d=this.y,f=this.width,p=this.height,m=e.MIN_SIZE/c,h=e.MIN_SIZE/l;a=Math.max(Math.min(a,1/f,1/p),m/f,h/p);let g=e._round(f*a),_=e._round(p*a);if(g===f&&_===p)return;this.#p||=[u,d,f,p];let v=s(f/2,p/2),y=e._round(u+v[0]),b=e._round(d+v[1]),x=s(g/2,_/2);this.x=y-x[0],this.y=b-x[1],this.width=g,this.height=_,this.setDims(c*g,l*_),this.fixAndSetPosition(),this._onResizing()}#P(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#A()}pointerdown(e){let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#I(e);return}this.#F(e)}get isSelected(){return this._uiManager.isSelected(this)}#F(e){let{isMac:t}=_l.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)}#I(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,r=new AbortController,i=this._uiManager.combinedSignal(r),a={capture:!0,passive:!1,signal:i},o=e=>{r.abort(),this.#i=null,this.#f=!1,this._uiManager.endDragSession()||this.#F(e),n&&this._onStopDragging()};t&&(this.#v=e.clientX,this.#y=e.clientY,this.#i=e.pointerId,this.#a=e.pointerType,window.addEventListener(`pointermove`,e=>{n||(n=!0,this._onStartDragging());let{clientX:t,clientY:r,pointerId:i}=e;if(i!==this.#i){Rl(e);return}let[a,o]=this.screenToPageTranslation(t-this.#v,r-this.#y);this.#v=t,this.#y=r,this._uiManager.dragSelectedEditors(a,o)},a),window.addEventListener(`touchmove`,Rl,a),window.addEventListener(`pointerdown`,e=>{e.pointerType===this.#a&&(this.#x||e.isPrimary)&&o(e),Rl(e)},a));let s=e=>{if(!this.#i||this.#i===e.pointerId){o(e);return}Rl(e)};window.addEventListener(`pointerup`,s,{signal:i}),window.addEventListener(`blur`,s,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#_&&clearTimeout(this.#_),this.#_=setTimeout(()=>{this.#_=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let r=this.parentScale,[i,a]=this.pageDimensions,[o,s]=this.pageTranslation,c=e/r,l=t/r,u=this.x*i,d=this.y*a,f=this.width*i,p=this.height*a;switch(n){case 0:return[u+c+o,a-d-l-p+s,u+c+f+o,a-d-l+s];case 90:return[u+l+o,a-d+c+s,u+l+p+o,a-d+c+f+s];case 180:return[u-c-f+o,a-d+l+s,u-c+o,a-d+l+p+s];case 270:return[u-l-p+o,a-d-c-f+s,u-l+o,a-d-c+s];default:throw Error(`Invalid rotation`)}}getRectInCurrentCoords(e,t){let[n,r,i,a]=e,o=i-n,s=a-r;switch(this.rotation){case 0:return[n,t-a,o,s];case 90:return[n,t-r,s,o];case 180:return[i,t-r,o,s];case 270:return[i,t-a,s,o];default:throw Error(`Invalid rotation`)}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){this.#h=!0}disableEditMode(){this.#h=!1}isInEditMode(){return this.#h}shouldGetKeyboardEvents(){return this.#g}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:r}=this.getClientDimensions(),{innerHeight:i,innerWidth:a}=window;return t<a&&r>0&&e<i&&n>0}#L(){if(this.#u||!this.div)return;this.#u=new AbortController;let e=this._uiManager.combinedSignal(this.#u);this.div.addEventListener(`focusin`,this.focusin.bind(this),{signal:e}),this.div.addEventListener(`focusout`,this.focusout.bind(this),{signal:e})}rebuild(){this.#L()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||``}}serialize(e=!1,t=null){q(`An editor must be serializable`)}static async deserialize(e,t,n){let r=new this.prototype.constructor({parent:t,id:t.getNextId(),uiManager:n});r.rotation=e.rotation,r.#e=e.accessibilityData;let[i,a]=r.pageDimensions,[o,s,c,l]=r.getRectInCurrentCoords(e.rect,a);return r.x=o/i,r.y=s/a,r.width=c/i,r.height=l/a,r}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#u?.abort(),this.#u=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#_&&=(clearTimeout(this.#_),null),this.#H(),this.removeEditToolbar(),this.#b){for(let e of this.#b.values())clearTimeout(e);this.#b=null}this.parent=null,this.#x?.destroy(),this.#x=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#D(),this.#s.classList.remove(`hidden`),Jl(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.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#s.children;if(!this.#t){this.#t=Array.from(n);let t=this.#R.bind(this),r=this.#z.bind(this),i=this._uiManager._signal;for(let n of this.#t){let a=n.getAttribute(`data-resizer-name`);n.setAttribute(`role`,`spinbutton`),n.addEventListener(`keydown`,t,{signal:i}),n.addEventListener(`blur`,r,{signal:i}),n.addEventListener(`focus`,this.#B.bind(this,a),{signal:i}),n.setAttribute(`data-l10n-id`,e._l10nResizer[a])}}let r=this.#t[0],i=0;for(let e of n){if(e===r)break;i++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(a!==i){if(a<i)for(let e=0;e<i-a;e++)this.#s.append(this.#s.firstChild);else if(a>i)for(let e=0;e<a-i;e++)this.#s.firstChild.before(this.#s.lastChild);let t=0;for(let r of n){let n=this.#t[t++].getAttribute(`data-resizer-name`);r.setAttribute(`data-l10n-id`,e._l10nResizer[n])}}this.#V(0),this.#g=!0,this.#s.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#R(t){e._resizerKeyboardManager.exec(this,t)}#z(e){this.#g&&e.relatedTarget?.parentNode!==this.#s&&this.#H()}#B(e){this.#d=this.#g?e:``}#V(e){if(this.#t)for(let t of this.#t)t.tabIndex=e}_resizeWithKeyboard(e,t){this.#g&&this.#j(this.#d,{deltaX:e,deltaY:t,fromKeyboard:!0})}#H(){this.#g=!1,this.#V(-1),this.#A()}_stopResizingWithKeyboard(){this.#H(),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.#n?.toggleAltTextBadge(!1)}unselect(){this.#s?.classList.add(`hidden`),this.div?.classList.remove(`selectedEditor`),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0)}updateParams(e,t){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#m}set isEditing(e){this.#m=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(e,t){this.#o=!0;let n=e/t,{style:r}=this.div;r.aspectRatio=n,r.height=`auto`}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:`added`}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){this.#b||=new Map;let{action:n}=t,r=this.#b.get(n);r&&clearTimeout(r),r=setTimeout(()=>{this._reportTelemetry(t),this.#b.delete(n),this.#b.size===0&&(this.#b=null)},e._telemetryTimeout),this.#b.set(n,r);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:t}})}show(e=this._isVisible){this.div.classList.toggle(`hidden`,!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#r=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#r=!0}renderAnnotationElement(e){let t=e.container.querySelector(`.annotationContent`);if(!t)t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.container.prepend(t);else if(t.nodeName===`CANVAS`){let e=t;t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.before(t)}return t}resetAnnotationElement(e){let{firstChild:t}=e.container;t?.nodeName===`DIV`&&t.classList.contains(`annotationContent`)&&t.remove()}},ru=class extends Q{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},iu=3285377520,au=4294901760,ou=65535,su=class{constructor(e){this.h1=e?e&4294967295:iu,this.h2=e?e&4294967295:iu}update(e){let t,n;if(typeof e==`string`){t=new Uint8Array(e.length*2),n=0;for(let r=0,i=e.length;r<i;r++){let i=e.charCodeAt(r);i<=255?t[n++]=i:(t[n++]=i>>>8,t[n++]=i&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error(`Invalid data format, must be a string or TypedArray.`);let r=n>>2,i=n-r*4,a=new Uint32Array(t.buffer,0,r),o=0,s=0,c=this.h1,l=this.h2,u=3432918353,d=461845907,f=11601,p=13715;for(let e=0;e<r;e++)e&1?(o=a[e],o=o*u&au|o*f&ou,o=o<<15|o>>>17,o=o*d&au|o*p&ou,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(s=a[e],s=s*u&au|s*f&ou,s=s<<15|s>>>17,s=s*d&au|s*p&ou,l^=s,l=l<<13|l>>>19,l=l*5+3864292196);switch(o=0,i){case 3:o^=t[r*4+2]<<16;case 2:o^=t[r*4+1]<<8;case 1:o^=t[r*4],o=o*u&au|o*f&ou,o=o<<15|o>>>17,o=o*d&au|o*p&ou,r&1?c^=o:l^=o}this.h1=c,this.h2=l}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&au|e*36045&ou,t=t*4283543511&au|((t<<16|e>>>16)*2950163797&au)>>>16,e^=t>>>1,e=e*444984403&au|e*60499&ou,t=t*3301882366&au|((t<<16|e>>>16)*3120437893&au)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}},cu=Object.freeze({map:null,hash:``,transfer:void 0}),lu=class{#e=!1;#t=null;#n=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(e,t){let n=this.#n.get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return this.#n.get(e)}remove(e){if(this.#n.delete(e),this.#n.size===0&&this.resetModified(),typeof this.onAnnotationEditor==`function`){for(let e of this.#n.values())if(e instanceof Q)return;this.onAnnotationEditor(null)}}setValue(e,t){let n=this.#n.get(e),r=!1;if(n!==void 0)for(let[e,i]of Object.entries(t))n[e]!==i&&(r=!0,n[e]=i);else r=!0,this.#n.set(e,t);r&&this.#r(),t instanceof Q&&typeof this.onAnnotationEditor==`function`&&this.onAnnotationEditor(t.constructor._type)}has(e){return this.#n.has(e)}getAll(){return this.#n.size>0?ml(this.#n):null}setAll(e){for(let[t,n]of Object.entries(e))this.setValue(t,n)}get size(){return this.#n.size}#r(){this.#e||(this.#e=!0,typeof this.onSetModified==`function`&&this.onSetModified())}resetModified(){this.#e&&(this.#e=!1,typeof this.onResetModified==`function`&&this.onResetModified())}get print(){return new uu(this)}get serializable(){if(this.#n.size===0)return cu;let e=new Map,t=new su,n=[],r=Object.create(null),i=!1;for(let[n,a]of this.#n){let o=a instanceof Q?a.serialize(!1,r):a;o&&(e.set(n,o),t.update(`${n}:${JSON.stringify(o)}`),i||=!!o.bitmap)}if(i)for(let t of e.values())t.bitmap&&n.push(t.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:cu}get editorStats(){let e=null,t=new Map;for(let n of this.#n.values()){if(!(n instanceof Q))continue;let r=n.telemetryFinalData;if(!r)continue;let{type:i}=r;t.has(i)||t.set(i,Object.getPrototypeOf(n).constructor),e||=Object.create(null);let a=e[i]||=new Map;for(let[e,t]of Object.entries(r)){if(e===`type`)continue;let n=a.get(e);n||(n=new Map,a.set(e,n));let r=n.get(t)??0;n.set(t,r+1)}}for(let[n,r]of t)e[n]=r.computeTelemetryFinalData(e[n]);return e}resetModifiedIds(){this.#t=null}get modifiedIds(){if(this.#t)return this.#t;let e=[];for(let t of this.#n.values())!(t instanceof Q)||!t.annotationElementId||!t.serialize()||e.push(t.annotationElementId);return this.#t={ids:new Set(e),hash:e.join(`,`)}}},uu=class extends lu{#e;constructor(e){super();let{map:t,hash:n,transfer:r}=e.serializable,i=structuredClone(t,r?{transfer:r}:null);this.#e={map:i,hash:n,transfer:r}}get print(){q(`Should not call PrintAnnotationStorage.print`)}get serializable(){return this.#e}get modifiedIds(){return Y(this,`modifiedIds`,{ids:new Set,hash:``})}},du=class{#e=new Set;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement(`style`),this._document.documentElement.getElementsByTagName(`head`)[0].append(this.styleElement));let t=this.styleElement.sheet;t.insertRule(e,t.cssRules.length)}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),this.#e.clear(),this.styleElement&&=(this.styleElement.remove(),null)}async loadSystemFont({systemFontInfo:e,_inspectFont:t}){if(!(!e||this.#e.has(e.loadedName))){if(J(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:n,src:r,style:i}=e,a=new FontFace(n,r,i);this.addNativeFontFace(a);try{await a.load(),this.#e.add(n),t?.(e)}catch{K(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}q(`Not implemented: loadSystemFont without the Font Loading API.`)}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let t=e.createNativeFontFace();if(t){this.addNativeFontFace(t);try{await t.loaded}catch(n){throw K(`Failed to load font '${t.family}': '${n}'.`),e.disableFontFace=!0,n}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(t=>{let n=this._queueLoadingCallback(t);this._prepareFontLoadEvent(e,n)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return Y(this,`isFontLoadingAPISupported`,e)}get isSyncFontLoadingSupported(){let e=!1;return(Fc||typeof navigator<`u`&&typeof navigator?.userAgent==`string`&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(e=!0),Y(this,`isSyncFontLoadingSupported`,e)}_queueLoadingCallback(e){function t(){for(J(!r.done,`completeRequest() cannot be called twice.`),r.done=!0;n.length>0&&n[0].done;){let e=n.shift();setTimeout(e.callback,0)}}let{loadingRequests:n}=this,r={done:!1,complete:t,callback:e};return n.push(r),r}get _loadTestFont(){let e=atob(`T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==`);return Y(this,`_loadTestFont`,e)}_prepareFontLoadEvent(e,t){function n(e,t){return e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3)&255}function r(e,t,n,r){let i=e.substring(0,t),a=e.substring(t+n);return i+r+a}let i,a,o=this._document.createElement(`canvas`);o.width=1,o.height=1;let s=o.getContext(`2d`),c=0;function l(e,t){if(++c>30){K(`Load test font never loaded.`),t();return}if(s.font=`30px `+e,s.fillText(`.`,0,20),s.getImageData(0,0,1,1).data[3]>0){t();return}setTimeout(l.bind(null,e,t))}let u=`lt${Date.now()}${this.loadTestFontId++}`,d=this._loadTestFont;d=r(d,976,u.length,u);let f=1482184792,p=n(d,16);for(i=0,a=u.length-3;i<a;i+=4)p=p-f+n(u,i)|0;i<u.length&&(p=p-f+n(u+`XXX`,i)|0),d=r(d,16,4,pl(p));let m=`@font-face {font-family:"${u}";src:${`url(data:font/opentype;base64,${btoa(d)});`}}`;this.insertRule(m);let h=this._document.createElement(`div`);h.style.visibility=`hidden`,h.style.width=h.style.height=`10px`,h.style.position=`absolute`,h.style.top=h.style.left=`0px`;for(let t of[e.loadedName,u]){let e=this._document.createElement(`span`);e.textContent=`Hi`,e.style.fontFamily=t,h.append(e)}this._document.body.append(h),l(u,()=>{h.remove(),t.complete()})}},fu=class{constructor(e,{disableFontFace:t=!1,fontExtraProperties:n=!1,inspectFont:r=null}){this.compiledGlyphs=Object.create(null);for(let t in e)this[t]=e[t];this.disableFontFace=t===!0,this.fontExtraProperties=n===!0,this._inspectFont=r}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(t.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${Tl(this.data)});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+`_path_`+t,r;try{r=e.get(n)}catch(e){K(`getPathGenerator - ignoring character: "${e}".`)}let i=new Path2D(r||``);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=i}},pu={DATA:1,ERROR:2},mu={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function hu(){}function gu(e){if(e instanceof ul||e instanceof ol||e instanceof sl||e instanceof il||e instanceof cl||e instanceof al)return e;switch(e instanceof Error||typeof e==`object`&&e||q(`wrapReason: Expected "reason" to be a (possibly cloned) Error.`),e.name){case`AbortException`:return new ul(e.message);case`InvalidPDFException`:return new ol(e.message);case`MissingPDFException`:return new sl(e.message);case`PasswordException`:return new il(e.message,e.code);case`UnexpectedResponseException`:return new cl(e.message,e.status);case`UnknownErrorException`:return new al(e.message,e.details)}return new al(e.message,e.toString())}var _u=class{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,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),n.addEventListener(`message`,this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#r(e);return}if(e.callback){let t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===pu.DATA)n.resolve(e.data);else if(e.callback===pu.ERROR)n.reject(gu(e.reason));else throw Error(`Unexpected callback case`);return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:n,targetName:r,callback:pu.DATA,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:n,targetName:r,callback:pu.ERROR,callbackId:e.callbackId,reason:gu(t)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},n)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,n,r){let i=this.streamId++,a=this.sourceName,o=this.targetName,s=this.comObj;return new ReadableStream({start:n=>{let c=Promise.withResolvers();return this.streamControllers[i]={controller:n,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},s.postMessage({sourceName:a,targetName:o,action:e,streamId:i,data:t,desiredSize:n.desiredSize},r),c.promise},pull:e=>{let t=Promise.withResolvers();return this.streamControllers[i].pullCall=t,s.postMessage({sourceName:a,targetName:o,stream:mu.PULL,streamId:i,desiredSize:e.desiredSize}),t.promise},cancel:e=>{J(e instanceof Error,`cancel must have a valid reason`);let t=Promise.withResolvers();return this.streamControllers[i].cancelCall=t,this.streamControllers[i].isClosed=!0,s.postMessage({sourceName:a,targetName:o,stream:mu.CANCEL,streamId:i,reason:gu(e)}),t.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this,o=this.actionHandler[e.action],s={enqueue(e,a=1,o){if(this.isCancelled)return;let s=this.desiredSize;this.desiredSize-=a,s>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:n,targetName:r,stream:mu.ENQUEUE,streamId:t,chunk:e},o)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:mu.CLOSE,streamId:t}),delete a.streamSinks[t])},error(e){J(e instanceof Error,`error must have a valid reason`),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:mu.ERROR,streamId:t,reason:gu(e)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};s.sinkCapability.resolve(),s.ready=s.sinkCapability.promise,this.streamSinks[t]=s,Promise.try(o,e.data,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.START_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.START_COMPLETE,streamId:t,reason:gu(e)})})}#r(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case mu.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(gu(e.reason));break;case mu.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(gu(e.reason));break;case mu.PULL:if(!o){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,success:!0});break}o.desiredSize<=0&&e.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=e.desiredSize,Promise.try(o.onPull||hu).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,reason:gu(e)})});break;case mu.ENQUEUE:if(J(a,`enqueue should have stream controller`),a.isClosed)break;a.controller.enqueue(e.chunk);break;case mu.CLOSE:if(J(a,`close should have stream controller`),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#i(a,t);break;case mu.ERROR:J(a,`error should have stream controller`),a.controller.error(gu(e.reason)),this.#i(a,t);break;case mu.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(gu(e.reason)),this.#i(a,t);break;case mu.CANCEL:if(!o)break;let s=gu(e.reason);Promise.try(o.onCancel||hu,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.CANCEL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.CANCEL_COMPLETE,streamId:t,reason:gu(e)})}),o.sinkCapability.reject(s),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error(`Unexpected stream case`)}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}},vu=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error(`Invalid canvas size`);let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset(e,t,n){if(!e.canvas)throw Error(`Canvas is not specified`);if(t<=0||n<=0)throw Error(`Invalid canvas size`);e.canvas.width=t,e.canvas.height=n}destroy(e){if(!e.canvas)throw Error(`Canvas is not specified`);e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){q("Abstract method `_createCanvas` called.")}},yu=class extends vu{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},bu=class{constructor({baseUrl:e=null,isCompressed:t=!0}){this.baseUrl=e,this.isCompressed=t}async fetch({name:e}){if(!this.baseUrl)throw Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!e)throw Error(`CMap name must be specified.`);let t=this.baseUrl+e+(this.isCompressed?`.bcmap`:``);return this._fetch(t).then(e=>({cMapData:e,isCompressed:this.isCompressed})).catch(e=>{throw Error(`Unable to load ${this.isCompressed?`binary `:``}CMap at: ${t}`)})}async _fetch(e){q("Abstract method `_fetch` called.")}},xu=class extends bu{async _fetch(e){let t=await Ol(e,this.isCompressed?`arraybuffer`:`text`);return t instanceof ArrayBuffer?new Uint8Array(t):fl(t)}},Su=class{addFilter(e){return`none`}addHCMFilter(e,t){return`none`}addAlphaFilter(e){return`none`}addLuminosityFilter(e){return`none`}addHighlightHCMFilter(e,t,n,r,i){return`none`}destroy(e=!1){}},Cu=class extends Su{#e;#t;#n;#r;#i;#a;#o=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super(),this.#r=e,this.#i=t}get#s(){return this.#t||=new Map}get#c(){return this.#a||=new Map}get#l(){if(!this.#n){let e=this.#i.createElement(`div`),{style:t}=e;t.visibility=`hidden`,t.contain=`strict`,t.width=t.height=0,t.position=`absolute`,t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS(El,`svg`);n.setAttribute(`width`,0),n.setAttribute(`height`,0),this.#n=this.#i.createElementNS(El,`defs`),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let t=e[0],n=Array(256);for(let e=0;e<256;e++)n[e]=t[e]/255;let r=n.join(`,`);return[r,r,r]}let[t,n,r]=e,i=Array(256),a=Array(256),o=Array(256);for(let e=0;e<256;e++)i[e]=t[e]/255,a[e]=n[e]/255,o[e]=r[e]/255;return[i.join(`,`),a.join(`,`),o.join(`,`)]}#d(e){if(this.#e===void 0){this.#e=``;let e=this.#i.URL;e!==this.#i.baseURI&&(jl(e)?K(`#createUrl: ignore "data:"-URL for performance reasons.`):this.#e=e.split(`#`,1)[0])}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return`none`;let t=this.#s.get(e);if(t)return t;let[n,r,i]=this.#u(e),a=e.length===1?n:`${n}${r}${i}`;if(t=this.#s.get(a),t)return this.#s.set(e,t),t;let o=`g_${this.#r}_transfer_map_${this.#o++}`,s=this.#d(o);this.#s.set(e,s),this.#s.set(a,s);let c=this.#m(o);return this.#g(n,r,i,c),s}addHCMFilter(e,t){let n=`${e}-${t}`,r=`base`,i=this.#c.get(r);if(i?.key===n||(i?(i.filter?.remove(),i.key=n,i.url=`none`,i.filter=null):(i={key:n,url:`none`,filter:null},this.#c.set(r,i)),!e||!t))return i.url;let a=this.#v(e);e=X.makeHexColor(...a);let o=this.#v(t);if(t=X.makeHexColor(...o),this.#l.style.color=``,e===`#000000`&&t===`#ffffff`||e===t)return i.url;let s=Array(256);for(let e=0;e<=255;e++){let t=e/255;s[e]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}let c=s.join(`,`),l=`g_${this.#r}_hcm_filter`,u=i.filter=this.#m(l);this.#g(c,c,c,u),this.#p(u);let d=(e,t)=>{let n=a[e]/255,r=o[e]/255,i=Array(t+1);for(let e=0;e<=t;e++)i[e]=n+e/t*(r-n);return i.join(`,`)};return this.#g(d(0,5),d(1,5),d(2,5),u),i.url=this.#d(l),i.url}addAlphaFilter(e){let t=this.#s.get(e);if(t)return t;let[n]=this.#u([e]),r=`alpha_${n}`;if(t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_alpha_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#_(n,o),a}addLuminosityFilter(e){let t=this.#s.get(e||`luminosity`);if(t)return t;let n,r;if(e?([n]=this.#u([e]),r=`luminosity_${n}`):r=`luminosity`,t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_luminosity_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#f(o),e&&this.#_(n,o),a}addHighlightHCMFilter(e,t,n,r,i){let a=`${t}-${n}-${r}-${i}`,o=this.#c.get(e);if(o?.key===a||(o?(o.filter?.remove(),o.key=a,o.url=`none`,o.filter=null):(o={key:a,url:`none`,filter:null},this.#c.set(e,o)),!t||!n))return o.url;let[s,c]=[t,n].map(this.#v.bind(this)),l=Math.round(.2126*s[0]+.7152*s[1]+.0722*s[2]),u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[d,f]=[r,i].map(this.#v.bind(this));u<l&&([l,u,d,f]=[u,l,f,d]),this.#l.style.color=``;let p=(e,t,n)=>{let r=Array(256),i=(u-l)/n,a=e/255,o=(t-e)/(255*n),s=0;for(let e=0;e<=n;e++){let t=Math.round(l+e*i),n=a+e*o;for(let e=s;e<=t;e++)r[e]=n;s=t+1}for(let e=s;e<256;e++)r[e]=r[s-1];return r.join(`,`)},m=`g_${this.#r}_hcm_${e}_filter`,h=o.filter=this.#m(m);return this.#p(h),this.#g(p(d[0],f[0],5),p(d[1],f[1],5),p(d[2],f[2],5),h),o.url=this.#d(m),o.url}destroy(e=!1){e&&this.#a?.size||(this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#o=0)}#f(e){let t=this.#i.createElementNS(El,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.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(t)}#p(e){let t=this.#i.createElementNS(El,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.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(t)}#m(e){let t=this.#i.createElementNS(El,`filter`);return t.setAttribute(`color-interpolation-filters`,`sRGB`),t.setAttribute(`id`,e),this.#l.append(t),t}#h(e,t,n){let r=this.#i.createElementNS(El,t);r.setAttribute(`type`,`discrete`),r.setAttribute(`tableValues`,n),e.append(r)}#g(e,t,n,r){let i=this.#i.createElementNS(El,`feComponentTransfer`);r.append(i),this.#h(i,`feFuncR`,e),this.#h(i,`feFuncG`,t),this.#h(i,`feFuncB`,n)}#_(e,t){let n=this.#i.createElementNS(El,`feComponentTransfer`);t.append(n),this.#h(n,`feFuncA`,e)}#v(e){return this.#l.style.color=e,Vl(getComputedStyle(this.#l).getPropertyValue(`color`))}},wu=class{constructor({baseUrl:e=null}){this.baseUrl=e}async fetch({filename:e}){if(!this.baseUrl)throw Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!e)throw Error(`Font filename must be specified.`);let t=`${this.baseUrl}${e}`;return this._fetch(t).catch(e=>{throw Error(`Unable to load font data at: ${t}`)})}async _fetch(e){q("Abstract method `_fetch` called.")}},Tu=class extends wu{async _fetch(e){let t=await Ol(e,`arraybuffer`);return new Uint8Array(t)}};Fc&&K("Please use the `legacy` build in Node.js environments.");async function Eu(e){let t=await process.getBuiltinModule(`fs`).promises.readFile(e);return new Uint8Array(t)}var Du=class extends Su{},Ou=class extends vu{_createCanvas(e,t){return process.getBuiltinModule(`module`).createRequire({}.url)(`@napi-rs/canvas`).createCanvas(e,t)}},ku=class extends bu{async _fetch(e){return Eu(e)}},Au=class extends wu{async _fetch(e){return Eu(e)}},ju={FILL:`Fill`,STROKE:`Stroke`,SHADING:`Shading`};function Mu(e,t){if(!t)return;let n=t[2]-t[0],r=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],n,r),e.clip(i)}var Nu=class{getPattern(){q("Abstract method `getPattern` called.")}},Pu=class extends Nu{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}_createGradient(e){let t;this._type===`axial`?t=e.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type===`radial`&&(t=e.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let e of this._colorStops)t.addColorStop(e[0],e[1]);return t}getPattern(e,t,n,r){let i;if(r===ju.STROKE||r===ju.FILL){let a=t.current.getClippedPathBoundingBox(r,Z(e))||[0,0,0,0],o=Math.ceil(a[2]-a[0])||1,s=Math.ceil(a[3]-a[1])||1,c=t.cachedCanvases.getCanvas(`pattern`,o,s),l=c.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-a[0],-a[1]),n=X.transform(n,[1,0,0,1,a[0],a[1]]),l.transform(...t.baseTransform),this.matrix&&l.transform(...this.matrix),Mu(l,this._bbox),l.fillStyle=this._createGradient(l),l.fill(),i=e.createPattern(c.canvas,`no-repeat`);let u=new DOMMatrix(n);i.setTransform(u)}else Mu(e,this._bbox),i=this._createGradient(e);return i}};function Fu(e,t,n,r,i,a,o,s){let c=t.coords,l=t.colors,u=e.data,d=e.width*4,f;c[n+1]>c[r+1]&&(f=n,n=r,r=f,f=a,a=o,o=f),c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=s,s=f),c[n+1]>c[r+1]&&(f=n,n=r,r=f,f=a,a=o,o=f);let p=(c[n]+t.offsetX)*t.scaleX,m=(c[n+1]+t.offsetY)*t.scaleY,h=(c[r]+t.offsetX)*t.scaleX,g=(c[r+1]+t.offsetY)*t.scaleY,_=(c[i]+t.offsetX)*t.scaleX,v=(c[i+1]+t.offsetY)*t.scaleY;if(m>=v)return;let y=l[a],b=l[a+1],x=l[a+2],S=l[o],C=l[o+1],w=l[o+2],T=l[s],E=l[s+1],D=l[s+2],O=Math.round(m),k=Math.round(v),A,j,M,ee,N,P,F,I;for(let e=O;e<=k;e++){if(e<g){let t=e<m?0:(m-e)/(m-g);A=p-(p-h)*t,j=y-(y-S)*t,M=b-(b-C)*t,ee=x-(x-w)*t}else{let t;t=e>v?1:g===v?0:(g-e)/(g-v),A=h-(h-_)*t,j=S-(S-T)*t,M=C-(C-E)*t,ee=w-(w-D)*t}let t;t=e<m?0:e>v?1:(m-e)/(m-v),N=p-(p-_)*t,P=y-(y-T)*t,F=b-(b-E)*t,I=x-(x-D)*t;let n=Math.round(Math.min(A,N)),r=Math.round(Math.max(A,N)),i=d*e+n*4;for(let e=n;e<=r;e++)t=(A-e)/(A-N),t<0?t=0:t>1&&(t=1),u[i++]=j-(j-P)*t|0,u[i++]=M-(M-F)*t|0,u[i++]=ee-(ee-I)*t|0,u[i++]=255}}function Iu(e,t,n){let r=t.coords,i=t.colors,a,o;switch(t.type){case`lattice`:let s=t.verticesPerRow,c=Math.floor(r.length/s)-1,l=s-1;for(a=0;a<c;a++){let t=a*s;for(let a=0;a<l;a++,t++)Fu(e,n,r[t],r[t+1],r[t+s],i[t],i[t+1],i[t+s]),Fu(e,n,r[t+s+1],r[t+1],r[t+s],i[t+s+1],i[t+1],i[t+s])}break;case`triangles`:for(a=0,o=r.length;a<o;a+=3)Fu(e,n,r[a],r[a+1],r[a+2],i[a],i[a+1],i[a+2]);break;default:throw Error(`illegal figure`)}}var Lu=class extends Nu{constructor(e){super(),this._coords=e[2],this._colors=e[3],this._figures=e[4],this._bounds=e[5],this._bbox=e[7],this._background=e[8],this.matrix=null}_createMeshCanvas(e,t,n){let r=1.1,i=3e3,a=Math.floor(this._bounds[0]),o=Math.floor(this._bounds[1]),s=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-o,l=Math.min(Math.ceil(Math.abs(s*e[0]*r)),i),u=Math.min(Math.ceil(Math.abs(c*e[1]*r)),i),d=s/l,f=c/u,p={coords:this._coords,colors:this._colors,offsetX:-a,offsetY:-o,scaleX:1/d,scaleY:1/f},m=l+4,h=u+4,g=n.getCanvas(`mesh`,m,h),_=g.context,v=_.createImageData(l,u);if(t){let e=v.data;for(let n=0,r=e.length;n<r;n+=4)e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=255}for(let e of this._figures)Iu(v,e,p);return _.putImageData(v,2,2),{canvas:g.canvas,offsetX:a-2*d,offsetY:o-2*f,scaleX:d,scaleY:f}}getPattern(e,t,n,r){Mu(e,this._bbox);let i;if(r===ju.SHADING)i=X.singularValueDecompose2dScale(Z(e));else if(i=X.singularValueDecompose2dScale(t.baseTransform),this.matrix){let e=X.singularValueDecompose2dScale(this.matrix);i=[i[0]*e[0],i[1]*e[1]]}let a=this._createMeshCanvas(i,r===ju.SHADING?null:this._background,t.cachedCanvases);return r!==ju.SHADING&&(e.setTransform(...t.baseTransform),this.matrix&&e.transform(...this.matrix)),e.translate(a.offsetX,a.offsetY),e.scale(a.scaleX,a.scaleY),e.createPattern(a.canvas,`no-repeat`)}},Ru=class extends Nu{getPattern(){return`hotpink`}};function zu(e){switch(e[0]){case`RadialAxial`:return new Pu(e);case`Mesh`:return new Lu(e);case`Dummy`:return new Ru}throw Error(`Unknown IR type: ${e[0]}`)}var Bu={COLORED:1,UNCOLORED:2},Vu=class e{static MAX_PATTERN_SIZE=3e3;constructor(e,t,n,r,i){this.operatorList=e[2],this.matrix=e[3],this.bbox=e[4],this.xstep=e[5],this.ystep=e[6],this.paintType=e[7],this.tilingType=e[8],this.color=t,this.ctx=n,this.canvasGraphicsFactory=r,this.baseTransform=i}createPatternCanvas(e){let{bbox:t,operatorList:n,paintType:r,tilingType:i,color:a,canvasGraphicsFactory:o}=this,{xstep:s,ystep:c}=this;s=Math.abs(s),c=Math.abs(c),el(`TilingType: `+i);let l=t[0],u=t[1],d=t[2],f=t[3],p=d-l,m=f-u,h=X.singularValueDecompose2dScale(this.matrix),g=X.singularValueDecompose2dScale(this.baseTransform),_=h[0]*g[0],v=h[1]*g[1],y=p,b=m,x=!1,S=!1,C=Math.ceil(s*_),w=Math.ceil(c*v),T=Math.ceil(p*_),E=Math.ceil(m*v);C>=T?y=s:x=!0,w>=E?b=c:S=!0;let D=this.getSizeAndScale(y,this.ctx.canvas.width,_),O=this.getSizeAndScale(b,this.ctx.canvas.height,v),k=e.cachedCanvases.getCanvas(`pattern`,D.size,O.size),A=k.context,j=o.createCanvasGraphics(A);if(j.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(j,r,a),A.translate(-D.scale*l,-O.scale*u),j.transform(D.scale,0,0,O.scale,0,0),A.save(),this.clipBbox(j,l,u,d,f),j.baseTransform=Z(j.ctx),j.executeOperatorList(n),j.endDrawing(),A.restore(),x||S){let t=k.canvas;x&&(y=s),S&&(b=c);let n=this.getSizeAndScale(y,this.ctx.canvas.width,_),r=this.getSizeAndScale(b,this.ctx.canvas.height,v),i=n.size,a=r.size,o=e.cachedCanvases.getCanvas(`pattern-workaround`,i,a),d=o.context,f=x?Math.floor(p/s):0,h=S?Math.floor(m/c):0;for(let e=0;e<=f;e++)for(let n=0;n<=h;n++)d.drawImage(t,i*e,a*n,i,a,0,0,i,a);return{canvas:o.canvas,scaleX:n.scale,scaleY:r.scale,offsetX:l,offsetY:u}}return{canvas:k.canvas,scaleX:D.scale,scaleY:O.scale,offsetX:l,offsetY:u}}getSizeAndScale(t,n,r){let i=Math.max(e.MAX_PATTERN_SIZE,n),a=Math.ceil(t*r);return a>=i?a=i:r=a/t,{scale:r,size:a}}clipBbox(e,t,n,r,i){let a=r-t,o=i-n;e.ctx.rect(t,n,a,o),e.current.updateRectMinMax(Z(e.ctx),[t,n,r,i]),e.clip(),e.endPath()}setFillAndStrokeStyleToContext(e,t,n){let r=e.ctx,i=e.current;switch(t){case Bu.COLORED:let e=this.ctx;r.fillStyle=e.fillStyle,r.strokeStyle=e.strokeStyle,i.fillColor=e.fillStyle,i.strokeColor=e.strokeStyle;break;case Bu.UNCOLORED:let a=X.makeHexColor(n[0],n[1],n[2]);r.fillStyle=a,r.strokeStyle=a,i.fillColor=a,i.strokeColor=a;break;default:throw new ll(`Unsupported paint type: ${t}`)}}getPattern(e,t,n,r){let i=n;r!==ju.SHADING&&(i=X.transform(i,t.baseTransform),this.matrix&&(i=X.transform(i,this.matrix)));let a=this.createPatternCanvas(t),o=new DOMMatrix(i);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);let s=e.createPattern(a.canvas,`repeat`);return s.setTransform(o),s}};function Hu({src:e,srcPos:t=0,dest:n,width:r,height:i,nonBlackColor:a=4294967295,inverseDecode:o=!1}){let s=_l.isLittleEndian?4278190080:255,[c,l]=o?[a,s]:[s,a],u=r>>3,d=r&7,f=e.length;n=new Uint32Array(n.buffer);let p=0;for(let r=0;r<i;r++){for(let r=t+u;t<r;t++){let r=t<f?e[t]:255;n[p++]=r&128?l:c,n[p++]=r&64?l:c,n[p++]=r&32?l:c,n[p++]=r&16?l:c,n[p++]=r&8?l:c,n[p++]=r&4?l:c,n[p++]=r&2?l:c,n[p++]=r&1?l:c}if(d===0)continue;let r=t<f?e[t++]:255;for(let e=0;e<d;e++)n[p++]=r&1<<7-e?l:c}return{srcPos:t,destPos:p}}var Uu=16,Wu=100,Gu=15,Ku=10,qu=1e3,Ju=16;function Yu(e,t){if(e._removeMirroring)throw Error(`Context is already forwarding operations.`);e.__originalSave=e.save,e.__originalRestore=e.restore,e.__originalRotate=e.rotate,e.__originalScale=e.scale,e.__originalTranslate=e.translate,e.__originalTransform=e.transform,e.__originalSetTransform=e.setTransform,e.__originalResetTransform=e.resetTransform,e.__originalClip=e.clip,e.__originalMoveTo=e.moveTo,e.__originalLineTo=e.lineTo,e.__originalBezierCurveTo=e.bezierCurveTo,e.__originalRect=e.rect,e.__originalClosePath=e.closePath,e.__originalBeginPath=e.beginPath,e._removeMirroring=()=>{e.save=e.__originalSave,e.restore=e.__originalRestore,e.rotate=e.__originalRotate,e.scale=e.__originalScale,e.translate=e.__originalTranslate,e.transform=e.__originalTransform,e.setTransform=e.__originalSetTransform,e.resetTransform=e.__originalResetTransform,e.clip=e.__originalClip,e.moveTo=e.__originalMoveTo,e.lineTo=e.__originalLineTo,e.bezierCurveTo=e.__originalBezierCurveTo,e.rect=e.__originalRect,e.closePath=e.__originalClosePath,e.beginPath=e.__originalBeginPath,delete e._removeMirroring},e.save=function(){t.save(),this.__originalSave()},e.restore=function(){t.restore(),this.__originalRestore()},e.translate=function(e,n){t.translate(e,n),this.__originalTranslate(e,n)},e.scale=function(e,n){t.scale(e,n),this.__originalScale(e,n)},e.transform=function(e,n,r,i,a,o){t.transform(e,n,r,i,a,o),this.__originalTransform(e,n,r,i,a,o)},e.setTransform=function(e,n,r,i,a,o){t.setTransform(e,n,r,i,a,o),this.__originalSetTransform(e,n,r,i,a,o)},e.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},e.rotate=function(e){t.rotate(e),this.__originalRotate(e)},e.clip=function(e){t.clip(e),this.__originalClip(e)},e.moveTo=function(e,n){t.moveTo(e,n),this.__originalMoveTo(e,n)},e.lineTo=function(e,n){t.lineTo(e,n),this.__originalLineTo(e,n)},e.bezierCurveTo=function(e,n,r,i,a,o){t.bezierCurveTo(e,n,r,i,a,o),this.__originalBezierCurveTo(e,n,r,i,a,o)},e.rect=function(e,n,r,i){t.rect(e,n,r,i),this.__originalRect(e,n,r,i)},e.closePath=function(){t.closePath(),this.__originalClosePath()},e.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}var Xu=class{constructor(e){this.canvasFactory=e,this.cache=Object.create(null)}getCanvas(e,t,n){let r;return this.cache[e]===void 0?(r=this.canvasFactory.create(t,n),this.cache[e]=r):(r=this.cache[e],this.canvasFactory.reset(r,t,n)),r}delete(e){delete this.cache[e]}clear(){for(let e in this.cache){let t=this.cache[e];this.canvasFactory.destroy(t),delete this.cache[e]}}};function Zu(e,t,n,r,i,a,o,s,c,l){let[u,d,f,p,m,h]=Z(e);if(d===0&&f===0){let g=o*u+m,_=Math.round(g),v=s*p+h,y=Math.round(v),b=(o+c)*u+m,x=Math.abs(Math.round(b)-_)||1,S=(s+l)*p+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(Math.sign(u),0,0,Math.sign(p),_,y),e.drawImage(t,n,r,i,a,0,0,x,C),e.setTransform(u,d,f,p,m,h),[x,C]}if(u===0&&p===0){let g=s*f+m,_=Math.round(g),v=o*d+h,y=Math.round(v),b=(s+l)*f+m,x=Math.abs(Math.round(b)-_)||1,S=(o+c)*d+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(0,Math.sign(d),Math.sign(f),0,_,y),e.drawImage(t,n,r,i,a,0,0,C,x),e.setTransform(u,d,f,p,m,h),[C,x]}e.drawImage(t,n,r,i,a,o,s,c,l);let g=Math.hypot(u,d),_=Math.hypot(f,p);return[g*c,_*l]}function Qu(e){let{width:t,height:n}=e;if(t>qu||n>qu)return null;let r=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),a=t+1,o=new Uint8Array(a*(n+1)),s,c,l,u=t+7&-8,d=new Uint8Array(u*n),f=0;for(let t of e.data){let e=128;for(;e>0;)d[f++]=t&e?0:255,e>>=1}let p=0;for(f=0,d[f]!==0&&(o[0]=1,++p),c=1;c<t;c++)d[f]!==d[f+1]&&(o[c]=d[f]?2:1,++p),f++;for(d[f]!==0&&(o[c]=2,++p),s=1;s<n;s++){f=s*u,l=s*a,d[f-u]!==d[f]&&(o[l]=d[f]?1:8,++p);let e=(d[f]?4:0)+(d[f-u]?8:0);for(c=1;c<t;c++)e=(e>>2)+(d[f+1]?4:0)+(d[f-u+1]?8:0),i[e]&&(o[l+c]=i[e],++p),f++;if(d[f-u]!==d[f]&&(o[l+c]=d[f]?2:4,++p),p>r)return null}for(f=u*(n-1),l=s*a,d[f]!==0&&(o[l]=8,++p),c=1;c<t;c++)d[f]!==d[f+1]&&(o[l+c]=d[f]?4:8,++p),f++;if(d[f]!==0&&(o[l+c]=4,++p),p>r)return null;let m=new Int32Array([0,a,-1,0,-a,0,0,0,1]),h=new Path2D;for(s=0;p&&s<=n;s++){let e=s*a,n=e+t;for(;e<n&&!o[e];)e++;if(e===n)continue;h.moveTo(e%a,s);let r=e,i=o[e];do{let t=m[i];do e+=t;while(!o[e]);let n=o[e];n!==5&&n!==10?(i=n,o[e]=0):(i=n&51*i>>4,o[e]&=i>>2|i<<2),h.lineTo(e%a,e/a|0),o[e]||--p}while(r!==e);--s}return d=null,o=null,function(e){e.save(),e.scale(1/t,-1/n),e.translate(0,-n),e.fill(h),e.beginPath(),e.restore()}}var $u=class{constructor(e,t){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Ic,this.textMatrixScale=1,this.fontMatrix=Lc,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=Wc.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,e,t])}clone(){let e=Object.create(this);return e.clipBox=this.clipBox.slice(),e}setCurrentPoint(e,t){this.x=e,this.y=t}updatePathMinMax(e,t,n){[t,n]=X.applyTransform([t,n],e),this.minX=Math.min(this.minX,t),this.minY=Math.min(this.minY,n),this.maxX=Math.max(this.maxX,t),this.maxY=Math.max(this.maxY,n)}updateRectMinMax(e,t){let n=X.applyTransform(t,e),r=X.applyTransform(t.slice(2),e),i=X.applyTransform([t[0],t[3]],e),a=X.applyTransform([t[2],t[1]],e);this.minX=Math.min(this.minX,n[0],r[0],i[0],a[0]),this.minY=Math.min(this.minY,n[1],r[1],i[1],a[1]),this.maxX=Math.max(this.maxX,n[0],r[0],i[0],a[0]),this.maxY=Math.max(this.maxY,n[1],r[1],i[1],a[1])}updateScalingPathMinMax(e,t){X.scaleMinMax(e,t),this.minX=Math.min(this.minX,t[0]),this.minY=Math.min(this.minY,t[1]),this.maxX=Math.max(this.maxX,t[2]),this.maxY=Math.max(this.maxY,t[3])}updateCurvePathMinMax(e,t,n,r,i,a,o,s,c,l){let u=X.bezierBoundingBox(t,n,r,i,a,o,s,c,l);l||this.updateRectMinMax(e,u)}getPathBoundingBox(e=ju.FILL,t=null){let n=[this.minX,this.minY,this.maxX,this.maxY];if(e===ju.STROKE){t||q(`Stroke bounding box must include transform.`);let e=X.singularValueDecompose2dScale(t),r=e[0]*this.lineWidth/2,i=e[1]*this.lineWidth/2;n[0]-=r,n[1]-=i,n[2]+=r,n[3]+=i}return n}updateClipFromPath(){let e=X.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(e){this.clipBox=e,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(e=ju.FILL,t=null){return X.intersect(this.clipBox,this.getPathBoundingBox(e,t))}};function ed(e,t){if(t instanceof ImageData){e.putImageData(t,0,0);return}let n=t.height,r=t.width,i=n%Ju,a=(n-i)/Ju,o=i===0?a:a+1,s=e.createImageData(r,Ju),c=0,l,u=t.data,d=s.data,f,p,m,h;if(t.kind===Gc.GRAYSCALE_1BPP){let t=u.byteLength,n=new Uint32Array(d.buffer,0,d.byteLength>>2),h=n.length,g=r+7>>3,_=4294967295,v=_l.isLittleEndian?4278190080:255;for(f=0;f<o;f++){for(m=f<a?Ju:i,l=0,p=0;p<m;p++){let e=t-c,i=0,a=e>g?r:e*8-7,o=a&-8,s=0,d=0;for(;i<o;i+=8)d=u[c++],n[l++]=d&128?_:v,n[l++]=d&64?_:v,n[l++]=d&32?_:v,n[l++]=d&16?_:v,n[l++]=d&8?_:v,n[l++]=d&4?_:v,n[l++]=d&2?_:v,n[l++]=d&1?_:v;for(;i<a;i++)s===0&&(d=u[c++],s=128),n[l++]=d&s?_:v,s>>=1}for(;l<h;)n[l++]=0;e.putImageData(s,0,f*Ju)}}else if(t.kind===Gc.RGBA_32BPP){for(p=0,h=r*Ju*4,f=0;f<a;f++)d.set(u.subarray(c,c+h)),c+=h,e.putImageData(s,0,p),p+=Ju;f<o&&(h=r*i*4,d.set(u.subarray(c,c+h)),e.putImageData(s,0,p))}else if(t.kind===Gc.RGB_24BPP)for(m=Ju,h=r*m,f=0;f<o;f++){for(f>=a&&(m=i,h=r*m),l=0,p=h;p--;)d[l++]=u[c++],d[l++]=u[c++],d[l++]=u[c++],d[l++]=255;e.putImageData(s,0,f*Ju)}else throw Error(`bad image kind: ${t.kind}`)}function td(e,t){if(t.bitmap){e.drawImage(t.bitmap,0,0);return}let n=t.height,r=t.width,i=n%Ju,a=(n-i)/Ju,o=i===0?a:a+1,s=e.createImageData(r,Ju),c=0,l=t.data,u=s.data;for(let t=0;t<o;t++){let n=t<a?Ju:i;({srcPos:c}=Hu({src:l,srcPos:c,dest:u,width:r,height:n,nonBlackColor:0})),e.putImageData(s,0,t*Ju)}}function nd(e,t){for(let n of[`strokeStyle`,`fillStyle`,`fillRule`,`globalAlpha`,`lineWidth`,`lineCap`,`lineJoin`,`miterLimit`,`globalCompositeOperation`,`font`,`filter`])e[n]!==void 0&&(t[n]=e[n]);e.setLineDash!==void 0&&(t.setLineDash(e.getLineDash()),t.lineDashOffset=e.lineDashOffset)}function rd(e){if(e.strokeStyle=e.fillStyle=`#000000`,e.fillRule=`nonzero`,e.globalAlpha=1,e.lineWidth=1,e.lineCap=`butt`,e.lineJoin=`miter`,e.miterLimit=10,e.globalCompositeOperation=`source-over`,e.font=`10px sans-serif`,e.setLineDash!==void 0&&(e.setLineDash([]),e.lineDashOffset=0),!Fc){let{filter:t}=e;t!==`none`&&t!==``&&(e.filter=`none`)}}function id(e,t){if(t)return!0;let n=X.singularValueDecompose2dScale(e);n[0]=Math.fround(n[0]),n[1]=Math.fround(n[1]);let r=Math.fround((globalThis.devicePixelRatio||1)*Dl.PDF_TO_CSS_UNITS);return n[0]<=r&&n[1]<=r}var ad=[`butt`,`round`,`square`],od=[`miter`,`round`,`bevel`],sd={},cd={},ld=class e{constructor(e,t,n,r,i,{optionalContentConfig:a,markedContentStack:o=null},s,c){this.ctx=e,this.current=new $u(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=t,this.objs=n,this.canvasFactory=r,this.filterFactory=i,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=a,this.cachedCanvases=new Xu(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=s,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(e,t=null){return typeof e==`string`?e.startsWith(`g_`)?this.commonObjs.get(e):this.objs.get(e):t}beginDrawing({transform:e,viewport:t,transparency:n=!1,background:r=null}){let i=this.ctx.canvas.width,a=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=r||`#ffffff`,this.ctx.fillRect(0,0,i,a),this.ctx.fillStyle=o,n){let e=this.cachedCanvases.getCanvas(`transparent`,i,a);this.compositeCtx=this.ctx,this.transparentCanvas=e.canvas,this.ctx=e.context,this.ctx.save(),this.ctx.transform(...Z(this.compositeCtx))}this.ctx.save(),rd(this.ctx),e&&(this.ctx.transform(...e),this.outputScaleX=e[0],this.outputScaleY=e[0]),this.ctx.transform(...t.transform),this.viewportScale=t.scale,this.baseTransform=Z(this.ctx)}executeOperatorList(e,t,n,r){let i=e.argsArray,a=e.fnArray,o=t||0,s=i.length;if(s===o)return o;let c=s-o>Ku&&typeof n==`function`,l=c?Date.now()+Gu:0,u=0,d=this.commonObjs,f=this.objs,p;for(;;){if(r!==void 0&&o===r.nextBreakPoint)return r.breakIt(o,n),o;if(p=a[o],p!==Yc.dependency)this[p].apply(this,i[o]);else for(let e of i[o]){let t=e.startsWith(`g_`)?d:f;if(!t.has(e))return t.get(e,n),o}if(o++,o===s)return o;if(c&&++u>Ku){if(Date.now()>l)return n(),o;u=0}}}#e(){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(),null)}endDrawing(){this.#e(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let e of this._cachedBitmapsMap.values()){for(let t of e.values())typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),this.#t()}#t(){if(this.pageColors){let e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!==`none`){let t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}}_scaleImage(e,t){let n=e.width??e.displayWidth,r=e.height??e.displayHeight,i=Math.max(Math.hypot(t[0],t[1]),1),a=Math.max(Math.hypot(t[2],t[3]),1),o=n,s=r,c=`prescale1`,l,u;for(;i>2&&o>1||a>2&&s>1;){let t=o,n=s;i>2&&o>1&&(t=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/t),a>2&&s>1&&(n=s>=16384?Math.floor(s/2)-1||1:Math.ceil(s)/2,a/=s/n),l=this.cachedCanvases.getCanvas(c,t,n),u=l.context,u.clearRect(0,0,t,n),u.drawImage(e,0,0,o,s,0,0,t,n),e=l.canvas,o=t,s=n,c=c===`prescale1`?`prescale2`:`prescale1`}return{img:e,paintWidth:o,paintHeight:s}}_createMaskCanvas(e){let t=this.ctx,{width:n,height:r}=e,i=this.current.fillColor,a=this.current.patternFill,o=Z(t),s,c,l,u;if((e.bitmap||e.data)&&e.count>1){let t=e.bitmap||e.data.buffer;c=JSON.stringify(a?o:[o.slice(0,4),i]),s=this._cachedBitmapsMap.get(t),s||(s=new Map,this._cachedBitmapsMap.set(t,s));let n=s.get(c);if(n&&!a)return{canvas:n,offsetX:Math.round(Math.min(o[0],o[2])+o[4]),offsetY:Math.round(Math.min(o[1],o[3])+o[5])};l=n}l||(u=this.cachedCanvases.getCanvas(`maskCanvas`,n,r),td(u.context,e));let d=X.transform(o,[1/n,0,0,-1/r,0,0]);d=X.transform(d,[1,0,0,1,0,-r]);let[f,p,m,h]=X.getAxialAlignedBoundingBox([0,0,n,r],d),g=Math.round(m-f)||1,_=Math.round(h-p)||1,v=this.cachedCanvases.getCanvas(`fillCanvas`,g,_),y=v.context,b=f,x=p;y.translate(-b,-x),y.transform(...d),l||(l=this._scaleImage(u.canvas,Ul(y)),l=l.img,s&&a&&s.set(c,l)),y.imageSmoothingEnabled=id(Z(y),e.interpolate),Zu(y,l,0,0,l.width,l.height,0,0,n,r),y.globalCompositeOperation=`source-in`;let S=X.transform(Ul(y),[1,0,0,1,-b,-x]);return y.fillStyle=a?i.getPattern(t,this,S,ju.FILL):i,y.fillRect(0,0,n,r),s&&!a&&(this.cachedCanvases.delete(`fillCanvas`),s.set(c,v.canvas)),{canvas:v.canvas,offsetX:Math.round(b),offsetY:Math.round(x)}}setLineWidth(e){e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(e){this.ctx.lineCap=ad[e]}setLineJoin(e){this.ctx.lineJoin=od[e]}setMiterLimit(e){this.ctx.miterLimit=e}setDash(e,t){let n=this.ctx;n.setLineDash!==void 0&&(n.setLineDash(e),n.lineDashOffset=t)}setRenderingIntent(e){}setFlatness(e){}setGState(e){for(let[t,n]of e)switch(t){case`LW`:this.setLineWidth(n);break;case`LC`:this.setLineCap(n);break;case`LJ`:this.setLineJoin(n);break;case`ML`:this.setMiterLimit(n);break;case`D`:this.setDash(n[0],n[1]);break;case`RI`:this.setRenderingIntent(n);break;case`FL`:this.setFlatness(n);break;case`Font`:this.setFont(n[0],n[1]);break;case`CA`:this.current.strokeAlpha=n;break;case`ca`:this.current.fillAlpha=n,this.ctx.globalAlpha=n;break;case`BM`:this.ctx.globalCompositeOperation=n;break;case`SMask`:this.current.activeSMask=n?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case`TR`:this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode():!this.current.activeSMask&&e&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw Error(`beginSMaskMode called while already in smask mode`);let e=this.ctx.canvas.width,t=this.ctx.canvas.height,n=`smaskGroupAt`+this.groupLevel,r=this.cachedCanvases.getCanvas(n,e,t);this.suspendedCtx=this.ctx,this.ctx=r.context;let i=this.ctx;i.setTransform(...Z(this.suspendedCtx)),nd(this.suspendedCtx,i),Yu(i,this.suspendedCtx),this.setGState([[`BM`,`source-over`],[`ca`,1],[`CA`,1]])}endSMaskMode(){if(!this.inSMaskMode)throw Error(`endSMaskMode called while not in smask mode`);this.ctx._removeMirroring(),nd(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(e){if(!this.current.activeSMask)return;e?(e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])):e=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let t=this.current.activeSMask,n=this.suspendedCtx;this.composeSMask(n,t,this.ctx,e),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(e,t,n,r){let i=r[0],a=r[1],o=r[2]-i,s=r[3]-a;o!==0&&s!==0&&(this.genericComposeSMask(t.context,n,o,s,t.subtype,t.backdrop,t.transferMap,i,a,t.offsetX,t.offsetY),e.save(),e.globalAlpha=1,e.globalCompositeOperation=`source-over`,e.setTransform(1,0,0,1,0,0),e.drawImage(n.canvas,0,0),e.restore())}genericComposeSMask(e,t,n,r,i,a,o,s,c,l,u){let d=e.canvas,f=s-l,p=c-u;if(a){let t=X.makeHexColor(...a);if(f<0||p<0||f+n>d.width||p+r>d.height){let e=this.cachedCanvases.getCanvas(`maskExtension`,n,r),i=e.context;i.drawImage(d,-f,-p),i.globalCompositeOperation=`destination-atop`,i.fillStyle=t,i.fillRect(0,0,n,r),i.globalCompositeOperation=`source-over`,d=e.canvas,f=p=0}else{e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);let i=new Path2D;i.rect(f,p,n,r),e.clip(i),e.globalCompositeOperation=`destination-atop`,e.fillStyle=t,e.fillRect(f,p,n,r),e.restore()}}t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0),i===`Alpha`&&o?t.filter=this.filterFactory.addAlphaFilter(o):i===`Luminosity`&&(t.filter=this.filterFactory.addLuminosityFilter(o));let m=new Path2D;m.rect(s,c,n,r),t.clip(m),t.globalCompositeOperation=`destination-in`,t.drawImage(d,f,p,n,r,s,c,n,r),t.restore()}save(){this.inSMaskMode?(nd(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let e=this.current;this.stateStack.push(e),this.current=e.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),nd(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(e,t,n,r,i,a){this.ctx.transform(e,t,n,r,i,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,n){let r=this.ctx,i=this.current,a=i.x,o=i.y,s,c,l=Z(r),u=l[0]===0&&l[3]===0||l[1]===0&&l[2]===0,d=u?n.slice(0):null;for(let n=0,f=0,p=e.length;n<p;n++)switch(e[n]|0){case Yc.rectangle:a=t[f++],o=t[f++];let e=t[f++],n=t[f++],p=a+e,m=o+n;r.moveTo(a,o),e===0||n===0?r.lineTo(p,m):(r.lineTo(p,o),r.lineTo(p,m),r.lineTo(a,m)),u||i.updateRectMinMax(l,[a,o,p,m]),r.closePath();break;case Yc.moveTo:a=t[f++],o=t[f++],r.moveTo(a,o),u||i.updatePathMinMax(l,a,o);break;case Yc.lineTo:a=t[f++],o=t[f++],r.lineTo(a,o),u||i.updatePathMinMax(l,a,o);break;case Yc.curveTo:s=a,c=o,a=t[f+4],o=t[f+5],r.bezierCurveTo(t[f],t[f+1],t[f+2],t[f+3],a,o),i.updateCurvePathMinMax(l,s,c,t[f],t[f+1],t[f+2],t[f+3],a,o,d),f+=6;break;case Yc.curveTo2:s=a,c=o,r.bezierCurveTo(a,o,t[f],t[f+1],t[f+2],t[f+3]),i.updateCurvePathMinMax(l,s,c,a,o,t[f],t[f+1],t[f+2],t[f+3],d),a=t[f+2],o=t[f+3],f+=4;break;case Yc.curveTo3:s=a,c=o,a=t[f+2],o=t[f+3],r.bezierCurveTo(t[f],t[f+1],a,o,a,o),i.updateCurvePathMinMax(l,s,c,t[f],t[f+1],a,o,a,o,d),f+=4;break;case Yc.closePath:r.closePath()}u&&i.updateScalingPathMinMax(l,d),i.setCurrentPoint(a,o)}closePath(){this.ctx.closePath()}stroke(e=!0){let t=this.ctx,n=this.current.strokeColor;t.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof n==`object`&&n?.getPattern?(t.save(),t.strokeStyle=n.getPattern(t,this,Ul(t),ju.STROKE),this.rescaleAndStroke(!1),t.restore()):this.rescaleAndStroke(!0)),e&&this.consumePath(this.current.getClippedPathBoundingBox()),t.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(e=!0){let t=this.ctx,n=this.current.fillColor,r=this.current.patternFill,i=!1;r&&(t.save(),t.fillStyle=n.getPattern(t,this,Ul(t),ju.FILL),i=!0);let a=this.current.getClippedPathBoundingBox();this.contentVisible&&a!==null&&(this.pendingEOFill?(t.fill(`evenodd`),this.pendingEOFill=!1):t.fill()),i&&t.restore(),e&&this.consumePath(a)}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=sd}eoClip(){this.pendingClip=cd}beginText(){this.current.textMatrix=Ic,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let e=this.pendingTextPaths,t=this.ctx;if(e===void 0){t.beginPath();return}let n=new Path2D,r=t.getTransform().invertSelf();for(let{transform:t,x:i,y:a,fontSize:o,path:s}of e)n.addPath(s,new DOMMatrix(t).preMultiplySelf(r).translate(i,a).scale(o,-o));t.clip(n),t.beginPath(),delete this.pendingTextPaths}setCharSpacing(e){this.current.charSpacing=e}setWordSpacing(e){this.current.wordSpacing=e}setHScale(e){this.current.textHScale=e/100}setLeading(e){this.current.leading=-e}setFont(e,t){let n=this.commonObjs.get(e),r=this.current;if(!n)throw Error(`Can't find font for ${e}`);if(r.fontMatrix=n.fontMatrix||Lc,(r.fontMatrix[0]===0||r.fontMatrix[3]===0)&&K(`Invalid font matrix for font `+e),t<0?(t=-t,r.fontDirection=-1):r.fontDirection=1,this.current.font=n,this.current.fontSize=t,n.isType3Font)return;let i=n.loadedName||`sans-serif`,a=n.systemFontInfo?.css||`"${i}", ${n.fallbackName}`,o=`normal`;n.black?o=`900`:n.bold&&(o=`bold`);let s=n.italic?`italic`:`normal`,c=t;t<Uu?c=Uu:t>Wu&&(c=Wu),this.current.fontSizeScale=t/c,this.ctx.font=`${s} ${o} ${c}px ${a}`}setTextRenderingMode(e){this.current.textRenderingMode=e}setTextRise(e){this.current.textRise=e}moveText(e,t){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=t}setLeadingMoveText(e,t){this.setLeading(-t),this.moveText(e,t)}setTextMatrix(e,t,n,r,i,a){this.current.textMatrix=[e,t,n,r,i,a],this.current.textMatrixScale=Math.hypot(e,t),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#n(e,t,n){let r=new Path2D;return r.addPath(e,new DOMMatrix(n).invertSelf().multiplySelf(t)),r}paintChar(e,t,n,r,i){let a=this.ctx,o=this.current,s=o.font,c=o.textRenderingMode,l=o.fontSize/o.fontSizeScale,u=c&Wc.FILL_STROKE_MASK,d=!!(c&Wc.ADD_TO_PATH_FLAG),f=o.patternFill&&!s.missingFile,p=o.patternStroke&&!s.missingFile,m;if((s.disableFontFace||d||f||p)&&(m=s.getPathGenerator(this.commonObjs,e)),s.disableFontFace||f||p){if(a.save(),a.translate(t,n),a.scale(l,-l),u===Wc.FILL||u===Wc.FILL_STROKE){if(r){let e=a.getTransform();a.setTransform(...r),a.fill(this.#n(m,e,r))}else a.fill(m)}if(u===Wc.STROKE||u===Wc.FILL_STROKE){if(i){let e=a.getTransform();a.setTransform(...i),a.stroke(this.#n(m,e,i))}else a.lineWidth/=l,a.stroke(m)}a.restore()}else(u===Wc.FILL||u===Wc.FILL_STROKE)&&a.fillText(e,t,n),(u===Wc.STROKE||u===Wc.FILL_STROKE)&&a.strokeText(e,t,n);d&&(this.pendingTextPaths||=[]).push({transform:Z(a),x:t,y:n,fontSize:l,path:m})}get isFontSubpixelAAEnabled(){let{context:e}=this.cachedCanvases.getCanvas(`isFontSubpixelAAEnabled`,10,10);e.scale(1.5,1),e.fillText(`I`,0,10);let t=e.getImageData(0,0,10,10).data,n=!1;for(let e=3;e<t.length;e+=4)if(t[e]>0&&t[e]<255){n=!0;break}return Y(this,`isFontSubpixelAAEnabled`,n)}showText(e){let t=this.current,n=t.font;if(n.isType3Font)return this.showType3Text(e);let r=t.fontSize;if(r===0)return;let i=this.ctx,a=t.fontSizeScale,o=t.charSpacing,s=t.wordSpacing,c=t.fontDirection,l=t.textHScale*c,u=e.length,d=n.vertical,f=d?1:-1,p=n.defaultVMetrics,m=r*t.fontMatrix[0],h=t.textRenderingMode===Wc.FILL&&!n.disableFontFace&&!t.patternFill;i.save(),i.transform(...t.textMatrix),i.translate(t.x,t.y+t.textRise),c>0?i.scale(l,-1):i.scale(l,1);let g,_;if(t.patternFill){i.save();let e=t.fillColor.getPattern(i,this,Ul(i),ju.FILL);g=Z(i),i.restore(),i.fillStyle=e}if(t.patternStroke){i.save();let e=t.strokeColor.getPattern(i,this,Ul(i),ju.STROKE);_=Z(i),i.restore(),i.strokeStyle=e}let v=t.lineWidth,y=t.textMatrixScale;if(y===0||v===0){let e=t.textRenderingMode&Wc.FILL_STROKE_MASK;(e===Wc.STROKE||e===Wc.FILL_STROKE)&&(v=this.getSinglePixelWidth())}else v/=y;if(a!==1&&(i.scale(a,a),v/=a),i.lineWidth=v,n.isInvalidPDFjsFont){let n=[],r=0;for(let t of e)n.push(t.unicode),r+=t.width;i.fillText(n.join(``),0,0),t.x+=r*m*l,i.restore(),this.compose();return}let b=0,x;for(x=0;x<u;++x){let t=e[x];if(typeof t==`number`){b+=f*t*r/1e3;continue}let l=!1,u=(t.isSpace?s:0)+o,v=t.fontChar,y=t.accent,S,C,w=t.width;if(d){let e=t.vmetric||p,n=-(t.vmetric?e[1]:w*.5)*m,r=e[2]*m;w=e?-e[0]:w,S=n/a,C=(b+r)/a}else S=b/a,C=0;if(n.remeasure&&w>0){let e=i.measureText(v).width*1e3/r*a;if(w<e&&this.isFontSubpixelAAEnabled){let t=w/e;l=!0,i.save(),i.scale(t,1),S/=t}else w!==e&&(S+=(w-e)/2e3*r/a)}if(this.contentVisible&&(t.isInFont||n.missingFile)){if(h&&!y)i.fillText(v,S,C);else if(this.paintChar(v,S,C,g,_),y){let e=S+r*y.offset.x/a,t=C-r*y.offset.y/a;this.paintChar(y.fontChar,e,t,g,_)}}let T=d?w*m-u*c:w*m+u*c;b+=T,l&&i.restore()}d?t.y-=b:t.x+=b*l,i.restore(),this.compose()}showType3Text(e){let t=this.ctx,n=this.current,r=n.font,i=n.fontSize,a=n.fontDirection,o=r.vertical?1:-1,s=n.charSpacing,c=n.wordSpacing,l=n.textHScale*a,u=n.fontMatrix||Lc,d=e.length,f=n.textRenderingMode===Wc.INVISIBLE,p,m,h,g;if(!(f||i===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,t.save(),t.transform(...n.textMatrix),t.translate(n.x,n.y),t.scale(l,a),p=0;p<d;++p){if(m=e[p],typeof m==`number`){g=o*m*i/1e3,this.ctx.translate(g,0),n.x+=g*l;continue}let a=(m.isSpace?c:0)+s,d=r.charProcOperatorList[m.operatorListId];if(!d){K(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),t.scale(i,i),t.transform(...u),this.executeOperatorList(d),this.restore()),h=X.applyTransform([m.width,0],u)[0]*i+a,t.translate(h,0),n.x+=h*l}t.restore(),this.processingType3=null}}setCharWidth(e,t){}setCharWidthAndBounds(e,t,n,r,i,a){this.ctx.rect(n,r,i-n,a-r),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let n;if(t[0]===`TilingPattern`){let r=t[1],i=this.baseTransform||Z(this.ctx);n=new Vu(t,r,this.ctx,{createCanvasGraphics:t=>new e(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})},i)}else n=this._getPattern(t[1],t[2]);return n}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(e,t,n){this.ctx.strokeStyle=this.current.strokeColor=X.makeHexColor(e,t,n),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor=`transparent`,this.current.patternStroke=!1}setFillRGBColor(e,t,n){this.ctx.fillStyle=this.current.fillColor=X.makeHexColor(e,t,n),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor=`transparent`,this.current.patternFill=!1}_getPattern(e,t=null){let n;return this.cachedPatterns.has(e)?n=this.cachedPatterns.get(e):(n=zu(this.getObject(e)),this.cachedPatterns.set(e,n)),t&&(n.matrix=t),n}shadingFill(e){if(!this.contentVisible)return;let t=this.ctx;this.save(),t.fillStyle=this._getPattern(e).getPattern(t,this,Ul(t),ju.SHADING);let n=Ul(t);if(n){let{width:e,height:r}=t.canvas,[i,a,o,s]=X.getAxialAlignedBoundingBox([0,0,e,r],n);this.ctx.fillRect(i,a,o-i,s-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){q(`Should not call beginInlineImage`)}beginImageData(){q(`Should not call beginImageData`)}paintFormXObjectBegin(e,t){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),e&&this.transform(...e),this.baseTransform=Z(this.ctx),t)){let e=t[2]-t[0],n=t[3]-t[1];this.ctx.rect(t[0],t[1],e,n),this.current.updateRectMinMax(Z(this.ctx),t),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let t=this.ctx;e.isolated||el(`TODO: Support non-isolated groups.`),e.knockout&&K(`Knockout groups not supported.`);let n=Z(t);if(e.matrix&&t.transform(...e.matrix),!e.bbox)throw Error(`Bounding box is required.`);let r=X.getAxialAlignedBoundingBox(e.bbox,Z(t)),i=[0,0,t.canvas.width,t.canvas.height];r=X.intersect(r,i)||[0,0,0,0];let a=Math.floor(r[0]),o=Math.floor(r[1]),s=Math.max(Math.ceil(r[2])-a,1),c=Math.max(Math.ceil(r[3])-o,1);this.current.startNewPathAndClipBox([0,0,s,c]);let l=`groupAt`+this.groupLevel;e.smask&&(l+=`_smask_`+this.smaskCounter++%2);let u=this.cachedCanvases.getCanvas(l,s,c),d=u.context;d.translate(-a,-o),d.transform(...n),e.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(t.setTransform(1,0,0,1,0,0),t.translate(a,o),t.save()),nd(t,d),this.ctx=d,this.setGState([[`BM`,`source-over`],[`ca`,1],[`CA`,1]]),this.groupStack.push(t),this.groupLevel++}endGroup(e){if(!this.contentVisible)return;this.groupLevel--;let t=this.ctx,n=this.groupStack.pop();if(this.ctx=n,this.ctx.imageSmoothingEnabled=!1,e.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let e=Z(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...e);let n=X.getAxialAlignedBoundingBox([0,0,t.canvas.width,t.canvas.height],e);this.ctx.drawImage(t.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(e,t,n,r,i){if(this.#e(),rd(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),t){let r=t[2]-t[0],a=t[3]-t[1];if(i&&this.annotationCanvasMap){n=n.slice(),n[4]-=t[0],n[5]-=t[1],t=t.slice(),t[0]=t[1]=0,t[2]=r,t[3]=a;let[i,o]=X.singularValueDecompose2dScale(Z(this.ctx)),{viewportScale:s}=this,c=Math.ceil(r*this.outputScaleX*s),l=Math.ceil(a*this.outputScaleY*s);this.annotationCanvas=this.canvasFactory.create(c,l);let{canvas:u,context:d}=this.annotationCanvas;this.annotationCanvasMap.set(e,u),this.annotationCanvas.savedCtx=this.ctx,this.ctx=d,this.ctx.save(),this.ctx.setTransform(i,0,0,-o,0,a*o),rd(this.ctx)}else rd(this.ctx),this.endPath(),this.ctx.rect(t[0],t[1],r,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new $u(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...n),this.transform(...r)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#t(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(e){if(!this.contentVisible)return;let t=e.count;e=this.getObject(e.data,e),e.count=t;let n=this.ctx,r=this.processingType3;if(r&&(r.compiled===void 0&&(r.compiled=Qu(e)),r.compiled)){r.compiled(n);return}let i=this._createMaskCanvas(e),a=i.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(a,i.offsetX,i.offsetY),n.restore(),this.compose()}paintImageMaskXObjectRepeat(e,t,n=0,r=0,i,a){if(!this.contentVisible)return;e=this.getObject(e.data,e);let o=this.ctx;o.save();let s=Z(o);o.transform(t,n,r,i,0,0);let c=this._createMaskCanvas(e);o.setTransform(1,0,0,1,c.offsetX-s[4],c.offsetY-s[5]);for(let e=0,l=a.length;e<l;e+=2){let l=X.transform(s,[t,n,r,i,a[e],a[e+1]]),[u,d]=X.applyTransform([0,0],l);o.drawImage(c.canvas,u,d)}o.restore(),this.compose()}paintImageMaskXObjectGroup(e){if(!this.contentVisible)return;let t=this.ctx,n=this.current.fillColor,r=this.current.patternFill;for(let i of e){let{data:e,width:a,height:o,transform:s}=i,c=this.cachedCanvases.getCanvas(`maskCanvas`,a,o),l=c.context;l.save(),td(l,this.getObject(e,i)),l.globalCompositeOperation=`source-in`,l.fillStyle=r?n.getPattern(l,this,Ul(t),ju.FILL):n,l.fillRect(0,0,a,o),l.restore(),t.save(),t.transform(...s),t.scale(1,-1),Zu(t,c.canvas,0,0,a,o,0,-1,1,1),t.restore()}this.compose()}paintImageXObject(e){if(!this.contentVisible)return;let t=this.getObject(e);if(!t){K(`Dependent image isn't ready yet`);return}this.paintInlineImageXObject(t)}paintImageXObjectRepeat(e,t,n,r){if(!this.contentVisible)return;let i=this.getObject(e);if(!i){K(`Dependent image isn't ready yet`);return}let a=i.width,o=i.height,s=[];for(let e=0,i=r.length;e<i;e+=2)s.push({transform:[t,0,0,n,r[e],r[e+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(i,s)}applyTransferMapsToCanvas(e){return this.current.transferMaps!==`none`&&(e.filter=this.current.transferMaps,e.drawImage(e.canvas,0,0),e.filter=`none`),e.canvas}applyTransferMapsToBitmap(e){if(this.current.transferMaps===`none`)return e.bitmap;let{bitmap:t,width:n,height:r}=e,i=this.cachedCanvases.getCanvas(`inlineImage`,n,r),a=i.context;return a.filter=this.current.transferMaps,a.drawImage(t,0,0),a.filter=`none`,i.canvas}paintInlineImageXObject(e){if(!this.contentVisible)return;let t=e.width,n=e.height,r=this.ctx;if(this.save(),!Fc){let{filter:e}=r;e!==`none`&&e!==``&&(r.filter=`none`)}r.scale(1/t,-1/n);let i;if(e.bitmap)i=this.applyTransferMapsToBitmap(e);else if(typeof HTMLElement==`function`&&e instanceof HTMLElement||!e.data)i=e;else{let r=this.cachedCanvases.getCanvas(`inlineImage`,t,n).context;ed(r,e),i=this.applyTransferMapsToCanvas(r)}let a=this._scaleImage(i,Ul(r));r.imageSmoothingEnabled=id(Z(r),e.interpolate),Zu(r,a.img,0,0,a.paintWidth,a.paintHeight,0,-n,t,n),this.compose(),this.restore()}paintInlineImageXObjectGroup(e,t){if(!this.contentVisible)return;let n=this.ctx,r;if(e.bitmap)r=e.bitmap;else{let t=e.width,n=e.height,i=this.cachedCanvases.getCanvas(`inlineImage`,t,n).context;ed(i,e),r=this.applyTransferMapsToCanvas(i)}for(let e of t)n.save(),n.transform(...e.transform),n.scale(1,-1),Zu(n,r,e.x,e.y,e.w,e.h,0,-1,1,1),n.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(e){}markPointProps(e,t){}beginMarkedContent(e){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(e,t){e===`OC`?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(t)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(e){let t=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(e);let n=this.ctx;this.pendingClip&&=(t||(this.pendingClip===cd?n.clip(`evenodd`):n.clip()),null),this.current.startNewPathAndClipBox(this.current.clipBox),n.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let e=Z(this.ctx);if(e[1]===0&&e[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(e[0]),Math.abs(e[3]));else{let t=Math.abs(e[0]*e[3]-e[2]*e[1]),n=Math.hypot(e[0],e[2]),r=Math.hypot(e[1],e[3]);this._cachedGetSinglePixelWidth=Math.max(n,r)/t}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:e}=this.current,{a:t,b:n,c:r,d:i}=this.ctx.getTransform(),a,o;if(n===0&&r===0){let n=Math.abs(t),r=Math.abs(i);if(n===r){if(e===0)a=o=1/n;else{let t=n*e;a=o=t<1?1/t:1}}else if(e===0)a=1/n,o=1/r;else{let t=n*e,i=r*e;a=t<1?1/t:1,o=i<1?1/i:1}}else{let s=Math.abs(t*i-n*r),c=Math.hypot(t,n),l=Math.hypot(r,i);if(e===0)a=l/s,o=c/s;else{let t=e*s;a=l>t?l/t:1,o=c>t?c/t:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(e){let{ctx:t}=this,{lineWidth:n}=this.current,[r,i]=this.getScaleForStroking();if(t.lineWidth=n||1,r===1&&i===1){t.stroke();return}let a=t.getLineDash();if(e&&t.save(),t.scale(r,i),a.length>0){let e=Math.max(r,i);t.setLineDash(a.map(t=>t/e)),t.lineDashOffset/=e}t.stroke(),e&&t.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};for(let e in Yc)ld.prototype[e]!==void 0&&(ld.prototype[Yc[e]]=ld.prototype[e]);var ud=class{static#e=null;static#t=``;static get workerPort(){return this.#e}static set workerPort(e){if(!(typeof Worker<`u`&&e instanceof Worker)&&e!==null)throw Error("Invalid `workerPort` type.");this.#e=e}static get workerSrc(){return this.#t}static set workerSrc(e){if(typeof e!=`string`)throw Error("Invalid `workerSrc` type.");this.#t=e}},dd=class{#e;#t;constructor({parsedData:e,rawData:t}){this.#e=e,this.#t=t}getRaw(){return this.#t}get(e){return this.#e.get(e)??null}getAll(){return ml(this.#e)}has(e){return this.#e.has(e)}},fd=Symbol(`INTERNAL`),pd=class{#e=!1;#t=!1;#n=!1;#r=!0;constructor(e,{name:t,intent:n,usage:r,rbGroups:i}){this.#e=!!(e&Bc.DISPLAY),this.#t=!!(e&Bc.PRINT),this.name=t,this.intent=n,this.usage=r,this.rbGroups=i}get visible(){if(this.#n)return this.#r;if(!this.#r)return!1;let{print:e,view:t}=this.usage;return this.#e?t?.viewState!==`OFF`:!this.#t||e?.printState!==`OFF`}_setVisible(e,t,n=!1){e!==fd&&q("Internal method `_setVisible` called."),this.#n=n,this.#r=t}},md=class{#e=null;#t=new Map;#n=null;#r=null;constructor(e,t=Bc.DISPLAY){if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,this.#r=e.order;for(let n of e.groups)this.#t.set(n.id,new pd(t,n));if(e.baseState===`OFF`)for(let e of this.#t.values())e._setVisible(fd,!1);for(let t of e.on)this.#t.get(t)._setVisible(fd,!0);for(let t of e.off)this.#t.get(t)._setVisible(fd,!1);this.#n=this.getHash()}}#i(e){let t=e.length;if(t<2)return!0;let n=e[0];for(let r=1;r<t;r++){let t=e[r],i;if(Array.isArray(t))i=this.#i(t);else if(this.#t.has(t))i=this.#t.get(t).visible;else return K(`Optional content group not found: ${t}`),!0;switch(n){case`And`:if(!i)return!1;break;case`Or`:if(i)return!0;break;case`Not`:return!i;default:return!0}}return n===`And`}isVisible(e){if(this.#t.size===0)return!0;if(!e)return el(`Optional content group not defined.`),!0;if(e.type===`OCG`)return this.#t.has(e.id)?this.#t.get(e.id).visible:(K(`Optional content group not found: ${e.id}`),!0);if(e.type===`OCMD`){if(e.expression)return this.#i(e.expression);if(!e.policy||e.policy===`AnyOn`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!0}return!1}if(e.policy===`AllOn`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!1}return!0}if(e.policy===`AnyOff`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!0}return!1}if(e.policy===`AllOff`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!1}return!0}return K(`Unknown optional content policy ${e.policy}.`),!0}return K(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,n=!0){let r=this.#t.get(e);if(!r){K(`Optional content group not found: ${e}`);return}if(n&&t&&r.rbGroups.length)for(let t of r.rbGroups)for(let n of t)n!==e&&this.#t.get(n)?._setVisible(fd,!1,!0);r._setVisible(fd,!!t,!0),this.#e=null}setOCGState({state:e,preserveRB:t}){let n;for(let r of e){switch(r){case`ON`:case`OFF`:case`Toggle`:n=r;continue}let e=this.#t.get(r);if(e)switch(n){case`ON`:this.setVisibility(r,!0,t);break;case`OFF`:this.setVisibility(r,!1,t);break;case`Toggle`:this.setVisibility(r,!e.visible,t)}}this.#e=null}get hasInitialVisibility(){return this.#n===null||this.getHash()===this.#n}getOrder(){return this.#t.size?this.#r?this.#r.slice():[...this.#t.keys()]:null}getGroups(){return this.#t.size>0?ml(this.#t):null}getGroup(e){return this.#t.get(e)||null}getHash(){if(this.#e!==null)return this.#e;let e=new su;for(let[t,n]of this.#t)e.update(`${t}:${n.visible}`);return this.#e=e.hexdigest()}},hd=class{constructor(e,{disableRange:t=!1,disableStream:n=!1}){J(e,`PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.`);let{length:r,initialData:i,progressiveDone:a,contentDispositionFilename:o}=e;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=o,i?.length>0){let e=i instanceof Uint8Array&&i.byteLength===i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer;this._queuedChunks.push(e)}this._pdfDataRangeTransport=e,this._isStreamingSupported=!n,this._isRangeSupported=!t,this._contentLength=r,this._fullRequestReader=null,this._rangeReaders=[],e.addRangeListener((e,t)=>{this._onReceiveData({begin:e,chunk:t})}),e.addProgressListener((e,t)=>{this._onProgress({loaded:e,total:t})}),e.addProgressiveReadListener(e=>{this._onReceiveData({chunk:e})}),e.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),e.transportReady()}_onReceiveData({begin:e,chunk:t}){let n=t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer;e===void 0?this._fullRequestReader?this._fullRequestReader._enqueue(n):this._queuedChunks.push(n):J(this._rangeReaders.some(function(t){return t._begin===e&&(t._enqueue(n),!0)}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(e){e.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:e.loaded}):this._fullRequestReader?.onProgress?.({loaded:e.loaded,total:e.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(e){let t=this._rangeReaders.indexOf(e);t>=0&&this._rangeReaders.splice(t,1)}getFullReader(){J(!this._fullRequestReader,`PDFDataTransportStream.getFullReader can only be called once.`);let e=this._queuedChunks;return this._queuedChunks=null,new gd(this,e,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new _d(this,e,t);return this._pdfDataRangeTransport.requestDataRange(e,t),this._rangeReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeReaders.slice(0))t.cancel(e);this._pdfDataRangeTransport.abort()}},gd=class{constructor(e,t,n=!1,r=null){this._stream=e,this._done=n||!1,this._filename=Ml(r)?r:null,this._queuedChunks=t||[],this._loaded=0;for(let e of this._queuedChunks)this._loaded+=e.byteLength;this._requests=[],this._headersReady=Promise.resolve(),e._fullRequestReader=this,this.onProgress=null}_enqueue(e){this._done||(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunks.push(e),this._loaded+=e.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};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||=!0}},_d=class{constructor(e,t,n){this._stream=e,this._begin=t,this._end=n,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(e){if(!this._done){if(this._requests.length===0)this._queuedChunk=e;else{this._requests.shift().resolve({value:e,done:!1});for(let e of this._requests)e.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){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}};function vd(e){let t=!0,n=r(`filename\\*`,`i`).exec(e);if(n){n=n[1];let e=s(n);return e=unescape(e),e=c(e),e=l(e),a(e)}if(n=o(e),n)return a(l(n));if(n=r(`filename`,`i`).exec(e),n){n=n[1];let e=s(n);return e=l(e),a(e)}function r(e,t){return RegExp(`(?:^|;)\\s*`+e+`\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)`,t)}function i(e,n){if(e){if(!/^[\x00-\xFF]+$/.test(n))return n;try{let r=new TextDecoder(e,{fatal:!0}),i=fl(n);n=r.decode(i),t=!1}catch{}}return n}function a(e){return t&&/[\x80-\xff]/.test(e)&&(e=i(`utf-8`,e),t&&(e=i(`iso-8859-1`,e))),e}function o(e){let t=[],n,i=r(`filename\\*((?!0\\d)\\d+)(\\*?)`,`ig`);for(;(n=i.exec(e))!==null;){let[,e,r,i]=n;if(e=parseInt(e,10),e in t){if(e===0)break;continue}t[e]=[r,i]}let a=[];for(let e=0;e<t.length&&e in t;++e){let[n,r]=t[e];r=s(r),n&&(r=unescape(r),e===0&&(r=c(r))),a.push(r)}return a.join(``)}function s(e){if(e.startsWith(`"`)){let t=e.slice(1).split(`\\"`);for(let e=0;e<t.length;++e){let n=t[e].indexOf(`"`);n!==-1&&(t[e]=t[e].slice(0,n),t.length=e+1),t[e]=t[e].replaceAll(/\\(.)/g,`$1`)}e=t.join(`"`)}return e}function c(e){let t=e.indexOf(`'`);return t===-1?e:i(e.slice(0,t),e.slice(t+1).replace(/^[^']*'/,``))}function l(e){return!e.startsWith(`=?`)||/[\x00-\x19\x80-\xff]/.test(e)?e:e.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(e,t,n,r){if(n===`q`||n===`Q`)return r=r.replaceAll(`_`,` `),r=r.replaceAll(/=([0-9a-fA-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))}),i(t,r);try{r=atob(r)}catch{}return i(t,r)})}return``}function yd(e,t){let n=new Headers;if(!e||!t||typeof t!=`object`)return n;for(let e in t){let r=t[e];r!==void 0&&n.append(e,r)}return n}function bd(e){try{return new URL(e).origin}catch{}return null}function xd({responseHeaders:e,isHttp:t,rangeChunkSize:n,disableRange:r}){let i={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(e.get(`Content-Length`),10);return!Number.isInteger(a)||(i.suggestedLength=a,a<=2*n)||r||!t||e.get(`Accept-Ranges`)!==`bytes`||(e.get(`Content-Encoding`)||`identity`)!==`identity`||(i.allowRangeRequests=!0),i}function Sd(e){let t=e.get(`Content-Disposition`);if(t){let e=vd(t);if(e.includes(`%`))try{e=decodeURIComponent(e)}catch{}if(Ml(e))return e}return null}function Cd(e,t){return e===404||e===0&&t.startsWith(`file:`)?new sl(`Missing PDF "`+t+`".`):new cl(`Unexpected server response (${e}) while retrieving PDF "${t}".`,e)}function wd(e){return e===200||e===206}function Td(e,t,n){return{method:`GET`,headers:e,signal:n.signal,mode:`cors`,credentials:t?`include`:`same-origin`,redirect:`follow`}}function Ed(e){return e instanceof Uint8Array?e.buffer:e instanceof ArrayBuffer?e:(K(`getArrayBuffer - unexpected data format: ${e}`),new Uint8Array(e).buffer)}var Dd=class{_responseOrigin=null;constructor(e){this.source=e,this.isHttp=/^https?:/i.test(e.url),this.headers=yd(this.isHttp,e.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return J(!this._fullRequestReader,`PDFFetchStream.getFullReader can only be called once.`),this._fullRequestReader=new Od(this),this._fullRequestReader}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new kd(this,e,t);return this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Od=class{constructor(e){this._stream=e,this._reader=null,this._loaded=0,this._filename=null;let t=e.source;this._withCredentials=t.withCredentials||!1,this._contentLength=t.length,this._headersCapability=Promise.withResolvers(),this._disableRange=t.disableRange||!1,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!t.disableStream,this._isRangeSupported=!t.disableRange;let n=new Headers(e.headers),r=t.url;fetch(r,Td(n,this._withCredentials,this._abortController)).then(t=>{if(e._responseOrigin=bd(t.url),!wd(t.status))throw Cd(t.status,r);this._reader=t.body.getReader(),this._headersCapability.resolve();let n=t.headers,{allowRangeRequests:i,suggestedLength:a}=xd({responseHeaders:n,isHttp:e.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=i,this._contentLength=a||this._contentLength,this._filename=Sd(n),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ul(`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;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Ed(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},kd=class{constructor(e,t,n){this._stream=e,this._reader=null,this._loaded=0;let r=e.source;this._withCredentials=r.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!r.disableStream,this._abortController=new AbortController;let i=new Headers(e.headers);i.append(`Range`,`bytes=${t}-${n-1}`);let a=r.url;fetch(a,Td(i,this._withCredentials,this._abortController)).then(t=>{let n=bd(t.url);if(n!==e._responseOrigin)throw Error(`Expected range response-origin "${n}" to match "${e._responseOrigin}".`);if(!wd(t.status))throw Cd(t.status,a);this._readCapability.resolve(),this._reader=t.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Ed(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},Ad=200,jd=206;function Md(e){let t=e.response;return typeof t==`string`?fl(t).buffer:t}var Nd=class{_responseOrigin=null;constructor({url:e,httpHeaders:t,withCredentials:n}){this.url=e,this.isHttp=/^https?:/i.test(e),this.headers=yd(this.isHttp,t),this.withCredentials=n||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(e){let t=new XMLHttpRequest,n=this.currXhrId++,r=this.pendingRequests[n]={xhr:t};t.open(`GET`,this.url),t.withCredentials=this.withCredentials;for(let[e,n]of this.headers)t.setRequestHeader(e,n);return this.isHttp&&`begin`in e&&`end`in e?(t.setRequestHeader(`Range`,`bytes=${e.begin}-${e.end-1}`),r.expectedStatus=jd):r.expectedStatus=Ad,t.responseType=`arraybuffer`,J(e.onError,"Expected `onError` callback to be provided."),t.onerror=()=>{e.onError(t.status)},t.onreadystatechange=this.onStateChange.bind(this,n),t.onprogress=this.onProgress.bind(this,n),r.onHeadersReceived=e.onHeadersReceived,r.onDone=e.onDone,r.onError=e.onError,r.onProgress=e.onProgress,t.send(null),n}onProgress(e,t){let n=this.pendingRequests[e];n&&n.onProgress?.(t)}onStateChange(e,t){let n=this.pendingRequests[e];if(!n)return;let r=n.xhr;if(r.readyState>=2&&n.onHeadersReceived&&(n.onHeadersReceived(),delete n.onHeadersReceived),r.readyState!==4||!(e in this.pendingRequests))return;if(delete this.pendingRequests[e],r.status===0&&this.isHttp){n.onError(r.status);return}let i=r.status||Ad;if((i!==Ad||n.expectedStatus!==jd)&&i!==n.expectedStatus){n.onError(r.status);return}let a=Md(r);if(i===jd){let e=r.getResponseHeader(`Content-Range`),t=/bytes (\d+)-(\d+)\/(\d+)/.exec(e);t?n.onDone({begin:parseInt(t[1],10),chunk:a}):(K(`Missing or invalid "Content-Range" header.`),n.onError(0))}else a?n.onDone({begin:0,chunk:a}):n.onError(r.status)}getRequestXhr(e){return this.pendingRequests[e].xhr}isPendingRequest(e){return e in this.pendingRequests}abortRequest(e){let t=this.pendingRequests[e].xhr;delete this.pendingRequests[e],t.abort()}},Pd=class{constructor(e){this._source=e,this._manager=new Nd(e),this._rangeChunkSize=e.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(e){let t=this._rangeRequestReaders.indexOf(e);t>=0&&this._rangeRequestReaders.splice(t,1)}getFullReader(){return J(!this._fullRequestReader,`PDFNetworkStream.getFullReader can only be called once.`),this._fullRequestReader=new Fd(this._manager,this._source),this._fullRequestReader}getRangeReader(e,t){let n=new Id(this._manager,e,t);return n.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Fd=class{constructor(e,t){this._manager=e,this._url=t.url,this._fullRequestId=e.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=t.disableRange||!1,this._contentLength=t.length,this._rangeChunkSize=t.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(){let e=this._fullRequestId,t=this._manager.getRequestXhr(e);this._manager._responseOrigin=bd(t.responseURL);let n=t.getAllResponseHeaders(),r=new Headers(n?n.trimStart().replace(/[^\S ]+$/,``).split(/[\r\n]+/).map(e=>{let[t,...n]=e.split(`: `);return[t,n.join(`: `)]}):[]),{allowRangeRequests:i,suggestedLength:a}=xd({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=a||this._contentLength,this._filename=Sd(r),this._isRangeSupported&&this._manager.abortRequest(e),this._headersCapability.resolve()}_onDone(e){if(e&&(this._requests.length>0?this._requests.shift().resolve({value:e.chunk,done:!1}):this._cachedChunks.push(e.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(e){this._storedError=Cd(e,this._url),this._headersCapability.reject(this._storedError);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(e){this.onProgress?.({loaded:e.loaded,total:e.lengthComputable?e.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};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e);for(let 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}},Id=class{constructor(e,t,n){this._manager=e,this._url=e.url,this._requestId=e.request({begin:t,end:n,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(){let e=bd(this._manager.getRequestXhr(this._requestId)?.responseURL);e!==this._manager._responseOrigin&&(this._storedError=Error(`Expected range response-origin "${e}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(e){let t=e.chunk;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(e){this._storedError??=Cd(e,this._url);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(e){this.isStreamingSupported||this.onProgress?.({loaded:e.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let 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()}},Ld=/^[a-z][a-z0-9\-+.]+:/i;function Rd(e){if(Ld.test(e))return new URL(e);let t=process.getBuiltinModule(`url`);return new URL(t.pathToFileURL(e))}var zd=class{constructor(e){this.source=e,this.url=Rd(e.url),J(this.url.protocol===`file:`,`PDFNodeStream only supports file:// URLs.`),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return J(!this._fullRequestReader,`PDFNodeStream.getFullReader can only be called once.`),this._fullRequestReader=new Bd(this),this._fullRequestReader}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new Vd(this,e,t);return this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Bd=class{constructor(e){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null;let t=e.source;this._contentLength=t.length,this._loaded=0,this._filename=null,this._disableRange=t.disableRange||!1,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!t.disableStream,this._isRangeSupported=!t.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();let n=process.getBuiltinModule(`fs`);n.promises.lstat(this._url).then(e=>{this._contentLength=e.size,this._setReadableStream(n.createReadStream(this._url)),this._headersCapability.resolve()},e=>{e.code===`ENOENT`&&(e=new sl(`Missing PDF "${this._url}".`)),this._storedError=e,this._headersCapability.reject(e)})}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;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on(`readable`,()=>{this._readCapability.resolve()}),e.on(`end`,()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on(`error`,e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new ul(`streaming is disabled`)),this._storedError&&this._readableStream.destroy(this._storedError)}},Vd=class{constructor(e,t,n){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let r=e.source;this._isStreamingSupported=!r.disableStream;let i=process.getBuiltinModule(`fs`);this._setReadableStream(i.createReadStream(this._url,{start:t,end:n-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;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on(`readable`,()=>{this._readCapability.resolve()}),e.on(`end`,()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on(`error`,e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}},Hd=1e5,Ud=30,Wd=.8,Gd=class e{#e=Promise.withResolvers();#t=null;#n=!1;#r=!!globalThis.FontInspector?.enabled;#i=null;#a=null;#o=0;#s=0;#c=null;#l=null;#u=0;#d=0;#f=Object.create(null);#p=[];#m=null;#h=[];#g=new WeakMap;#_=null;static#v=new Map;static#y=new Map;static#b=new WeakMap;static#x=null;static#S=new Set;constructor({textContentSource:t,container:n,viewport:r}){if(t instanceof ReadableStream)this.#m=t;else if(typeof t==`object`)this.#m=new ReadableStream({start(e){e.enqueue(t),e.close()}});else throw Error(`No "textContentSource" parameter specified.`);this.#t=this.#l=n,this.#d=r.scale*(globalThis.devicePixelRatio||1),this.#u=r.rotation,this.#a={div:null,properties:null,ctx:null};let{pageWidth:i,pageHeight:a,pageX:o,pageY:s}=r.rawDims;this.#_=[1,0,0,-1,-o,s+a],this.#s=i,this.#o=a,e.#O(),Wl(n,r),this.#e.promise.finally(()=>{e.#S.delete(this),this.#a=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:e,isFirefox:t}=_l.platform;return Y(this,`fontFamilyMap`,new Map([[`sans-serif`,`${e&&t?`Calibri, `:``}sans-serif`],[`monospace`,`${e&&t?`Lucida Console, `:``}monospace`]]))}render(){let t=()=>{this.#c.read().then(({value:e,done:n})=>{if(n){this.#e.resolve();return}this.#i??=e.lang,Object.assign(this.#f,e.styles),this.#C(e.items),t()},this.#e.reject)};return this.#c=this.#m.getReader(),e.#S.add(this),t(),this.#e.promise}update({viewport:t,onBefore:n=null}){let r=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#u&&(n?.(),this.#u=i,Wl(this.#l,{rotation:i})),r!==this.#d){n?.(),this.#d=r;let t={div:null,properties:null,ctx:e.#E(this.#i)};for(let e of this.#h)t.properties=this.#g.get(e),t.div=e,this.#T(t)}}cancel(){let e=new ul(`TextLayer task cancelled.`);this.#c?.cancel(e).catch(()=>{}),this.#c=null,this.#e.reject(e)}get textDivs(){return this.#h}get textContentItemsStr(){return this.#p}#C(t){if(this.#n)return;this.#a.ctx??=e.#E(this.#i);let n=this.#h,r=this.#p;for(let e of t){if(n.length>Hd){K(`Ignoring additional textDivs for performance reasons.`),this.#n=!0;return}if(e.str===void 0){if(e.type===`beginMarkedContentProps`||e.type===`beginMarkedContent`){let t=this.#t;this.#t=document.createElement(`span`),this.#t.classList.add(`markedContent`),e.id!==null&&this.#t.setAttribute(`id`,`${e.id}`),t.append(this.#t)}else e.type===`endMarkedContent`&&(this.#t=this.#t.parentNode);continue}r.push(e.str),this.#w(e)}}#w(t){let n=document.createElement(`span`),r={angle:0,canvasWidth:0,hasText:t.str!==``,hasEOL:t.hasEOL,fontSize:0};this.#h.push(n);let i=X.transform(this.#_,t.transform),a=Math.atan2(i[1],i[0]),o=this.#f[t.fontName];o.vertical&&(a+=Math.PI/2);let s=this.#r&&o.fontSubstitution||o.fontFamily;s=e.fontFamilyMap.get(s)||s;let c=Math.hypot(i[2],i[3]),l=c*e.#k(s,this.#i),u,d;a===0?(u=i[4],d=i[5]-l):(u=i[4]+l*Math.sin(a),d=i[5]-l*Math.cos(a));let f=`calc(var(--scale-factor)*`,p=n.style;this.#t===this.#l?(p.left=`${(100*u/this.#s).toFixed(2)}%`,p.top=`${(100*d/this.#o).toFixed(2)}%`):(p.left=`${f}${u.toFixed(2)}px)`,p.top=`${f}${d.toFixed(2)}px)`),p.fontSize=`${f}${(e.#x*c).toFixed(2)}px)`,p.fontFamily=s,r.fontSize=c,n.setAttribute(`role`,`presentation`),n.textContent=t.str,n.dir=t.dir,this.#r&&(n.dataset.fontName=o.fontSubstitutionLoadedName||t.fontName),a!==0&&(r.angle=180/Math.PI*a);let m=!1;if(t.str.length>1)m=!0;else if(t.str!==` `&&t.transform[0]!==t.transform[3]){let e=Math.abs(t.transform[0]),n=Math.abs(t.transform[3]);e!==n&&Math.max(e,n)/Math.min(e,n)>1.5&&(m=!0)}if(m&&(r.canvasWidth=o.vertical?t.height:t.width),this.#g.set(n,r),this.#a.div=n,this.#a.properties=r,this.#T(this.#a),r.hasText&&this.#t.append(n),r.hasEOL){let e=document.createElement(`br`);e.setAttribute(`role`,`presentation`),this.#t.append(e)}}#T(t){let{div:n,properties:r,ctx:i}=t,{style:a}=n,o=``;if(e.#x>1&&(o=`scale(${1/e.#x})`),r.canvasWidth!==0&&r.hasText){let{fontFamily:t}=a,{canvasWidth:s,fontSize:c}=r;e.#D(i,c*this.#d,t);let{width:l}=i.measureText(n.textContent);l>0&&(o=`scaleX(${s*this.#d/l}) ${o}`)}r.angle!==0&&(o=`rotate(${r.angle}deg) ${o}`),o.length>0&&(a.transform=o)}static cleanup(){if(!(this.#S.size>0)){this.#v.clear();for(let{canvas:e}of this.#y.values())e.remove();this.#y.clear()}}static#E(e=null){let t=this.#y.get(e||=``);if(!t){let n=document.createElement(`canvas`);n.className=`hiddenCanvasElement`,n.lang=e,document.body.append(n),t=n.getContext(`2d`,{alpha:!1,willReadFrequently:!0}),this.#y.set(e,t),this.#b.set(t,{size:0,family:``})}return t}static#D(e,t,n){let r=this.#b.get(e);(t!==r.size||n!==r.family)&&(e.font=`${t}px ${n}`,r.size=t,r.family=n)}static#O(){if(this.#x!==null)return;let e=document.createElement(`div`);e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize=`1px`,e.style.position=`absolute`,e.textContent=`X`,document.body.append(e),this.#x=e.getBoundingClientRect().height,e.remove()}static#k(e,t){let n=this.#v.get(e);if(n)return n;let r=this.#E(t);r.canvas.width=r.canvas.height=Ud,this.#D(r,Ud,e);let i=r.measureText(``),a=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(a){let t=a/(a+o);return this.#v.set(e,t),r.canvas.width=r.canvas.height=0,t}r.strokeStyle=`red`,r.clearRect(0,0,Ud,Ud),r.strokeText(`g`,0,0);let s=r.getImageData(0,0,Ud,Ud).data;o=0;for(let e=s.length-1-3;e>=0;e-=4)if(s[e]>0){o=Math.ceil(e/4/Ud);break}r.clearRect(0,0,Ud,Ud),r.strokeText(`A`,0,Ud),s=r.getImageData(0,0,Ud,Ud).data,a=0;for(let e=0,t=s.length;e<t;e+=4)if(s[e]>0){a=Ud-Math.floor(e/4/Ud);break}r.canvas.width=r.canvas.height=0;let c=a?a/(a+o):Wd;return this.#v.set(e,c),c}},Kd=class e{static textContent(t){let n=[],r={items:n,styles:Object.create(null)};function i(t){if(!t)return;let r=null,a=t.name;if(a===`#text`)r=t.value;else if(e.shouldBuildText(a))t?.attributes?.textContent?r=t.attributes.textContent:t.value&&(r=t.value);else return;if(r!==null&&n.push({str:r}),t.children)for(let e of t.children)i(e)}return i(t),r}static shouldBuildText(e){return e!==`textarea`&&e!==`input`&&e!==`option`&&e!==`select`}},qd=65536,Jd=100,Yd=5e3,Xd=Fc?Ou:yu,Zd=Fc?ku:xu,Qd=Fc?Du:Cu,$d=Fc?Au:Tu;function ef(e={}){typeof e==`string`||e instanceof URL?e={url:e}:(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});let t=new af,{docId:n}=t,r=e.url?tf(e.url):null,i=e.data?nf(e.data):null,a=e.httpHeaders||null,o=e.withCredentials===!0,s=e.password??null,c=e.range instanceof of?e.range:null,l=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:qd,u=e.worker instanceof uf?e.worker:null,d=e.verbosity,f=typeof e.docBaseUrl==`string`&&!jl(e.docBaseUrl)?e.docBaseUrl:null,p=typeof e.cMapUrl==`string`?e.cMapUrl:null,m=e.cMapPacked!==!1,h=e.CMapReaderFactory||Zd,g=typeof e.standardFontDataUrl==`string`?e.standardFontDataUrl:null,_=e.StandardFontDataFactory||$d,v=e.stopAtErrors!==!0,y=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,b=e.isEvalSupported!==!1,x=typeof e.isOffscreenCanvasSupported==`boolean`?e.isOffscreenCanvasSupported:!Fc,S=typeof e.isImageDecoderSupported==`boolean`?e.isImageDecoderSupported:!Fc&&(_l.platform.isFirefox||!globalThis.chrome),C=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,w=typeof e.disableFontFace==`boolean`?e.disableFontFace:Fc,T=e.fontExtraProperties===!0,E=e.enableXfa===!0,D=e.ownerDocument||globalThis.document,O=e.disableRange===!0,k=e.disableStream===!0,A=e.disableAutoFetch===!0,j=e.pdfBug===!0,M=e.CanvasFactory||Xd,ee=e.FilterFactory||Qd,N=e.enableHWA===!0,P=c?c.length:e.length??NaN,F=typeof e.useSystemFonts==`boolean`?e.useSystemFonts:!Fc&&!w,I=typeof e.useWorkerFetch==`boolean`?e.useWorkerFetch:h===xu&&_===Tu&&p&&g&&Il(p,document.baseURI)&&Il(g,document.baseURI);Qc(d);let te={canvasFactory:new M({ownerDocument:D,enableHWA:N}),filterFactory:new ee({docId:n,ownerDocument:D}),cMapReaderFactory:I?null:new h({baseUrl:p,isCompressed:m}),standardFontDataFactory:I?null:new _({baseUrl:g})};if(!u){let e={verbosity:d,port:ud.workerPort};u=e.port?uf.fromPort(e):new uf(e),t._worker=u}let ne={docId:n,apiVersion:`4.10.38`,data:i,password:s,disableAutoFetch:A,rangeChunkSize:l,length:P,docBaseUrl:f,enableXfa:E,evaluatorOptions:{maxImageSize:y,disableFontFace:w,ignoreErrors:v,isEvalSupported:b,isOffscreenCanvasSupported:x,isImageDecoderSupported:S,canvasMaxAreaInBytes:C,fontExtraProperties:T,useSystemFonts:F,cMapUrl:I?p:null,standardFontDataUrl:I?g:null}},re={disableFontFace:w,fontExtraProperties:T,ownerDocument:D,pdfBug:j,styleElement:null,loadingParams:{disableAutoFetch:A,enableXfa:E}};return u.promise.then(function(){if(t.destroyed)throw Error(`Loading aborted`);if(u.destroyed)throw Error(`Worker was destroyed`);let e=u.messageHandler.sendWithPromise(`GetDocRequest`,ne,i?[i.buffer]:null),s;if(c)s=new hd(c,{disableRange:O,disableStream:k});else if(!i){if(!r)throw Error("getDocument - no `url` parameter provided.");let e;if(Fc){if(Il(r)){if(typeof fetch>`u`||typeof Response>`u`||!(`body`in Response.prototype))throw Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");e=Dd}else e=zd}else e=Il(r)?Dd:Pd;s=new e({url:r,length:P,httpHeaders:a,withCredentials:o,rangeChunkSize:l,disableRange:O,disableStream:k})}return e.then(e=>{if(t.destroyed)throw Error(`Loading aborted`);if(u.destroyed)throw Error(`Worker was destroyed`);let r=new _u(n,e,u.port),i=new df(r,t,s,re,te);t._transport=i,r.send(`Ready`,null)})}).catch(t._capability.reject),t}function tf(e){if(e instanceof URL)return e.href;try{return new URL(e,window.location).href}catch{if(Fc&&typeof e==`string`)return e}throw Error(`Invalid PDF url data: either string or URL-object is expected in the url property.`)}function nf(e){if(Fc&&typeof Buffer<`u`&&e instanceof Buffer)throw Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if(typeof e==`string`)return fl(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`object`&&!isNaN(e?.length))return new Uint8Array(e);throw Error(`Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.`)}function rf(e){return typeof e==`object`&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0}var af=class e{static#e=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${e.#e++}`,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(e){throw this._worker?.port&&delete this._worker._pendingDestroy,e}this._transport=null,this._worker?.destroy(),this._worker=null}},of=class{constructor(e,t,n=!1,r=null){this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=r,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(e){this._rangeListeners.push(e)}addProgressListener(e){this._progressListeners.push(e)}addProgressiveReadListener(e){this._progressiveReadListeners.push(e)}addProgressiveDoneListener(e){this._progressiveDoneListeners.push(e)}onDataRange(e,t){for(let n of this._rangeListeners)n(e,t)}onDataProgress(e,t){this._readyCapability.promise.then(()=>{for(let n of this._progressListeners)n(e,t)})}onDataProgressiveRead(e){this._readyCapability.promise.then(()=>{for(let t of this._progressiveReadListeners)t(e)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(let e of this._progressiveDoneListeners)e()})}transportReady(){this._readyCapability.resolve()}requestDataRange(e,t){q(`Abstract method PDFDataRangeTransport.requestDataRange`)}abort(){}},sf=class{constructor(e,t){this._pdfInfo=e,this._transport=t}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 Y(this,`isPureXfa`,!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}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:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}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(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}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()}},cf=class{#e=null;#t=!1;constructor(e,t,n,r=!1){this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=r?new Fl:null,this._pdfBug=r,this.commonObjs=n.commonObjs,this.objs=new pf,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:e,rotation:t=this.rotate,offsetX:n=0,offsetY:r=0,dontFlip:i=!1}={}){return new kl({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:r,dontFlip:i})}getAnnotations({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Y(this,`isPureXfa`,!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:e,viewport:t,intent:n=`display`,annotationMode:r=Vc.ENABLE,transform:i=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:s=null,pageColors:c=null,printAnnotationStorage:l=null,isEditing:u=!1}){this._stats?.time(`Overall`);let d=this._transport.getRenderingIntent(n,r,l,u),{renderingIntent:f,cacheKey:p}=d;this.#t=!1,this.#r(),o||=this._transport.getOptionalContentConfig(f);let m=this._intentStates.get(p);m||(m=Object.create(null),this._intentStates.set(p,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);let h=!!(f&Bc.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(d));let g=e=>{m.renderTasks.delete(_),(this._maybeCleanupAfterRender||h)&&(this.#t=!0),this.#n(!h),e?(_.capability.reject(e),this._abortOperatorList({intentState:m,reason:e instanceof Error?e:Error(e)})):_.capability.resolve(),this._stats&&(this._stats.timeEnd(`Rendering`),this._stats.timeEnd(`Overall`),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},_=new hf({callback:g,params:{canvasContext:e,viewport:t,transform:i,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:s,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!h,pdfBug:this._pdfBug,pageColors:c});(m.renderTasks||=new Set).add(_);let v=_.task;return Promise.all([m.displayReadyCapability.promise,o]).then(([e,t])=>{if(this.destroyed){g();return}if(this._stats?.time(`Rendering`),!(t.renderingIntent&f))throw Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");_.initializeGraphics({transparency:e,optionalContentConfig:t}),_.operatorListChanged()}).catch(g),v}getOperatorList({intent:e=`display`,annotationMode:t=Vc.ENABLE,printAnnotationStorage:n=null,isEditing:r=!1}={}){function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(s))}let a=this._transport.getRenderingIntent(e,t,n,r,!0),o=this._intentStates.get(a.cacheKey);o||(o=Object.create(null),this._intentStates.set(a.cacheKey,o));let s;return o.opListReadCapability||(s=Object.create(null),s.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(s),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(a)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream(`GetTextContent`,{pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(e){return e.items.length}})}getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(e=>Kd.textContent(e));let t=this.streamTextContent(e);return new Promise(function(e,n){function r(){i.read().then(function({value:t,done:n}){if(n){e(a);return}a.lang??=t.lang,Object.assign(a.styles,t.styles),a.items.push(...t.items),r()},n)}let i=t.getReader(),a={items:[],styles:Object.create(null),lang:null};r()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let e=[];for(let t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:Error(`Page was destroyed.`),force:!0}),!t.opListReadCapability)for(let n of t.renderTasks)e.push(n.completed),n.cancel();return this.objs.clear(),this.#t=!1,this.#r(),Promise.all(e)}cleanup(e=!1){this.#t=!0;let t=this.#n(!1);return e&&t&&(this._stats&&=new Fl),t}#n(e=!1){if(this.#r(),!this.#t||this.destroyed)return!1;if(e)return this.#e=setTimeout(()=>{this.#e=null,this.#n(!1)},Yd),!1;for(let{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#t=!1,!0}#r(){this.#e&&=(clearTimeout(this.#e),null)}_startRenderPage(e,t){let n=this._intentStates.get(t);n&&(this._stats?.timeEnd(`Page Request`),n.displayReadyCapability?.resolve(e))}_renderPageChunk(e,t){for(let n=0,r=e.length;n<r;n++)t.operatorList.fnArray.push(e.fnArray[n]),t.operatorList.argsArray.push(e.argsArray[n]);t.operatorList.lastChunk=e.lastChunk,t.operatorList.separateAnnots=e.separateAnnots;for(let e of t.renderTasks)e.operatorListChanged();e.lastChunk&&this.#n(!0)}_pumpOperatorList({renderingIntent:e,cacheKey:t,annotationStorageSerializable:n,modifiedIds:r}){let{map:i,transfer:a}=n,o=this._transport.messageHandler.sendWithStream(`GetOperatorList`,{pageIndex:this._pageIndex,intent:e,cacheKey:t,annotationStorage:i,modifiedIds:r},a).getReader(),s=this._intentStates.get(t);s.streamReader=o;let c=()=>{o.read().then(({value:e,done:t})=>{if(t){s.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(e,s),c())},e=>{if(s.streamReader=null,!this._transport.destroyed){if(s.operatorList){s.operatorList.lastChunk=!0;for(let e of s.renderTasks)e.operatorListChanged();this.#n(!0)}if(s.displayReadyCapability)s.displayReadyCapability.reject(e);else if(s.opListReadCapability)s.opListReadCapability.reject(e);else throw e}})};c()}_abortOperatorList({intentState:e,reason:t,force:n=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&=(clearTimeout(e.streamReaderCancelTimeout),null),!n){if(e.renderTasks.size>0)return;if(t instanceof Al){let n=Jd;t.extraDelay>0&&t.extraDelay<1e3&&(n+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},n);return}}if(e.streamReader.cancel(new ul(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(let[t,n]of this._intentStates)if(n===e){this._intentStates.delete(t);break}this.cleanup()}}}get stats(){return this._stats}},lf=class{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[e]of this.#e)e.call(this,n)})}addEventListener(e,t,n=null){let r=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){K("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,t);r=()=>i.removeEventListener(`abort`,a),i.addEventListener(`abort`,a)}this.#e.set(t,r)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},uf=class e{static#e=0;static#t=!1;static#n;static{Fc&&(this.#t=!0,ud.workerSrc||=`./pdf.worker.mjs`),this._isSameOrigin=(e,t)=>{let n;try{if(n=new URL(e),!n.origin||n.origin===`null`)return!1}catch{return!1}let r=new URL(t,n);return n.origin===r.origin},this._createCDNWrapper=e=>{let t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:`text/javascript`}))}}constructor({name:t=null,port:n=null,verbosity:r=$c()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if(e.#n?.has(n))throw Error(`Cannot use more than one PDFWorker per port.`);(e.#n||=new WeakMap).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return this._readyCapability.promise}#r(){this._readyCapability.resolve(),this._messageHandler.send(`configure`,{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(e){this._port=e,this._messageHandler=new _u(`main`,`worker`,e),this._messageHandler.on(`ready`,function(){}),this.#r()}_initialize(){if(e.#t||e.#i){this._setupFakeWorker();return}let{workerSrc:t}=e;try{e._isSameOrigin(window.location.href,t)||(t=e._createCDNWrapper(new URL(t,window.location).href));let n=new Worker(t,{type:`module`}),r=new _u(`main`,`worker`,n),i=()=>{a.abort(),r.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(Error(`Worker was destroyed`)):this._setupFakeWorker()},a=new AbortController;n.addEventListener(`error`,()=>{this._webWorker||i()},{signal:a.signal}),r.on(`test`,e=>{if(a.abort(),this.destroyed||!e){i();return}this._messageHandler=r,this._port=n,this._webWorker=n,this.#r()}),r.on(`ready`,e=>{if(a.abort(),this.destroyed){i();return}try{o()}catch{this._setupFakeWorker()}});let o=()=>{let e=new Uint8Array;r.send(`test`,e,[e.buffer])};o();return}catch{el(`The worker has been disabled.`)}this._setupFakeWorker()}_setupFakeWorker(){e.#t||=(K(`Setting up fake worker.`),!0),e._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(Error(`Worker was destroyed`));return}let n=new lf;this._port=n;let r=`fake${e.#e++}`,i=new _u(r+`_worker`,r,n);t.setup(i,n),this._messageHandler=new _u(r,r+`_worker`,n),this.#r()}).catch(e=>{this._readyCapability.reject(Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,e.#n?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw Error(`PDFWorker.fromPort - invalid method signature.`);let n=this.#n?.get(t.port);if(n){if(n._pendingDestroy)throw Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new e(t)}static get workerSrc(){if(ud.workerSrc)return ud.workerSrc;throw Error(`No "GlobalWorkerOptions.workerSrc" specified.`)}static get#i(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return Y(this,`_setupFakeWorkerGlobal`,(async()=>this.#i?this.#i:(await import(this.workerSrc)).WorkerMessageHandler)())}},df=class{#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=null;constructor(e,t,n,r,i){this.messageHandler=e,this.loadingTask=t,this.commonObjs=new pf,this.fontLoader=new du({ownerDocument:r.ownerDocument,styleElement:r.styleElement}),this.loadingParams=r.loadingParams,this._params=r,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.cMapReaderFactory=i.cMapReaderFactory,this.standardFontDataFactory=i.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=n,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#a(e,t=null){let n=this.#e.get(e);if(n)return n;let r=this.messageHandler.sendWithPromise(e,t);return this.#e.set(e,r),r}get annotationStorage(){return Y(this,`annotationStorage`,new lu)}getRenderingIntent(e,t=Vc.ENABLE,n=null,r=!1,i=!1){let a=Bc.DISPLAY,o=cu;switch(e){case`any`:a=Bc.ANY;break;case`display`:break;case`print`:a=Bc.PRINT;break;default:K(`getRenderingIntent - invalid intent: ${e}`)}let s=a&Bc.PRINT&&n instanceof uu?n:this.annotationStorage;switch(t){case Vc.DISABLE:a+=Bc.ANNOTATIONS_DISABLE;break;case Vc.ENABLE:break;case Vc.ENABLE_FORMS:a+=Bc.ANNOTATIONS_FORMS;break;case Vc.ENABLE_STORAGE:a+=Bc.ANNOTATIONS_STORAGE,o=s.serializable;break;default:K(`getRenderingIntent - invalid annotationMode: ${t}`)}r&&(a+=Bc.IS_EDITING),i&&(a+=Bc.OPLIST);let{ids:c,hash:l}=s.modifiedIds,u=[a,o.hash,l];return{renderingIntent:a,cacheKey:u.join(`_`),annotationStorageSerializable:o,modifiedIds:c}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#i?.reject(Error(`Worker was destroyed during onPassword callback`));let e=[];for(let t of this.#t.values())e.push(t._destroy());this.#t.clear(),this.#n.clear(),this.#r.clear(),this.hasOwnProperty(`annotationStorage`)&&this.annotationStorage.resetModified();let t=this.messageHandler.sendWithPromise(`Terminate`,null);return e.push(t),Promise.all(e).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(),Gd.cleanup(),this._networkStream?.cancelAllRequests(new ul(`Worker was terminated.`)),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:e,loadingTask:t}=this;e.on(`GetReader`,(e,t)=>{J(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=e=>{this._lastProgress={loaded:e.loaded,total:e.total}},t.onPull=()=>{this._fullReader.read().then(function({value:e,done:n}){if(n){t.close();return}J(e instanceof ArrayBuffer,`GetReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{this._fullReader.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`ReaderHeadersReady`,async e=>{await this._fullReader.headersReady;let{isStreamingSupported:n,isRangeSupported:r,contentLength:i}=this._fullReader;return(!n||!r)&&(this._lastProgress&&t.onProgress?.(this._lastProgress),this._fullReader.onProgress=e=>{t.onProgress?.({loaded:e.loaded,total:e.total})}),{isStreamingSupported:n,isRangeSupported:r,contentLength:i}}),e.on(`GetRangeReader`,(e,t)=>{J(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let n=this._networkStream.getRangeReader(e.begin,e.end);if(!n){t.close();return}t.onPull=()=>{n.read().then(function({value:e,done:n}){if(n){t.close();return}J(e instanceof ArrayBuffer,`GetRangeReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{n.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`GetDoc`,({pdfInfo:e})=>{this._numPages=e.numPages,this._htmlForXfa=e.htmlForXfa,delete e.htmlForXfa,t._capability.resolve(new sf(e,this))}),e.on(`DocException`,e=>{t._capability.reject(gu(e))}),e.on(`PasswordRequest`,e=>{this.#i=Promise.withResolvers();try{if(!t.onPassword)throw gu(e);t.onPassword(e=>{e instanceof Error?this.#i.reject(e):this.#i.resolve({password:e})},e.code)}catch(e){this.#i.reject(e)}return this.#i.promise}),e.on(`DataLoaded`,e=>{t.onProgress?.({loaded:e.length,total:e.length}),this.downloadInfoCapability.resolve(e)}),e.on(`StartRenderPage`,e=>{this.destroyed||this.#t.get(e.pageIndex)._startRenderPage(e.transparency,e.cacheKey)}),e.on(`commonobj`,([t,n,r])=>{if(this.destroyed||this.commonObjs.has(t))return null;switch(n){case`Font`:let{disableFontFace:i,fontExtraProperties:a,pdfBug:o}=this._params;if(`error`in r){let e=r.error;K(`Error during font loading: ${e}`),this.commonObjs.resolve(t,e);break}let s=new fu(r,{disableFontFace:i,fontExtraProperties:a,inspectFont:o&&globalThis.FontInspector?.enabled?(e,t)=>globalThis.FontInspector.fontAdded(e,t):null});this.fontLoader.bind(s).catch(()=>e.sendWithPromise(`FontFallback`,{id:t})).finally(()=>{!a&&s.data&&(s.data=null),this.commonObjs.resolve(t,s)});break;case`CopyLocalImage`:let{imageRef:c}=r;J(c,`The imageRef must be defined.`);for(let e of this.#t.values())for(let[,n]of e.objs)if(n?.ref===c)return n.dataLen?(this.commonObjs.resolve(t,structuredClone(n)),n.dataLen):null;break;case`FontPath`:case`Image`:case`Pattern`:this.commonObjs.resolve(t,r);break;default:throw Error(`Got unknown common object type ${n}`)}return null}),e.on(`obj`,([e,t,n,r])=>{if(this.destroyed)return;let i=this.#t.get(t);if(!i.objs.has(e)){if(i._intentStates.size===0){r?.bitmap?.close();return}switch(n){case`Image`:i.objs.resolve(e,r),r?.dataLen>Rc&&(i._maybeCleanupAfterRender=!0);break;case`Pattern`:i.objs.resolve(e,r);break;default:throw Error(`Got unknown object type ${n}`)}}}),e.on(`DocProgress`,e=>{this.destroyed||t.onProgress?.({loaded:e.loaded,total:e.total})}),e.on(`FetchBuiltInCMap`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.cMapReaderFactory)throw Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(e)}),e.on(`FetchStandardFontData`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.standardFontDataFactory)throw Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(e)})}getData(){return this.messageHandler.sendWithPromise(`GetData`,null)}saveDocument(){this.annotationStorage.size<=0&&K("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise(`SaveDocument`,{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:this._fullReader?.filename??null},t).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this._numPages)return Promise.reject(Error(`Invalid page request.`));let t=e-1,n=this.#n.get(t);if(n)return n;let r=this.messageHandler.sendWithPromise(`GetPage`,{pageIndex:t}).then(n=>{if(this.destroyed)throw Error(`Transport destroyed`);n.refStr&&this.#r.set(n.refStr,e);let r=new cf(t,n,this,this._params.pdfBug);return this.#t.set(t,r),r});return this.#n.set(t,r),r}getPageIndex(e){return rf(e)?this.messageHandler.sendWithPromise(`GetPageIndex`,{num:e.num,gen:e.gen}):Promise.reject(Error(`Invalid pageIndex request.`))}getAnnotations(e,t){return this.messageHandler.sendWithPromise(`GetAnnotations`,{pageIndex:e,intent:t})}getFieldObjects(){return this.#a(`GetFieldObjects`)}hasJSActions(){return this.#a(`HasJSActions`)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise(`GetCalculationOrderIds`,null)}getDestinations(){return this.messageHandler.sendWithPromise(`GetDestinations`,null)}getDestination(e){return typeof e==`string`?this.messageHandler.sendWithPromise(`GetDestination`,{id:e}):Promise.reject(Error(`Invalid destination request.`))}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.#a(`GetDocJSActions`)}getPageJSActions(e){return this.messageHandler.sendWithPromise(`GetPageJSActions`,{pageIndex:e})}getStructTree(e){return this.messageHandler.sendWithPromise(`GetStructTree`,{pageIndex:e})}getOutline(){return this.messageHandler.sendWithPromise(`GetOutline`,null)}getOptionalContentConfig(e){return this.#a(`GetOptionalContentConfig`).then(t=>new md(t,e))}getPermissions(){return this.messageHandler.sendWithPromise(`GetPermissions`,null)}getMetadata(){let e=`GetMetadata`,t=this.#e.get(e);if(t)return t;let n=this.messageHandler.sendWithPromise(e,null).then(e=>({info:e[0],metadata:e[1]?new dd(e[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#e.set(e,n),n}getMarkInfo(){return this.messageHandler.sendWithPromise(`GetMarkInfo`,null)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise(`Cleanup`,null);for(let e of this.#t.values())if(!e.cleanup())throw Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(!0),Gd.cleanup()}}cachedPageNumber(e){if(!rf(e))return null;let t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`;return this.#r.get(t)??null}},ff=Symbol(`INITIAL_DATA`),pf=class{#e=Object.create(null);#t(e){return this.#e[e]||={...Promise.withResolvers(),data:ff}}get(e,t=null){if(t){let n=this.#t(e);return n.promise.then(()=>t(n.data)),null}let n=this.#e[e];if(!n||n.data===ff)throw Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){let t=this.#e[e];return!!t&&t.data!==ff}delete(e){let t=this.#e[e];return!t||t.data===ff?!1:(delete this.#e[e],!0)}resolve(e,t=null){let n=this.#t(e);n.data=t,n.resolve()}clear(){for(let e in this.#e){let{data:t}=this.#e[e];t?.bitmap?.close()}this.#e=Object.create(null)}*[Symbol.iterator](){for(let e in this.#e){let{data:t}=this.#e[e];t!==ff&&(yield[e,t])}}},mf=class{#e=null;constructor(e){this.#e=e,this.onContinue=null}get promise(){return this.#e.capability.promise}cancel(e=0){this.#e.cancel(null,e)}get separateAnnots(){let{separateAnnots:e}=this.#e.operatorList;if(!e)return!1;let{annotationCanvasMap:t}=this.#e;return e.form||e.canvas&&t?.size>0}},hf=class e{#e=null;static#t=new WeakSet;constructor({callback:e,params:t,objs:n,commonObjs:r,annotationCanvasMap:i,operatorList:a,pageIndex:o,canvasFactory:s,filterFactory:c,useRequestAnimationFrame:l=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=e,this.params=t,this.objs=n,this.commonObjs=r,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=o,this.canvasFactory=s,this.filterFactory=c,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=l===!0&&typeof window<`u`,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new mf(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=t.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){if(this.cancelled)return;if(this._canvas){if(e.#t.has(this._canvas))throw Error(`Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.`);e.#t.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());let{canvasContext:r,viewport:i,transform:a,background:o}=this.params;this.gfx=new ld(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:a,viewport:i,transparency:t,background:o}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,n=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#e&&=(window.cancelAnimationFrame(this.#e),null),e.#t.delete(this._canvas),this.callback(t||new Al(`Rendering cancelled, page ${this._pageIndex+1}`,n))}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.#e=window.requestAnimationFrame(()=>{this.#e=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(),e.#t.delete(this._canvas),this.callback())))}},gf=`4.10.38`,_f=`f9bea397f`;function vf(e){return Math.floor(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`)}function yf(e){return Math.max(0,Math.min(255,255*e))}var bf=class{static CMYK_G([e,t,n,r]){return[`G`,1-Math.min(1,.3*e+.59*n+.11*t+r)]}static G_CMYK([e]){return[`CMYK`,0,0,0,1-e]}static G_RGB([e]){return[`RGB`,e,e,e]}static G_rgb([e]){return e=yf(e),[e,e,e]}static G_HTML([e]){let t=vf(e);return`#${t}${t}${t}`}static RGB_G([e,t,n]){return[`G`,.3*e+.59*t+.11*n]}static RGB_rgb(e){return e.map(yf)}static RGB_HTML(e){return`#${e.map(vf).join(``)}`}static T_HTML(){return`#00000000`}static T_rgb(){return[null]}static CMYK_RGB([e,t,n,r]){return[`RGB`,1-Math.min(1,e+r),1-Math.min(1,n+r),1-Math.min(1,t+r)]}static CMYK_rgb([e,t,n,r]){return[yf(1-Math.min(1,e+r)),yf(1-Math.min(1,n+r)),yf(1-Math.min(1,t+r))]}static CMYK_HTML(e){let t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,n]){let r=1-e,i=1-t,a=1-n;return[`CMYK`,r,i,a,Math.min(r,i,a)]}},xf=class{create(e,t,n=!1){if(e<=0||t<=0)throw Error(`Invalid SVG dimensions`);let r=this._createSVG(`svg:svg`);return r.setAttribute(`version`,`1.1`),n||(r.setAttribute(`width`,`${e}px`),r.setAttribute(`height`,`${t}px`)),r.setAttribute(`preserveAspectRatio`,`none`),r.setAttribute(`viewBox`,`0 0 ${e} ${t}`),r}createElement(e){if(typeof e!=`string`)throw Error(`Invalid SVG element type`);return this._createSVG(e)}_createSVG(e){q("Abstract method `_createSVG` called.")}},Sf=class extends xf{_createSVG(e){return document.createElementNS(El,e)}},Cf=class{static setupStorage(e,t,n,r,i){let a=r.getValue(t,{value:null});switch(n.name){case`textarea`:if(a.value!==null&&(e.textContent=a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})});break;case`input`:if(n.attributes.type===`radio`||n.attributes.type===`checkbox`){if(a.value===n.attributes.xfaOn?e.setAttribute(`checked`,!0):a.value===n.attributes.xfaOff&&e.removeAttribute(`checked`),i===`print`)break;e.addEventListener(`change`,e=>{r.setValue(t,{value:e.target.checked?e.target.getAttribute(`xfaOn`):e.target.getAttribute(`xfaOff`)})})}else{if(a.value!==null&&e.setAttribute(`value`,a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})})}break;case`select`:if(a.value!==null){e.setAttribute(`value`,a.value);for(let e of n.children)e.attributes.value===a.value?e.attributes.selected=!0:e.attributes.hasOwnProperty(`selected`)&&delete e.attributes.selected}e.addEventListener(`input`,e=>{let n=e.target.options,i=n.selectedIndex===-1?``:n[n.selectedIndex].value;r.setValue(t,{value:i})})}}static setAttributes({html:e,element:t,storage:n=null,intent:r,linkService:i}){let{attributes:a}=t,o=e instanceof HTMLAnchorElement;a.type===`radio`&&(a.name=`${a.name}-${r}`);for(let[t,n]of Object.entries(a))if(n!=null)switch(t){case`class`:n.length&&e.setAttribute(t,n.join(` `));break;case`dataId`:break;case`id`:e.setAttribute(`data-element-id`,n);break;case`style`:Object.assign(e.style,n);break;case`textContent`:e.textContent=n;break;default:(!o||t!==`href`&&t!==`newWindow`)&&e.setAttribute(t,n)}o&&i.addLinkAttributes(e,a.href,a.newWindow),n&&a.dataId&&this.setupStorage(e,a.dataId,t,n)}static render(e){let t=e.annotationStorage,n=e.linkService,r=e.xfaHtml,i=e.intent||`display`,a=document.createElement(r.name);r.attributes&&this.setAttributes({html:a,element:r,intent:i,linkService:n});let o=i!==`richText`,s=e.div;if(s.append(a),e.viewport){let t=`matrix(${e.viewport.transform.join(`,`)})`;s.style.transform=t}o&&s.setAttribute(`class`,`xfaLayer xfaFont`);let c=[];if(r.children.length===0){if(r.value){let e=document.createTextNode(r.value);a.append(e),o&&Kd.shouldBuildText(r.name)&&c.push(e)}return{textDivs:c}}let l=[[r,-1,a]];for(;l.length>0;){let[e,r,a]=l.at(-1);if(r+1===e.children.length){l.pop();continue}let s=e.children[++l.at(-1)[1]];if(s===null)continue;let{name:u}=s;if(u===`#text`){let e=document.createTextNode(s.value);c.push(e),a.append(e);continue}let d=s?.attributes?.xmlns?document.createElementNS(s.attributes.xmlns,u):document.createElement(u);if(a.append(d),s.attributes&&this.setAttributes({html:d,element:s,storage:t,intent:i,linkService:n}),s.children?.length>0)l.push([s,-1,d]);else if(s.value){let e=document.createTextNode(s.value);o&&Kd.shouldBuildText(u)&&c.push(e),d.append(e)}}for(let e of s.querySelectorAll(`.xfaNonInteractive input, .xfaNonInteractive textarea`))e.setAttribute(`readOnly`,!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(`,`)})`;e.div.style.transform=t,e.div.hidden=!1}},wf=1e3,Tf=9,Ef=new WeakSet;function Df(e){return{width:e[2]-e[0],height:e[3]-e[1]}}var Of=class{static create(e){switch(e.data.annotationType){case Kc.LINK:return new Af(e);case Kc.TEXT:return new jf(e);case Kc.WIDGET:switch(e.data.fieldType){case`Tx`:return new Nf(e);case`Btn`:return e.data.radioButton?new If(e):e.data.checkBox?new Ff(e):new Lf(e);case`Ch`:return new Rf(e);case`Sig`:return new Pf(e)}return new Mf(e);case Kc.POPUP:return new zf(e);case Kc.FREETEXT:return new Vf(e);case Kc.LINE:return new Hf(e);case Kc.SQUARE:return new Uf(e);case Kc.CIRCLE:return new Wf(e);case Kc.POLYLINE:return new Gf(e);case Kc.CARET:return new qf(e);case Kc.INK:return new Jf(e);case Kc.POLYGON:return new Kf(e);case Kc.HIGHLIGHT:return new Yf(e);case Kc.UNDERLINE:return new Xf(e);case Kc.SQUIGGLY:return new Zf(e);case Kc.STRIKEOUT:return new Qf(e);case Kc.STAMP:return new $f(e);case Kc.FILEATTACHMENT:return new ep(e);default:return new kf(e)}}},kf=class e{#e=null;#t=!1;#n=null;constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:r=!1}={}){this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,t&&(this.container=this._createContainer(n)),r&&this._createQuadrilaterals()}static _hasPopupData({titleObj:e,contentsObj:t,richText:n}){return!!(e?.str||t?.str||n?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return e._hasPopupData(this.data)}updateEdited(e){if(!this.container)return;this.#e||={rect:this.data.rect.slice(0)};let{rect:t}=e;t&&this.#r(t),this.#n?.popup.updateEdited(e)}resetEdited(){this.#e&&=(this.#r(this.#e.rect),this.#n?.popup.resetEdited(),null)}#r(e){let{container:{style:t},data:{rect:n,rotation:r},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:a,pageX:o,pageY:s}}}}=this;n?.splice(0,4,...e);let{width:c,height:l}=Df(e);t.left=`${100*(e[0]-o)/i}%`,t.top=`${100*(a-e[3]+s)/a}%`,r===0?(t.width=`${100*c/i}%`,t.height=`${100*l/a}%`):this.setRotation(r)}_createContainer(e){let{data:t,parent:{page:n,viewport:r}}=this,i=document.createElement(`section`);i.setAttribute(`data-annotation-id`,t.id),this instanceof Mf||(i.tabIndex=wf);let{style:a}=i;if(a.zIndex=this.parent.zIndex++,t.alternativeText&&(i.title=t.alternativeText),t.noRotate&&i.classList.add(`norotate`),!t.rect||this instanceof zf){let{rotation:e}=t;return!t.hasOwnCanvas&&e!==0&&this.setRotation(e,i),i}let{width:o,height:s}=Df(t.rect);if(!e&&t.borderStyle.width>0){a.borderWidth=`${t.borderStyle.width}px`;let e=t.borderStyle.horizontalCornerRadius,n=t.borderStyle.verticalCornerRadius;switch(e>0||n>0?a.borderRadius=`calc(${e}px * var(--scale-factor)) / calc(${n}px * var(--scale-factor))`:this instanceof If&&(a.borderRadius=`calc(${o}px * var(--scale-factor)) / calc(${s}px * var(--scale-factor))`),t.borderStyle.style){case qc.SOLID:a.borderStyle=`solid`;break;case qc.DASHED:a.borderStyle=`dashed`;break;case qc.BEVELED:K(`Unimplemented border style: beveled`);break;case qc.INSET:K(`Unimplemented border style: inset`);break;case qc.UNDERLINE:a.borderBottomStyle=`solid`}let r=t.borderColor||null;r?(this.#t=!0,a.borderColor=X.makeHexColor(r[0]|0,r[1]|0,r[2]|0)):a.borderWidth=0}let c=X.normalizeRect([t.rect[0],n.view[3]-t.rect[1]+n.view[1],t.rect[2],n.view[3]-t.rect[3]+n.view[1]]),{pageWidth:l,pageHeight:u,pageX:d,pageY:f}=r.rawDims;a.left=`${100*(c[0]-d)/l}%`,a.top=`${100*(c[1]-f)/u}%`;let{rotation:p}=t;return t.hasOwnCanvas||p===0?(a.width=`${100*o/l}%`,a.height=`${100*s/u}%`):this.setRotation(p,i),i}setRotation(e,t=this.container){if(!this.data.rect)return;let{pageWidth:n,pageHeight:r}=this.parent.viewport.rawDims,{width:i,height:a}=Df(this.data.rect),o,s;e%180==0?(o=100*i/n,s=100*a/r):(o=100*a/n,s=100*i/r),t.style.width=`${o}%`,t.style.height=`${s}%`,t.setAttribute(`data-main-rotation`,(360-e)%360)}get _commonActions(){let e=(e,t,n)=>{let r=n.detail[e],i=r[0],a=r.slice(1);n.target.style[t]=bf[`${i}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[t]:bf[`${i}_rgb`](a)})};return Y(this,`_commonActions`,{display:e=>{let{display:t}=e.detail,n=t%2==1;this.container.style.visibility=n?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noView:n,noPrint:t===1||t===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{let{hidden:t}=e.detail;this.container.style.visibility=t?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noPrint:t,noView:t})},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:t=>{e(`bgColor`,`backgroundColor`,t)},fillColor:t=>{e(`fillColor`,`backgroundColor`,t)},fgColor:t=>{e(`fgColor`,`color`,t)},textColor:t=>{e(`textColor`,`color`,t)},borderColor:t=>{e(`borderColor`,`borderColor`,t)},strokeColor:t=>{e(`strokeColor`,`borderColor`,t)},rotation:e=>{let t=e.detail.rotation;this.setRotation(t),this.annotationStorage.setValue(this.data.id,{rotation:t})}})}_dispatchEventFromSandbox(e,t){let n=this._commonActions;for(let r of Object.keys(t.detail))(e[r]||n[r])?.(t)}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;let t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;let n=this._commonActions;for(let[r,i]of Object.entries(t)){let a=n[r];a&&(a({detail:{[r]:i},target:e}),delete t[r])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[t,n,r,i]=this.data.rect.map(e=>Math.fround(e));if(e.length===8){let[a,o,s,c]=e.subarray(2,6);if(r===a&&i===o&&t===s&&n===c)return}let{style:a}=this.container,o;if(this.#t){let{borderColor:e,borderWidth:t}=a;a.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="${e}" stroke-width="${t}">`],this.container.classList.add(`hasBorder`)}let s=r-t,c=i-n,{svgFactory:l}=this,u=l.createElement(`svg`);u.classList.add(`quadrilateralsContainer`),u.setAttribute(`width`,0),u.setAttribute(`height`,0);let d=l.createElement(`defs`);u.append(d);let f=l.createElement(`clipPath`),p=`clippath_${this.data.id}`;f.setAttribute(`id`,p),f.setAttribute(`clipPathUnits`,`objectBoundingBox`),d.append(f);for(let n=2,r=e.length;n<r;n+=8){let r=e[n],a=e[n+1],u=e[n+2],d=e[n+3],p=l.createElement(`rect`),m=(u-t)/s,h=(i-a)/c,g=(r-u)/s,_=(a-d)/c;p.setAttribute(`x`,m),p.setAttribute(`y`,h),p.setAttribute(`width`,g),p.setAttribute(`height`,_),f.append(p),o?.push(`<rect vector-effect="non-scaling-stroke" x="${m}" y="${h}" width="${g}" height="${_}"/>`)}this.#t&&(o.push(`</g></svg>')`),a.backgroundImage=o.join(``)),this.container.append(u),this.container.style.clipPath=`url(#${p})`}_createPopup(){let{data:e}=this,t=this.#n=new zf({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(t.render())}render(){q("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){let n=[];if(this._fieldObjects){let r=this._fieldObjects[e];if(r)for(let{page:e,id:i,exportValues:a}of r){if(e===-1||i===t)continue;let r=typeof a==`string`?a:null,o=document.querySelector(`[data-element-id="${i}"]`);if(o&&!Ef.has(o)){K(`_getElementsByName - element not allowed: ${i}`);continue}n.push({id:i,exportValue:r,domElement:o})}return n}for(let r of document.getElementsByName(e)){let{exportValue:e}=r,i=r.getAttribute(`data-element-id`);i!==t&&Ef.has(r)&&n.push({id:i,exportValue:e,domElement:r})}return n}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(){let e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(let t of e)t.classList.add(`highlightArea`);else e.classList.add(`highlightArea`)}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener(`dblclick`,()=>{this.linkService.eventBus?.dispatch(`switchannotationeditormode`,{source:this,mode:e,editId:t})})}},Af=class extends kf{constructor(e,t=null){super(e,{isRenderable:!0,ignoreBorder:!!t?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=e.data.isTooltipOnly}render(){let{data:e,linkService:t}=this,n=document.createElement(`a`);n.setAttribute(`data-element-id`,e.id);let r=!1;return e.url?(t.addLinkAttributes(n,e.url,e.newWindow),r=!0):e.action?(this._bindNamedAction(n,e.action),r=!0):e.attachment?(this.#t(n,e.attachment,e.attachmentDest),r=!0):e.setOCGState?(this.#n(n,e.setOCGState),r=!0):e.dest?(this._bindLink(n,e.dest),r=!0):(e.actions&&(e.actions.Action||e.actions[`Mouse Up`]||e.actions[`Mouse Down`])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(n,e),r=!0),e.resetForm?(this._bindResetFormAction(n,e.resetForm),r=!0):this.isTooltipOnly&&!r&&(this._bindLink(n,``),r=!0)),this.container.classList.add(`linkAnnotation`),r&&this.container.append(n),this.container}#e(){this.container.setAttribute(`data-internal-link`,``)}_bindLink(e,t){e.href=this.linkService.getDestinationHash(t),e.onclick=()=>(t&&this.linkService.goToDestination(t),!1),(t||t===``)&&this.#e()}_bindNamedAction(e,t){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeNamedAction(t),!1),this.#e()}#t(e,t,n=null){e.href=this.linkService.getAnchorUrl(``),t.description&&(e.title=t.description),e.onclick=()=>(this.downloadManager?.openOrDownloadData(t.content,t.filename,n),!1),this.#e()}#n(e,t){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeSetOCGState(t),!1),this.#e()}_bindJSAction(e,t){e.href=this.linkService.getAnchorUrl(``);let n=new Map([[`Action`,`onclick`],[`Mouse Up`,`onmouseup`],[`Mouse Down`,`onmousedown`]]);for(let r of Object.keys(t.actions)){let i=n.get(r);i&&(e[i]=()=>(this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t.id,name:r}}),!1))}e.onclick||=()=>!1,this.#e()}_bindResetFormAction(e,t){let n=e.onclick;if(n||(e.href=this.linkService.getAnchorUrl(``)),this.#e(),!this._fieldObjects){K('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),n||(e.onclick=()=>!1);return}e.onclick=()=>{n?.();let{fields:e,refs:r,include:i}=t,a=[];if(e.length!==0||r.length!==0){let t=new Set(r);for(let n of e){let e=this._fieldObjects[n]||[];for(let{id:n}of e)t.add(n)}for(let e of Object.values(this._fieldObjects))for(let n of e)t.has(n.id)===i&&a.push(n)}else for(let e of Object.values(this._fieldObjects))a.push(...e);let o=this.annotationStorage,s=[];for(let e of a){let{id:t}=e;switch(s.push(t),e.type){case`text`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}case`checkbox`:case`radiobutton`:{let n=e.defaultValue===e.exportValues;o.setValue(t,{value:n});break}case`combobox`:case`listbox`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}default:continue}let n=document.querySelector(`[data-element-id="${t}"]`);if(n){if(!Ef.has(n)){K(`_bindResetFormAction - element not allowed: ${t}`);continue}n.dispatchEvent(new Event(`resetform`))}}return this.enableScripting&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:`app`,ids:s,name:`ResetForm`}}),!1}}},jf=class extends kf{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add(`textAnnotation`);let e=document.createElement(`img`);return e.src=this.imageResourcesPath+`annotation-`+this.data.name.toLowerCase()+`.svg`,e.setAttribute(`data-l10n-id`,`pdfjs-text-annotation-type`),e.setAttribute(`data-l10n-args`,JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(e),this.container}},Mf=class extends kf{render(){return this.container}showElementAndHideCanvas(e){this.data.hasOwnCanvas&&(e.previousSibling?.nodeName===`CANVAS`&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return _l.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,n,r,i){n.includes(`mouse`)?e.addEventListener(n,e=>{this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e),shift:e.shiftKey,modifier:this._getKeyModifier(e)}})}):e.addEventListener(n,e=>{if(n===`blur`){if(!t.focused||!e.relatedTarget)return;t.focused=!1}else if(n===`focus`){if(t.focused)return;t.focused=!0}i&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e)}})})}_setEventListeners(e,t,n,r){for(let[i,a]of n)(a===`Action`||this.data.actions?.[a])&&((a===`Focus`||a===`Blur`)&&(t||={focused:!1}),this._setEventListener(e,t,i,a,r),a===`Focus`&&!this.data.actions?.Blur?this._setEventListener(e,t,`blur`,`Blur`,null):a===`Blur`&&!this.data.actions?.Focus&&this._setEventListener(e,t,`focus`,`Focus`,null))}_setBackgroundColor(e){let t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?`transparent`:X.makeHexColor(t[0],t[1],t[2])}_setTextStyle(e){let t=[`left`,`center`,`right`],{fontColor:n}=this.data.defaultAppearanceData,r=this.data.defaultAppearanceData.fontSize||Tf,i=e.style,a,o=e=>Math.round(10*e)/10;if(this.data.multiLine){let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2),t=e/(Math.round(e/(zc*r))||1);a=Math.min(r,o(t/zc))}else{let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(r,o(e/zc))}i.fontSize=`calc(${a}px * var(--scale-factor))`,i.color=X.makeHexColor(n[0],n[1],n[2]),this.data.textAlignment!==null&&(i.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute(`required`,!0):e.removeAttribute(`required`),e.setAttribute(`aria-required`,t)}},Nf=class extends Mf{constructor(e){let t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,n,r){let i=this.annotationStorage;for(let a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[t]=n),i.setValue(a.id,{[r]:n})}render(){let e=this.annotationStorage,t=this.data.id;this.container.classList.add(`textWidgetAnnotation`);let n=null;if(this.renderForms){let r=e.getValue(t,{value:this.data.fieldValue}),i=r.value||``,a=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;a&&i.length>a&&(i=i.slice(0,a));let o=r.formattedValue||this.data.textContent?.join(`
440
+ `)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,``));let s={userValue:i,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(n=document.createElement(`textarea`),n.textContent=o??i,this.data.doNotScroll&&(n.style.overflowY=`hidden`)):(n=document.createElement(`input`),n.type=`text`,n.setAttribute(`value`,o??i),this.data.doNotScroll&&(n.style.overflowX=`hidden`)),this.data.hasOwnCanvas&&(n.hidden=!0),Ef.add(n),n.setAttribute(`data-element-id`,t),n.disabled=this.data.readOnly,n.name=this.data.fieldName,n.tabIndex=wf,this._setRequired(n,this.data.required),a&&(n.maxLength=a),n.addEventListener(`input`,r=>{e.setValue(t,{value:r.target.value}),this.setPropertyOnSiblings(n,`value`,r.target.value,`value`),s.formattedValue=null}),n.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue??``;n.value=s.userValue=t,s.formattedValue=null});let c=e=>{let{formattedValue:t}=s;t!=null&&(e.target.value=t),e.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener(`focus`,e=>{if(s.focused)return;let{target:t}=e;s.userValue&&(t.value=s.userValue),s.lastCommittedValue=t.value,s.commitKey=1,this.data.actions?.Focus||(s.focused=!0)}),n.addEventListener(`updatefromsandbox`,n=>{this.showElementAndHideCanvas(n.target),this._dispatchEventFromSandbox({value(n){s.userValue=n.detail.value??``,e.setValue(t,{value:s.userValue.toString()}),n.target.value=s.userValue},formattedValue(n){let{formattedValue:r}=n.detail;s.formattedValue=r,r!=null&&n.target!==document.activeElement&&(n.target.value=r),e.setValue(t,{formattedValue:r})},selRange(e){e.target.setSelectionRange(...e.detail.selRange)},charLimit:n=>{let{charLimit:r}=n.detail,{target:i}=n;if(r===0){i.removeAttribute(`maxLength`);return}i.setAttribute(`maxLength`,r);let a=s.userValue;!a||a.length<=r||(a=a.slice(0,r),i.value=s.userValue=a,e.setValue(t,{value:a}),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:a,willCommit:!0,commitKey:1,selStart:i.selectionStart,selEnd:i.selectionEnd}}))}},n)}),n.addEventListener(`keydown`,e=>{s.commitKey=1;let n=-1;if(e.key===`Escape`?n=0:e.key===`Enter`&&!this.data.multiLine?n=2:e.key===`Tab`&&(s.commitKey=3),n===-1)return;let{value:r}=e.target;s.lastCommittedValue!==r&&(s.lastCommittedValue=r,s.userValue=r,this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:r,willCommit:!0,commitKey:n,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}))});let r=c;c=null,n.addEventListener(`blur`,e=>{if(!s.focused||!e.relatedTarget)return;this.data.actions?.Blur||(s.focused=!1);let{value:n}=e.target;s.userValue=n,s.lastCommittedValue!==n&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:n,willCommit:!0,commitKey:s.commitKey,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}),r(e)}),this.data.actions?.Keystroke&&n.addEventListener(`beforeinput`,e=>{s.lastCommittedValue=null;let{data:n,target:r}=e,{value:i,selectionStart:a,selectionEnd:o}=r,c=a,l=o;switch(e.inputType){case`deleteWordBackward`:{let e=i.substring(0,a).match(/\w*[^\w]*$/);e&&(c-=e[0].length);break}case`deleteWordForward`:{let e=i.substring(a).match(/^[^\w]*\w*/);e&&(l+=e[0].length);break}case`deleteContentBackward`:a===o&&--c;break;case`deleteContentForward`:a===o&&(l+=1)}e.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:i,change:n||``,willCommit:!1,selStart:c,selEnd:l}})}),this._setEventListeners(n,s,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.value)}if(c&&n.addEventListener(`blur`,c),this.data.comb){let e=(this.data.rect[2]-this.data.rect[0])/a;n.classList.add(`comb`),n.style.letterSpacing=`calc(${e}px * var(--scale-factor) - 1ch)`}}else n=document.createElement(`div`),n.textContent=this.data.fieldValue,n.style.verticalAlign=`middle`,n.style.display=`table-cell`,this.data.hasOwnCanvas&&(n.hidden=!0);return this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}},Pf=class extends Mf{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}},Ff=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.exportValue===t.fieldValue}).value;typeof r==`string`&&(r=r!==`Off`,e.setValue(n,{value:r})),this.container.classList.add(`buttonWidgetAnnotation`,`checkBox`);let i=document.createElement(`input`);return Ef.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`checkbox`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.setAttribute(`exportValue`,t.exportValue),i.tabIndex=wf,i.addEventListener(`change`,r=>{let{name:i,checked:a}=r.target;for(let r of this._getElementsByName(i,n)){let n=a&&r.exportValue===t.exportValue;r.domElement&&(r.domElement.checked=n),e.setValue(r.id,{value:n})}e.setValue(n,{value:a})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue||`Off`;e.target.checked=n===t.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value(t){t.target.checked=t.detail.value!==`Off`,e.setValue(n,{value:t.target.checked})}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},If=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`buttonWidgetAnnotation`,`radioButton`);let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.fieldValue===t.buttonValue}).value;if(typeof r==`string`&&(r=r!==t.buttonValue,e.setValue(n,{value:r})),r)for(let r of this._getElementsByName(t.fieldName,n))e.setValue(r.id,{value:!1});let i=document.createElement(`input`);if(Ef.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`radio`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.tabIndex=wf,i.addEventListener(`change`,t=>{let{name:r,checked:i}=t.target;for(let t of this._getElementsByName(r,n))e.setValue(t.id,{value:!1});e.setValue(n,{value:i})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue;e.target.checked=n!=null&&n===t.buttonValue}),this.enableScripting&&this.hasJSActions){let r=t.buttonValue;i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value:t=>{let i=r===t.detail.value;for(let r of this._getElementsByName(t.target.name)){let t=i&&r.id===n;r.domElement&&(r.domElement.checked=t),e.setValue(r.id,{value:t})}}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)}return this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},Lf=class extends Af{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){let e=super.render();e.classList.add(`buttonWidgetAnnotation`,`pushButton`);let t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener(`updatefromsandbox`,e=>{this._dispatchEventFromSandbox({},e)})),e}},Rf=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`choiceWidgetAnnotation`);let e=this.annotationStorage,t=this.data.id,n=e.getValue(t,{value:this.data.fieldValue}),r=document.createElement(`select`);Ef.add(r),r.setAttribute(`data-element-id`,t),r.disabled=this.data.readOnly,this._setRequired(r,this.data.required),r.name=this.data.fieldName,r.tabIndex=wf;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(r.size=this.data.options.length,this.data.multiSelect&&(r.multiple=!0)),r.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue;for(let e of r.options)e.selected=e.value===t});for(let e of this.data.options){let t=document.createElement(`option`);t.textContent=e.displayValue,t.value=e.exportValue,n.value.includes(e.exportValue)&&(t.setAttribute(`selected`,!0),i=!1),r.append(t)}let a=null;if(i){let e=document.createElement(`option`);e.value=` `,e.setAttribute(`hidden`,!0),e.setAttribute(`selected`,!0),r.prepend(e),a=()=>{e.remove(),r.removeEventListener(`input`,a),a=null},r.addEventListener(`input`,a)}let o=e=>{let t=e?`value`:`textContent`,{options:n,multiple:i}=r;return i?Array.prototype.filter.call(n,e=>e.selected).map(e=>e[t]):n.selectedIndex===-1?null:n[n.selectedIndex][t]},s=o(!1),c=e=>{let t=e.target.options;return Array.prototype.map.call(t,e=>({displayValue:e.textContent,exportValue:e.value}))};return this.enableScripting&&this.hasJSActions?(r.addEventListener(`updatefromsandbox`,n=>{this._dispatchEventFromSandbox({value(n){a?.();let i=n.detail.value,c=new Set(Array.isArray(i)?i:[i]);for(let e of r.options)e.selected=c.has(e.value);e.setValue(t,{value:o(!0)}),s=o(!1)},multipleSelection(e){r.multiple=!0},remove(n){let i=r.options,a=n.detail.remove;i[a].selected=!1,r.remove(a),i.length>0&&Array.prototype.findIndex.call(i,e=>e.selected)===-1&&(i[0].selected=!0),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},clear(n){for(;r.length!==0;)r.remove(0);e.setValue(t,{value:null,items:[]}),s=o(!1)},insert(n){let{index:i,displayValue:a,exportValue:l}=n.detail.insert,u=r.children[i],d=document.createElement(`option`);d.textContent=a,d.value=l,u?u.before(d):r.append(d),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},items(n){let{items:i}=n.detail;for(;r.length!==0;)r.remove(0);for(let e of i){let{displayValue:t,exportValue:n}=e,i=document.createElement(`option`);i.textContent=t,i.value=n,r.append(i)}r.options.length>0&&(r.options[0].selected=!0),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},indices(n){let r=new Set(n.detail.indices);for(let e of n.target.options)e.selected=r.has(e.index);e.setValue(t,{value:o(!0)}),s=o(!1)},editable(e){e.target.disabled=!e.detail.editable}},n)}),r.addEventListener(`input`,n=>{let r=o(!0),i=o(!1);e.setValue(t,{value:r}),n.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:s,change:i,changeEx:r,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(r,null,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`],[`input`,`Action`],[`input`,`Validate`]],e=>e.target.value)):r.addEventListener(`input`,function(n){e.setValue(t,{value:o(!0)})}),this.data.combo&&this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},zf=class extends kf{constructor(e){let{data:t,elements:n}=e;super(e,{isRenderable:kf._hasPopupData(t)}),this.elements=n,this.popup=null}render(){this.container.classList.add(`popupAnnotation`);let e=this.popup=new Bf({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}),t=[];for(let n of this.elements)n.popup=e,n.container.ariaHasPopup=`dialog`,t.push(n.data.id),n.addHighlightArea();return this.container.setAttribute(`aria-controls`,t.map(e=>`${wl}${e}`).join(`,`)),this.container}},Bf=class{#e=this.#C.bind(this);#t=this.#D.bind(this);#n=this.#E.bind(this);#r=this.#T.bind(this);#i=null;#a=null;#o=null;#s=null;#c=null;#l=null;#u=null;#d=!1;#f=null;#p=null;#m=null;#h=null;#g=null;#_=null;#v=!1;constructor({container:e,color:t,elements:n,titleObj:r,modificationDate:i,contentsObj:a,richText:o,parent:s,rect:c,parentRect:l,open:u}){this.#a=e,this.#g=r,this.#o=a,this.#h=o,this.#l=s,this.#i=t,this.#m=c,this.#u=l,this.#c=n,this.#s=zl.toDateObject(i),this.trigger=n.flatMap(e=>e.getElementsToTriggerPopup());for(let e of this.trigger)e.addEventListener(`click`,this.#r),e.addEventListener(`mouseenter`,this.#n),e.addEventListener(`mouseleave`,this.#t),e.classList.add(`popupTriggerArea`);for(let e of n)e.container?.addEventListener(`keydown`,this.#e);this.#a.hidden=!0,u&&this.#T()}render(){if(this.#f)return;let e=this.#f=document.createElement(`div`);if(e.className=`popup`,this.#i){let t=e.style.outlineColor=X.makeHexColor(...this.#i);CSS.supports(`background-color`,`color-mix(in srgb, red 30%, white)`)?e.style.backgroundColor=`color-mix(in srgb, ${t} 30%, white)`:e.style.backgroundColor=X.makeHexColor(...this.#i.map(e=>Math.floor(.7*(255-e)+e)))}let t=document.createElement(`span`);t.className=`header`;let n=document.createElement(`h1`);if(t.append(n),{dir:n.dir,str:n.textContent}=this.#g,e.append(t),this.#s){let e=document.createElement(`span`);e.classList.add(`popupDate`),e.setAttribute(`data-l10n-id`,`pdfjs-annotation-date-time-string`),e.setAttribute(`data-l10n-args`,JSON.stringify({dateObj:this.#s.valueOf()})),t.append(e)}let r=this.#y;if(r)Cf.render({xfaHtml:r,intent:`richText`,div:e}),e.lastChild.classList.add(`richText`,`popupContent`);else{let t=this._formatContents(this.#o);e.append(t)}this.#a.append(e)}get#y(){let e=this.#h,t=this.#o;return e?.str&&(!t?.str||t.str===e.str)&&this.#h.html||null}get#b(){return this.#y?.attributes?.style?.fontSize||0}get#x(){return this.#y?.attributes?.style?.color||null}#S(e){let t=[],n={str:e,html:{name:`div`,attributes:{dir:`auto`},children:[{name:`p`,children:t}]}},r={style:{color:this.#x,fontSize:this.#b?`calc(${this.#b}px * var(--scale-factor))`:``}};for(let n of e.split(`
441
+ `))t.push({name:`span`,value:n,attributes:r});return n}_formatContents({str:e,dir:t}){let n=document.createElement(`p`);n.classList.add(`popupContent`),n.dir=t;let r=e.split(/(?:\r\n?|\n)/);for(let e=0,t=r.length;e<t;++e){let i=r[e];n.append(document.createTextNode(i)),e<t-1&&n.append(document.createElement(`br`))}return n}#C(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key===`Enter`||e.key===`Escape`&&this.#d)&&this.#T()}updateEdited({rect:e,popupContent:t}){this.#_||={contentsObj:this.#o,richText:this.#h},e&&(this.#p=null),t&&(this.#h=this.#S(t),this.#o=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#_&&({contentsObj:this.#o,richText:this.#h}=this.#_,this.#_=null,this.#f?.remove(),this.#f=null,this.#p=null)}#w(){if(this.#p!==null)return;let{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:r,pageY:i}}}=this.#l,a=!!this.#u,o=a?this.#u:this.#m;for(let e of this.#c)if(!o||X.intersect(e.data.rect,o)!==null){o=e.data.rect,a=!0;break}let s=X.normalizeRect([o[0],e[3]-o[1]+e[1],o[2],e[3]-o[3]+e[1]]),c=a?o[2]-o[0]+5:0,l=s[0]+c,u=s[1];this.#p=[100*(l-r)/t,100*(u-i)/n];let{style:d}=this.#a;d.left=`${this.#p[0]}%`,d.top=`${this.#p[1]}%`}#T(){this.#d=!this.#d,this.#d?(this.#E(),this.#a.addEventListener(`click`,this.#r),this.#a.addEventListener(`keydown`,this.#e)):(this.#D(),this.#a.removeEventListener(`click`,this.#r),this.#a.removeEventListener(`keydown`,this.#e))}#E(){this.#f||this.render(),this.isVisible?this.#d&&this.#a.classList.add(`focused`):(this.#w(),this.#a.hidden=!1,this.#a.style.zIndex=parseInt(this.#a.style.zIndex)+1e3)}#D(){this.#a.classList.remove(`focused`),!(this.#d||!this.isVisible)&&(this.#a.hidden=!0,this.#a.style.zIndex=parseInt(this.#a.style.zIndex)-1e3)}forceHide(){this.#v=this.isVisible,this.#v&&(this.#a.hidden=!0)}maybeShow(){this.#v&&(this.#f||this.#E(),this.#v=!1,this.#a.hidden=!1)}get isVisible(){return this.#a.hidden===!1}},Vf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=W.FREETEXT}render(){if(this.container.classList.add(`freeTextAnnotation`),this.textContent){let e=document.createElement(`div`);e.classList.add(`annotationTextContent`),e.setAttribute(`role`,`comment`);for(let t of this.textContent){let n=document.createElement(`span`);n.textContent=t,e.append(n)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},Hf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`lineAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=this.#e=this.svgFactory.createElement(`svg:line`);return i.setAttribute(`x1`,e.rect[2]-e.lineCoordinates[0]),i.setAttribute(`y1`,e.rect[3]-e.lineCoordinates[1]),i.setAttribute(`x2`,e.rect[2]-e.lineCoordinates[2]),i.setAttribute(`y2`,e.rect[3]-e.lineCoordinates[3]),i.setAttribute(`stroke-width`,e.borderStyle.width||1),i.setAttribute(`stroke`,`transparent`),i.setAttribute(`fill`,`transparent`),r.append(i),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Uf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`squareAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:rect`);return a.setAttribute(`x`,i/2),a.setAttribute(`y`,i/2),a.setAttribute(`width`,t-i),a.setAttribute(`height`,n-i),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Wf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`circleAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:ellipse`);return a.setAttribute(`cx`,t/2),a.setAttribute(`cy`,n/2),a.setAttribute(`rx`,t/2-i/2),a.setAttribute(`ry`,n/2-i/2),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Gf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`polylineAnnotation`,this.svgElementName=`svg:polyline`}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,vertices:t,borderStyle:n,popupRef:r}}=this;if(!t)return this.container;let{width:i,height:a}=Df(e),o=this.svgFactory.create(i,a,!0),s=[];for(let n=0,r=t.length;n<r;n+=2){let r=t[n]-e[0],i=e[3]-t[n+1];s.push(`${r},${i}`)}s=s.join(` `);let c=this.#e=this.svgFactory.createElement(this.svgElementName);return c.setAttribute(`points`,s),c.setAttribute(`stroke-width`,n.width||1),c.setAttribute(`stroke`,`transparent`),c.setAttribute(`fill`,`transparent`),o.append(c),this.container.append(o),!r&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Kf=class extends Gf{constructor(e){super(e),this.containerClassName=`polygonAnnotation`,this.svgElementName=`svg:polygon`}},qf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add(`caretAnnotation`),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}},Jf=class extends kf{#e=null;#t=[];constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`inkAnnotation`,this.svgElementName=`svg:polyline`,this.annotationEditorType=this.data.it===`InkHighlight`?W.HIGHLIGHT:W.INK}#n(e,t){switch(e){case 90:return{transform:`rotate(90) translate(${-t[0]},${t[1]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};case 180:return{transform:`rotate(180) translate(${-t[2]},${t[1]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]};case 270:return{transform:`rotate(270) translate(${-t[2]},${t[3]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};default:return{transform:`translate(${-t[0]},${t[3]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]}}}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,rotation:t,inkLists:n,borderStyle:r,popupRef:i}}=this,{transform:a,width:o,height:s}=this.#n(t,e),c=this.svgFactory.create(o,s,!0),l=this.#e=this.svgFactory.createElement(`svg:g`);c.append(l),l.setAttribute(`stroke-width`,r.width||1),l.setAttribute(`stroke-linecap`,`round`),l.setAttribute(`stroke-linejoin`,`round`),l.setAttribute(`stroke-miterlimit`,10),l.setAttribute(`stroke`,`transparent`),l.setAttribute(`fill`,`transparent`),l.setAttribute(`transform`,a);for(let e=0,t=n.length;e<t;e++){let t=this.svgFactory.createElement(this.svgElementName);this.#t.push(t),t.setAttribute(`points`,n[e].join(`,`)),l.append(t)}return!i&&this.hasPopupData&&this._createPopup(),this.container.append(c),this._editOnDoubleClick(),this.container}updateEdited(e){super.updateEdited(e);let{thickness:t,points:n,rect:r}=e,i=this.#e;if(t>=0&&i.setAttribute(`stroke-width`,t||1),n)for(let e=0,t=this.#t.length;e<t;e++)this.#t[e].setAttribute(`points`,n[e].join(`,`));if(r){let{transform:e,width:t,height:n}=this.#n(this.data.rotation,r);i.parentElement.setAttribute(`viewBox`,`0 0 ${t} ${n}`),i.setAttribute(`transform`,e)}}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Yf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=W.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`highlightAnnotation`),this._editOnDoubleClick(),this.container}},Xf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`underlineAnnotation`),this.container}},Zf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`squigglyAnnotation`),this.container}},Qf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`strikeoutAnnotation`),this.container}},$f=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=W.STAMP}render(){return this.container.classList.add(`stampAnnotation`),this.container.setAttribute(`role`,`img`),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},ep=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0});let{file:t}=this.data;this.filename=t.filename,this.content=t.content,this.linkService.eventBus?.dispatch(`fileattachmentannotation`,{source:this,...t})}render(){this.container.classList.add(`fileAttachmentAnnotation`);let{container:e,data:t}=this,n;t.hasAppearance||t.fillAlpha===0?n=document.createElement(`div`):(n=document.createElement(`img`),n.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(t.name)?`paperclip`:`pushpin`}.svg`,t.fillAlpha&&t.fillAlpha<1&&(n.style=`filter: opacity(${Math.round(t.fillAlpha*100)}%);`)),n.addEventListener(`dblclick`,this.#t.bind(this)),this.#e=n;let{isMac:r}=_l.platform;return e.addEventListener(`keydown`,e=>{e.key===`Enter`&&(r?e.metaKey:e.ctrlKey)&&this.#t()}),!t.popupRef&&this.hasPopupData?this._createPopup():n.classList.add(`popupTriggerArea`),e.append(n),e}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}#t(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}},tp=class{#e=null;#t=null;#n=new Map;#r=null;constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:r,page:i,viewport:a,structTreeLayer:o}){this.div=e,this.#e=t,this.#t=n,this.#r=o||null,this.page=i,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=r}hasEditableAnnotations(){return this.#n.size>0}async#i(e,t){let n=e.firstChild||e,r=n.id=`${wl}${t}`,i=await this.#r?.getAriaAttributes(r);if(i)for(let[e,t]of i)n.setAttribute(e,t);this.div.append(e),this.#e?.moveElementInDOM(this.div,e,n,!1)}async render(e){let{annotations:t}=e,n=this.div;Wl(n,this.viewport);let r=new Map,i={data:null,layer:n,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||``,renderForms:e.renderForms!==!1,svgFactory:new Sf,annotationStorage:e.annotationStorage||new lu,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(let e of t){if(e.noHTML)continue;let t=e.annotationType===Kc.POPUP;if(t){let t=r.get(e.id);if(!t)continue;i.elements=t}else{let{width:t,height:n}=Df(e.rect);if(t<=0||n<=0)continue}i.data=e;let n=Of.create(i);if(!n.isRenderable)continue;if(!t&&e.popupRef){let t=r.get(e.popupRef);t?t.push(n):r.set(e.popupRef,[n])}let a=n.render();e.hidden&&(a.style.visibility=`hidden`),await this.#i(a,e.id),n._isEditable&&(this.#n.set(n.data.id,n),this._annotationEditorUIManager?.renderAnnotationElement(n))}this.#a()}update({viewport:e}){let t=this.div;this.viewport=e,Wl(t,{rotation:e.rotation}),this.#a(),t.hidden=!1}#a(){if(!this.#t)return;let e=this.div;for(let[t,n]of this.#t){let r=e.querySelector(`[data-annotation-id="${t}"]`);if(!r)continue;n.className=`annotationContent`;let{firstChild:i}=r;i?i.nodeName===`CANVAS`?i.replaceWith(n):i.classList.contains(`annotationContent`)?i.after(n):i.before(n):r.append(n)}this.#t.clear()}getEditableAnnotations(){return Array.from(this.#n.values())}getEditableAnnotation(e){return this.#n.get(e)}},np=/\r\n?|\n/g,rp=class e extends Q{#e;#t=``;#n=`${this.id}-editor`;#r=null;#i;static _freeTextDefaultContent=``;static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.isEmpty(),r=eu.TRANSLATE_SMALL,i=eu.TRANSLATE_BIG;return Y(this,`_keyboardManager`,new Ql([[[`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:[-r,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t._translateEmpty,{args:[-i,0],checker:n}],[[`ArrowRight`,`mac+ArrowRight`],t._translateEmpty,{args:[r,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t._translateEmpty,{args:[i,0],checker:n}],[[`ArrowUp`,`mac+ArrowUp`],t._translateEmpty,{args:[0,-r],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t._translateEmpty,{args:[0,-i],checker:n}],[[`ArrowDown`,`mac+ArrowDown`],t._translateEmpty,{args:[0,r],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t._translateEmpty,{args:[0,i],checker:n}]]))}static _type=`freetext`;static _editorType=W.FREETEXT;constructor(t){super({...t,name:`freeTextEditor`}),this.#e=t.color||e._defaultColor||Q._defaultLineColor,this.#i=t.fontSize||e._defaultFontSize}static initialize(e,t){Q.initialize(e,t);let n=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(n.getPropertyValue(`--freetext-padding`))}static updateDefaultParams(t,n){switch(t){case G.FREETEXT_SIZE:e._defaultFontSize=n;break;case G.FREETEXT_COLOR:e._defaultColor=n}}updateParams(e,t){switch(e){case G.FREETEXT_SIZE:this.#a(t);break;case G.FREETEXT_COLOR:this.#o(t)}}static get defaultPropertiesToUpdate(){return[[G.FREETEXT_SIZE,e._defaultFontSize],[G.FREETEXT_COLOR,e._defaultColor||Q._defaultLineColor]]}get propertiesToUpdate(){return[[G.FREETEXT_SIZE,this.#i],[G.FREETEXT_COLOR,this.#e]]}#a(e){let t=e=>{this.editorDiv.style.fontSize=`calc(${e}px * var(--scale-factor))`,this.translate(0,-(e-this.#i)*this.parentScale),this.#i=e,this.#c()},n=this.#i;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#o(e){let t=e=>{this.#e=this.editorDiv.style.color=e},n=this.#e;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(e,t){this._uiManager.translateSelectedEditors(e,t,!0)}getInitialTranslation(){let t=this.parentScale;return[-e._internalPadding*t,-(e._internalPadding+this.#i)*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(W.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove(`enabled`),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute(`aria-activedescendant`),this.#r=new AbortController;let e=this._uiManager.combinedSignal(this.#r);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(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add(`enabled`),this.editorDiv.contentEditable=!1,this.div.setAttribute(`aria-activedescendant`,this.#n),this._isDraggable=!0,this.#r?.abort(),this.#r=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){this.width||(this.enableEditMode(),e&&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()}#s(){let t=[];this.editorDiv.normalize();let n=null;for(let r of this.editorDiv.childNodes)(n?.nodeType!==Node.TEXT_NODE||r.nodeName!==`BR`)&&(t.push(e.#l(r)),n=r);return t.join(`
442
+ `)}#c(){let[e,t]=this.parentDimensions,n;if(this.isAttachedToDOM)n=this.div.getBoundingClientRect();else{let{currentLayer:e,div:t}=this,r=t.style.display,i=t.classList.contains(`hidden`);t.classList.remove(`hidden`),t.style.display=`hidden`,e.div.append(this.div),n=t.getBoundingClientRect(),t.remove(),t.style.display=r,t.classList.toggle(`hidden`,i)}this.rotation%180==this.parentRotation%180?(this.width=n.width/e,this.height=n.height/t):(this.width=n.height/e,this.height=n.width/t),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let e=this.#t,t=this.#t=this.#s().trimEnd();if(e===t)return;let n=e=>{if(this.#t=e,!e){this.remove();return}this.#u(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{n(t)},undo:()=>{n(e)},mustExec:!1}),this.#c()}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(t){e._keyboardManager.exec(this,t)}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,t;this.width&&(e=this.x,t=this.y),super.render(),this.editorDiv=document.createElement(`div`),this.editorDiv.className=`internal`,this.editorDiv.setAttribute(`id`,this.#n),this.editorDiv.setAttribute(`data-l10n-id`,`pdfjs-free-text2`),this.editorDiv.setAttribute(`data-l10n-attrs`,`default-content`),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:n}=this.editorDiv;if(n.fontSize=`calc(${this.#i}px * var(--scale-factor))`,n.color=this.#e,this.div.append(this.editorDiv),this.overlayDiv=document.createElement(`div`),this.overlayDiv.classList.add(`overlay`,`enabled`),this.div.append(this.overlayDiv),Jl(this,this.div,[`dblclick`,`keydown`]),this.width){let[n,r]=this.parentDimensions;if(this.annotationElementId){let{position:i}=this._initialData,[a,o]=this.getInitialTranslation();[a,o]=this.pageTranslationToScreen(a,o);let[s,c]=this.pageDimensions,[l,u]=this.pageTranslation,d,f;switch(this.rotation){case 0:d=e+(i[0]-l)/s,f=t+this.height-(i[1]-u)/c;break;case 90:d=e+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[o,-a];break;case 180:d=e-this.width+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[-a,-o];break;case 270:d=e+(i[0]-l-this.height*c)/s,f=t+(i[1]-u-this.width*s)/c,[a,o]=[-o,a]}this.setAt(d*n,f*r,a,o)}else this.setAt(e*n,t*r,this.width*n,this.height*r);this.#u(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#l(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(np,``)}editorDivPaste(t){let n=t.clipboardData||window.clipboardData,{types:r}=n;if(r.length===1&&r[0]===`text/plain`)return;t.preventDefault();let i=e.#f(n.getData(`text`)||``).replaceAll(np,`
443
+ `);if(!i)return;let a=window.getSelection();if(!a.rangeCount)return;this.editorDiv.normalize(),a.deleteFromDocument();let o=a.getRangeAt(0);if(!i.includes(`
444
+ `)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),a.collapseToStart();return}let{startContainer:s,startOffset:c}=o,l=[],u=[];if(s.nodeType===Node.TEXT_NODE){let t=s.parentElement;if(u.push(s.nodeValue.slice(c).replaceAll(np,``)),t!==this.editorDiv){let n=l;for(let r of this.editorDiv.childNodes){if(r===t){n=u;continue}n.push(e.#l(r))}}l.push(s.nodeValue.slice(0,c).replaceAll(np,``))}else if(s===this.editorDiv){let t=l,n=0;for(let r of this.editorDiv.childNodes)n++===c&&(t=u),t.push(e.#l(r))}this.#t=`${l.join(`
445
+ `)}${i}${u.join(`
446
+ `)}`,this.#u();let d=new Range,f=l.reduce((e,t)=>e+t.length,0);for(let{firstChild:e}of this.editorDiv.childNodes)if(e.nodeType===Node.TEXT_NODE){let t=e.nodeValue.length;if(f<=t){d.setStart(e,f),d.setEnd(e,f);break}f-=t}a.removeAllRanges(),a.addRange(d)}#u(){if(this.editorDiv.replaceChildren(),this.#t)for(let e of this.#t.split(`
447
+ `)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),this.editorDiv.append(t)}}#d(){return this.#t.replaceAll(`\xA0`,` `)}static#f(e){return e.replaceAll(` `,`\xA0`)}get contentDiv(){return this.editorDiv}static async deserialize(t,n,r){let i=null;if(t instanceof Vf){let{data:{defaultAppearanceData:{fontSize:e,fontColor:n},rect:r,rotation:a,id:o,popupRef:s},textContent:c,textPosition:l,parent:{page:{pageNumber:u}}}=t;if(!c||c.length===0)return null;i=t={annotationType:W.FREETEXT,color:Array.from(n),fontSize:e,value:c.join(`
448
+ `),position:l,pageIndex:u-1,rect:r.slice(0),rotation:a,id:o,deleted:!1,popupRef:s}}let a=await super.deserialize(t,n,r);return a.#i=t.fontSize,a.#e=X.makeHexColor(...t.color),a.#t=e.#f(t.value),a.annotationElementId=t.id||null,a._initialData=i,a}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n=e._internalPadding*this.parentScale,r=this.getRect(n,n),i=Q._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#e),a={annotationType:W.FREETEXT,color:i,fontSize:this.#i,value:this.#d(),pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?a:this.annotationElementId&&!this.#p(a)?null:(a.id=this.annotationElementId,a)}#p(e){let{value:t,fontSize:n,color:r,pageIndex:i}=this._initialData;return this._hasBeenMoved||e.value!==t||e.fontSize!==n||e.color.some((e,t)=>e!==r[t])||e.pageIndex!==i}renderAnnotationElement(t){let n=super.renderAnnotationElement(t);if(this.deleted)return n;let{style:r}=n;r.fontSize=`calc(${this.#i}px * var(--scale-factor))`,r.color=this.#e,n.replaceChildren();for(let e of this.#t.split(`
449
+ `)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),n.append(t)}let i=e._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#t}),n}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}},$=class{static PRECISION=1e-4;toSVGPath(){q("Abstract method `toSVGPath` must be implemented.")}get box(){q("Abstract getter `box` must be implemented.")}serialize(e,t){q("Abstract method `serialize` must be implemented.")}static _rescale(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o<s;o+=2)a[o]=t+e[o]*r,a[o+1]=n+e[o+1]*i;return a}static _rescaleAndSwap(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o<s;o+=2)a[o]=t+e[o+1]*r,a[o+1]=n+e[o]*i;return a}static _translate(e,t,n,r){r||=new Float32Array(e.length);for(let i=0,a=e.length;i<a;i+=2)r[i]=t+e[i],r[i+1]=n+e[i+1];return r}static svgRound(e){return Math.round(e*1e4)}static _normalizePoint(e,t,n,r,i){switch(i){case 90:return[1-t/n,e/r];case 180:return[1-e/n,1-t/r];case 270:return[t/n,1-e/r];default:return[e/n,t/r]}}static _normalizePagePoint(e,t,n){switch(n){case 90:return[1-t,e];case 180:return[1-e,1-t];case 270:return[t,1-e];default:return[e,t]}}static createBezierPoints(e,t,n,r,i,a){return[(e+5*n)/6,(t+5*r)/6,(5*n+i)/6,(5*r+a)/6,(n+i)/2,(r+a)/2]}},ip=class e{#e;#t=[];#n;#r;#i=[];#a=new Float32Array(18);#o;#s;#c;#l;#u;#d;#f=[];static#p=8;static#m=2;static#h=e.#p+e.#m;constructor({x:t,y:n},r,i,a,o,s=0){this.#e=r,this.#d=a*i,this.#r=o,this.#a.set([NaN,NaN,NaN,NaN,t,n],6),this.#n=s,this.#l=e.#p*i,this.#c=e.#h*i,this.#u=i,this.#f.push(t,n)}isEmpty(){return isNaN(this.#a[8])}#g(){let e=this.#a.subarray(4,6),t=this.#a.subarray(16,18),[n,r,i,a]=this.#e;return[(this.#o+(e[0]-t[0])/2-n)/i,(this.#s+(e[1]-t[1])/2-r)/a,(this.#o+(t[0]-e[0])/2-n)/i,(this.#s+(t[1]-e[1])/2-r)/a]}add({x:e,y:t}){this.#o=e,this.#s=t;let[n,r,i,a]=this.#e,[o,s,c,l]=this.#a.subarray(8,12),u=e-c,d=t-l,f=Math.hypot(u,d);if(f<this.#c)return!1;let p=f-this.#l,m=p/f,h=m*u,g=m*d,_=o,v=s;o=c,s=l,c+=h,l+=g,this.#f?.push(e,t);let y=-g/p,b=h/p,x=y*this.#d,S=b*this.#d;return this.#a.set(this.#a.subarray(2,8),0),this.#a.set([c+x,l+S],4),this.#a.set(this.#a.subarray(14,18),12),this.#a.set([c-x,l-S],16),isNaN(this.#a[6])?(this.#i.length===0&&(this.#a.set([o+x,s+S],2),this.#i.push(NaN,NaN,NaN,NaN,(o+x-n)/i,(s+S-r)/a),this.#a.set([o-x,s-S],14),this.#t.push(NaN,NaN,NaN,NaN,(o-x-n)/i,(s-S-r)/a)),this.#a.set([_,v,o,s,c,l],6),!this.isEmpty()):(this.#a.set([_,v,o,s,c,l],6),Math.abs(Math.atan2(v-s,_-o)-Math.atan2(g,h))<Math.PI/2?([o,s,c,l]=this.#a.subarray(2,6),this.#i.push(NaN,NaN,NaN,NaN,((o+c)/2-n)/i,((s+l)/2-r)/a),[o,s,_,v]=this.#a.subarray(14,18),this.#t.push(NaN,NaN,NaN,NaN,((_+o)/2-n)/i,((v+s)/2-r)/a),!0):([_,v,o,s,c,l]=this.#a.subarray(0,6),this.#i.push(((_+5*o)/6-n)/i,((v+5*s)/6-r)/a,((5*o+c)/6-n)/i,((5*s+l)/6-r)/a,((o+c)/2-n)/i,((s+l)/2-r)/a),[c,l,o,s,_,v]=this.#a.subarray(12,18),this.#t.push(((_+5*o)/6-n)/i,((v+5*s)/6-r)/a,((5*o+c)/6-n)/i,((5*s+l)/6-r)/a,((o+c)/2-n)/i,((s+l)/2-r)/a),!0))}toSVGPath(){if(this.isEmpty())return``;let e=this.#i,t=this.#t;if(isNaN(this.#a[6])&&!this.isEmpty())return this.#_();let n=[];n.push(`M${e[4]} ${e[5]}`);for(let t=6;t<e.length;t+=6)isNaN(e[t])?n.push(`L${e[t+4]} ${e[t+5]}`):n.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#y(n);for(let e=t.length-6;e>=6;e-=6)isNaN(t[e])?n.push(`L${t[e+4]} ${t[e+5]}`):n.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);return this.#v(n),n.join(` `)}#_(){let[e,t,n,r]=this.#e,[i,a,o,s]=this.#g();return`M${(this.#a[2]-e)/n} ${(this.#a[3]-t)/r} L${(this.#a[4]-e)/n} ${(this.#a[5]-t)/r} L${i} ${a} L${o} ${s} L${(this.#a[16]-e)/n} ${(this.#a[17]-t)/r} L${(this.#a[14]-e)/n} ${(this.#a[15]-t)/r} Z`}#v(e){let t=this.#t;e.push(`L${t[4]} ${t[5]} Z`)}#y(e){let[t,n,r,i]=this.#e,a=this.#a.subarray(4,6),o=this.#a.subarray(16,18),[s,c,l,u]=this.#g();e.push(`L${(a[0]-t)/r} ${(a[1]-n)/i} L${s} ${c} L${l} ${u} L${(o[0]-t)/r} ${(o[1]-n)/i}`)}newFreeDrawOutline(e,t,n,r,i,a){return new ap(e,t,n,r,i,a)}getOutlines(){let e=this.#i,t=this.#t,n=this.#a,[r,i,a,o]=this.#e,s=new Float32Array((this.#f?.length??0)+2);for(let e=0,t=s.length-2;e<t;e+=2)s[e]=(this.#f[e]-r)/a,s[e+1]=(this.#f[e+1]-i)/o;if(s[s.length-2]=(this.#o-r)/a,s[s.length-1]=(this.#s-i)/o,isNaN(n[6])&&!this.isEmpty())return this.#b(s);let c=new Float32Array(this.#i.length+24+this.#t.length),l=e.length;for(let t=0;t<l;t+=2){if(isNaN(e[t])){c[t]=c[t+1]=NaN;continue}c[t]=e[t],c[t+1]=e[t+1]}l=this.#S(c,l);for(let e=t.length-6;e>=6;e-=6)for(let n=0;n<6;n+=2){if(isNaN(t[e+n])){c[l]=c[l+1]=NaN,l+=2;continue}c[l]=t[e+n],c[l+1]=t[e+n+1],l+=2}return this.#x(c,l),this.newFreeDrawOutline(c,s,this.#e,this.#u,this.#n,this.#r)}#b(e){let t=this.#a,[n,r,i,a]=this.#e,[o,s,c,l]=this.#g(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(t[2]-n)/i,(t[3]-r)/a,NaN,NaN,NaN,NaN,(t[4]-n)/i,(t[5]-r)/a,NaN,NaN,NaN,NaN,o,s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,(t[16]-n)/i,(t[17]-r)/a,NaN,NaN,NaN,NaN,(t[14]-n)/i,(t[15]-r)/a],0),this.newFreeDrawOutline(u,e,this.#e,this.#u,this.#n,this.#r)}#x(e,t){let n=this.#t;return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6}#S(e,t){let n=this.#a.subarray(4,6),r=this.#a.subarray(16,18),[i,a,o,s]=this.#e,[c,l,u,d]=this.#g();return e.set([NaN,NaN,NaN,NaN,(n[0]-i)/o,(n[1]-a)/s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-a)/s],t),t+=24}},ap=class extends ${#e;#t=new Float32Array(4);#n;#r;#i;#a;#o;constructor(e,t,n,r,i,a){super(),this.#o=e,this.#i=t,this.#e=n,this.#a=r,this.#n=i,this.#r=a,this.lastPoint=[NaN,NaN],this.#s(a);let[o,s,c,l]=this.#t;for(let t=0,n=e.length;t<n;t+=2)e[t]=(e[t]-o)/c,e[t+1]=(e[t+1]-s)/l;for(let e=0,n=t.length;e<n;e+=2)t[e]=(t[e]-o)/c,t[e+1]=(t[e+1]-s)/l}toSVGPath(){let e=[`M${this.#o[4]} ${this.#o[5]}`];for(let t=6,n=this.#o.length;t<n;t+=6){if(isNaN(this.#o[t])){e.push(`L${this.#o[t+4]} ${this.#o[t+5]}`);continue}e.push(`C${this.#o[t]} ${this.#o[t+1]} ${this.#o[t+2]} ${this.#o[t+3]} ${this.#o[t+4]} ${this.#o[t+5]}`)}return e.push(`Z`),e.join(` `)}serialize([e,t,n,r],i){let a=n-e,o=r-t,s,c;switch(i){case 0:s=$._rescale(this.#o,e,r,a,-o),c=$._rescale(this.#i,e,r,a,-o);break;case 90:s=$._rescaleAndSwap(this.#o,e,t,a,o),c=$._rescaleAndSwap(this.#i,e,t,a,o);break;case 180:s=$._rescale(this.#o,n,t,-a,o),c=$._rescale(this.#i,n,t,-a,o);break;case 270:s=$._rescaleAndSwap(this.#o,n,r,-a,-o),c=$._rescaleAndSwap(this.#i,n,r,-a,-o)}return{outline:Array.from(s),points:[Array.from(c)]}}#s(e){let t=this.#o,n=t[4],r=t[5],i=n,a=r,o=n,s=r,c=n,l=r,u=e?Math.max:Math.min;for(let e=6,d=t.length;e<d;e+=6){if(isNaN(t[e]))i=Math.min(i,t[e+4]),a=Math.min(a,t[e+5]),o=Math.max(o,t[e+4]),s=Math.max(s,t[e+5]),l<t[e+5]?(c=t[e+4],l=t[e+5]):l===t[e+5]&&(c=u(c,t[e+4]));else{let d=X.bezierBoundingBox(n,r,...t.slice(e,e+6));i=Math.min(i,d[0]),a=Math.min(a,d[1]),o=Math.max(o,d[2]),s=Math.max(s,d[3]),l<d[3]?(c=d[2],l=d[3]):l===d[3]&&(c=u(c,d[2]))}n=t[e+4],r=t[e+5]}let d=this.#t;d[0]=i-this.#n,d[1]=a-this.#n,d[2]=o-i+2*this.#n,d[3]=s-a+2*this.#n,this.lastPoint=[c,l]}get box(){return this.#t}newOutliner(e,t,n,r,i,a=0){return new ip(e,t,n,r,i,a)}getNewOutline(e,t){let[n,r,i,a]=this.#t,[o,s,c,l]=this.#e,u=i*c,d=a*l,f=n*c+o,p=r*l+s,m=this.newOutliner({x:this.#i[0]*u+f,y:this.#i[1]*d+p},this.#e,this.#a,e,this.#r,t??this.#n);for(let e=2;e<this.#i.length;e+=2)m.add({x:this.#i[e]*u+f,y:this.#i[e+1]*d+p});return m.getOutlines()}},op=class{#e;#t;#n=[];#r=[];constructor(e,t=0,n=0,r=!0){let i=1/0,a=-1/0,o=1/0,s=-1/0,c=10**-4;for(let{x:n,y:r,width:l,height:u}of e){let e=Math.floor((n-t)/c)*c,d=Math.ceil((n+l+t)/c)*c,f=Math.floor((r-t)/c)*c,p=Math.ceil((r+u+t)/c)*c,m=[e,f,p,!0],h=[d,f,p,!1];this.#n.push(m,h),i=Math.min(i,e),a=Math.max(a,d),o=Math.min(o,f),s=Math.max(s,p)}let l=a-i+2*n,u=s-o+2*n,d=i-n,f=o-n,p=this.#n.at(r?-1:-2),m=[p[0],p[2]];for(let e of this.#n){let[t,n,r]=e;e[0]=(t-d)/l,e[1]=(n-f)/u,e[2]=(r-f)/u}this.#e=new Float32Array([d,f,l,u]),this.#t=m}getOutlines(){this.#n.sort((e,t)=>e[0]-t[0]||e[1]-t[1]||e[2]-t[2]);let e=[];for(let t of this.#n)t[3]?(e.push(...this.#c(t)),this.#o(t)):(this.#s(t),e.push(...this.#c(t)));return this.#i(e)}#i(e){let t=[],n=new Set;for(let n of e){let[e,r,i]=n;t.push([e,r,n],[e,i,n])}t.sort((e,t)=>e[1]-t[1]||e[0]-t[0]);for(let e=0,r=t.length;e<r;e+=2){let r=t[e][2],i=t[e+1][2];r.push(i),i.push(r),n.add(r),n.add(i)}let r=[],i;for(;n.size>0;){let e=n.values().next().value,[t,a,o,s,c]=e;n.delete(e);let l=t,u=a;for(i=[t,o],r.push(i);;){let e;if(n.has(s))e=s;else if(n.has(c))e=c;else break;n.delete(e),[t,a,o,s,c]=e,l!==t&&(i.push(l,u,t,u===a?a:o),l=t),u=u===a?o:a}i.push(l,u)}return new sp(r,this.#e,this.#t)}#a(e){let t=this.#r,n=0,r=t.length-1;for(;n<=r;){let i=n+r>>1,a=t[i][0];if(a===e)return i;a<e?n=i+1:r=i-1}return r+1}#o([,e,t]){let n=this.#a(e);this.#r.splice(n,0,[e,t])}#s([,e,t]){let n=this.#a(e);for(let r=n;r<this.#r.length;r++){let[n,i]=this.#r[r];if(n!==e)break;if(n===e&&i===t){this.#r.splice(r,1);return}}for(let r=n-1;r>=0;r--){let[n,i]=this.#r[r];if(n!==e)break;if(n===e&&i===t){this.#r.splice(r,1);return}}}#c(e){let[t,n,r]=e,i=[[t,n,r]],a=this.#a(r);for(let e=0;e<a;e++){let[n,r]=this.#r[e];for(let e=0,a=i.length;e<a;e++){let[,o,s]=i[e];if(!(r<=o||s<=n)){if(o>=n){if(s>r)i[e][1]=r;else{if(a===1)return[];i.splice(e,1),e--,a--}continue}i[e][2]=n,s>r&&i.push([t,r,s])}}}return i}},sp=class extends ${#e;#t;constructor(e,t,n){super(),this.#t=e,this.#e=t,this.lastPoint=n}toSVGPath(){let e=[];for(let t of this.#t){let[n,r]=t;e.push(`M${n} ${r}`);for(let i=2;i<t.length;i+=2){let a=t[i],o=t[i+1];a===n?(e.push(`V${o}`),r=o):o===r&&(e.push(`H${a}`),n=a)}e.push(`Z`)}return e.join(` `)}serialize([e,t,n,r],i){let a=[],o=n-e,s=r-t;for(let t of this.#t){let n=Array(t.length);for(let i=0;i<t.length;i+=2)n[i]=e+t[i]*o,n[i+1]=r-t[i+1]*s;a.push(n)}return a}get box(){return this.#e}get classNamesForOutlining(){return[`highlightOutline`]}},cp=class extends ip{newFreeDrawOutline(e,t,n,r,i,a){return new lp(e,t,n,r,i,a)}},lp=class extends ap{newOutliner(e,t,n,r,i,a=0){return new cp(e,t,n,r,i,a)}},up=class e{#e=null;#t=null;#n;#r=null;#i=!1;#a=!1;#o=null;#s;#c=null;#l=null;#u;static#d=null;static get _keyboardManager(){return Y(this,`_keyboardManager`,new Ql([[[`Escape`,`mac+Escape`],e.prototype._hideDropdownFromKeyboard],[[` `,`mac+ `],e.prototype._colorSelectFromKeyboard],[[`ArrowDown`,`ArrowRight`,`mac+ArrowDown`,`mac+ArrowRight`],e.prototype._moveToNext],[[`ArrowUp`,`ArrowLeft`,`mac+ArrowUp`,`mac+ArrowLeft`],e.prototype._moveToPrevious],[[`Home`,`mac+Home`],e.prototype._moveToBeginning],[[`End`,`mac+End`],e.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:n=null}){t?(this.#a=!1,this.#u=G.HIGHLIGHT_COLOR,this.#o=t):(this.#a=!0,this.#u=G.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||n,this.#s=this.#l._eventBus,this.#n=t?.color||this.#l?.highlightColors.values().next().value||`#FFFF98`,e.#d||=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(){let e=this.#e=document.createElement(`button`);e.className=`colorPicker`,e.tabIndex=`0`,e.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-button`),e.setAttribute(`aria-haspopup`,!0);let t=this.#l._signal;e.addEventListener(`click`,this.#h.bind(this),{signal:t}),e.addEventListener(`keydown`,this.#m.bind(this),{signal:t});let n=this.#t=document.createElement(`span`);return n.className=`swatch`,n.setAttribute(`aria-hidden`,!0),n.style.backgroundColor=this.#n,e.append(n),e}renderMainDropdown(){let e=this.#r=this.#f();return e.setAttribute(`aria-orientation`,`horizontal`),e.setAttribute(`aria-labelledby`,`highlightColorPickerLabel`),e}#f(){let t=document.createElement(`div`),n=this.#l._signal;t.addEventListener(`contextmenu`,Ll,{signal:n}),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(let[r,i]of this.#l.highlightColors){let a=document.createElement(`button`);a.tabIndex=`0`,a.role=`option`,a.setAttribute(`data-color`,i),a.title=r,a.setAttribute(`data-l10n-id`,e.#d[r]);let o=document.createElement(`span`);a.append(o),o.className=`swatch`,o.style.backgroundColor=i,a.setAttribute(`aria-selected`,i===this.#n),a.addEventListener(`click`,this.#p.bind(this,i),{signal:n}),t.append(a)}return t.addEventListener(`keydown`,this.#m.bind(this),{signal:n}),t}#p(e,t){t.stopPropagation(),this.#s.dispatch(`switchannotationeditorparams`,{source:this,type:this.#u,value:e})}_colorSelectFromKeyboard(e){if(e.target===this.#e){this.#h(e);return}let t=e.target.getAttribute(`data-color`);t&&this.#p(t,e)}_moveToNext(e){if(!this.#_){this.#h(e);return}if(e.target===this.#e){this.#r.firstChild?.focus();return}e.target.nextSibling?.focus()}_moveToPrevious(e){if(e.target===this.#r?.firstChild||e.target===this.#e){this.#_&&this._hideDropdownFromKeyboard();return}this.#_||this.#h(e),e.target.previousSibling?.focus()}_moveToBeginning(e){if(!this.#_){this.#h(e);return}this.#r.firstChild?.focus()}_moveToEnd(e){if(!this.#_){this.#h(e);return}this.#r.lastChild?.focus()}#m(t){e._keyboardManager.exec(this,t)}#h(e){if(this.#_){this.hideDropdown();return}if(this.#i=e.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener(`pointerdown`,this.#g.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#r){this.#r.classList.remove(`hidden`);return}let t=this.#r=this.#f();this.#e.append(t)}#g(e){this.#r?.contains(e.target)||this.hideDropdown()}hideDropdown(){this.#r?.classList.add(`hidden`),this.#c?.abort(),this.#c=null}get#_(){return this.#r&&!this.#r.classList.contains(`hidden`)}_hideDropdownFromKeyboard(){if(!this.#a){if(!this.#_){this.#o?.unselect();return}this.hideDropdown(),this.#e.focus({preventScroll:!0,focusVisible:this.#i})}}updateColor(e){if(this.#t&&(this.#t.style.backgroundColor=e),!this.#r)return;let t=this.#l.highlightColors.values();for(let n of this.#r.children)n.setAttribute(`aria-selected`,t.next().value===e)}destroy(){this.#e?.remove(),this.#e=null,this.#t=null,this.#r?.remove(),this.#r=null}},dp=class e extends Q{#e=null;#t=0;#n;#r=null;#i=null;#a=null;#o=null;#s=0;#c=null;#l=null;#u=null;#d=!1;#f=null;#p;#m=null;#h=``;#g;#_=``;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type=`highlight`;static _editorType=W.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId=``;static get _keyboardManager(){let t=e.prototype;return Y(this,`_keyboardManager`,new Ql([[[`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||e._defaultColor,this.#g=t.thickness||e._defaultThickness,this.#p=t.opacity||e._defaultOpacity,this.#n=t.boxes||null,this.#_=t.methodOfCreation||``,this.#h=t.text||``,this._isDraggable=!1,t.highlightId>-1?(this.#d=!0,this.#y(t),this.#w()):this.#n&&(this.#e=t.anchorNode,this.#t=t.anchorOffset,this.#o=t.focusNode,this.#s=t.focusOffset,this.#v(),this.#w(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:`added`,type:this.#d?`free_highlight`:`highlight`,color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#g,methodOfCreation:this.#_}}get telemetryFinalData(){return{type:`highlight`,color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get(`color`).size}}#v(){let e=new op(this.#n,.001);this.#l=e.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;let t=new op(this.#n,.0025,.001,this._uiManager.direction===`ltr`);this.#a=t.getOutlines();let{lastPoint:n}=this.#a;this.#f=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#y({highlightOutlines:t,highlightId:n,clipPathId:r}){if(this.#l=t,this.#a=t.getNewOutline(this.#g/2+1.5,.0025),n>=0)this.#u=n,this.#r=r,this.parent.drawLayer.finalizeDraw(n,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#m=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},!0);else if(this.parent){let n=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#u,{bbox:e.#T(this.#l.box,(n-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#m,{bbox:e.#T(this.#a.box,n),path:{d:this.#a.toSVGPath()}})}let[i,a,o,s]=t.box;switch(this.rotation){case 0:this.x=i,this.y=a,this.width=o,this.height=s;break;case 90:{let[e,t]=this.parentDimensions;this.x=a,this.y=1-i,this.width=o*t/e,this.height=s*e/t;break}case 180:this.x=1-i,this.y=1-a,this.width=o,this.height=s;break;case 270:{let[e,t]=this.parentDimensions;this.x=1-a,this.y=i,this.width=o*t/e,this.height=s*e/t;break}}let{lastPoint:c}=this.#a;this.#f=[(c[0]-i)/o,(c[1]-a)/s]}static initialize(t,n){Q.initialize(t,n),e._defaultColor||=n.highlightColors?.values().next().value||`#fff066`}static updateDefaultParams(t,n){switch(t){case G.HIGHLIGHT_DEFAULT_COLOR:e._defaultColor=n;break;case G.HIGHLIGHT_THICKNESS:e._defaultThickness=n}}translateInPage(e,t){}get toolbarPosition(){return this.#f}updateParams(e,t){switch(e){case G.HIGHLIGHT_COLOR:this.#b(t);break;case G.HIGHLIGHT_THICKNESS:this.#x(t)}}static get defaultPropertiesToUpdate(){return[[G.HIGHLIGHT_DEFAULT_COLOR,e._defaultColor],[G.HIGHLIGHT_THICKNESS,e._defaultThickness]]}get propertiesToUpdate(){return[[G.HIGHLIGHT_COLOR,this.color||e._defaultColor],[G.HIGHLIGHT_THICKNESS,this.#g||e._defaultThickness],[G.HIGHLIGHT_FREE,this.#d]]}#b(t){let n=(e,t)=>{this.color=e,this.#p=t,this.parent?.drawLayer.updateProperties(this.#u,{root:{fill:e,"fill-opacity":t}}),this.#i?.updateColor(e)},r=this.color,i=this.#p;this.addCommands({cmd:n.bind(this,t,e._defaultOpacity),undo:n.bind(this,r,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`color_changed`,color:this._uiManager.highlightColorNames.get(t)},!0)}#x(e){let t=this.#g,n=e=>{this.#g=e,this.#S(e)};this.addCommands({cmd:n.bind(this,e),undo:n.bind(this,t),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`thickness_changed`,thickness:e},!0)}async addEditToolbar(){let e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(this.#i=new up({editor:this}),e.addColorPicker(this.#i)),e):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(e,t){return super.getRect(e,t,this.#O())}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),e&&this.div.focus()}remove(){this.#C(),this._reportTelemetry({action:`deleted`}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#w(),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?this.#C():e&&(this.#w(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),this.show(this._isVisible),t&&this.select()}#S(e){if(!this.#d)return;this.#y({highlightOutlines:this.#l.getNewOutline(e/2)}),this.fixAndSetPosition();let[t,n]=this.parentDimensions;this.setDims(this.width*t,this.height*n)}#C(){this.#u===null||!this.parent||(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#m),this.#m=null)}#w(e=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#r}=e.drawLayer.draw({bbox:this.#l.box,root:{viewBox:`0 0 1 1`,fill:this.color,"fill-opacity":this.#p},rootClass:{highlight:!0,free:this.#d},path:{d:this.#l.toSVGPath()}},!1,!0),this.#m=e.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#d},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},this.#d),this.#c&&(this.#c.style.clipPath=this.#r))}static#T([e,t,n,r],i){switch(i){case 90:return[1-t-r,e,r,n];case 180:return[1-e-n,1-t-r,n,r];case 270:return[t,1-e-n,r,n]}return[e,t,n,r]}rotate(t){let{drawLayer:n}=this.parent,r;this.#d?(t=(t-this.rotation+360)%360,r=e.#T(this.#l.box,t)):r=e.#T([this.x,this.y,this.width,this.height],t),n.updateProperties(this.#u,{bbox:r,root:{"data-main-rotation":t}}),n.updateProperties(this.#m,{bbox:e.#T(this.#a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;let e=super.render();this.#h&&(e.setAttribute(`aria-label`,this.#h),e.setAttribute(`role`,`mark`)),this.#d?e.classList.add(`free`):this.div.addEventListener(`keydown`,this.#E.bind(this),{signal:this._uiManager._signal});let t=this.#c=document.createElement(`div`);e.append(t),t.setAttribute(`aria-hidden`,`true`),t.className=`internal`,t.style.clipPath=this.#r;let[n,r]=this.parentDimensions;return this.setDims(this.width*n,this.height*r),Jl(this,this.#c,[`pointerover`,`pointerleave`]),this.enableEditing(),e}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1}})}#E(t){e._keyboardManager.exec(this,t)}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:this.#D(!0);break;case 1:case 3:this.#D(!1)}}#D(e){if(!this.#e)return;let t=window.getSelection();e?t.setPosition(this.#e,this.#t):t.setPosition(this.#o,this.#s)}select(){super.select(),this.#m&&this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#m&&(this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{selected:!1}}),this.#d||this.#D(!1))}get _mustFixPosition(){return!this.#d}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.updateProperties(this.#u,{rootClass:{hidden:!e}}),this.parent.drawLayer.updateProperties(this.#m,{rootClass:{hidden:!e}}))}#O(){return this.#d?this.rotation:0}#k(){if(this.#d)return null;let[e,t]=this.pageDimensions,[n,r]=this.pageTranslation,i=this.#n,a=new Float32Array(i.length*8),o=0;for(let{x:s,y:c,width:l,height:u}of i){let i=s*e+n,d=(1-c)*t+r;a[o]=a[o+4]=i,a[o+1]=a[o+3]=d,a[o+2]=a[o+6]=i+l*e,a[o+5]=a[o+7]=d-u*t,o+=8}return a}#A(e){return this.#l.serialize(e,this.#O())}static startHighlighting(e,t,{target:n,x:r,y:i}){let{x:a,y:o,width:s,height:c}=n.getBoundingClientRect(),l=new AbortController,u=e.combinedSignal(l),d=t=>{l.abort(),this.#M(e,t)};window.addEventListener(`blur`,d,{signal:u}),window.addEventListener(`pointerup`,d,{signal:u}),window.addEventListener(`pointerdown`,Rl,{capture:!0,passive:!1,signal:u}),window.addEventListener(`contextmenu`,Ll,{signal:u}),n.addEventListener(`pointermove`,this.#j.bind(this,e),{signal:u}),this._freeHighlight=new cp({x:r,y:i},[a,o,s,c],e.scale,this._defaultThickness/2,t,.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#j(e,t){this._freeHighlight.add(t)&&e.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#M(e,t){this._freeHighlight.isEmpty()?e.drawLayer.remove(this._freeHighlightId):e.createAndAddNewEditor(t,!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(e,t,n){let r=null;if(e instanceof Yf){let{data:{quadPoints:t,rect:n,rotation:i,id:a,color:o,opacity:s,popupRef:c},parent:{page:{pageNumber:l}}}=e;r=e={annotationType:W.HIGHLIGHT,color:Array.from(o),opacity:s,quadPoints:t,boxes:null,pageIndex:l-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:c}}else if(e instanceof Jf){let{data:{inkLists:t,rect:n,rotation:i,id:a,color:o,borderStyle:{rawWidth:s},popupRef:c},parent:{page:{pageNumber:l}}}=e;r=e={annotationType:W.HIGHLIGHT,color:Array.from(o),thickness:s,inkLists:t,boxes:null,pageIndex:l-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:c}}let{color:i,quadPoints:a,inkLists:o,opacity:s}=e,c=await super.deserialize(e,t,n);c.color=X.makeHexColor(...i),c.#p=s||1,o&&(c.#g=e.thickness),c.annotationElementId=e.id||null,c._initialData=r;let[l,u]=c.pageDimensions,[d,f]=c.pageTranslation;if(a){let e=c.#n=[];for(let t=0;t<a.length;t+=8)e.push({x:(a[t]-d)/l,y:1-(a[t+1]-f)/u,width:(a[t+2]-a[t])/l,height:(a[t+1]-a[t+5])/u});c.#v(),c.#w(),c.rotate(c.rotation)}else if(o){c.#d=!0;let e=o[0],n={x:e[0]-d,y:u-(e[1]-f)},r=new cp(n,[0,0,l,u],1,c.#g/2,!0,.001);for(let t=0,i=e.length;t<i;t+=2)n.x=e[t]-d,n.y=u-(e[t+1]-f),r.add(n);let{id:i,clipPathId:a}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:`0 0 1 1`,fill:c.color,"fill-opacity":c._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:r.toSVGPath()}},!0,!0);c.#y({highlightOutlines:r.getOutlines(),highlightId:i,clipPathId:a}),c.#w()}return c}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();let t=this.getRect(0,0),n=Q._colorManager.convert(this.color),r={annotationType:W.HIGHLIGHT,color:n,opacity:this.#p,thickness:this.#g,quadPoints:this.#k(),outlines:this.#A(t),pageIndex:this.pageIndex,rect:t,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#N(r)?null:(r.id=this.annotationElementId,r)}#N(e){let{color:t}=this._initialData;return e.color.some((e,n)=>e!==t[n])}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}},fp=class{#e=Object.create(null);updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(let[t,n]of Object.entries(e))this.updateProperty(t,n)}updateSVGProperty(e,t){this.#e[e]=t}toSVGProperties(){let e=this.#e;return this.#e=Object.create(null),{root:e}}reset(){this.#e=Object.create(null)}updateAll(e=this){this.updateProperties(e)}clone(){q(`Not implemented`)}},pp=class e extends Q{#e=null;#t;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#n=null;static#r=null;static#i=null;static#a=NaN;static#o=null;static#s=null;static#c=NaN;static _INNER_MARGIN=3;constructor(e){super(e),this.#t=e.mustBeCommitted||!1,e.drawOutlines&&(this.#l(e),this.#f())}#l({drawOutlines:e,drawId:t,drawingOptions:n}){this.#e=e,this._drawingOptions||=n,t>=0?(this._drawId=t,this.parent.drawLayer.finalizeDraw(t,e.defaultProperties)):this._drawId=this.#u(e,this.parent),this.#h(e.box)}#u(t,n){let{id:r}=n.drawLayer.draw(e._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return r}static _mergeSVGProperties(e,t){let n=new Set(Object.keys(e));for(let[r,i]of Object.entries(t))n.has(r)?Object.assign(e[r],i):e[r]=i;return e}static getDefaultDrawingOptions(e){q(`Not implemented`)}static get typesMap(){q(`Not implemented`)}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,n){let r=this.typesMap.get(t);r&&this._defaultDrawingOptions.updateProperty(r,n),this._currentParent&&(e.#n.updateProperty(r,n),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(e,t){let n=this.constructor.typesMap.get(e);n&&this._updateProperty(e,n,t)}static get defaultPropertiesToUpdate(){let e=[],t=this._defaultDrawingOptions;for(let[n,r]of this.typesMap)e.push([n,t[r]]);return e}get propertiesToUpdate(){let e=[],{_drawingOptions:t}=this;for(let[n,r]of this.constructor.typesMap)e.push([n,t[r]]);return e}_updateProperty(e,t,n){let r=this._drawingOptions,i=r[t],a=e=>{r.updateProperty(t,e);let n=this.#e.updateProperty(t,e);n&&this.#h(n),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties())};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizingSVGProperties(this.#m()),{bbox:this.#g()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizedSVGProperties(this.#m()),{bbox:this.#g()}))}_onTranslating(e,t){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#g(e,t)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathTranslatedSVGProperties(this.#m(),this.parentDimensions),{bbox:this.#g()}))}_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(e){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#t&&(this.#t=!1,this.commit(),this.parent.setSelected(this),e&&this.isOnScreen&&this.div.focus())}remove(){this.#d(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#h(this.#e.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?(this._uiManager.removeShouldRescale(this),this.#d()):e&&(this._uiManager.addShouldRescale(this),this.#f(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),t&&this.select()}#d(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(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=this.#u(this.#e,e)}}#p([e,t,n,r]){let{parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[t,1-e,a/i*n,i/a*r];case 180:return[1-e,1-t,n,r];case 270:return[1-t,e,a/i*n,i/a*r];default:return[e,t,n,r]}}#m(){let{x:e,y:t,width:n,height:r,parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[1-t,e,i/a*n,a/i*r];case 180:return[1-e,1-t,n,r];case 270:return[t,1-e,i/a*n,a/i*r];default:return[e,t,n,r]}}#h(e){if([this.x,this.y,this.width,this.height]=this.#p(e),this.div){this.fixAndSetPosition();let[e,t]=this.parentDimensions;this.setDims(this.width*e,this.height*t)}this._onResized()}#g(){let{x:e,y:t,width:n,height:r,rotation:i,parentRotation:a,parentDimensions:[o,s]}=this;switch((i*4+a)/90){case 1:return[1-t-r,e,r,n];case 2:return[1-e-n,1-t-r,n,r];case 3:return[t,1-e-n,r,n];case 4:return[e,t-o/s*n,s/o*r,o/s*n];case 5:return[1-t,e,o/s*n,s/o*r];case 6:return[1-e-s/o*r,1-t,s/o*r,o/s*n];case 7:return[t-o/s*n,1-e-s/o*r,o/s*n,s/o*r];case 8:return[e-n,t-r,n,r];case 9:return[1-t,e-n,r,n];case 10:return[1-e,1-t,n,r];case 11:return[t-r,1-e,r,n];case 12:return[e-s/o*r,t,s/o*r,o/s*n];case 13:return[1-t-o/s*n,e-s/o*r,o/s*n,s/o*r];case 14:return[1-e,1-t-o/s*n,s/o*r,o/s*n];case 15:return[t,1-e,o/s*n,s/o*r];default:return[e,t,n,r]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties({bbox:this.#g()},this.#e.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#h(this.#e.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let e=super.render();e.classList.add(`draw`);let t=document.createElement(`div`);e.append(t),t.setAttribute(`aria-hidden`,`true`),t.className=`internal`;let[n,r]=this.parentDimensions;return this.setDims(this.width*n,this.height*r),this._uiManager.addShouldRescale(this),this.disableEditing(),e}static createDrawerInstance(e,t,n,r,i){q(`Not implemented`)}static startDrawing(t,n,r,i){let{target:a,offsetX:o,offsetY:s,pointerId:c,pointerType:l}=i;if(e.#o&&e.#o!==l)return;let{viewport:{rotation:u}}=t,{width:d,height:f}=a.getBoundingClientRect(),p=e.#r=new AbortController,m=t.combinedSignal(p);if(e.#a||=c,e.#o??=l,window.addEventListener(`pointerup`,t=>{e.#a===t.pointerId?this._endDraw(t):e.#s?.delete(t.pointerId)},{signal:m}),window.addEventListener(`pointercancel`,t=>{e.#a===t.pointerId?this._currentParent.endDrawingSession():e.#s?.delete(t.pointerId)},{signal:m}),window.addEventListener(`pointerdown`,t=>{e.#o===t.pointerType&&((e.#s||=new Set).add(t.pointerId),e.#n.isCancellable()&&(e.#n.removeLastElement(),e.#n.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:m}),window.addEventListener(`contextmenu`,Ll,{signal:m}),a.addEventListener(`pointermove`,this._drawMove.bind(this),{signal:m}),a.addEventListener(`touchmove`,t=>{t.timeStamp===e.#c&&Rl(t)},{signal:m}),t.toggleDrawing(),n._editorUndoBar?.hide(),e.#n){t.drawLayer.updateProperties(this._currentDrawId,e.#n.startNew(o,s,d,f,u));return}n.updateUIForDefaultProperties(this),e.#n=this.createDrawerInstance(o,s,d,f,u),e.#i=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(e.#i.toSVGProperties(),e.#n.defaultSVGProperties),!0,!1)}static _drawMove(t){if(e.#c=-1,!e.#n)return;let{offsetX:n,offsetY:r,pointerId:i}=t;if(e.#a===i){if(e.#s?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,e.#n.add(n,r)),e.#c=t.timeStamp,Rl(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,e.#n=null,e.#i=null,e.#o=null,e.#c=NaN),e.#r&&(e.#r.abort(),e.#r=null,e.#a=NaN,e.#s=null)}static _endDraw(t){let n=this._currentParent;if(n){if(n.toggleDrawing(!0),this._cleanup(!1),t&&n.drawLayer.updateProperties(this._currentDrawId,e.#n.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){let t=e.#n,r=this._currentDrawId,i=t.getLastElement();n.addCommands({cmd:()=>{n.drawLayer.updateProperties(r,t.setLastElement(i))},undo:()=>{n.drawLayer.updateProperties(r,t.removeLastElement())},mustExec:!1,type:G.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){let n=this._currentParent;if(!n)return null;if(n.toggleDrawing(!0),n.cleanUndoStack(G.DRAW_STEP),!e.#n.isEmpty()){let{pageDimensions:[r,i],scale:a}=n,o=n.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:e.#n.getOutlines(r*a,i*a,a,this._INNER_MARGIN),drawingOptions:e.#i,mustBeCommitted:!t});return this._cleanup(!0),o}return n.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,t,n,r,i,a){q(`Not implemented`)}static async deserialize(e,t,n){let{rawDims:{pageWidth:r,pageHeight:i,pageX:a,pageY:o}}=t.viewport,s=this.deserializeDraw(a,o,r,i,this._INNER_MARGIN,e),c=await super.deserialize(e,t,n);return c.createDrawingOptions(e),c.#l({drawOutlines:s}),c.#f(),c.onScaleChanging(),c.rotate(),c}serializeDraw(e){let[t,n]=this.pageTranslation,[r,i]=this.pageDimensions;return this.#e.serialize([t,n,r,i],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}},mp=class{#e=new Float64Array(6);#t;#n;#r;#i;#a;#o=``;#s=0;#c=new hp;#l;#u;constructor(e,t,n,r,i,a){this.#l=n,this.#u=r,this.#r=i,this.#i=a,[e,t]=this.#d(e,t);let o=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t],this.#n=[{line:o,points:this.#a}],this.#e.set(o,0)}updateProperty(e,t){e===`stroke-width`&&(this.#i=t)}#d(e,t){return $._normalizePoint(e,t,this.#l,this.#u,this.#r)}isEmpty(){return!this.#n||this.#n.length===0}isCancellable(){return this.#a.length<=10}add(e,t){[e,t]=this.#d(e,t);let[n,r,i,a]=this.#e.subarray(2,6),o=e-i,s=t-a;return Math.hypot(this.#l*o,this.#u*s)<=2?null:(this.#a.push(e,t),isNaN(n)?(this.#e.set([i,a,e,t],2),this.#t.push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(this.#e[0])&&this.#t.splice(6,6),this.#e.set([n,r,i,a,e,t],0),this.#t.push(...$.createBezierPoints(n,r,i,a,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){return this.add(e,t)||(this.#a.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,n,r,i){this.#l=n,this.#u=r,this.#r=i,[e,t]=this.#d(e,t);let a=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t];let o=this.#n.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#n.push({line:a,points:this.#a}),this.#e.set(a,0),this.#s=0,this.toSVGPath(),null}getLastElement(){return this.#n.at(-1)}setLastElement(e){return this.#n?(this.#n.push(e),this.#t=e.line,this.#a=e.points,this.#s=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(e)}removeLastElement(){if(!this.#n)return this.#c.removeLastElement();this.#n.pop(),this.#o=``;for(let e=0,t=this.#n.length;e<t;e++){let{line:t,points:n}=this.#n[e];this.#t=t,this.#a=n,this.#s=0,this.toSVGPath()}return{path:{d:this.#o}}}toSVGPath(){let e=$.svgRound(this.#t[4]),t=$.svgRound(this.#t[5]);if(this.#a.length===2)return this.#o=`${this.#o} M ${e} ${t} Z`,this.#o;if(this.#a.length<=6){let n=this.#o.lastIndexOf(`M`);this.#o=`${this.#o.slice(0,n)} M ${e} ${t}`,this.#s=6}if(this.#a.length===4){let e=$.svgRound(this.#t[10]),t=$.svgRound(this.#t[11]);return this.#o=`${this.#o} L ${e} ${t}`,this.#s=12,this.#o}let n=[];this.#s===0&&(n.push(`M ${e} ${t}`),this.#s=6);for(let e=this.#s,t=this.#t.length;e<t;e+=6){let[t,r,i,a,o,s]=this.#t.slice(e,e+6).map($.svgRound);n.push(`C${t} ${r} ${i} ${a} ${o} ${s}`)}return this.#o+=n.join(` `),this.#s=this.#t.length,this.#o}getOutlines(e,t,n,r){let i=this.#n.at(-1);return i.line=new Float32Array(i.line),i.points=new Float32Array(i.points),this.#c.build(this.#n,e,t,n,this.#r,this.#i,r),this.#e=null,this.#t=null,this.#n=null,this.#o=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:`0 0 10000 10000`},rootClass:{draw:!0},bbox:[0,0,1,1]}}},hp=class e extends ${#e;#t=0;#n;#r;#i;#a;#o;#s;#c;build(e,t,n,r,i,a,o){this.#i=t,this.#a=n,this.#o=r,this.#s=i,this.#c=a,this.#n=o??0,this.#r=e,this.#d()}setLastElement(e){return this.#r.push(e),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#r.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){let e=[];for(let{line:t}of this.#r){if(e.push(`M${$.svgRound(t[4])} ${$.svgRound(t[5])}`),t.length===6){e.push(`Z`);continue}if(t.length===12){e.push(`L${$.svgRound(t[10])} ${$.svgRound(t[11])}`);continue}for(let n=6,r=t.length;n<r;n+=6){let[r,i,a,o,s,c]=t.subarray(n,n+6).map($.svgRound);e.push(`C${r} ${i} ${a} ${o} ${s} ${c}`)}}return e.join(``)}serialize([e,t,n,r],i){let a=[],o=[],[s,c,l,u]=this.#u(),d,f,p,m,h,g,_,v,y;switch(this.#s){case 0:y=$._rescale,d=e,f=t+r,p=n,m=-r,h=e+s*n,g=t+(1-c-u)*r,_=e+(s+l)*n,v=t+(1-c)*r;break;case 90:y=$._rescaleAndSwap,d=e,f=t,p=n,m=r,h=e+c*n,g=t+s*r,_=e+(c+u)*n,v=t+(s+l)*r;break;case 180:y=$._rescale,d=e+n,f=t,p=-n,m=r,h=e+(1-s-l)*n,g=t+c*r,_=e+(1-s)*n,v=t+(c+u)*r;break;case 270:y=$._rescaleAndSwap,d=e+n,f=t+r,p=-n,m=-r,h=e+(1-c-u)*n,g=t+(1-s-l)*r,_=e+(1-c)*n,v=t+(1-s)*r}for(let{line:e,points:t}of this.#r)a.push(y(e,d,f,p,m,i?Array(e.length):null)),o.push(y(t,d,f,p,m,i?Array(t.length):null));return{lines:a,points:o,rect:[h,g,_,v]}}static deserialize(t,n,r,i,a,{paths:{lines:o,points:s},rotation:c,thickness:l}){let u=[],d,f,p,m,h;switch(c){case 0:h=$._rescale,d=-t/r,f=n/i+1,p=1/r,m=-1/i;break;case 90:h=$._rescaleAndSwap,d=-n/i,f=-t/r,p=1/i,m=1/r;break;case 180:h=$._rescale,d=t/r+1,f=-n/i,p=-1/r,m=1/i;break;case 270:h=$._rescaleAndSwap,d=n/i+1,f=t/r+1,p=-1/i,m=-1/r}if(!o){o=[];for(let e of s){let t=e.length;if(t===2){o.push(new Float32Array([NaN,NaN,NaN,NaN,e[0],e[1]]));continue}if(t===4){o.push(new Float32Array([NaN,NaN,NaN,NaN,e[0],e[1],NaN,NaN,NaN,NaN,e[2],e[3]]));continue}let n=new Float32Array(3*(t-2));o.push(n);let[r,i,a,s]=e.subarray(0,4);n.set([NaN,NaN,NaN,NaN,r,i],0);for(let o=4;o<t;o+=2){let t=e[o],c=e[o+1];n.set($.createBezierPoints(r,i,a,s,t,c),(o-2)*3),[r,i,a,s]=[a,s,t,c]}}}for(let e=0,t=o.length;e<t;e++)u.push({line:h(o[e].map(e=>e??NaN),d,f,p,m),points:h(s[e].map(e=>e??NaN),d,f,p,m)});let g=new e;return g.build(u,r,i,1,c,l,a),g}#l(e=this.#c){let t=this.#n+e/2*this.#o;return this.#s%180==0?[t/this.#i,t/this.#a]:[t/this.#a,t/this.#i]}#u(){let[e,t,n,r]=this.#e,[i,a]=this.#l(0);return[e+i,t+a,n-2*i,r-2*a]}#d(){let e=this.#e=new Float32Array([1/0,1/0,-1/0,-1/0]);for(let{line:t}of this.#r){if(t.length<=12){for(let n=4,r=t.length;n<r;n+=6){let[r,i]=t.subarray(n,n+2);e[0]=Math.min(e[0],r),e[1]=Math.min(e[1],i),e[2]=Math.max(e[2],r),e[3]=Math.max(e[3],i)}continue}let n=t[4],r=t[5];for(let i=6,a=t.length;i<a;i+=6){let[a,o,s,c,l,u]=t.subarray(i,i+6);X.bezierBoundingBox(n,r,a,o,s,c,l,u,e),n=l,r=u}}let[t,n]=this.#l();e[0]=Math.min(1,Math.max(0,e[0]-t)),e[1]=Math.min(1,Math.max(0,e[1]-n)),e[2]=Math.min(1,Math.max(0,e[2]+t)),e[3]=Math.min(1,Math.max(0,e[3]+n)),e[2]-=e[0],e[3]-=e[1]}get box(){return this.#e}updateProperty(e,t){return e===`stroke-width`?this.#f(t):null}#f(e){let[t,n]=this.#l();this.#c=e;let[r,i]=this.#l(),[a,o]=[r-t,i-n],s=this.#e;return s[0]-=a,s[1]-=o,s[2]+=2*a,s[3]+=2*o,s}updateParentDimensions([e,t],n){let[r,i]=this.#l();this.#i=e,this.#a=t,this.#o=n;let[a,o]=this.#l(),s=a-r,c=o-i,l=this.#e;return l[0]-=s,l[1]-=c,l[2]+=2*s,l[3]+=2*c,l}updateRotation(e){return this.#t=e,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#e.map($.svgRound).join(` `)}get defaultProperties(){let[e,t]=this.#e;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`}}}get rotationTransform(){let[,,e,t]=this.#e,n=0,r=0,i=0,a=0,o=0,s=0;switch(this.#t){case 90:r=t/e,i=-e/t,o=e;break;case 180:n=-1,a=-1,o=e,s=t;break;case 270:r=-t/e,i=e/t,s=t;break;default:return``}return`matrix(${n} ${r} ${i} ${a} ${$.svgRound(o)} ${$.svgRound(s)})`}getPathResizingSVGProperties([e,t,n,r]){let[i,a]=this.#l(),[o,s,c,l]=this.#e;if(Math.abs(c-i)<=$.PRECISION||Math.abs(l-a)<=$.PRECISION){let i=e+n/2-(o+c/2),a=t+r/2-(s+l/2);return{path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:`${this.rotationTransform} translate(${i} ${a})`}}}let u=(n-2*i)/(c-2*i),d=(r-2*a)/(l-2*a),f=c/n,p=l/r;return{path:{"transform-origin":`${$.svgRound(o)} ${$.svgRound(s)}`,transform:`${this.rotationTransform} scale(${f} ${p}) translate(${$.svgRound(i)} ${$.svgRound(a)}) scale(${u} ${d}) translate(${$.svgRound(-i)} ${$.svgRound(-a)})`}}}getPathResizedSVGProperties([e,t,n,r]){let[i,a]=this.#l(),o=this.#e,[s,c,l,u]=o;if(o[0]=e,o[1]=t,o[2]=n,o[3]=r,Math.abs(l-i)<=$.PRECISION||Math.abs(u-a)<=$.PRECISION){let i=e+n/2-(s+l/2),a=t+r/2-(c+u/2);for(let{line:e,points:t}of this.#r)$._translate(e,i,a,e),$._translate(t,i,a,t);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}let d=(n-2*i)/(l-2*i),f=(r-2*a)/(u-2*a),p=-d*(s+i)+e+i,m=-f*(c+a)+t+a;if(d!==1||f!==1||p!==0||m!==0)for(let{line:e,points:t}of this.#r)$._rescale(e,p,m,d,f,e),$._rescale(t,p,m,d,f,t);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([e,t],n){let[r,i]=n,a=this.#e,o=e-a[0],s=t-a[1];if(this.#i===r&&this.#a===i)for(let{line:e,points:t}of this.#r)$._translate(e,o,s,e),$._translate(t,o,s,t);else{let e=this.#i/r,t=this.#a/i;this.#i=r,this.#a=i;for(let{line:n,points:r}of this.#r)$._rescale(n,o,s,e,t,n),$._rescale(r,o,s,e,t,r);a[2]*=e,a[3]*=t}return a[0]=e,a[1]=t,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`}}}get defaultSVGProperties(){let e=this.#e;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${$.svgRound(e[0])} ${$.svgRound(e[1])}`,transform:this.rotationTransform||null},bbox:e}}},gp=class e extends fp{#e;constructor(e){super(),this.#e=e,super.updateProperties({fill:`none`,stroke:Q._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-miterlimit":10})}updateSVGProperty(e,t){e===`stroke-width`&&(t??=this[`stroke-width`],t*=this.#e.realScale),super.updateSVGProperty(e,t)}clone(){let t=new e(this.#e);return t.updateAll(this),t}},_p=class e extends pp{static _type=`ink`;static _editorType=W.INK;static _defaultDrawingOptions=null;constructor(e){super({...e,name:`inkEditor`}),this._willKeepAspectRatio=!0}static initialize(e,t){Q.initialize(e,t),this._defaultDrawingOptions=new gp(t.viewParameters)}static getDefaultDrawingOptions(e){let t=this._defaultDrawingOptions.clone();return t.updateProperties(e),t}static get supportMultipleDrawings(){return!0}static get typesMap(){return Y(this,`typesMap`,new Map([[G.INK_THICKNESS,`stroke-width`],[G.INK_COLOR,`stroke`],[G.INK_OPACITY,`stroke-opacity`]]))}static createDrawerInstance(e,t,n,r,i){return new mp(e,t,n,r,i,this._defaultDrawingOptions[`stroke-width`])}static deserializeDraw(e,t,n,r,i,a){return hp.deserialize(e,t,n,r,i,a)}static async deserialize(e,t,n){let r=null;if(e instanceof Jf){let{data:{inkLists:t,rect:n,rotation:i,id:a,color:o,opacity:s,borderStyle:{rawWidth:c},popupRef:l},parent:{page:{pageNumber:u}}}=e;r=e={annotationType:W.INK,color:Array.from(o),thickness:c,opacity:s,paths:{points:t},boxes:null,pageIndex:u-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:l}}let i=await super.deserialize(e,t,n);return i.annotationElementId=e.id||null,i._initialData=r,i}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();let{_drawId:e,_drawingOptions:t,parent:n}=this;t.updateSVGProperty(`stroke-width`),n.drawLayer.updateProperties(e,t.toSVGProperties())}static onScaleChangingWhenDrawing(){let e=this._currentParent;e&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty(`stroke-width`),e.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:n,opacity:r}){this._drawingOptions=e.getDefaultDrawingOptions({stroke:X.makeHexColor(...t),"stroke-width":n,"stroke-opacity":r})}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let{lines:t,points:n,rect:r}=this.serializeDraw(e),{_drawingOptions:{stroke:i,"stroke-opacity":a,"stroke-width":o}}=this,s={annotationType:W.INK,color:Q._colorManager.convert(i),opacity:a,thickness:o,paths:{lines:t,points:n},pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?s:this.annotationElementId&&!this.#e(s)?null:(s.id=this.annotationElementId,s)}#e(e){let{color:t,thickness:n,opacity:r,pageIndex:i}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||e.color.some((e,n)=>e!==t[n])||e.thickness!==n||e.opacity!==r||e.pageIndex!==i}renderAnnotationElement(e){let{points:t,rect:n}=this.serializeDraw(!1);return e.updateEdited({rect:n,thickness:this._drawingOptions[`stroke-width`],points:t}),null}},vp=class e extends Q{#e=null;#t=null;#n=null;#r=null;#i=null;#a=``;#o=null;#s=null;#c=!1;#l=!1;static _type=`stamp`;static _editorType=W.STAMP;constructor(e){super({...e,name:`stampEditor`}),this.#r=e.bitmapUrl,this.#i=e.bitmapFile}static initialize(e,t){Q.initialize(e,t)}static get supportedTypes(){return Y(this,`supportedTypes`,[`apng`,`avif`,`bmp`,`gif`,`jpeg`,`png`,`svg+xml`,`webp`,`x-icon`].map(e=>`image/${e}`))}static get supportedTypesStr(){return Y(this,`supportedTypesStr`,this.supportedTypes.join(`,`))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,t){t.pasteEditor(W.STAMP,{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:`stamp`,hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(e){let t=e.get(`hasAltText`);return{hasAltText:t.get(!0)??0,hasNoAltText:t.get(!1)??0}}#u(e,t=!1){if(!e){this.remove();return}this.#e=e.bitmap,t||(this.#t=e.id,this.#c=e.isSvg),e.file&&(this.#a=e.file.name),this.#p()}#d(){if(this.#n=null,this._uiManager.enableWaiting(!1),this.#o){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){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(e=null,t=!0){if(this.hasAltTextData())return null;let{mlManager:n}=this._uiManager;if(!n)throw Error(`No ML.`);if(!await n.isEnabledFor(`altText`))throw Error(`ML isn't enabled for alt text.`);let{data:r,width:i,height:a}=e||this.copyCanvas(null,null,!0).imageData,o=await n.guess({name:`altText`,request:{data:r,width:i,height:a,channels:r.length/(i*a)}});if(!o)throw Error(`No response from the AI service.`);if(o.error)throw Error(`Error from the AI service.`);if(o.cancel)return null;if(!o.output)throw Error(`No valid response from the AI service.`);let s=o.output;return await this.setGuessedAltText(s),t&&!this.hasAltTextData()&&(this.altTextData={alt:s,decorative:!1}),s}#f(){if(this.#t){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#t).then(e=>this.#u(e,!0)).finally(()=>this.#d());return}if(this.#r){let e=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromUrl(e).then(e=>this.#u(e)).finally(()=>this.#d());return}if(this.#i){let e=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromFile(e).then(e=>this.#u(e)).finally(()=>this.#d());return}let t=document.createElement(`input`);t.type=`file`,t.accept=e.supportedTypesStr;let n=this._uiManager._signal;this.#n=new Promise(e=>{t.addEventListener(`change`,async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);let e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:`pdfjs.image.image_selected`,data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#u(e)}e()},{signal:n}),t.addEventListener(`cancel`,()=>{this.remove(),e()},{signal:n})}).finally(()=>this.#d()),t.click()}remove(){this.#t&&(this.#e=null,this._uiManager.imageManager.deleteId(this.#t),this.#o?.remove(),this.#o=null,this.#s&&=(clearTimeout(this.#s),null)),super.remove()}rebuild(){if(!this.parent){this.#t&&this.#f();return}super.rebuild(),this.div!==null&&(this.#t&&this.#o===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(e){this._isDraggable=!0,e&&this.div.focus()}isEmpty(){return!(this.#n||this.#e||this.#r||this.#i||this.#t)}get isResizable(){return!0}render(){if(this.div)return this.div;let e,t;if(this.width&&(e=this.x,t=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute(`role`,`figure`),this.addAltTextButton(),this.#e?this.#p():this.#f(),this.width&&!this.annotationElementId){let[n,r]=this.parentDimensions;this.setAt(e*n,t*r,this.width*n,this.height*r)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(this.#s!==null&&clearTimeout(this.#s),this.#s=setTimeout(()=>{this.#s=null,this.#h()},200))}#p(){let{div:e}=this,{width:t,height:n}=this.#e,[r,i]=this.pageDimensions,a=.75;if(this.width)t=this.width*r,n=this.height*i;else if(t>a*r||n>a*i){let e=Math.min(a*r/t,a*i/n);t*=e,n*=e}let[o,s]=this.parentDimensions;this.setDims(t*o/r,n*s/i),this._uiManager.enableWaiting(!1);let c=this.#o=document.createElement(`canvas`);c.setAttribute(`role`,`img`),this.addContainer(c),this.width=t/r,this.height=n/i,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),this.#h(),this.#l||=(this.parent.addUndoableEditor(this),!0),this._reportTelemetry({action:`inserted_image`}),this.#a&&c.setAttribute(`aria-label`,this.#a)}copyCanvas(e,t,n=!1){e||=224;let{width:r,height:i}=this.#e,a=new Gl,o=this.#e,s=r,c=i,l=null;if(t){if(r>t||i>t){let e=Math.min(t/r,t/i);s=Math.floor(r*e),c=Math.floor(i*e)}l=document.createElement(`canvas`);let e=l.width=Math.ceil(s*a.sx),n=l.height=Math.ceil(c*a.sy);this.#c||(o=this.#m(e,n));let u=l.getContext(`2d`);u.filter=this._uiManager.hcmFilter;let d=`white`,f=`#cfcfd8`;this._uiManager.hcmFilter===`none`?window.matchMedia?.(`(prefers-color-scheme: dark)`).matches&&(d=`#8f8f9d`,f=`#42414d`):f=`black`;let p=15*a.sx,m=15*a.sy,h=new OffscreenCanvas(p*2,m*2),g=h.getContext(`2d`);g.fillStyle=d,g.fillRect(0,0,p*2,m*2),g.fillStyle=f,g.fillRect(0,0,p,m),g.fillRect(p,m,p,m),u.fillStyle=u.createPattern(h,`repeat`),u.fillRect(0,0,e,n),u.drawImage(o,0,0,o.width,o.height,0,0,e,n)}let u=null;if(n){let t,n;if(a.symmetric&&o.width<e&&o.height<e)t=o.width,n=o.height;else if(o=this.#e,r>e||i>e){let a=Math.min(e/r,e/i);t=Math.floor(r*a),n=Math.floor(i*a),this.#c||(o=this.#m(t,n))}let s=new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0});s.drawImage(o,0,0,o.width,o.height,0,0,t,n),u={width:t,height:n,data:s.getImageData(0,0,t,n).data}}return{canvas:l,width:s,height:c,imageData:u}}#m(e,t){let{width:n,height:r}=this.#e,i=n,a=r,o=this.#e;for(;i>2*e||a>2*t;){let n=i,r=a;i>2*e&&(i=i>=16384?Math.floor(i/2)-1:Math.ceil(i/2)),a>2*t&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));let s=new OffscreenCanvas(i,a);s.getContext(`2d`).drawImage(o,0,0,n,r,0,0,i,a),o=s.transferToImageBitmap()}return o}#h(){let[e,t]=this.parentDimensions,{width:n,height:r}=this,i=new Gl,a=Math.ceil(n*e*i.sx),o=Math.ceil(r*t*i.sy),s=this.#o;if(!s||s.width===a&&s.height===o)return;s.width=a,s.height=o;let c=this.#c?this.#e:this.#m(a,o),l=s.getContext(`2d`);l.filter=this._uiManager.hcmFilter,l.drawImage(c,0,0,c.width,c.height,0,0,a,o)}getImageForAltText(){return this.#o}#g(e){if(e){if(this.#c){let e=this._uiManager.imageManager.getSvgUrl(this.#t);if(e)return e}let e=document.createElement(`canvas`);return{width:e.width,height:e.height}=this.#e,e.getContext(`2d`).drawImage(this.#e,0,0),e.toDataURL()}if(this.#c){let[e,t]=this.pageDimensions,n=Math.round(this.width*e*Dl.PDF_TO_CSS_UNITS),r=Math.round(this.height*t*Dl.PDF_TO_CSS_UNITS),i=new OffscreenCanvas(n,r);return i.getContext(`2d`).drawImage(this.#e,0,0,this.#e.width,this.#e.height,0,0,n,r),i.transferToImageBitmap()}return structuredClone(this.#e)}static async deserialize(e,t,n){let r=null;if(e instanceof $f){let{data:{rect:i,rotation:a,id:o,structParent:s,popupRef:c},container:l,parent:{page:{pageNumber:u}}}=e,d=l.querySelector(`canvas`),f=n.imageManager.getFromCanvas(l.id,d);d.remove();let p=(await t._structTree.getAriaAttributes(`${wl}${o}`))?.get(`aria-label`)||``;r=e={annotationType:W.STAMP,bitmapId:f.id,bitmap:f.bitmap,pageIndex:u-1,rect:i.slice(0),rotation:a,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:s,popupRef:c}}let i=await super.deserialize(e,t,n),{rect:a,bitmap:o,bitmapUrl:s,bitmapId:c,isSvg:l,accessibilityData:u}=e;c&&n.imageManager.isValidId(c)?(i.#t=c,o&&(i.#e=o)):i.#r=s,i.#c=l;let[d,f]=i.pageDimensions;return i.width=(a[2]-a[0])/d,i.height=(a[3]-a[1])/f,i.annotationElementId=e.id||null,u&&(i.altTextData=u),i._initialData=r,i.#l=!!r,i}serialize(e=!1,t=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n={annotationType:W.STAMP,bitmapId:this.#t,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(e)return n.bitmapUrl=this.#g(!0),n.accessibilityData=this.serializeAltText(!0),n;let{decorative:r,altText:i}=this.serializeAltText(!1);if(!r&&i&&(n.accessibilityData={type:`Figure`,alt:i}),this.annotationElementId){let e=this.#_(n);if(e.isSame)return null;e.isSameAltText?delete n.accessibilityData:n.accessibilityData.structParent=this._initialData.structParent??-1}if(n.id=this.annotationElementId,t===null)return n;t.stamps||=new Map;let a=this.#c?(n.rect[2]-n.rect[0])*(n.rect[3]-n.rect[1]):null;if(!t.stamps.has(this.#t))t.stamps.set(this.#t,{area:a,serialized:n}),n.bitmap=this.#g(!1);else if(this.#c){let e=t.stamps.get(this.#t);a>e.area&&(e.area=a,e.serialized.bitmap.close(),e.serialized.bitmap=this.#g(!1))}return n}#_(e){let{pageIndex:t,accessibilityData:{altText:n}}=this._initialData,r=e.pageIndex===t,i=(e.accessibilityData?.alt||``)===n;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&r&&i,isSameAltText:i}}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}},yp=class e{#e;#t=!1;#n=null;#r=null;#i=null;#a=new Map;#o=!1;#s=!1;#c=!1;#l=null;#u=null;#d=null;#f=null;#p;static _initialized=!1;static#m=new Map([rp,_p,vp,dp].map(e=>[e._editorType,e]));constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:i,accessibilityManager:a,annotationLayer:o,drawLayer:s,textLayer:c,viewport:l,l10n:u}){let d=[...e.#m.values()];if(!e._initialized){e._initialized=!0;for(let e of d)e.initialize(u,t)}t.registerEditorTypes(d),this.#p=t,this.pageIndex=n,this.div=r,this.#e=a,this.#n=o,this.viewport=l,this.#d=c,this.drawLayer=s,this._structTree=i,this.#p.addLayer(this)}get isEmpty(){return this.#a.size===0}get isInvisible(){return this.isEmpty&&this.#p.getMode()===W.NONE}updateToolbar(e){this.#p.updateToolbar(e)}updateMode(t=this.#p.getMode()){switch(this.#y(),t){case W.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case W.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case W.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:n}=this.div;for(let r of e.#m.values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(e){return e===this.#d?.div}setEditingState(e){this.#p.setEditingState(e)}addCommands(e){this.#p.addCommands(e)}cleanUndoStack(e){this.#p.cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle(`drawing`,!e)}togglePointerEvents(e=!1){this.div.classList.toggle(`disabled`,!e)}toggleAnnotationLayerPointerEvents(e=!1){this.#n?.div.classList.toggle(`disabled`,!e)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);let e=new Set;for(let t of this.#a.values())t.enableEditing(),t.show(!0),t.annotationElementId&&(this.#p.removeChangedExistingAnnotation(t),e.add(t.annotationElementId));if(!this.#n){this.#c=!1;return}let t=this.#n.getEditableAnnotations();for(let n of t){if(n.hide(),this.#p.isDeletedAnnotationElement(n.data.id)||e.has(n.data.id))continue;let t=await this.deserialize(n);t&&(this.addOrRebuild(t),t.enableEditing())}this.#c=!1}disable(){this.#s=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let t=new Map,n=new Map;for(let e of this.#a.values())if(e.disableEditing(),e.annotationElementId){if(e.serialize()!==null){t.set(e.annotationElementId,e);continue}n.set(e.annotationElementId,e),this.getEditableAnnotation(e.annotationElementId)?.show(),e.remove()}if(this.#n){let e=this.#n.getEditableAnnotations();for(let r of e){let{id:e}=r.data;if(this.#p.isDeletedAnnotationElement(e))continue;let i=n.get(e);if(i){i.resetAnnotationElement(r),i.show(!1),r.show();continue}i=t.get(e),i&&(this.#p.addChangedExistingAnnotation(i),i.renderAnnotationElement(r)&&i.show(!1)),r.show()}}this.#y(),this.isEmpty&&(this.div.hidden=!0);let{classList:r}=this.div;for(let t of e.#m.values())r.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#s=!1}getEditableAnnotation(e){return this.#n?.getEditableAnnotation(e)||null}setActiveEditor(e){this.#p.getActive()!==e&&this.#p.setActiveEditor(e)}enableTextSelection(){if(this.div.tabIndex=-1,this.#d?.div&&!this.#f){this.#f=new AbortController;let e=this.#p.combinedSignal(this.#f);this.#d.div.addEventListener(`pointerdown`,this.#h.bind(this),{signal:e}),this.#d.div.classList.add(`highlighting`)}}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#d.div.classList.remove(`highlighting`))}#h(e){this.#p.unselectAll();let{target:t}=e;if(t===this.#d.div||(t.getAttribute(`role`)===`img`||t.classList.contains(`endOfContent`))&&this.#d.div.contains(t)){let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t)return;this.#p.showAllEditors(`highlight`,!0,!0),this.#d.div.classList.add(`free`),this.toggleDrawing(),dp.startHighlighting(this,this.#p.direction===`ltr`,{target:this.#d.div,x:e.x,y:e.y}),this.#d.div.addEventListener(`pointerup`,()=>{this.#d.div.classList.remove(`free`),this.toggleDrawing(!0)},{once:!0,signal:this.#p._signal}),e.preventDefault()}}enableClick(){if(this.#r)return;this.#r=new AbortController;let e=this.#p.combinedSignal(this.#r);this.div.addEventListener(`pointerdown`,this.pointerdown.bind(this),{signal:e});let t=this.pointerup.bind(this);this.div.addEventListener(`pointerup`,t,{signal:e}),this.div.addEventListener(`pointercancel`,t,{signal:e})}disableClick(){this.#r?.abort(),this.#r=null}attach(e){this.#a.set(e.id,e);let{annotationElementId:t}=e;t&&this.#p.isDeletedAnnotationElement(t)&&this.#p.removeDeletedAnnotationElement(e)}detach(e){this.#a.delete(e.id),this.#e?.removePointerInTextLayer(e.contentDiv),!this.#s&&e.annotationElementId&&this.#p.addDeletedAnnotationElement(e)}remove(e){this.detach(e),this.#p.removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){e.parent!==this&&(e.parent&&e.annotationElementId&&(this.#p.addDeletedAnnotationElement(e.annotationElementId),Q.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),e.parent?.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),this.#p.addEditor(e),this.attach(e),!e.isAttachedToDOM){let t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!this.#c),this.#p.addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){if(!e.isAttachedToDOM)return;let{activeElement:t}=document;e.div.contains(t)&&!this.#i&&(e._focusEventsAllowed=!1,this.#i=setTimeout(()=>{this.#i=null,e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this.#p._signal}),t.focus())},0)),e._structTreeParentId=this.#e?.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||=this,e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){this.addCommands({cmd:()=>e._uiManager.rebuild(e),undo:()=>{e.remove()},mustExec:!1})}getNextId(){return this.#p.getId()}get#g(){return e.#m.get(this.#p.getMode())}combinedSignal(e){return this.#p.combinedSignal(e)}#_(e){let t=this.#g;return t?new t.prototype.constructor(e):null}canCreateNewEmptyEditor(){return this.#g?.canCreateNewEmptyEditor()}pasteEditor(e,t){this.#p.updateToolbar(e),this.#p.updateMode(e);let{offsetX:n,offsetY:r}=this.#v(),i=this.getNextId(),a=this.#_({parent:this,id:i,x:n,y:r,uiManager:this.#p,isCentered:!0,...t});a&&this.add(a)}async deserialize(t){return await e.#m.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#p)||null}createAndAddNewEditor(e,t,n={}){let r=this.getNextId(),i=this.#_({parent:this,id:r,x:e.offsetX,y:e.offsetY,uiManager:this.#p,isCentered:t,...n});return i&&this.add(i),i}#v(){let{x:e,y:t,width:n,height:r}=this.div.getBoundingClientRect(),i=Math.max(0,e),a=Math.max(0,t),o=Math.min(window.innerWidth,e+n),s=Math.min(window.innerHeight,t+r),c=(i+o)/2-e,l=(a+s)/2-t,[u,d]=this.viewport.rotation%180==0?[c,l]:[l,c];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#v(),!0)}setSelected(e){this.#p.setSelected(e)}toggleSelected(e){this.#p.toggleSelected(e)}unselect(e){this.#p.unselect(e)}pointerup(e){let{isMac:t}=_l.platform;if(!(e.button!==0||e.ctrlKey&&t)&&e.target===this.div&&this.#o&&(this.#o=!1,!(this.#g?.isDrawer&&this.#g.supportMultipleDrawings))){if(!this.#t){this.#t=!0;return}if(this.#p.getMode()===W.STAMP){this.#p.unselectAll();return}this.createAndAddNewEditor(e,!1)}}pointerdown(e){if(this.#p.getMode()===W.HIGHLIGHT&&this.enableTextSelection(),this.#o){this.#o=!1;return}let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(this.#o=!0,this.#g?.isDrawer){this.startDrawingSession(e);return}let n=this.#p.getActive();this.#t=!n||n.isEmpty()}startDrawingSession(e){if(this.div.focus(),this.#l){this.#g.startDrawing(this,this.#p,!1,e);return}this.#p.setCurrentDrawingSession(this),this.#l=new AbortController;let t=this.#p.combinedSignal(this.#l);this.div.addEventListener(`blur`,({relatedTarget:e})=>{e&&!this.div.contains(e)&&(this.#u=null,this.commitOrRemove())},{signal:t}),this.#g.startDrawing(this,this.#p,!1,e)}pause(e){if(e){let{activeElement:e}=document;this.div.contains(e)&&(this.#u=e);return}this.#u&&setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(e=!1){return this.#l?(this.#p.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#u=null,this.#g.endDrawing(e)):null}findNewParent(e,t,n){let r=this.#p.findParent(t,n);return r===null||r===this?!1:(r.changeParent(e),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#g.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#p.getActive()?.parent===this&&(this.#p.commitOrRemove(),this.#p.setActiveEditor(null)),this.#i&&=(clearTimeout(this.#i),null);for(let e of this.#a.values())this.#e?.removePointerInTextLayer(e.contentDiv),e.setParent(null),e.isAttachedToDOM=!1,e.div.remove();this.div=null,this.#a.clear(),this.#p.removeLayer(this)}#y(){for(let e of this.#a.values())e.isEmpty()&&e.remove()}render({viewport:e}){this.viewport=e,Wl(this.div,e);for(let e of this.#p.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:e}){this.#p.commitOrRemove(),this.#y();let t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,Wl(this.div,{rotation:n}),t!==n)for(let e of this.#a.values())e.rotate(n)}get pageDimensions(){let{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return this.#p.viewParameters.realScale}},bp=class e{#e=null;#t=0;#n=new Map;#r=new Map;constructor({pageIndex:e}){this.pageIndex=e}setParent(e){if(!this.#e){this.#e=e;return}if(this.#e!==e){if(this.#n.size>0)for(let t of this.#n.values())t.remove(),e.append(t);this.#e=e}}static get _svgFactory(){return Y(this,`_svgFactory`,new Sf)}static#i(e,[t,n,r,i]){let{style:a}=e;a.top=`${100*n}%`,a.left=`${100*t}%`,a.width=`${100*r}%`,a.height=`${100*i}%`}#a(){let t=e._svgFactory.create(1,1,!0);return this.#e.append(t),t.setAttribute(`aria-hidden`,!0),t}#o(t,n){let r=e._svgFactory.createElement(`clipPath`);t.append(r);let i=`clip_${n}`;r.setAttribute(`id`,i),r.setAttribute(`clipPathUnits`,`objectBoundingBox`);let a=e._svgFactory.createElement(`use`);return r.append(a),a.setAttribute(`href`,`#${n}`),a.classList.add(`clip`),i}#s(e,t){for(let[n,r]of Object.entries(t))r===null?e.removeAttribute(n):e.setAttribute(n,r)}draw(t,n=!1,r=!1){let i=this.#t++,a=this.#a(),o=e._svgFactory.createElement(`defs`);a.append(o);let s=e._svgFactory.createElement(`path`);o.append(s);let c=`path_p${this.pageIndex}_${i}`;s.setAttribute(`id`,c),s.setAttribute(`vector-effect`,`non-scaling-stroke`),n&&this.#r.set(i,s);let l=r?this.#o(o,c):null,u=e._svgFactory.createElement(`use`);return a.append(u),u.setAttribute(`href`,`#${c}`),this.updateProperties(a,t),this.#n.set(i,a),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,n){let r=this.#t++,i=this.#a(),a=e._svgFactory.createElement(`defs`);i.append(a);let o=e._svgFactory.createElement(`path`);a.append(o);let s=`path_p${this.pageIndex}_${r}`;o.setAttribute(`id`,s),o.setAttribute(`vector-effect`,`non-scaling-stroke`);let c;if(n){let t=e._svgFactory.createElement(`mask`);a.append(t),c=`mask_p${this.pageIndex}_${r}`,t.setAttribute(`id`,c),t.setAttribute(`maskUnits`,`objectBoundingBox`);let n=e._svgFactory.createElement(`rect`);t.append(n),n.setAttribute(`width`,`1`),n.setAttribute(`height`,`1`),n.setAttribute(`fill`,`white`);let i=e._svgFactory.createElement(`use`);t.append(i),i.setAttribute(`href`,`#${s}`),i.setAttribute(`stroke`,`none`),i.setAttribute(`fill`,`black`),i.setAttribute(`fill-rule`,`nonzero`),i.classList.add(`mask`)}let l=e._svgFactory.createElement(`use`);i.append(l),l.setAttribute(`href`,`#${s}`),c&&l.setAttribute(`mask`,`url(#${c})`);let u=l.cloneNode();return i.append(u),l.classList.add(`mainOutline`),u.classList.add(`secondaryOutline`),this.updateProperties(i,t),this.#n.set(r,i),r}finalizeDraw(e,t){this.#r.delete(e),this.updateProperties(e,t)}updateProperties(t,n){if(!n)return;let{root:r,bbox:i,rootClass:a,path:o}=n,s=typeof t==`number`?this.#n.get(t):t;if(s){if(r&&this.#s(s,r),i&&e.#i(s,i),a){let{classList:e}=s;for(let[t,n]of Object.entries(a))e.toggle(t,n)}if(o){let e=s.firstChild.firstChild;this.#s(e,o)}}}updateParent(e,t){if(t===this)return;let n=this.#n.get(e);n&&(t.#e.append(n),this.#n.delete(e),t.#n.set(e,n))}remove(e){this.#r.delete(e),this.#e!==null&&(this.#n.get(e).remove(),this.#n.delete(e))}destroy(){this.#e=null;for(let e of this.#n.values())e.remove();this.#n.clear(),this.#r.clear()}};globalThis.pdfjsTestingUtils={HighlightOutliner:op},U.AbortException,U.AnnotationEditorLayer,U.AnnotationEditorParamsType,U.AnnotationEditorType,U.AnnotationEditorUIManager,U.AnnotationLayer,U.AnnotationMode,U.ColorPicker,U.DOMSVGFactory,U.DrawLayer,U.FeatureTest;var xp=U.GlobalWorkerOptions;U.ImageKind,U.InvalidPDFException,U.MissingPDFException,U.OPS,U.OutputScale,U.PDFDataRangeTransport,U.PDFDateString,U.PDFWorker,U.PasswordResponses,U.PermissionFlag,U.PixelsPerInch,U.RenderingCancelledException,U.TextLayer,U.TouchManager,U.UnexpectedResponseException,U.Util,U.VerbosityLevel,U.XfaLayer,U.build,U.createValidAbsoluteUrl,U.fetchData;var Sp=U.getDocument;U.getFilenameFromUrl,U.getPdfFilenameFromUrl,U.getXfaPageViewport,U.isDataScheme,U.isPdfFile,U.noContextMenu,U.normalizeUnicode,U.setLayerDimensions,U.shadow,U.stopEvent;var Cp=U.version,wp=null;function Tp(){let e=document.createElement(`div`);e.style.width=`1in`,document.body.append(e);let t=e.offsetWidth;return e.remove(),t}function Ep(){let e=wp??Tp();return wp=e,e/72}function Dp(e,t=500){if(typeof e!=`function`)throw TypeError(`The first argument is not a function.`);let n=null;return function(...r){n&&clearTimeout(n),n=setTimeout(()=>{n=null,e.apply(this,r)},t)}}function Op(e){return e.arrayBuffer?e.arrayBuffer():new Promise((t,n)=>{let r=new FileReader;r.addEventListener(`load`,()=>{let e=r.result;if(!(e instanceof ArrayBuffer)){n(Error(`Failed to read file as ArrayBuffer.`));return}t(e)}),r.addEventListener(`error`,n),r.readAsArrayBuffer(e)})}Ap()||(xp.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Cp}/pdf.worker.min.mjs`);function kp(){if(typeof window>`u`)return!0;try{return window.self===window.top}catch{return!1}}function Ap(){try{return typeof OffscreenCanvas<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen==`function`&&kp()}catch{return!1}}function jp(e,t){let n=Ep()/window.devicePixelRatio,r={...e,id:t,units:n};return Ap()?Mp(r):Np(r)}async function Mp({data:e,password:t,id:n,page:r,units:i,scale:a}){let o=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require("url").pathToFileURL(__dirname+`/assets/pdfjs.worker-QHzJtIzr.js`).href:new URL(`assets/pdfjs.worker-QHzJtIzr.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});try{return o.postMessage({data:e,password:t,id:n,page:r,units:i,scale:a}),await new Promise((e,t)=>{let r=()=>{o.removeEventListener(`message`,i),o.removeEventListener(`error`,a)},i=i=>{if(i.data.status){if(r(),i.data.status===`success`){let{bitmap:t,width:r,height:a,pages:o}=i.data;if(t&&n){let n=document.createElement(`canvas`),i=n.getContext(`2d`);return n.width=r,n.height=a,i?.drawImage(t,0,0),t.close(),e({pages:o,canvas:n})}return e({pages:o,canvas:null})}if(i.data.status===`error`)return t(i.data.error)}},a=e=>{r(),t(Error(`Worker error: ${e.message}`))};o.addEventListener(`message`,i),o.addEventListener(`error`,a,{once:!0})})}finally{o.terminate()}}async function Np({data:e,password:t,id:n,page:r,scale:i,units:a}){let o=await Sp({data:await Op(e),password:t}).promise;try{let e=o.numPages;if(!n)return{canvas:null,pages:e};let t=await o.getPage(r),s=t.getViewport({scale:i}),c=document.createElement(`canvas`),l=c.getContext(`2d`);if(!l)throw Error(`Failed to get 2d context`);let u={canvasContext:l,viewport:s,transform:[a,0,0,a,0,0]};return c.width=Math.floor(s.width*a),c.height=Math.floor(s.height*a),await t.render(u).promise,{canvas:c,pages:e}}finally{o.destroy()}}var Pp=new Map;function Fp(e){let t=new jo(e);return Pp.set(e,t),t}function Ip(e){let t=Date.now();return{PDFId:`${e.name}-${t}`,name:e.name.replace(/.pdf/,``),updateDate:t,data:e}}async function Lp({src:e},t,n){if(!e||!n)return null;let{objects:r,options:i}=await Ys(e),a=r.filter(e=>e!==null),o=oo.groupSVGElements(a,i);for(let e of a)e.stroke=n;return o.hoverCursor=`pointer`,o.stroke=`${n}-${t}`,o}function Rp(e,t){Pp.get(e)&&Vp(e,qp(t,1/3))}async function zp(e,t){let n=Date.now(),r={PDFId:`${e.name}-${n}`,name:e.name.replace(/.png|.jpg|.jpeg/,``),updateDate:n,data:e};return t&&Bp(t,{data:e}),{...r,pages:1}}async function Bp(e,{data:t,scale:n=.5}){if(!Pp.get(e))return;let r=URL.createObjectURL(t),i=await Fs.fromURL(r);i.scale(n),Vp(e,i),URL.revokeObjectURL(r)}function Vp(e,t){let n=Pp.get(e);n&&(n.setDimensions({width:t.getScaledWidth(),height:t.getScaledHeight()}),t.set({originX:`left`,originY:`top`,left:0,top:0}),n.backgroundImage=t,n.renderAll())}function Hp(e,t){if(!t)return;let{oCoords:n}=e;if(!n)return;let{x:r,y:i}=n.tl.touchCorner.tl,{height:a,width:o,scaleY:s,scaleX:c}=t;t.top=i-a*s/2,t.left=r-o*c/2,t.setCoords()}function Up(e,t,n){!n||!e||(n.scale(1/t),Hp(e,n))}function Wp(e,t){if(!e)return;let n=e._cornerSize||6;e.borderScaleFactor=1/t,e.cornerSize=1/t*n,e.touchCornerSize=n*4*(1/t),e.setCoords()}function Gp(e){let t=Pp.get(e);t&&(t.discardActiveObject(),t.renderAll())}function Kp(e){let t=Pp.get(e);t&&(t.clear(),Pp.delete(e))}function qp(e,t){return new Fs(e,{scaleX:t,scaleY:t})}function Jp(e,t){if(!t)return;let{left:n,top:r}=e,i=t.x*e.getScaledWidth(),a=t.y*e.getScaledHeight();e.set({left:n-i,top:r-a,originX:`left`,originY:`top`})}function Yp(e,t,n){let r=e.type;return{"application/pdf":Xp,"image/png":Qp,"image/jpeg":Qp}[r]?.(e,t,n)??Promise.reject(Error(`Unsupported ${r} file type.`))}async function Xp(e,t,n){let r=Ip(e),i=await Zp({page:1,data:e,scale:.8,password:t},n);return{...r,pages:i}}async function Zp(e,t){let{canvas:n,pages:r}=await jp(e,t);return n&&t&&Rp(t,n),r}async function Qp(e,t,n){return await zp(e,n)}function $p(e,t){let n=Pp.get(e);if(!n)return;let r=n.getActiveObject();r&&(r instanceof Ca?r.forEachObject(e=>{e.set(t)}):r.set(t),n.renderAll())}async function em(e,t){let n=Pp.get(e);if(!n)return;let r=n?.getActiveObject();if(!r)return;let i=await r.clone(c);i instanceof Ca?i.forEachObject(e=>{n.add(e),t(n,e)}):(n.add(i),t(n,i)),Jp(i,{x:-.1,y:-.1}),n.setActiveObject(i)}function tm(e){let t=Pp.get(e);if(!t)return;let n=t.getActiveObject();n&&(n instanceof Ca?(n.forEachObject(e=>{t.remove(e)}),t.discardActiveObject()):t.remove(n))}function nm(e){let{id:n=``,selectionOptions:r,pointerDown:o,pointerMove:c,pointerUp:l,selectionCreated:u,selectionCleared:d}=e||{},f=(0,t.useRef)(null),p=(0,t.useRef)(null),m=(0,t.useRef)(1),h=(0,t.useRef)({...s});function g(){if(!n||Pp.has(n))return;let e=Fp(n);return e.on(`selection:created`,t=>{if(u?.(t),t.selected.length<=1)return;let n=e.getActiveObject();n&&(p.current=n,r?.value&&p.current.set(r.value),p.current._cornerSize=p.current.cornerSize,T(m.current))}),e.on(`selection:cleared`,t=>{d?.(t),D(e)}),o&&e.on(`mouse:down`,o),c&&e.on(`mouse:move`,c),l&&e.on(`mouse:up`,l),e}function _(e,t){return Yp(e,t,n)}function v(e){return Zp(e,n)}function y({data:e,scale:t=.5}){return Bp(n,{data:e,scale:t})}async function b(e,t,r){let a=Pp.get(n);if(!a)return;let o=await Fs.fromURL(e,{},{...i,...t});Jp(o,r),a.add(o),S(a,o),a.setActiveObject(o)}function x(e,t,r){let i=Pp.get(n);if(!i)return;let o=new ls(e,{...a,...t});Jp(o,r),i.add(o),S(i,o),i.setActiveObject(o)}function S(e,t){t.on(`selected`,t=>C({canvas:e,target:t.target})),t.on(`modified`,t=>C({canvas:e,target:t.target})),t.on(`scaling`,()=>D(e)),t.on(`moving`,()=>D(e)),t.on(`rotating`,()=>D(e)),t._cornerSize=t._cornerSize??t.cornerSize}async function C({canvas:e,target:t,stroke:n=h.current.stroke,uuid:r=Date.now()}){if(e.getActiveObjects().length>1||f.current?.stroke===`${n}-${r}`)return;let i=await Lp(h.current,r,n);D(e),f.current=i,p.current=t,w(e,t,r),T(m.current,!0),i&&e.add(i)}function w(e,t,n){f.current&&(f.current.on(`selected`,()=>{e.remove(t),D(e)}),f.current.on(`mouseover`,()=>{C({canvas:e,target:t,stroke:h.current.hoverStroke,uuid:n})}),f.current.on(`mouseout`,()=>{C({canvas:e,target:t,stroke:h.current.stroke,uuid:n})}))}function T(e,t=!1){let r=Pp.get(n);m.current=e,r&&(Wp(p.current,e),Up(p.current,e,f.current),!t&&r.renderAll())}function E(e){if(!e)return;h.current={...h.current,...e};let t=Pp.get(n);!f||!p.current||!t||C({target:p.current,canvas:t})}function D(e){p.current=null,f.current&&=(e.remove(f.current),null)}function O(){Gp(n)}function k(){Kp(n)}function A(e){$p(n,e)}function j(){return em(n,S)}function M(){tm(n)}return{createCanvas:g,loadFile:_,specifyPage:v,renderImage:y,addFabric:b,addTextFabric:x,clearActive:O,deleteCanvas:k,scaleFabric:T,setCloseSvgOptions:E,setActiveFabric:A,copyActiveFabric:j,deleteActiveFabric:M}}function rm(e){let n=(0,t.useRef)(0);return(0,t.useEffect)(()=>{let t=Dp(()=>{let{innerWidth:t}=globalThis;t!==n.current&&(n.current=t,e())});return n.current=window.innerWidth,window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[]),null}var im=(0,t.forwardRef)(am);function am({file:e,page:r=1,canvasId:i=`PDF-canvas`,fileZoom:a=1,fileScale:s=1,canvasScale:c=1,canvasClass:l=``,isDrop:u=!1,password:d,dropTextOptions:f,dropImageOptions:p,closeSvgOptions:m,selectionOptions:h,manualReload:g,onLoaded:_,onReload:v,onPointerDown:y,onPointerMove:b,onPointerUp:x,onSelectionCreated:S,onSelectionCleared:C},w){let T=(0,t.useRef)(null),E=`${i}-${r-1}`,D=(0,t.useMemo)(()=>a*c,[a,c]),{createCanvas:O,specifyPage:k,addFabric:A,addTextFabric:j,renderImage:M,clearActive:ee,deleteCanvas:N,scaleFabric:P,setActiveFabric:F,setCloseSvgOptions:I,copyActiveFabric:te,deleteActiveFabric:ne}=nm({id:E,selectionOptions:(0,t.useMemo)(()=>({...o,...h}),[h]),pointerDown:y,pointerMove:b,pointerUp:x,selectionCreated:S,selectionCleared:C});rm(se);async function re(){requestAnimationFrame(async()=>{if(O(),e.data?.type.startsWith(`image/`)){let t=e.data;t&&M({data:t,scale:s/3}),_?.();return}let t=e.data;t&&await k({page:r,data:t,scale:s,password:d}),_?.()})}function ie(e){if(e.preventDefault(),e.stopPropagation(),!u||!e.dataTransfer)return;let{dataTransfer:t,nativeEvent:n}=e,{offsetX:r,offsetY:i}=n,a=t.getData(`text/plain`),o=t.getData(`text/uri-list`),s=t.getData(`custom/offset`),c=s?JSON.parse(s):null,l={top:i,left:r},d={x:c?.offsetX??0,y:c?.offsetY??0};o?ae(o,l,d):a&&oe(a,l,d)}function ae(e,t,n){A(e,{...p,...t},n)}function oe(e,t,n){j(e,{...f,...t},n)}function se(){g||re(),v?.()}return(0,t.useImperativeHandle)(w,()=>({reload:re,addImage:ae,addText:oe,clearActive:ee,deleteCanvas:N,setActiveFabric:F,copyActiveFabric:te,deleteActiveFabric:ne,canvasRef:T})),(0,t.useEffect)(()=>{se()},[s,r,e,d]),(0,t.useEffect)(()=>{P(D)},[D]),(0,t.useEffect)(()=>{I(m)},[m]),(0,t.useEffect)(()=>()=>N(),[]),(0,n.jsx)(`div`,{style:{transform:`scale(${D})`},onDragOver:e=>e.preventDefault(),onDragEnter:e=>e.preventDefault(),onDrop:ie,children:(0,n.jsx)(`canvas`,{id:E,ref:T,className:l})})}e.default=im,e.loadFile=Yp,e.useFabric=nm});