@component-hook/pdf-canvas 1.3.0-alpha.3 → 1.3.0-alpha.5
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.
- package/dist/react/assets/pdfjs.worker-DawqtvLM.js +12 -0
- package/dist/react/pdf-canvas.es.d.ts +1 -1
- package/dist/react/pdf-canvas.es.js +6618 -8293
- package/dist/react/pdf-canvas.umd.js +68 -68
- package/dist/vue/assets/pdfjs.worker-DawqtvLM.js +12 -0
- package/dist/vue/pdf-canvas.es.d.ts +1 -1
- package/dist/vue/pdf-canvas.es.js +6202 -7878
- package/dist/vue/pdf-canvas.umd.js +64 -64
- package/package.json +2 -2
- package/dist/react/assets/pdfjs.worker-CJ2MeDJc.js +0 -12
- package/dist/vue/assets/pdfjs.worker-CJ2MeDJc.js +0 -12
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
void main(){}`),i=t.createShader(t.FRAGMENT_SHADER);return!!i&&(t.shaderSource(i,s),t.compileShader(i),!!t.getShaderParameter(i,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find((s=>this.testPrecision(e,s))),e.getExtension("WEBGL_lose_context").loseContext(),Ie("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Ac={};let Qo;const xe=()=>Qo||(Qo={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Cc,dispose(){},copyPasteData:Ac}),Ms=()=>xe().document,ei=()=>xe().window,ta=()=>{var a;return Math.max((a=q.devicePixelRatio)!==null&&a!==void 0?a:ei().devicePixelRatio,1)},si=new class{constructor(){C(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="".concat(e.toLowerCase(),"_").concat((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}=q,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},ur="6.9.0";function ns(){}const qe=Math.PI/2,Be=2*Math.PI,fr=Math.PI/180,Rt=Object.freeze([1,0,0,1,0,0]),gr=16,Ke=.4477152502,U="center",J="left",Yt="top",pr="bottom",ft="right",Ft="none",mr=/\r?\n/,ea="moving",Ni="scaling",sa="rotating",yr="rotate",ia="skewing",ii="resizing",Tc="modifyPoly",Ec="modifyPath",ji="changed",Hi="scale",It="scaleX",Zt="scaleY",Ds="skewX",Ps="skewY",yt="fill",Bt="stroke",zi="modified",Os="json",br="svg",I=new class{constructor(){this[Os]=new Map,this[br]=new Map}has(a){return this[Os].has(a)}getClass(a){const t=this[Os].get(a);if(!t)throw new we("No class registered for ".concat(a));return t}setClass(a,t){t?this[Os].set(t,a):(this[Os].set(a.type,a),this[Os].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[br].get(a)}setSVGClass(a,t){this[br].set(t??a.type.toLowerCase(),a)}},Gi=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 kc{constructor(){C(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach((s=>{let[i,n]=s;this.on(i,n)})),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach((i=>{let[n,r]=i;s.push(this.once(n,r))})),()=>s.forEach((i=>i()))}if(e){const s=this.on(t,(function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()}));return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach((s=>{let[i,n]=s;this._removeEventListener(i,n)})):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const rs=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},de=a=>{if(a===0)return 1;switch(Math.abs(a)/qe){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ue=a=>{if(a===0)return 0;const t=a/qe,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class E{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 E(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new E(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new E(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new E(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,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(t){return this.x*=t,this.y*=t,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(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 E(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 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"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new E(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:vr;const s=ue(t),i=de(t),n=this.subtract(e);return new E(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 E(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 vr=new E(0,0),Vi=a=>!!a&&Array.isArray(a._objects);function na(a){class t extends a{constructor(){super(...arguments),C(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach((o=>this._onObjectAdded(o))),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach((o=>this._onObjectAdded(o))),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return r.forEach((h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),i.push(h),this._onObjectRemoved(h))})),i}forEachObject(s){this.getObjects().forEach(((i,n,r)=>s(i,n,r)))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter((r=>r.isType(...i)))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some((n=>n instanceof t&&n.contains(s,!0)))}complexity(){return this._objects.reduce(((s,i)=>s+=i.complexity?i.complexity():0),0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(rs(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(rs(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 rs(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 rs(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(rs(this._objects,s),this._objects.splice(i,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,i,n){let r;if(n){r=i;for(let o=i-1;o>=0;--o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let o=i+1;o<this._objects.length;++o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:o}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const l=[],c=new E(i,n),d=c.add(new E(r,o));for(let u=this._objects.length-1;u>=0;u--){const f=this._objects[u];f.selectable&&f.visible&&(h&&f.intersectsWithRect(c,d)||f.isContainedWithinRect(c,d)||h&&f.containsPoint(c)||h&&f.containsPoint(d))&&l.push(f)}return l}}return t}class ra extends kc{_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 ni(a){return ei().requestAnimationFrame(a)}function oa(a){return ei().cancelAnimationFrame(a)}let Mc=0;const Je=()=>Mc++,Se=()=>{const a=Ms().createElement("canvas");if(!a||a.getContext===void 0)throw new we("Failed to create `canvas` element");return a},aa=()=>Ms().createElement("img"),Qt=a=>{const t=Se();return t.width=a.width,t.height=a.height,t},_r=(a,t,e)=>a.toDataURL("image/".concat(t),e),wr=(a,t,e)=>new Promise(((s,i)=>{a.toBlob(s,"image/".concat(t),e)})),lt=a=>a*fr,Ce=a=>a/fr,ha=a=>a.every(((t,e)=>t===Rt[e])),Mt=(a,t,e)=>new E(a).transform(t,e),$t=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 E(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},gt=(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]],Wi=(a,t)=>a.reduceRight(((e,s)=>s&&e?gt(s,e,t):s||e),void 0)||Rt.concat(),la=a=>{let[t,e]=a;return Math.atan2(e,t)},os=a=>{const t=la(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:Ce(t),scaleX:s,scaleY:i,skewX:Ce(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},Ls=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function as(){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=lt(a),i=de(s),n=ue(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const Ui=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},ca=a=>Math.tan(lt(a)),xr=a=>[1,0,ca(a),1,0,0],Sr=a=>[1,ca(a),0,1,0,0],ri=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=Ui(s?-t:t,i?-e:e);return n&&(o=gt(o,xr(n),!0)),r&&(o=gt(o,Sr(r),!0)),o},da=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=Ls(t,e);s&&(i=gt(i,as({angle:s})));const n=ri(a);return ha(n)||(i=gt(i,n)),i},oi=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 dr("loadImage"));const n=aa();let r;t&&(r=function(h){n.src="",i(h)},t.addEventListener("abort",r,{once:!0}));const o=function(){n.onload=n.onerror=null,r&&t?.removeEventListener("abort",r),s(n)};a?(n.onload=o,n.onerror=function(){r&&t?.removeEventListener("abort",r),i(new we("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()}))},Rs=function(a){let{signal:t,reviver:e=ns}=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)}))}))},ai=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)?Rs([o],{signal:t}).then((h=>{let[l]=h;return i.push(l),l})):o)),r=Object.keys(a);Promise.all(n).then((o=>o.reduce(((h,l,c)=>(h[r[c]]=l,h)),{}))).then(e).catch((o=>{i.forEach((h=>{h.dispose&&h.dispose()})),s(o)})).finally((()=>{t&&t.removeEventListener("abort",s)}))}))},hs=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce(((t,e)=>(e in a&&(t[e]=a[e]),t)),{})},Cr=(a,t)=>Object.keys(a).reduce(((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e)),{}),st=(a,t)=>parseFloat(Number(a).toFixed(t)),Fs=a=>"matrix("+a.map((t=>st(t,q.NUM_FRACTION_DIGITS))).join(" ")+")",re=a=>!!a&&a.toLive!==void 0,ua=a=>!!a&&typeof a.toObject=="function",fa=a=>!!a&&a.offsetX!==void 0&&"source"in a,ls=a=>!!a&&"multiSelectionStacking"in a;function ga(a){const t=a&&fe(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 fe=a=>a.ownerDocument||null,pa=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},ma=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))},Ar=(a,t)=>{let{width:e,height:s}=t;e&&(a.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(a.style.height=typeof s=="number"?"".concat(s,"px"):s)};function ya(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=Ft,a}class ba{constructor(t){C(this,"_originalCanvasStyle",void 0),C(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&Ms().getElementById(t)||Se();var s;if(e.hasAttribute("data-fabric"))throw new we("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width","".concat(e)),i.setAttribute("height","".concat(s)),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;ma(s,i,t,e)}setCSSDimensions(t){Ar(this.lower.el,t)}calcOffset(){return(function(t){var e;const s=t&&fe(t),i={left:0,top:0};if(!s)return i;const n=((e=pa(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};i.left+=parseInt(n.borderLeftWidth,10)||0,i.top+=parseInt(n.borderTopWidth,10)||0,i.left+=parseInt(n.paddingLeft,10)||0,i.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const o=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const h=ga(t);return{left:r.left+h.left-(o.clientLeft||0)+i.left,top:r.top+h.top-(o.clientTop||0)+i.top}})(this.lower.el)}dispose(){xe().dispose(this.lower.el),delete this.lower}}const Dc={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...Rt]},Pc=["objects"];class hi extends na(ra){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 hi.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 ba(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&&(Ie("warn",`Canvas is trying to add an object that belongs to a different canvas.
|
|
3
|
-
Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?
|
|
1
|
+
(function(J,W){typeof exports=="object"&&typeof module<"u"?W(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],W):(J=typeof globalThis<"u"?globalThis:J||self,W(J["pdf-canvas"]={},J.Vue))})(this,(function(J,W){"use strict";var Hl=J=>{throw TypeError(J)};var ko=(J,W,dt)=>W.has(J)||Hl("Cannot "+dt);var pe=(J,W,dt)=>(ko(J,W,"read from private field"),dt?dt.call(J):W.get(J)),Xs=(J,W,dt)=>W.has(J)?Hl("Cannot add the same private member more than once"):W instanceof WeakSet?W.add(J):W.set(J,dt),Si=(J,W,dt,ys)=>(ko(J,W,"write to private field"),ys?ys.call(J,dt):W.set(J,dt),dt),Xn=(J,W,dt)=>(ko(J,W,"access private method"),dt);var zl=(J,W,dt,ys)=>({set _($n){Si(J,W,$n,dt)},get _(){return pe(J,W,ys)}});var Vn,bs,vs,zs,Un,Gs,Yn;var dt=typeof document<"u"?document.currentScript:null;const ys="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",$n={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Gl={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Vl={borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Xl={stroke:"#000",hoverStroke:"#B7EC5D",src:ys},Wl=["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 h=o.call(n,r);if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)})(s,"string");return typeof i=="symbol"?i:i+""})(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function Mo(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);t&&(s=s.filter((function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable}))),e.push.apply(e,s)}return e}function w(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Mo(Object(e),!0).forEach((function(s){x(a,s,e[s])})):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):Mo(Object(e)).forEach((function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(e,s))}))}return a}function it(a,t){if(a==null)return{};var e,s,i=(function(r,o){if(r==null)return{};var h={};for(var l in r)if({}.hasOwnProperty.call(r,l)){if(o.indexOf(l)>=0)continue;h[l]=r[l]}return h})(a,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(a);for(s=0;s<n.length;s++)e=n[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(a,e)&&(i[e]=a[e])}return i}function me(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class Po{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 K=new class extends Po{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=w(w({},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 Po,e=a?.reduce(((s,i)=>(s[i]=t[i],s)),{})||t;this.configure(e)}},Me=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 be extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class qn extends be{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class Ul{}class Yl extends Ul{testPrecision(t,e){const s="precision ".concat(e,` float;
|
|
2
|
+
void main(){}`),i=t.createShader(t.FRAGMENT_SHADER);return!!i&&(t.shaderSource(i,s),t.compileShader(i),!!t.getShaderParameter(i,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find((s=>this.testPrecision(e,s))),e.getExtension("WEBGL_lose_context").loseContext(),Me("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const $l={};let Oo;const ve=()=>Oo||(Oo={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Yl,dispose(){},copyPasteData:$l}),_s=()=>ve().document,Ws=()=>ve().window,Do=()=>{var a;return Math.max((a=K.devicePixelRatio)!==null&&a!==void 0?a:Ws().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="".concat(e.toLowerCase(),"_").concat((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}=K,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},Kn="6.9.0";function Ze(){}const ze=Math.PI/2,Pe=2*Math.PI,Jn=Math.PI/180,Rt=Object.freeze([1,0,0,1,0,0]),Zn=16,Ge=.4477152502,X="center",Z="left",Xt="top",Qn="bottom",ft="right",Lt="none",tr=/\r?\n/,Ro="moving",Ci="scaling",Lo="rotating",er="rotate",Fo="skewing",Ys="resizing",ql="modifyPoly",Kl="modifyPath",Ai="changed",Ti="scale",Ft="scaleX",qt="scaleY",ws="skewX",xs="skewY",bt="fill",It="stroke",Ei="modified",Ss="json",sr="svg",F=new class{constructor(){this[Ss]=new Map,this[sr]=new Map}has(a){return this[Ss].has(a)}getClass(a){const t=this[Ss].get(a);if(!t)throw new be("No class registered for ".concat(a));return t}setClass(a,t){t?this[Ss].set(t,a):(this[Ss].set(a.type,a),this[Ss].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[sr].get(a)}setSVGClass(a,t){this[sr].set(t??a.type.toLowerCase(),a)}},ki=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 Jl{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 Qe=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},re=a=>{if(a===0)return 1;switch(Math.abs(a)/ze){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},oe=a=>{if(a===0)return 0;const t=a/ze,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class C{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 C(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new C(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new C(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new C(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new C(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new C(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new C(this.x/t.x,this.y/t.y)}scalarDivide(t){return new C(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 C(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 C(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new C(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new C(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ir;const s=oe(t),i=re(t),n=this.subtract(e);return new C(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 C(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 C(0,0),Mi=a=>!!a&&Array.isArray(a._objects);function Io(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((h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),i.push(h),this._onObjectRemoved(h))})),i}forEachObject(s){this.getObjects().forEach(((i,n,r)=>s(i,n,r)))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter((r=>r.isType(...i)))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some((n=>n instanceof t&&n.contains(s,!0)))}complexity(){return this._objects.reduce(((s,i)=>s+=i.complexity?i.complexity():0),0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(Qe(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Qe(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 Qe(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 Qe(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Qe(this._objects,s),this._objects.splice(i,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,i,n){let r;if(n){r=i;for(let o=i-1;o>=0;--o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let o=i+1;o<this._objects.length;++o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:o}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const l=[],c=new C(i,n),u=c.add(new C(r,o));for(let d=this._objects.length-1;d>=0;d--){const f=this._objects[d];f.selectable&&f.visible&&(h&&f.intersectsWithRect(c,u)||f.isContainedWithinRect(c,u)||h&&f.containsPoint(c)||h&&f.containsPoint(u))&&l.push(f)}return l}}return t}class No extends Jl{_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 $s(a){return Ws().requestAnimationFrame(a)}function jo(a){return Ws().cancelAnimationFrame(a)}let Zl=0;const Ve=()=>Zl++,ye=()=>{const a=_s().createElement("canvas");if(!a||a.getContext===void 0)throw new be("Failed to create `canvas` element");return a},Bo=()=>_s().createElement("img"),Kt=a=>{const t=ye();return t.width=a.width,t.height=a.height,t},nr=(a,t,e)=>a.toDataURL("image/".concat(t),e),rr=(a,t,e)=>new Promise(((s,i)=>{a.toBlob(s,"image/".concat(t),e)})),lt=a=>a*Jn,_e=a=>a/Jn,Ho=a=>a.every(((t,e)=>t===Rt[e])),Tt=(a,t,e)=>new C(a).transform(t,e),Wt=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 C(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},gt=(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]],Pi=(a,t)=>a.reduceRight(((e,s)=>s&&e?gt(s,e,t):s||e),void 0)||Rt.concat(),zo=a=>{let[t,e]=a;return Math.atan2(e,t)},ts=a=>{const t=zo(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:_e(t),scaleX:s,scaleY:i,skewX:_e(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},Cs=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function es(){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=lt(a),i=re(s),n=oe(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const Oi=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},Go=a=>Math.tan(lt(a)),or=a=>[1,0,Go(a),1,0,0],ar=a=>[1,Go(a),0,1,0,0],qs=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=Oi(s?-t:t,i?-e:e);return n&&(o=gt(o,or(n),!0)),r&&(o=gt(o,ar(r),!0)),o},Vo=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=Cs(t,e);s&&(i=gt(i,es({angle:s})));const n=qs(a);return Ho(n)||(i=gt(i,n)),i},Ks=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 qn("loadImage"));const n=Bo();let r;t&&(r=function(h){n.src="",i(h)},t.addEventListener("abort",r,{once:!0}));const o=function(){n.onload=n.onerror=null,r&&t?.removeEventListener("abort",r),s(n)};a?(n.onload=o,n.onerror=function(){r&&t?.removeEventListener("abort",r),i(new be("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()}))},As=function(a){let{signal:t,reviver:e=Ze}=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=>F.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&&F.has(o.type)?As([o],{signal:t}).then((h=>{let[l]=h;return i.push(l),l})):o)),r=Object.keys(a);Promise.all(n).then((o=>o.reduce(((h,l,c)=>(h[r[c]]=l,h)),{}))).then(e).catch((o=>{i.forEach((h=>{h.dispose&&h.dispose()})),s(o)})).finally((()=>{t&&t.removeEventListener("abort",s)}))}))},ss=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce(((t,e)=>(e in a&&(t[e]=a[e]),t)),{})},hr=(a,t)=>Object.keys(a).reduce(((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e)),{}),et=(a,t)=>parseFloat(Number(a).toFixed(t)),Ts=a=>"matrix("+a.map((t=>et(t,K.NUM_FRACTION_DIGITS))).join(" ")+")",ee=a=>!!a&&a.toLive!==void 0,Xo=a=>!!a&&typeof a.toObject=="function",Wo=a=>!!a&&a.offsetX!==void 0&&"source"in a,is=a=>!!a&&"multiSelectionStacking"in a;function Uo(a){const t=a&&ae(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 ae=a=>a.ownerDocument||null,Yo=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},$o=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))},lr=(a,t)=>{let{width:e,height:s}=t;e&&(a.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(a.style.height=typeof s=="number"?"".concat(s,"px"):s)};function qo(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=Lt,a}class Ko{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&&_s().getElementById(t)||ye();var s;if(e.hasAttribute("data-fabric"))throw new be("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width","".concat(e)),i.setAttribute("height","".concat(s)),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;$o(s,i,t,e)}setCSSDimensions(t){lr(this.lower.el,t)}calcOffset(){return(function(t){var e;const s=t&&ae(t),i={left:0,top:0};if(!s)return i;const n=((e=Yo(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};i.left+=parseInt(n.borderLeftWidth,10)||0,i.top+=parseInt(n.borderTopWidth,10)||0,i.left+=parseInt(n.paddingLeft,10)||0,i.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const o=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const h=Uo(t);return{left:r.left+h.left-(o.clientLeft||0)+i.left,top:r.top+h.top-(o.clientTop||0)+i.top}})(this.lower.el)}dispose(){ve().dispose(this.lower.el),delete this.lower}}const Ql={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...Rt]},tc=["objects"];class Zs extends Io(No){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 Zs.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new Ko(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(Me("warn",`Canvas is trying to add an object that belongs to a different canvas.
|
|
3
|
+
Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?Do():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const i=w({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=Tt(t,Wt(i));i[0]=e,i[3]=e;const r=Tt(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new C(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 C(-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=$s((()=>this.renderAndReset())))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Wt(this.viewportTransform),i=Tt({x:0,y:0},s),n=Tt({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new C(o.x,r.y),bl:new C(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(jo(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const s=this.viewportTransform,i=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),i&&(i._set("canvas",this),i.shouldCache(),i._transformDone=!0,i.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,i)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const s=this.viewportTransform;t.save(),t.transform(...s),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let s=0,i=e.length;s<i;++s)e[s]&&e[s].render(t)}_renderBackgroundOrOverlay(t,e){const s=this["".concat(e,"Color")],i=this["".concat(e,"Image")],n=this.viewportTransform,r=this["".concat(e,"Vpt")];if(!s&&!i)return;const o=ee(s);if(s){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=o?s.toLive(t):s,r&&t.transform(...n),o){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const h=s.gradientTransform||s.patternTransform;h&&t.transform(...h)}t.fill(),t.restore()}if(i){t.save();const{skipOffscreen:h}=this;this.skipOffscreen=r,r&&t.transform(...n),i.render(t),this.skipOffscreen=h,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenter(){return{top:this.height/2,left:this.width/2}}getCenterPoint(){return new C(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new C(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new C(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 C(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new C(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Tt(this.getCenterPoint(),Wt(this.viewportTransform))}_centerObject(t,e){t.setXY(e,X,X),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 w(w(w({version:Kn},ss(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 ee(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),ee(o)?o.excludeFromExport||(s.overlay=o.toObject(e)):o&&(s.overlay=o),i&&!i.excludeFromExport&&(s.backgroundImage=this._toObject(i,t,e)),n&&!n.excludeFromExport&&(s.overlayImage=this._toObject(n,t,e)),s}toSVG(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const s=[];return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push('<g clip-path="url(#'.concat(this.clipPath.clipPathId,`)" >
|
|
4
4
|
`)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
|
|
5
5
|
`),this._setSVGBgOverlayColor(s,"overlay"),this._setSVGBgOverlayImage(s,"overlayImage",e),s.push("</svg>"),s.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",`" standalone="no" ?>
|
|
6
6
|
`,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
|
7
|
-
`)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=
|
|
8
|
-
`,"<desc>Created with Fabric.js ",
|
|
7
|
+
`)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=K.NUM_FRACTION_DIGITS,r=e.viewBox;let o;if(r)o='viewBox="'.concat(r.x," ").concat(r.y," ").concat(r.width," ").concat(r.height,'" ');else if(this.svgViewportTransformation){const h=this.viewportTransform;o='viewBox="'.concat(et(-h[4]/h[0],n)," ").concat(et(-h[5]/h[3],n)," ").concat(et(this.width/h[0],n)," ").concat(et(this.height/h[3],n),'" ')}else o='viewBox="0 0 '.concat(this.width," ").concat(this.height,'" ');t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',i,'" ',o,`xml:space="preserve">
|
|
8
|
+
`,"<desc>Created with Fabric.js ",Kn,`</desc>
|
|
9
9
|
`,`<defs>
|
|
10
10
|
`,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
|
|
11
|
-
`)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(
|
|
11
|
+
`)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(Ve()),'<clipPath id="'.concat(e.clipPathId,`" >
|
|
12
12
|
`).concat(e.toClipPathSVG(t.reviver),`</clipPath>
|
|
13
|
-
`)):""}createSVGRefElementsMarkup(){return["background","overlay"].map((t=>{const e=this["".concat(t,"Color")];if(
|
|
13
|
+
`)):""}createSVGRefElementsMarkup(){return["background","overlay"].map((t=>{const e=this["".concat(t,"Color")];if(ee(e)){const s=this["".concat(t,"Vpt")],i=this.viewportTransform,n={isType:()=>!1,width:this.width/(s?i[0]:1),height:this.height/(s?i[3]:1)};return e.toSVG(n,{additionalTransform:s?Ts(i):""})}})).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=K.fontPaths;this._objects.forEach((function n(r){t.push(r),Mi(r)&&r._objects.forEach(n)})),t.forEach((n=>{if(!(r=n)||typeof r._renderText!="function")return;var r;const{styles:o,fontFamily:h}=n;!e[h]&&s[h]&&(e[h]=!0,o&&Object.values(o).forEach((l=>{Object.values(l).forEach((c=>{let{fontFamily:u=""}=c;!e[u]&&s[u]&&(e[u]=!0)}))})))}));const i=Object.keys(e).map((n=>` @font-face {
|
|
14
14
|
font-family: '`.concat(n,`';
|
|
15
15
|
src: url('`).concat(s[n],`');
|
|
16
16
|
}
|
|
17
17
|
`))).join("");return i?` <style type="text/css"><![CDATA[
|
|
18
18
|
`.concat(i,`]]></style>
|
|
19
|
-
`):""}_setSVGObjects(t,e){this.forEachObject((s=>{s.excludeFromExport||this._setSVGObject(t,s,e)}))}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const i=this[e];i&&!i.excludeFromExport&&i.toSVG&&t.push(i.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(
|
|
19
|
+
`):""}_setSVGObjects(t,e){this.forEachObject((s=>{s.excludeFromExport||this._setSVGObject(t,s,e)}))}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const i=this[e];i&&!i.excludeFromExport&&i.toSVG&&t.push(i.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(ee(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?Ts(Wt(this.viewportTransform)):"";t.push('<rect transform="'.concat(o," translate(").concat(n/2,",").concat(r/2,')" x="').concat(s.offsetX-n/2,'" y="').concat(s.offsetY-r/2,'" width="').concat(i!=="repeat-y"&&i!=="no-repeat"||!Wo(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!Wo(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
|
|
20
20
|
`))}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',s,'"',`></rect>
|
|
21
|
-
`)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new we("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[]}=i,r=nt(i,Pc),{backgroundImage:o,background:h,overlayImage:l,overlay:c,clipPath:d}=r,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Rs(n,{reviver:e,signal:s}),ai({backgroundImage:o,backgroundColor:h,overlayImage:l,overlayColor:c,clipPath:d},{signal:s})]).then((f=>{let[g,p]=f;return this.clear(),this.add(...g),this.set(r),this.set(p),this.renderOnAddRemove=u,this}))}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=Qt(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 _r(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 wr(this.toCanvasElement(r,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:i,top:n,filter:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const o=(e||this.width)*t,h=(s||this.height)*t,l=this.getZoom(),c=this.width,d=this.height,u=this.skipControlsDrawing,f=l*t,g=this.viewportTransform,p=[f,0,0,f,(g[4]-(i||0))*t,(g[5]-(n||0))*t],y=this.enableRetinaScaling,m=Qt({width:o,height:h}),b=r?this._objects.filter((v=>r(v))):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=o,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),b),this.viewportTransform=g,this.width=c,this.height=d,this.calcViewportBoundaries(),this.enableRetinaScaling=y,this.skipControlsDrawing=u,m}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Gi.cancelByCanvas(this),this.disposed=!0,new Promise(((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()}))}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject((t=>t.dispose())),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}C(hi,"ownDefaults",Dc);const Oc=["touchstart","touchmove","touchend"],va=a=>{const t=ga(a.target),e=(function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s})(a);return new E(e.clientX+t.left,e.clientY+t.top)},Xi=a=>Oc.includes(a.type)||a.pointerType==="touch",_a=a=>{a.preventDefault(),a.stopPropagation()},Ae=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:h}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},Lc=["translateX","translateY","scaleX","scaleY"],wa=(a,t)=>Is(a,gt(t,a.calcOwnMatrix())),Is=(a,t)=>{const e=os(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=nt(e,Lc),h=new E(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,U,U)},xa=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},Tr=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}),Yi=(a,t,e)=>{const s=a/2,i=t/2,n=[new E(-s,-i),new E(s,-i),new E(-s,i),new E(s,i)].map((o=>o.transform(e))),r=Ae(n);return new E(r.width,r.height)},li=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Rt;return gt($t(arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rt),a)},cs=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Rt;return a.transform(li(t,e))},Sa=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Rt;return a.transform(li(t,e),!0)},Er=(a,t,e)=>{const s=li(t,e);return Is(a,gt(s,a.calcOwnMatrix())),s},Ca=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),S(S({},t),{},{target:s})),s.fire(a,t)},Rc={left:-.5,top:-.5,center:0,bottom:.5,right:.5},bt=a=>typeof a=="string"?Rc[a]:a-.5,$i="not-allowed";function Aa(a){return bt(a.originX)===bt(U)&&bt(a.originY)===bt(U)}function Ta(a){return .5-bt(a)}const ge=(a,t)=>a[t],Ea=(a,t,e,s)=>({e:a,transform:t,pointer:new E(e,s)});function ka(a,t){const e=a.getTotalAngle()+Ce(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function kr(a,t,e,s,i){var n;let{target:r,corner:o}=a;const h=r.controls[o],l=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,c=r.padding/l,d=(function(u,f,g,p){const y=u.getRelativeCenterPoint(),m=g!==void 0&&p!==void 0?u.translateToGivenOrigin(y,U,U,g,p):new E(u.left,u.top);return(u.angle?f.rotate(-lt(u.angle),y):f).subtract(m)})(r,new E(s,i),t,e);return d.x>=c&&(d.x-=c),d.x<=-c&&(d.x+=c),d.y>=c&&(d.y-=c),d.y<=c&&(d.y+=c),d.x-=h.offsetX,d.y-=h.offsetY,d}const Fc=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!ge(i,"lockMovementX")&&i.left!==o,c=!ge(i,"lockMovementY")&&i.top!==h;return l&&i.set(J,o),c&&i.set(Yt,h),(l||c)&&Ca(ea,Ea(a,t,e,s)),l||c},qi=a=>a.replace(/\s+/g," "),Ma={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"},Mr=(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),Da=(a,t,e,s)=>{a/=255,t/=255,e/=255;const i=Math.max(a,t,e),n=Math.min(a,t,e);let r,o;const h=(i+n)/2;if(i===n)r=o=0;else{const l=i-n;switch(o=h>.5?l/(2-i-n):l/(i+n),i){case a:r=(t-e)/l+(t<e?6:0);break;case t:r=(e-a)/l+2;break;case e:r=(a-t)/l+4}r/=6}return[Math.round(360*r),Math.round(100*o),Math.round(100*h),s]},Pa=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},Ki=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),Oa=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class Q{constructor(t){if(C(this,"isUnrecognised",!1),t)if(t instanceof Q)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 Ma&&(t=Ma[t]),t==="transparent"?[255,255,255,0]:Q.sourceFromHex(t)||Q.sourceFromRgb(t)||Q.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=Da(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=Da(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(i,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return"".concat(Ki(t)).concat(Ki(e)).concat(Ki(s)).concat(Ki(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(Oa(this.getSource())),this}toBlackWhite(t){const[e,,,s]=Oa(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof Q||(t=new Q(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map(((o,h)=>Math.round(.5*o+.5*s[h])));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return Q.fromRgba(t)}static fromRgba(t){return new Q(Q.sourceFromRgb(t))}static sourceFromRgb(t){const e=qi(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 Q.fromHsla(t)}static fromHsla(t){return new Q(Q.sourceFromHsl(t))}static sourceFromHsl(t){const e=qi(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=(Q.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,o,h;if(i===0)r=o=h=n;else{const l=n<=.5?n*(i+1):n+i-n*i,c=2*n-l;r=Mr(c,l,s+1/3),o=Mr(c,l,s),h=Mr(c,l,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),Pa(e[4])]}static fromHex(t){return new Q(Q.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map((h=>h+h)):e.match(/.{2}/g);const[i,n,r,o=255]=s.map((h=>parseInt(h,16)));return[i,n,r,o/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?Ce(s):e.includes("turn")?360*s:s}}const Nt=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:gr;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=q.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}},Dr=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}},ci=function(a,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const n=new Q(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(a,": ").concat(e,"; ").concat(s?"".concat(a,"-opacity: ").concat(s,"; "):""):"".concat(a,'="').concat(e,'" ').concat(s?"".concat(a,'-opacity="').concat(s,'" '):"")};class La{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",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=this.opacity!==void 0?this.opacity:"1",c=this.visible?"":" visibility: hidden;",d=t?"":this.getSvgFilter(),u=ci(yt,this.fill);return[ci(Bt,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",h,"; ",u,"fill-rule: ",e,"; ","opacity: ",l,";",d,c].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),i='transform="'.concat(Fs(s));return"".concat(i).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=i,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:i,additionalTransform:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=e?"":'style="'.concat(this.getSvgStyles(),'" '),o=i?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,d=this.stroke,u=this.fill,f=this.shadow,g=[],p=t.indexOf("COMMON_PARTS");let y;h&&(h.clipPathId="CLIPPATH_".concat(Je()),y='<clipPath id="'.concat(h.clipPathId,`" >
|
|
21
|
+
`)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new be("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[]}=i,r=it(i,tc),{backgroundImage:o,background:h,overlayImage:l,overlay:c,clipPath:u}=r,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([As(n,{reviver:e,signal:s}),Js({backgroundImage:o,backgroundColor:h,overlayImage:l,overlayColor:c,clipPath:u},{signal:s})]).then((f=>{let[g,p]=f;return this.clear(),this.add(...g),this.set(r),this.set(p),this.renderOnAddRemove=d,this}))}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=Kt(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,h=(s||this.height)*t,l=this.getZoom(),c=this.width,u=this.height,d=this.skipControlsDrawing,f=l*t,g=this.viewportTransform,p=[f,0,0,f,(g[4]-(i||0))*t,(g[5]-(n||0))*t],b=this.enableRetinaScaling,m=Kt({width:o,height:h}),v=r?this._objects.filter((y=>r(y))):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=o,this.height=h,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}),ki.cancelByCanvas(this),this.disposed=!0,new Promise(((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()}))}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject((t=>t.dispose())),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}x(Zs,"ownDefaults",Ql);const ec=["touchstart","touchmove","touchend"],Jo=a=>{const t=Uo(a.target),e=(function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s})(a);return new C(e.clientX+t.left,e.clientY+t.top)},Di=a=>ec.includes(a.type)||a.pointerType==="touch",Zo=a=>{a.preventDefault(),a.stopPropagation()},we=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:h}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},sc=["translateX","translateY","scaleX","scaleY"],Qo=(a,t)=>Es(a,gt(t,a.calcOwnMatrix())),Es=(a,t)=>{const e=ts(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=it(e,sc),h=new C(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,X,X)},ta=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}),Ri=(a,t,e)=>{const s=a/2,i=t/2,n=[new C(-s,-i),new C(s,-i),new C(-s,i),new C(s,i)].map((o=>o.transform(e))),r=we(n);return new C(r.width,r.height)},Qs=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Rt;return gt(Wt(arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rt),a)},ns=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Rt;return a.transform(Qs(t,e))},ea=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Rt;return a.transform(Qs(t,e),!0)},ur=(a,t,e)=>{const s=Qs(t,e);return Es(a,gt(s,a.calcOwnMatrix())),s},sa=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),w(w({},t),{},{target:s})),s.fire(a,t)},ic={left:-.5,top:-.5,center:0,bottom:.5,right:.5},vt=a=>typeof a=="string"?ic[a]:a-.5,Li="not-allowed";function ia(a){return vt(a.originX)===vt(X)&&vt(a.originY)===vt(X)}function na(a){return .5-vt(a)}const he=(a,t)=>a[t],ra=(a,t,e,s)=>({e:a,transform:t,pointer:new C(e,s)});function oa(a,t){const e=a.getTotalAngle()+_e(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function dr(a,t,e,s,i){var n;let{target:r,corner:o}=a;const h=r.controls[o],l=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,c=r.padding/l,u=(function(d,f,g,p){const b=d.getRelativeCenterPoint(),m=g!==void 0&&p!==void 0?d.translateToGivenOrigin(b,X,X,g,p):new C(d.left,d.top);return(d.angle?f.rotate(-lt(d.angle),b):f).subtract(m)})(r,new C(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-=h.offsetX,u.y-=h.offsetY,u}const nc=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!he(i,"lockMovementX")&&i.left!==o,c=!he(i,"lockMovementY")&&i.top!==h;return l&&i.set(Z,o),c&&i.set(Xt,h),(l||c)&&sa(Ro,ra(a,t,e,s)),l||c},Fi=a=>a.replace(/\s+/g," "),aa={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"},fr=(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),ha=(a,t,e,s)=>{a/=255,t/=255,e/=255;const i=Math.max(a,t,e),n=Math.min(a,t,e);let r,o;const h=(i+n)/2;if(i===n)r=o=0;else{const l=i-n;switch(o=h>.5?l/(2-i-n):l/(i+n),i){case a:r=(t-e)/l+(t<e?6:0);break;case t:r=(e-a)/l+2;break;case e:r=(a-t)/l+4}r/=6}return[Math.round(360*r),Math.round(100*o),Math.round(100*h),s]},la=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},Ii=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),ca=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class tt{constructor(t){if(x(this,"isUnrecognised",!1),t)if(t instanceof tt)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 aa&&(t=aa[t]),t==="transparent"?[255,255,255,0]:tt.sourceFromHex(t)||tt.sourceFromRgb(t)||tt.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=ha(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=ha(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(i,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return"".concat(Ii(t)).concat(Ii(e)).concat(Ii(s)).concat(Ii(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(ca(this.getSource())),this}toBlackWhite(t){const[e,,,s]=ca(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof tt||(t=new tt(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map(((o,h)=>Math.round(.5*o+.5*s[h])));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return tt.fromRgba(t)}static fromRgba(t){return new tt(tt.sourceFromRgb(t))}static sourceFromRgb(t){const e=Fi(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,la(e[4])]}}static fromHsl(t){return tt.fromHsla(t)}static fromHsla(t){return new tt(tt.sourceFromHsl(t))}static sourceFromHsl(t){const e=Fi(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=(tt.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,o,h;if(i===0)r=o=h=n;else{const l=n<=.5?n*(i+1):n+i-n*i,c=2*n-l;r=fr(c,l,s+1/3),o=fr(c,l,s),h=fr(c,l,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),la(e[4])]}static fromHex(t){return new tt(tt.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map((h=>h+h)):e.match(/.{2}/g);const[i,n,r,o=255]=s.map((h=>parseInt(h,16)));return[i,n,r,o/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?_e(s):e.includes("turn")?360*s:s}}const Nt=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Zn;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=K.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}},gr=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==Lt?[n.slice(1,4),n.slice(5,8)]:n===Lt?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},ti=function(a,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const n=new tt(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(a,": ").concat(e,"; ").concat(s?"".concat(a,"-opacity: ").concat(s,"; "):""):"".concat(a,'="').concat(e,'" ').concat(s?"".concat(a,'-opacity="').concat(s,'" '):"")};class ua{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):Lt,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=this.opacity!==void 0?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),d=ti(bt,this.fill);return[ti(It,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",h,"; ",d,"fill-rule: ",e,"; ","opacity: ",l,";",u,c].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),i='transform="'.concat(Ts(s));return"".concat(i).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=i,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:i,additionalTransform:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=e?"":'style="'.concat(this.getSvgStyles(),'" '),o=i?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],p=t.indexOf("COMMON_PARTS");let b;h&&(h.clipPathId="CLIPPATH_".concat(Ve()),b='<clipPath id="'.concat(h.clipPathId,`" >
|
|
22
22
|
`).concat(h.toClipPathSVG(s),`</clipPath>
|
|
23
23
|
`)),c&&g.push("<g ",o,this.getSvgCommons(),` >
|
|
24
24
|
`),g.push("<g ",this.getSvgTransform(!1),c?"":o+this.getSvgCommons(),` >
|
|
25
|
-
`);const m=[r,l,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[p]=m,
|
|
25
|
+
`);const m=[r,l,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[p]=m,ee(d)&&g.push(d.toSVG(this)),ee(u)&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(b),g.push(t.join("")),g.push(`</g>
|
|
26
26
|
`),c&&g.push(`</g>
|
|
27
|
-
`),s?s(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==
|
|
28
|
-
<feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(
|
|
29
|
-
<feOffset dx="`).concat(
|
|
27
|
+
`),s?s(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==bt?' paint-order="'.concat(this.paintFirst,'" '):""}}function Ni(a){return new RegExp("^("+a.join("|")+")\\b","i")}const rs="textDecorationThickness",da=["fontSize","fontWeight","fontFamily","fontStyle"],fa=["underline","overline","linethrough"],ga=[...da,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],pa=[...ga,...fa,"textBackgroundColor","direction",rs],rc=[...da,...fa,It,"strokeWidth",bt,"deltaY","textBackgroundColor",rs],oc={_reNewline:tr,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:Z,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:Z,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,[rs]:66.667},xe="justify",ji="justify-left",ei="justify-right",si="justify-center";var ma,ba,va;const le=String.raw(ma||(ma=me(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),pr=String.raw(ba||(ba=me(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),mr="http://www.w3.org/2000/svg",ac=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+le+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+le+"))?\\s+(.*)"),hc={cx:Z,x:Z,r:"radius",cy:Xt,y:Xt,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":rs},br="font-size",vr="clip-path",lc=Ni(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),cc=Ni(["symbol","image","marker","pattern","view","svg"]),ya=Ni(["symbol","g","a","svg","clipPath","defs"]),_a=new RegExp(String.raw(va||(va=me(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),le,pr,le,pr,le,pr,le)),uc=new C(1,0),wa=new C,yr=(a,t)=>a.rotate(t),Bi=(a,t)=>new C(t).subtract(a),Hi=a=>a.distanceFrom(wa),zi=(a,t)=>Math.atan2(ks(a,t),Sa(a,t)),xa=a=>zi(uc,a),Gi=a=>a.eq(wa)?a:a.scalarDivide(Hi(a)),_r=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return Gi(new C(-a.y,a.x).scalarMultiply(t?1:-1))},ks=(a,t)=>a.x*t.y-a.y*t.x,Sa=(a,t)=>a.x*t.x+a.y*t.y,wr=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=ks(t,e),i=ks(t,a),n=ks(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},Ca="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Aa=new RegExp("(?:\\s|^)"+Ca+Ca+"("+le+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Oe{constructor(t){const e=typeof t=="string"?Oe.parseShadow(t):t;Object.assign(this,Oe.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=yr(new C(this.offsetX,this.offsetY),lt(-t.angle)),s=new tt(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*et((Math.abs(e.x)+this.blur)/t.width,K.NUM_FRACTION_DIGITS)+20,n=100*et((Math.abs(e.y)+this.blur)/t.height,K.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(n,'%" height="').concat(100+2*n,'%" x="-').concat(i,'%" width="').concat(100+2*i,`%" >
|
|
28
|
+
<feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(et(this.blur?this.blur/2:0,K.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
|
|
29
|
+
<feOffset dx="`).concat(et(e.x,K.NUM_FRACTION_DIGITS),'" dy="').concat(et(e.y,K.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
|
|
30
30
|
<feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
|
|
31
31
|
<feComposite in2="oBlur" operator="in" />
|
|
32
32
|
<feMerge>
|
|
@@ -34,44 +34,44 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
34
34
|
<feMergeNode in="SourceGraphic"></feMergeNode>
|
|
35
35
|
</feMerge>
|
|
36
36
|
</filter>
|
|
37
|
-
`)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=Ne.ownDefaults;return this.includeDefaultValues?t:Cr(t,((s,i)=>s!==e[i]))}static async fromObject(t){return new this(t)}}C(Ne,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),C(Ne,"type","shadow"),I.setClass(Ne,"shadow");const us=(a,t,e)=>Math.max(a,Math.min(t,e)),Vc=[Yt,J,It,Zt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Ds,Ps],je=[yt,Bt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Wc={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:J,originY:Yt,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:yt,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},Nr=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/Be*Math.asin(1):e/Be*Math.asin(t/a),{a,c:t,p:e,s}),$a=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*Be/e),qa=(a,t,e,s)=>-e*Math.cos(a/s*qe)+e+t,jr=(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-jr(s-a,0,e,s)+t;var Uc=Object.freeze({__proto__:null,defaultEasing:qa,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:h}=Nr(i,e,n,1.70158);return-$a(r,o,h,a,s)+t},easeInExpo:(a,t,e,s)=>a===0?t:e*2**(10*(a/s-1))+t,easeInOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(a/=s/2)<1?e/2*(a*a*((1+(i*=1.525))*a-i))+t:e/2*((a-=2)*a*((1+(i*=1.525))*a+i)+2)+t},easeInOutBounce:(a,t,e,s)=>a<s/2?.5*Ka(2*a,0,e,s)+t:.5*jr(2*a-s,0,e,s)+.5*e+t,easeInOutCirc:(a,t,e,s)=>(a/=s/2)<1?-e/2*(Math.sqrt(1-a**2)-1)+t:e/2*(Math.sqrt(1-(a-=2)*a)+1)+t,easeInOutCubic:(a,t,e,s)=>(a/=s/2)<1?e/2*a**3+t:e/2*((a-2)**3+2)+t,easeInOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:o,p:h,c:l}=Nr(i,e,n,1.70158);return a<1?-.5*$a(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*Be/h)*.5+l+t},easeInOutExpo:(a,t,e,s)=>a===0?t:a===s?t+e:(a/=s/2)<1?e/2*2**(10*(a-1))+t:e/2*-(2**(-10*--a)+2)+t,easeInOutQuad:(a,t,e,s)=>(a/=s/2)<1?e/2*a**2+t:-e/2*(--a*(a-2)-1)+t,easeInOutQuart:(a,t,e,s)=>(a/=s/2)<1?e/2*a**4+t:-e/2*((a-=2)*a**3-2)+t,easeInOutQuint:(a,t,e,s)=>(a/=s/2)<1?e/2*a**5+t:e/2*((a-2)**5+2)+t,easeInOutSine:(a,t,e,s)=>-e/2*(Math.cos(Math.PI*a/s)-1)+t,easeInQuad:(a,t,e,s)=>e*(a/=s)*a+t,easeInQuart:(a,t,e,s)=>e*(a/=s)*a**3+t,easeInQuint:(a,t,e,s)=>e*(a/s)**5+t,easeInSine:(a,t,e,s)=>-e*Math.cos(a/s*qe)+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:jr,easeOutCirc:(a,t,e,s)=>e*Math.sqrt(1-(a=a/s-1)*a)+t,easeOutCubic:(a,t,e,s)=>e*((a/s-1)**3+1)+t,easeOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h,c:l}=Nr(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*Be/h)+l+t},easeOutExpo:(a,t,e,s)=>a===s?t+e:e*-(2**(-10*a/s)+1)+t,easeOutQuad:(a,t,e,s)=>-e*(a/=s)*(a-2)+t,easeOutQuart:(a,t,e,s)=>-e*((a=a/s-1)*a**3-1)+t,easeOutQuint:(a,t,e,s)=>e*((a/s-1)**5+1)+t,easeOutSine:(a,t,e,s)=>e*Math.sin(a/s*qe)+t});const Xc=()=>!1;class Hr{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=qa,onStart:o=ns,onChange:h=ns,onComplete:l=ns,abort:c=Xc,target:d}=t;C(this,"_state","pending"),C(this,"durationProgress",0),C(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=o,this._onChange=h,this._onComplete=l,this._abort=c,this.target=d,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout((()=>ni(t)),this.delay):ni(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),ni(this.tick)))}register(){Gi.push(this)}unregister(){Gi.remove(this)}abort(){this._state="aborted",this.unregister()}}const Yc=["startValue","endValue"];class $c extends Hr{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(S(S({},nt(t,Yc)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const qc=["startValue","endValue"];class Kc extends Hr{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(S(S({},nt(t,qc)),{},{startValue:e,byValue:s.map(((i,n)=>i-e[n]))}))}calculate(t){const e=this.startValue.map(((s,i)=>this.easing(t,s,this.byValue[i],this.duration,i)));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const Jc=["startValue","endValue","easing","onChange","onComplete","abort"],Zc=(a,t,e,s)=>t+e*(1-Math.cos(a/s*qe)),zr=a=>a&&((t,e,s)=>a(new Q(t).toRgba(),e,s));class Qc extends Hr{constructor(t){let{startValue:e,endValue:s,easing:i=Zc,onChange:n,onComplete:r,abort:o}=t,h=nt(t,Jc);const l=new Q(e).getSource(),c=new Q(s).getSource();super(S(S({},h),{},{startValue:l,byValue:c.map(((d,u)=>d-l[u])),easing:i,onChange:zr(n),onComplete:zr(r),abort:zr(o)}))}calculate(t){const[e,s,i,n]=this.startValue.map(((o,h)=>this.easing(t,o,this.byValue[h],this.duration,h))),r=[...[e,s,i].map(Math.round),us(0,n,1)];return{value:r,valueProgress:r.map(((o,h)=>this.byValue[h]!==0?Math.abs((o-this.startValue[h])/this.byValue[h]):0)).find((o=>o!==0))||0}}}function Gr(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new Kc(a):new $c(a);return t.start(),t}function Ja(a){const t=new Qc(a);return t.start(),t}class at{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some((e=>e.eq(t)))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter((i=>!this.includes(i)))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=Qi(e,s),r=Qi(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 E(t).setX(Math.min(t.x-1,...e.map((n=>n.x))));let i=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,s);if(r.includes(t))return!0;i+=+(r.status==="Intersection")}return i%2==1}static intersectLineLine(t,e,s,i){let n=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const o=e.x-t.x,h=e.y-t.y,l=i.x-s.x,c=i.y-s.y,d=t.x-s.x,u=t.y-s.y,f=l*u-c*d,g=o*u-h*d,p=c*o-l*h;if(p!==0){const y=f/p,m=g/p;return(n||0<=y&&y<=1)&&(r||0<=m&&m<=1)?new at("Intersection").append(new E(t.x+y*o,t.y+y*h)):new at}if(f===0||g===0){const y=n||r||at.isPointContained(t,s,i)||at.isPointContained(e,s,i)||at.isPointContained(s,t,e)||at.isPointContained(i,t,e);return new at(y?"Coincident":void 0)}return new at("Parallel")}static intersectSegmentLine(t,e,s,i){return at.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return at.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new at,r=s.length;for(let o,h,l,c=0;c<r;c++){if(o=s[c],h=s[(c+1)%r],l=at.intersectLineLine(t,e,o,h,i,!1),l.status==="Coincident")return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return at.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new at,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=at.intersectSegmentPolygon(o,h,e);l.status==="Coincident"?(n.push(l),s.append(o,h)):s.append(...l.points)}return n.length>0&&n.length===t.length?new at("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new E(n.x,i.y),o=new E(i.x,n.y);return at.intersectPolygonPolygon(t,[i,r,n,o])}}class td extends ra{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?Mt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Mt(t,$t(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new E(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=>Mt(o,r)))}return n}intersectsWithRect(t,e){return at.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=at.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every((e=>t.containsPoint(e)))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return at.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some((s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y))||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every((s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y)))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Ae(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(It,t),this._set(Zt,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?Ce(la(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||Rt.concat()}calcACoords(){const t=as({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=Ls(e,s),n=gt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:Mt({x:-o,y:-h},n),tr:Mt({x:o,y:-h},n),bl:Mt({x:-o,y:h},n),br:Mt({x:o,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,bt(this.originX),bt(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=gt(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),i={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=da(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new E(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=S({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,o=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new E(r*e.scaleX,o*e.scaleY):Yi(r,o,ri(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=bt(i)-bt(e),l=bt(n)-bt(s);if(h||l){const c=this._getTransformedDimensions();r+=h*c.x,o+=l*c.y}return new E(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(lt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,U,U,e,s);return this.angle?i.rotate(lt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Mt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new E(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const i=this.translateToCenterPoint(t,e,s),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),J,Yt)}}const ed=["type"],sd=["extraParam"];let He=class ar extends td{static getDefaults(){return ar.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){Ie("warn","Setting type has no effect",t)}constructor(t){super(),C(this,"_cacheContext",null),Object.assign(this,ar.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Se(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=q.maxCacheSideLimit,n=q.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=q.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=si.limitDimsByArea(r),l=us(n,o,i),c=us(n,h,i);return e>l&&(t.zoomX/=e/l,t.width=l,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:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),l=s!==t.width||i!==t.height,c=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(l||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 d=o/2,u=h/2;return this.cacheTranslationX=Math.round(t.width/2-d)+d,this.cacheTranslationY=Math.round(t.height/2-u)+u,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 E(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=os(this.calcTransformMatrix());return new E(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!==Zt||(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 Ne||(e=new Ne(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===Bt&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=Qt(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=$t(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,re(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&&(re(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||Rt,o=n*i,h=r*i,l=e.nonScaling?new E(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*q.browserShadowBlurConstant*(o+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!re(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===Bt?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const i=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,o=i.y/this.scaleY/n,h=Qt({width:Math.ceil(r),height:Math.ceil(o)}),l=h.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(r,0),l.lineTo(r,o),l.lineTo(0,o),l.closePath(),l.translate(r/2,o/2),l.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(l,e),l.fillStyle=e.toLive(t),l.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=l.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new E(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=Tr(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?ta():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(b=>new hi(b,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&xa(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Er(this,this.getViewportTransform()),this.setCoords();const l=Se(),c=this.getBoundingRect(),d=this.shadow,u=new E;if(d){const b=d.blur,v=d.nonScaling?new E(1,1):this.getObjectScaling();u.x=2*Math.round(n(d.offsetX)+b)*n(v.x),u.y=2*Math.round(n(d.offsetY)+b)*n(v.y)}const f=c.width+u.x,g=c.height+u.y;l.width=Math.ceil(f),l.height=Math.ceil(g);const p=h(l);t.format==="jpeg"&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new E(p.width/2,p.height/2),U,U);const y=this.canvas;p._objects=[this],this.set("canvas",p),this.setCoords();const m=p.toCanvasElement(o||1,t);return this.set("canvas",y),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 _r(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return wr(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.translateToOriginPoint(this.getRelativeCenterPoint(),s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Gi.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&xe().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce(((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s}),{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:o,onChange:h,onComplete:l}=s,c=S(S({},s),{},{target:this,startValue:o??i.reduce(((d,u)=>d[u]),this),endValue:e,abort:r?.bind(this),onChange:(d,u,f)=>{i.reduce(((g,p,y)=>(y===i.length-1&&(g[p]=d),g[p])),this),h&&h(d,u,f)},onComplete:(d,u,f)=>{this.setCoords(),l&&l(d,u,f)}});return n?Ja(c):Gr(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(ar.customProperties,this.constructor.customProperties||[]);let e;const s=q.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:l,top:c,originX:d,originY:u,width:f,height:g,strokeWidth:p,strokeLineCap:y,strokeDashOffset:m,strokeLineJoin:b,strokeUniform:v,strokeMiterLimit:_,scaleX:w,scaleY:x,angle:T,flipX:A,flipY:k,opacity:R,visible:D,backgroundColor:F,fillRule:M,paintFirst:P,globalCompositeOperation:B,skewX:O,skewY:L}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const H=ct=>st(ct,s),Z=S(S({},hs(this,t)),{},{type:this.constructor.type,version:ur,originX:d,originY:u,left:H(l),top:H(c),width:H(f),height:H(g),fill:ua(n)?n.toObject():n,stroke:ua(r)?r.toObject():r,strokeWidth:H(p),strokeDashArray:h&&h.concat(),strokeLineCap:y,strokeDashOffset:m,strokeLineJoin:b,strokeUniform:v,strokeMiterLimit:H(_),scaleX:H(w),scaleY:H(x),angle:H(T),flipX:A,flipY:k,opacity:H(R),shadow:o&&o.toObject(),visible:D,backgroundColor:F,fillRule:M,paintFirst:P,globalCompositeOperation:B,skewX:H(O),skewY:H(L)},e?{clipPath:e}:null);return this.includeDefaultValues?Z:this._removeDefaultValues(Z)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Cr(t,((i,n)=>{if(n===J||n===Yt||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)}))}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=nt(t,ed),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=nt(s,sd);return ai(e,n).then((r=>i?(delete r[i],new this(e[i],r)):new this(r)))}static fromObject(t,e){return this._fromObject(t,e)}};C(He,"stateProperties",Vc),C(He,"cacheProperties",je),C(He,"ownDefaults",Wc),C(He,"type","FabricObject"),C(He,"colorProperties",[yt,Bt,"backgroundColor"]),C(He,"customProperties",[]),I.setClass(He),I.setClass(He,"object");const Ns=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&Ca(a,S(S({},Ea(s,i,n,r)),e)),o};function js(a){return(t,e,s,i)=>{const{target:n,originX:r,originY:o}=e,h=n.getRelativeCenterPoint(),l=n.translateToOriginPoint(h,r,o),c=a(t,e,s,i);return n.setPositionByOrigin(l,e.originX,e.originY),c}}const Za=Ns(ii,js(((a,t,e,s)=>{const i=kr(t,t.originX,t.originY,e,s);if(bt(t.originX)===bt(U)||bt(t.originX)===bt(ft)&&i.x<0||bt(t.originX)===bt(J)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=Aa(t)?2:1,h=n.width,l=Math.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(l,1)),h!==n.width}return!1})));function id(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?Bt:yt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor);let c,d=t,u=e;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(c=n,a.scale(1,r/n),u=e*n/r):r>n?(c=r,a.scale(n/r,1),d=t*r/n):c=n,a.beginPath(),a.arc(d,u,c/2,0,Be,!1),a[h](),l&&a.stroke(),a.restore()}function nd(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?Bt:yt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor),c=n/2,d=r/2;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",a.translate(t,e);const u=i.getTotalAngle();a.rotate(lt(u)),a["".concat(h,"Rect")](-c,-d,n,r),l&&a.strokeRect(-c,-d,n,r),a.restore()}class me{constructor(t){C(this,"visible",!0),C(this,"actionName",Hi),C(this,"angle",0),C(this,"x",0),C(this,"y",0),C(this,"offsetX",0),C(this,"offsetY",0),C(this,"sizeX",0),C(this,"sizeY",0),C(this,"touchSizeX",0),C(this,"touchSizeY",0),C(this,"cursorStyle","crosshair"),C(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:l}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&at.isPointInPolygon(s,[r,o,h,l])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new E(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=Wi([Ls(s,i),as({angle:t}),Ui((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new E(-.5,-.5).transform(o),tr:new E(.5,-.5).transform(o),br:new E(.5,.5).transform(o),bl:new E(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?id.call(this,t,e,s,i,n):nd.call(this,t,e,s,i,n)}}const rd=(a,t,e)=>e.lockRotation?$i:t.cursorStyle,od=Ns(sa,js(((a,t,e,s)=>{let{target:i,ex:n,ey:r,theta:o,originX:h,originY:l}=t;const c=i.translateToOriginPoint(i.getRelativeCenterPoint(),h,l);if(ge(i,"lockRotation"))return!1;const d=Math.atan2(r-c.y,n-c.x),u=Math.atan2(s-c.y,e-c.x);let f=Ce(u-d+o);if(i.snapAngle&&i.snapAngle>0){const p=i.snapAngle,y=i.snapThreshold||p,m=Math.ceil(f/p)*p,b=Math.floor(f/p)*p;Math.abs(f-b)<y?f=b:Math.abs(f-m)<y&&(f=m)}f<0&&(f=360+f),f%=360;const g=i.angle!==f;return i.angle=f,g})));function Qa(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function th(a,t,e){const s=ge(a,"lockScalingX"),i=ge(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 ad=["e","se","s","sw","w","nw","n","ne","e"],fi=(a,t,e)=>{const s=Qa(a,e);if(th(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return $i;const i=ka(e,t);return"".concat(ad[i],"-resize")};function Vr(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Qa(a,n);let h,l,c,d,u,f;if(th(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(h=kr(t,t.originX,t.originY,e,s),u=r!=="y"?Math.sign(h.x||t.signX||1):1,f=r!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=u),t.signY||(t.signY=f),ge(n,"lockScalingFlip")&&(t.signX!==u||t.signY!==f))return!1;if(d=n._getTransformedDimensions(),o&&!r){const y=Math.abs(h.x)+Math.abs(h.y),{original:m}=t,b=y/(Math.abs(d.x*m.scaleX/n.scaleX)+Math.abs(d.y*m.scaleY/n.scaleY));l=m.scaleX*b,c=m.scaleY*b}else l=Math.abs(h.x*n.scaleX/d.x),c=Math.abs(h.y*n.scaleY/d.y);Aa(t)&&(l*=2,c*=2),t.signX!==u&&r!=="y"&&(t.originX=Ta(t.originX),l*=-1,t.signX=u),t.signY!==f&&r!=="x"&&(t.originY=Ta(t.originY),c*=-1,t.signY=f)}const g=n.scaleX,p=n.scaleY;return r?(r==="x"&&n.set(It,l),r==="y"&&n.set(Zt,c)):(!ge(n,"lockScalingX")&&n.set(It,l),!ge(n,"lockScalingY")&&n.set(Zt,c)),g!==n.scaleX||p!==n.scaleY}const nn=Ns(Ni,js(((a,t,e,s)=>Vr(a,t,e,s)))),hd=Ns(Ni,js(((a,t,e,s)=>Vr(a,t,e,s,{by:"x"})))),ld=Ns(Ni,js(((a,t,e,s)=>Vr(a,t,e,s,{by:"y"})))),cd=["target","ex","ey","skewingSide"],Wr={x:{counterAxis:"y",scale:It,skew:Ds,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Zt,skew:Ps,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},dd=["ns","nesw","ew","nwse"],ud=(a,t,e)=>{if(t.x!==0&&ge(e,"lockSkewingY")||t.y!==0&&ge(e,"lockSkewingX"))return $i;const s=ka(e,t)%4;return"".concat(dd[s],"-resize")};function eh(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:c}=Wr[a];if(ge(n,h))return!1;const{origin:d,flip:u}=Wr[r],f=bt(e[d])*(n[u]?-1:1),g=-Math.sign(f)*(n[c]?-1:1),p=.5*-((n[l]===0&&kr(e,U,U,s,i)[a]>0||n[l]>0?1:-1)*g)+.5;return Ns(ia,js(((m,b,v,_)=>(function(w,x,T){let{target:A,ex:k,ey:R,skewingSide:D}=x,F=nt(x,cd);const{skew:M}=Wr[w],P=T.subtract(new E(k,R)).divide(new E(A.scaleX,A.scaleY))[w],B=A[M],O=F[M],L=Math.tan(lt(O)),H=w==="y"?A._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:A._getTransformedDimensions({scaleX:1,scaleY:1}).y,Z=2*P*D/Math.max(H,1)+L,ct=Ce(Math.atan(Z));A.set(M,ct);const Ut=B!==A[M];if(Ut&&w==="y"){const{skewX:dt,scaleX:it}=A,Xt=A._getTransformedDimensions({skewY:B}),ne=A._getTransformedDimensions(),Lt=dt!==0?Xt.x/ne.x:1;Lt!==1&&A.set(It,Lt*it)}return Ut})(a,b,new E(v,_)))))(t,S(S({},e),{},{[o]:p,skewingSide:g}),s,i)}const fd=(a,t,e,s)=>eh("x",a,t,e,s),gd=(a,t,e,s)=>eh("y",a,t,e,s);function rn(a,t){return a[t.canvas.altActionKey]}const on=(a,t,e)=>{const s=rn(a,e);return t.x===0?s?Ds:Zt:t.y===0?s?Ps:It:""},Hs=(a,t,e)=>rn(a,e)?ud(0,t,e):fi(a,t,e),sh=(a,t,e,s)=>rn(a,t.target)?gd(a,t,e,s):hd(a,t,e,s),ih=(a,t,e,s)=>rn(a,t.target)?fd(a,t,e,s):ld(a,t,e,s),nh=()=>({ml:new me({x:-.5,y:0,cursorStyleHandler:Hs,actionHandler:sh,getActionName:on}),mr:new me({x:.5,y:0,cursorStyleHandler:Hs,actionHandler:sh,getActionName:on}),mb:new me({x:0,y:.5,cursorStyleHandler:Hs,actionHandler:ih,getActionName:on}),mt:new me({x:0,y:-.5,cursorStyleHandler:Hs,actionHandler:ih,getActionName:on}),tl:new me({x:-.5,y:-.5,cursorStyleHandler:fi,actionHandler:nn}),tr:new me({x:.5,y:-.5,cursorStyleHandler:fi,actionHandler:nn}),bl:new me({x:-.5,y:.5,cursorStyleHandler:fi,actionHandler:nn}),br:new me({x:.5,y:.5,cursorStyleHandler:fi,actionHandler:nn}),mtr:new me({x:0,y:-.5,actionHandler:od,cursorStyleHandler:rd,offsetY:-40,withConnection:!0,actionName:yr})}),pd=()=>({mr:new me({x:.5,y:0,actionHandler:Za,cursorStyleHandler:Hs,actionName:ii}),ml:new me({x:-.5,y:0,actionHandler:Za,cursorStyleHandler:Hs,actionName:ii})}),md=()=>S(S({},nh()),pd());class gi extends He{static getDefaults(){return S(S({},super.getDefaults()),gi.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),gi.ownDefaults),this.setOptions(t)}static createControls(){return{controls:nh()}}_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(Hi))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=Ls(e.x,e.y),i=as({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=gt(s,i),r=gt(t,n),o=gt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?os(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const l=this._calculateCurrentDimensions(h),c={};return this.forEachControl(((d,u)=>{const f=d.positionHandler(l,o,this,d);c[u]=Object.assign(f,this._calcCornerCoords(d,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(lt(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=S({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=S({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=gt(r,this.calcTransformMatrix()),c=os(l);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(lt(this.group?c.angle:this.angle)),o&&this.drawBorders(t,c,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=Yi(this.width,this.height,ri(e)),r=this.isStrokeAccountedForInDimensions()?vr:(this.strokeUniform?new E().scalarAdd(this.canvas?this.canvas.getZoom():1):new E(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=S({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl(((h,l)=>{if(h.getVisibility(this,l)){const c=this.oCoords[l];h.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 rh(a,t){return t.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((s=>{s!=="constructor"&&Object.defineProperty(a.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))}))})),a}C(gi,"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 Dt extends gi{}rh(Dt,[La]),I.setClass(Dt),I.setClass(Dt,"object");const oh=(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 ah{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new E(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new E(1/this.options.scaleX,1/this.options.scaleY):new E(1,1)}createSideVector(t,e){const s=Qi(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 E(t);return e.y+=e.x*Math.tan(lt(this.options.skewY)),e.x+=e.y*Math.tan(lt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const yd=new E;class zs extends ah{static getOrthogonalRotationFactor(t,e){const s=e?en(t,e):Wa(t);return Math.abs(s)<qe?-1:1}constructor(t,e,s,i){super(i),C(this,"AB",void 0),C(this,"AC",void 0),C(this,"alpha",void 0),C(this,"bisector",void 0),this.A=new E(t),this.B=new E(e),this.C=new E(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=en(this.AB,this.AC),this.bisector=sn(Fr(this.AB.eq(yd)?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=Ir(i),r=zs.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%Be==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?tn(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return tn(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new E(zs.getOrthogonalRotationFactor(this.bisector),zs.getOrthogonalRotationFactor(new E(this.bisector.y,this.bisector.x)));return[new E(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new E(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach((n=>{Br(n,t,e)&&s.push(this.A.add(n))})),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:o,strokeUniform:h}=this.options,l=new E(Math.tan(lt(i)),Math.tan(lt(n))),c=this.strokeProjectionMagnitude,d=h?c/o/Math.sqrt(1/o**2+1/r**2*l.y**2):c/Math.sqrt(1+l.y**2),u=new E(Math.sqrt(Math.max(c**2-d**2,0)),d),f=h?c/Math.sqrt(1+l.x**2*(1/o)**2/(1/r+1/r*l.x*l.y)**2):c/Math.sqrt(1+l.x**2/(1+l.x*l.y)**2),g=new E(f,Math.sqrt(Math.max(c**2-f**2,0)));return[g,g.scalarMultiply(-1),u,u.scalarMultiply(-1)].map((p=>this.applySkew(h?p.multiply(this.strokeUniformScalar):p))).forEach((p=>{Br(p,t,e)&&s.push(this.applySkew(this.A).add(p))})),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Be==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=Bs(i,r)>0,h=o?i:n,l=o?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,l)):t.push(...this.projectRoundNoSkew(h,l)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map((t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector})))}}class hh extends ah{constructor(t,e,s){super(s),this.A=new E(t),this.T=new E(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(Ir(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 E(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 zs(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new E(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(sn(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 lh=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 E(r)),n)),[new E(a[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((o,h)=>{for(let l=o.length-1;l>=0;l--)if(h(o[l],l,o))return l;return-1})(i,(o=>!o.eq(n)));i.splice(r+1)}return i.forEach(((n,r,o)=>{let h,l;r===0?(l=o[1],h=e?n:o[o.length-1]):r===o.length-1?(h=o[r-1],l=e?n:o[0]):(h=o[r-1],l=o[r+1]),e&&o.length===1?s.push(...new hh(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new zs(n,h,l,t).project()):s.push(...new hh(n,r===0?l:h,t).project())})),s},Ur=a=>{const t={};return Object.keys(a).forEach((e=>{t[e]={},Object.keys(a[e]).forEach((s=>{t[e][s]=S({},a[e][s])}))})),t},ch=a=>a.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">");let pi;const an=a=>{if(pi||pi||(pi="Intl"in ei()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),pi){const t=pi.segment(a);return Array.from(t).map((e=>{let{segment:s}=e;return s}))}return bd(a)},bd=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=vd(a,s))!==!1&&t.push(e);return t},vd=(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 _d=Object.freeze({__proto__:null,capitalize:function(a){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(a.charAt(0).toUpperCase()).concat(t?a.slice(1):a.slice(1).toLowerCase())},escapeXml:ch,graphemeSplit:an});const hn=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)},dh=(a,t)=>{const e=t.split(`
|
|
38
|
-
`),s=[];let i=-1,n={};a=
|
|
39
|
-
`)]}static async fromElement(t,e,s){const i=ze(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,c=nt(i,Hd);return new this(S(S(S({},e),c),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}C(Ee,"type","Rect"),C(Ee,"cacheProperties",[...je,...wh]),C(Ee,"ownDefaults",{rx:0,ry:0}),C(Ee,"ATTRIBUTE_NAMES",[...Ze,"x","y","rx","ry","width","height"]),I.setClass(Ee),I.setSVGClass(Ee);const Ge="initialization",cn="added",$r="removed",dn="imperative",xh=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?li(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),c=e&&l?Sa(new E(s,s),void 0,a.calcTransformMatrix()):vr,d=!e&&l?s:0,u=Yi(i+d,n+d,Wi([o,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[h.subtract(u),h.add(u)]};class un{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===Ge||e===dn||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Ge&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===dn&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Ae(t.map((d=>xh(i,d))).reduce(((d,u)=>d.concat(u)),[])),l=new E(o,h),c=new E(n,r).add(l.scalarDivide(2));if(s===Ge){const d=this.getInitialSize(e,{size:l,center:c});return{center:c,relativeCorrection:new E(0,0),size:d}}return{center:c.transform(i.calcOwnMatrix()),size:l}}}C(un,"type","strategy");class qr extends un{shouldPerformLayout(t){return!0}}C(qr,"type","fit-content"),I.setClass(qr);const zd=["strategy"],Gd=["target","strategy","bubbles","prevStrategy"],Sh="layoutManager";class mi{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new qr;C(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=S(S({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[zi,ea,ii,sa,Ni,ia,ji,Tc,Ec].map((i=>t.on(i,(n=>this.performLayout(i===zi?{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===Ge||s===cn?this.subscribeTargets(t):s===$r&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===dn&&t.deep){const n=nt(t,zd);e.forEachObject((r=>r.layoutManager&&r.layoutManager.performLayout(S(S({},n),{},{bubbles:!1,target:r}))))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===Ge?new E:e.getRelativeCenterPoint(),{center:o,correction:h=new E,relativeCorrection:l=new E}=n,c=r.subtract(o).add(h).transform(i===Ge?Rt:$t(e.calcOwnMatrix()),!0).add(l);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===Ge?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*bt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*bt(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}=t,o=nt(t,Gd),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;n&&l!=null&&l.layoutManager&&((o.path||(o.path=[])).push(s),l.layoutManager.performLayout(S(S({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach((e=>e.forEach((s=>s())))),t.clear()}toObject(){return{type:Sh,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}I.setClass(mi,Sh);const Vd=["type","objects","layoutManager"];class Wd extends mi{performLayout(){}}class te extends na(Dt){static getDefaults(){return S(S({},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(),C(this,"_activeObjects",[]),C(this,"__objectSelectionTracker",void 0),C(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 mi,this.layoutManager.performLayout({type:Ge,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(Ie("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(Ie("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(cn,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(cn,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange($r,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&&Is(t,gt($t(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||(Is(t,gt(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=Dt.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(...$t(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(S({target:this,type:dn},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 S(S(S({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject((t=>{this._watchObject(!1,t),t.dispose()})),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Ee.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const i=e.join("");return t?t(i):i}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
|
|
37
|
+
`)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=Oe.ownDefaults;return this.includeDefaultValues?t:hr(t,((s,i)=>s!==e[i]))}static async fromObject(t){return new this(t)}}x(Oe,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),x(Oe,"type","shadow"),F.setClass(Oe,"shadow");const os=(a,t,e)=>Math.max(a,Math.min(t,e)),dc=[Xt,Z,Ft,qt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",ws,xs],De=[bt,It,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],fc={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:Z,originY:Xt,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:bt,fill:"rgb(0,0,0)",fillRule:"nonzero",stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,globalCompositeOperation:"source-over",backgroundColor:"",shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},xr=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/Pe*Math.asin(1):e/Pe*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)*Pe/e),Ea=(a,t,e,s)=>-e*Math.cos(a/s*ze)+e+t,Sr=(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-Sr(s-a,0,e,s)+t;var gc=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:h}=xr(i,e,n,1.70158);return-Ta(r,o,h,a,s)+t},easeInExpo:(a,t,e,s)=>a===0?t:e*2**(10*(a/s-1))+t,easeInOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(a/=s/2)<1?e/2*(a*a*((1+(i*=1.525))*a-i))+t:e/2*((a-=2)*a*((1+(i*=1.525))*a+i)+2)+t},easeInOutBounce:(a,t,e,s)=>a<s/2?.5*ka(2*a,0,e,s)+t:.5*Sr(2*a-s,0,e,s)+.5*e+t,easeInOutCirc:(a,t,e,s)=>(a/=s/2)<1?-e/2*(Math.sqrt(1-a**2)-1)+t:e/2*(Math.sqrt(1-(a-=2)*a)+1)+t,easeInOutCubic:(a,t,e,s)=>(a/=s/2)<1?e/2*a**3+t:e/2*((a-2)**3+2)+t,easeInOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:o,p:h,c:l}=xr(i,e,n,1.70158);return a<1?-.5*Ta(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*Pe/h)*.5+l+t},easeInOutExpo:(a,t,e,s)=>a===0?t:a===s?t+e:(a/=s/2)<1?e/2*2**(10*(a-1))+t:e/2*-(2**(-10*--a)+2)+t,easeInOutQuad:(a,t,e,s)=>(a/=s/2)<1?e/2*a**2+t:-e/2*(--a*(a-2)-1)+t,easeInOutQuart:(a,t,e,s)=>(a/=s/2)<1?e/2*a**4+t:-e/2*((a-=2)*a**3-2)+t,easeInOutQuint:(a,t,e,s)=>(a/=s/2)<1?e/2*a**5+t:e/2*((a-2)**5+2)+t,easeInOutSine:(a,t,e,s)=>-e/2*(Math.cos(Math.PI*a/s)-1)+t,easeInQuad:(a,t,e,s)=>e*(a/=s)*a+t,easeInQuart:(a,t,e,s)=>e*(a/=s)*a**3+t,easeInQuint:(a,t,e,s)=>e*(a/s)**5+t,easeInSine:(a,t,e,s)=>-e*Math.cos(a/s*ze)+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:Sr,easeOutCirc:(a,t,e,s)=>e*Math.sqrt(1-(a=a/s-1)*a)+t,easeOutCubic:(a,t,e,s)=>e*((a/s-1)**3+1)+t,easeOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h,c:l}=xr(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*Pe/h)+l+t},easeOutExpo:(a,t,e,s)=>a===s?t+e:e*-(2**(-10*a/s)+1)+t,easeOutQuad:(a,t,e,s)=>-e*(a/=s)*(a-2)+t,easeOutQuart:(a,t,e,s)=>-e*((a=a/s-1)*a**3-1)+t,easeOutQuint:(a,t,e,s)=>e*((a/s-1)**5+1)+t,easeOutSine:(a,t,e,s)=>e*Math.sin(a/s*ze)+t});const pc=()=>!1;class Cr{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Ea,onStart:o=Ze,onChange:h=Ze,onComplete:l=Ze,abort:c=pc,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=h,this._onComplete=l,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((()=>$s(t)),this.delay):$s(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),$s(this.tick)))}register(){ki.push(this)}unregister(){ki.remove(this)}abort(){this._state="aborted",this.unregister()}}const mc=["startValue","endValue"];class bc extends Cr{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(w(w({},it(t,mc)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const vc=["startValue","endValue"];class yc extends Cr{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(w(w({},it(t,vc)),{},{startValue:e,byValue:s.map(((i,n)=>i-e[n]))}))}calculate(t){const e=this.startValue.map(((s,i)=>this.easing(t,s,this.byValue[i],this.duration,i)));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const _c=["startValue","endValue","easing","onChange","onComplete","abort"],wc=(a,t,e,s)=>t+e*(1-Math.cos(a/s*ze)),Ar=a=>a&&((t,e,s)=>a(new tt(t).toRgba(),e,s));class xc extends Cr{constructor(t){let{startValue:e,endValue:s,easing:i=wc,onChange:n,onComplete:r,abort:o}=t,h=it(t,_c);const l=new tt(e).getSource(),c=new tt(s).getSource();super(w(w({},h),{},{startValue:l,byValue:c.map(((u,d)=>u-l[d])),easing:i,onChange:Ar(n),onComplete:Ar(r),abort:Ar(o)}))}calculate(t){const[e,s,i,n]=this.startValue.map(((o,h)=>this.easing(t,o,this.byValue[h],this.duration,h))),r=[...[e,s,i].map(Math.round),os(0,n,1)];return{value:r,valueProgress:r.map(((o,h)=>this.byValue[h]!==0?Math.abs((o-this.startValue[h])/this.byValue[h]):0)).find((o=>o!==0))||0}}}function Tr(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new yc(a):new bc(a);return t.start(),t}function Ma(a){const t=new xc(a);return t.start(),t}class ht{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=Bi(e,s),r=Bi(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 C(t).setX(Math.min(t.x-1,...e.map((n=>n.x))));let i=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,s);if(r.includes(t))return!0;i+=+(r.status==="Intersection")}return i%2==1}static intersectLineLine(t,e,s,i){let n=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const o=e.x-t.x,h=e.y-t.y,l=i.x-s.x,c=i.y-s.y,u=t.x-s.x,d=t.y-s.y,f=l*d-c*u,g=o*d-h*u,p=c*o-l*h;if(p!==0){const b=f/p,m=g/p;return(n||0<=b&&b<=1)&&(r||0<=m&&m<=1)?new ht("Intersection").append(new C(t.x+b*o,t.y+b*h)):new ht}if(f===0||g===0){const b=n||r||ht.isPointContained(t,s,i)||ht.isPointContained(e,s,i)||ht.isPointContained(s,t,e)||ht.isPointContained(i,t,e);return new ht(b?"Coincident":void 0)}return new ht("Parallel")}static intersectSegmentLine(t,e,s,i){return ht.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return ht.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 ht,r=s.length;for(let o,h,l,c=0;c<r;c++){if(o=s[c],h=s[(c+1)%r],l=ht.intersectLineLine(t,e,o,h,i,!1),l.status==="Coincident")return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return ht.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new ht,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=ht.intersectSegmentPolygon(o,h,e);l.status==="Coincident"?(n.push(l),s.append(o,h)):s.append(...l.points)}return n.length>0&&n.length===t.length?new ht("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 C(n.x,i.y),o=new C(i.x,n.y);return ht.intersectPolygonPolygon(t,[i,r,n,o])}}class Sc extends No{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?Tt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Tt(t,Wt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new C(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=>Tt(o,r)))}return n}intersectsWithRect(t,e){return ht.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=ht.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 ht.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 we(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Ft,t),this._set(qt,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?_e(zo(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||Rt.concat()}calcACoords(){const t=es({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=Cs(e,s),n=gt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:Tt({x:-o,y:-h},n),tr:Tt({x:o,y:-h},n),bl:Tt({x:-o,y:h},n),br:Tt({x:o,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,vt(this.originX),vt(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=gt(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),i={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=Vo(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new C(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=w({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,o=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new C(r*e.scaleX,o*e.scaleY):Ri(r,o,qs(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=vt(i)-vt(e),l=vt(n)-vt(s);if(h||l){const c=this._getTransformedDimensions();r+=h*c.x,o+=l*c.y}return new C(r,o)}translateToCenterPoint(t,e,s){if(e===X&&s===X)return t;const i=this.translateToGivenOrigin(t,e,s,X,X);return this.angle?i.rotate(lt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,X,X,e,s);return this.angle?i.rotate(lt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Tt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new C(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const i=this.translateToCenterPoint(t,e,s),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),Z,Xt)}}const Cc=["type"],Ac=["extraParam"];let Re=class Wn extends Sc{static getDefaults(){return Wn.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){Me("warn","Setting type has no effect",t)}constructor(t){super(),x(this,"_cacheContext",null),Object.assign(this,Wn.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=ye(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=K.maxCacheSideLimit,n=K.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=K.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=Us.limitDimsByArea(r),l=os(n,o,i),c=os(n,h,i);return e>l&&(t.zoomX/=e/l,t.width=l,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:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),l=s!==t.width||i!==t.height,c=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(l||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=h/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 C(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=ts(this.calcTransformMatrix());return new C(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!==Ft&&t!==qt||(e=this._constrainScale(e)),t===Ft&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Oe||(e=new Oe(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===It&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=Kt(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=Wt(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,ee(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&&(ee(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||Rt,o=n*i,h=r*i,l=e.nonScaling?new C(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*K.browserShadowBlurConstant*(o+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!ee(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===It?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const i=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,o=i.y/this.scaleY/n,h=Kt({width:Math.ceil(r),height:Math.ceil(o)}),l=h.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(r,0),l.lineTo(r,o),l.lineTo(0,o),l.closePath(),l.translate(r/2,o/2),l.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(l,e),l.fillStyle=e.toLive(t),l.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=l.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new C(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(F.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?Do():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(v=>new Zs(v,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&ta(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&ur(this,this.getViewportTransform()),this.setCoords();const l=ye(),c=this.getBoundingRect(),u=this.shadow,d=new C;if(u){const v=u.blur,y=u.nonScaling?new C(1,1):this.getObjectScaling();d.x=2*Math.round(n(u.offsetX)+v)*n(y.x),d.y=2*Math.round(n(u.offsetY)+v)*n(y.y)}const f=c.width+d.x,g=c.height+d.y;l.width=Math.ceil(f),l.height=Math.ceil(g);const p=h(l);t.format==="jpeg"&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new C(p.width/2,p.height/2),X,X);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=X,this.originY=X,this.left=n,this.top=r}if(this.set("angle",t),e){const{x:n,y:r}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){ki.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&ve().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce(((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s}),{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:o,onChange:h,onComplete:l}=s,c=w(w({},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),h&&h(u,d,f)},onComplete:(u,d,f)=>{this.setCoords(),l&&l(u,d,f)}});return n?Ma(c):Tr(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(Wn.customProperties,this.constructor.customProperties||[]);let e;const s=K.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:l,top:c,originX:u,originY:d,width:f,height:g,strokeWidth:p,strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:y,strokeMiterLimit:_,scaleX:S,scaleY:A,angle:T,flipX:E,flipY:O,opacity:N,visible:D,backgroundColor:L,fillRule:M,paintFirst:P,globalCompositeOperation:j,skewX:k,skewY:R}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const G=ct=>et(ct,s),at=w(w({},ss(this,t)),{},{type:this.constructor.type,version:Kn,originX:u,originY:d,left:G(l),top:G(c),width:G(f),height:G(g),fill:Xo(n)?n.toObject():n,stroke:Xo(r)?r.toObject():r,strokeWidth:G(p),strokeDashArray:h&&h.concat(),strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:y,strokeMiterLimit:G(_),scaleX:G(S),scaleY:G(A),angle:G(T),flipX:E,flipY:O,opacity:G(N),shadow:o&&o.toObject(),visible:D,backgroundColor:L,fillRule:M,paintFirst:P,globalCompositeOperation:j,skewX:G(k),skewY:G(R)},e?{clipPath:e}:null);return this.includeDefaultValues?at:this._removeDefaultValues(at)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return hr(t,((i,n)=>{if(n===Z||n===Xt||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)}))}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=it(t,Cc),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=it(s,Ac);return Js(e,n).then((r=>i?(delete r[i],new this(e[i],r)):new this(r)))}static fromObject(t,e){return this._fromObject(t,e)}};x(Re,"stateProperties",dc),x(Re,"cacheProperties",De),x(Re,"ownDefaults",fc),x(Re,"type","FabricObject"),x(Re,"colorProperties",[bt,It,"backgroundColor"]),x(Re,"customProperties",[]),F.setClass(Re),F.setClass(Re,"object");const Ms=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&sa(a,w(w({},ra(s,i,n,r)),e)),o};function Ps(a){return(t,e,s,i)=>{const{target:n,originX:r,originY:o}=e,h=n.getRelativeCenterPoint(),l=n.translateToOriginPoint(h,r,o),c=a(t,e,s,i);return n.setPositionByOrigin(l,e.originX,e.originY),c}}const Pa=Ms(Ys,Ps(((a,t,e,s)=>{const i=dr(t,t.originX,t.originY,e,s);if(vt(t.originX)===vt(X)||vt(t.originX)===vt(ft)&&i.x<0||vt(t.originX)===vt(Z)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=ia(t)?2:1,h=n.width,l=Math.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(l,1)),h!==n.width}return!1})));function Tc(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?It:bt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor);let c,u=t,d=e;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(c=n,a.scale(1,r/n),d=e*n/r):r>n?(c=r,a.scale(n/r,1),u=t*r/n):c=n,a.beginPath(),a.arc(u,d,c/2,0,Pe,!1),a[h](),l&&a.stroke(),a.restore()}function Ec(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?It:bt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor),c=n/2,u=r/2;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",a.translate(t,e);const d=i.getTotalAngle();a.rotate(lt(d)),a["".concat(h,"Rect")](-c,-u,n,r),l&&a.strokeRect(-c,-u,n,r),a.restore()}class ce{constructor(t){x(this,"visible",!0),x(this,"actionName",Ti),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)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:l}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&ht.isPointInPolygon(s,[r,o,h,l])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new C(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=Pi([Cs(s,i),es({angle:t}),Oi((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new C(-.5,-.5).transform(o),tr:new C(.5,-.5).transform(o),br:new C(.5,.5).transform(o),bl:new C(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?Tc.call(this,t,e,s,i,n):Ec.call(this,t,e,s,i,n)}}const kc=(a,t,e)=>e.lockRotation?Li:t.cursorStyle,Mc=Ms(Lo,Ps(((a,t,e,s)=>{let{target:i,ex:n,ey:r,theta:o,originX:h,originY:l}=t;const c=i.translateToOriginPoint(i.getRelativeCenterPoint(),h,l);if(he(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=_e(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 Oa(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Da(a,t,e){const s=he(a,"lockScalingX"),i=he(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 Pc=["e","se","s","sw","w","nw","n","ne","e"],ii=(a,t,e)=>{const s=Oa(a,e);if(Da(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return Li;const i=oa(e,t);return"".concat(Pc[i],"-resize")};function Er(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Oa(a,n);let h,l,c,u,d,f;if(Da(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(h=dr(t,t.originX,t.originY,e,s),d=r!=="y"?Math.sign(h.x||t.signX||1):1,f=r!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=d),t.signY||(t.signY=f),he(n,"lockScalingFlip")&&(t.signX!==d||t.signY!==f))return!1;if(u=n._getTransformedDimensions(),o&&!r){const b=Math.abs(h.x)+Math.abs(h.y),{original:m}=t,v=b/(Math.abs(u.x*m.scaleX/n.scaleX)+Math.abs(u.y*m.scaleY/n.scaleY));l=m.scaleX*v,c=m.scaleY*v}else l=Math.abs(h.x*n.scaleX/u.x),c=Math.abs(h.y*n.scaleY/u.y);ia(t)&&(l*=2,c*=2),t.signX!==d&&r!=="y"&&(t.originX=na(t.originX),l*=-1,t.signX=d),t.signY!==f&&r!=="x"&&(t.originY=na(t.originY),c*=-1,t.signY=f)}const g=n.scaleX,p=n.scaleY;return r?(r==="x"&&n.set(Ft,l),r==="y"&&n.set(qt,c)):(!he(n,"lockScalingX")&&n.set(Ft,l),!he(n,"lockScalingY")&&n.set(qt,c)),g!==n.scaleX||p!==n.scaleY}const Vi=Ms(Ci,Ps(((a,t,e,s)=>Er(a,t,e,s)))),Oc=Ms(Ci,Ps(((a,t,e,s)=>Er(a,t,e,s,{by:"x"})))),Dc=Ms(Ci,Ps(((a,t,e,s)=>Er(a,t,e,s,{by:"y"})))),Rc=["target","ex","ey","skewingSide"],kr={x:{counterAxis:"y",scale:Ft,skew:ws,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:qt,skew:xs,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Lc=["ns","nesw","ew","nwse"],Fc=(a,t,e)=>{if(t.x!==0&&he(e,"lockSkewingY")||t.y!==0&&he(e,"lockSkewingX"))return Li;const s=oa(e,t)%4;return"".concat(Lc[s],"-resize")};function Ra(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:c}=kr[a];if(he(n,h))return!1;const{origin:u,flip:d}=kr[r],f=vt(e[u])*(n[d]?-1:1),g=-Math.sign(f)*(n[c]?-1:1),p=.5*-((n[l]===0&&dr(e,X,X,s,i)[a]>0||n[l]>0?1:-1)*g)+.5;return Ms(Fo,Ps(((m,v,y,_)=>(function(S,A,T){let{target:E,ex:O,ey:N,skewingSide:D}=A,L=it(A,Rc);const{skew:M}=kr[S],P=T.subtract(new C(O,N)).divide(new C(E.scaleX,E.scaleY))[S],j=E[M],k=L[M],R=Math.tan(lt(k)),G=S==="y"?E._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:E._getTransformedDimensions({scaleX:1,scaleY:1}).y,at=2*P*D/Math.max(G,1)+R,ct=_e(Math.atan(at));E.set(M,ct);const At=j!==E[M];if(At&&S==="y"){const{skewX:wt,scaleX:nt}=E,Vt=E._getTransformedDimensions({skewY:j}),Ee=E._getTransformedDimensions(),ut=wt!==0?Vt.x/Ee.x:1;ut!==1&&E.set(Ft,ut*nt)}return At})(a,v,new C(y,_)))))(t,w(w({},e),{},{[o]:p,skewingSide:g}),s,i)}const Ic=(a,t,e,s)=>Ra("x",a,t,e,s),Nc=(a,t,e,s)=>Ra("y",a,t,e,s);function Xi(a,t){return a[t.canvas.altActionKey]}const Wi=(a,t,e)=>{const s=Xi(a,e);return t.x===0?s?ws:qt:t.y===0?s?xs:Ft:""},Os=(a,t,e)=>Xi(a,e)?Fc(0,t,e):ii(a,t,e),La=(a,t,e,s)=>Xi(a,t.target)?Nc(a,t,e,s):Oc(a,t,e,s),Fa=(a,t,e,s)=>Xi(a,t.target)?Ic(a,t,e,s):Dc(a,t,e,s),Ia=()=>({ml:new ce({x:-.5,y:0,cursorStyleHandler:Os,actionHandler:La,getActionName:Wi}),mr:new ce({x:.5,y:0,cursorStyleHandler:Os,actionHandler:La,getActionName:Wi}),mb:new ce({x:0,y:.5,cursorStyleHandler:Os,actionHandler:Fa,getActionName:Wi}),mt:new ce({x:0,y:-.5,cursorStyleHandler:Os,actionHandler:Fa,getActionName:Wi}),tl:new ce({x:-.5,y:-.5,cursorStyleHandler:ii,actionHandler:Vi}),tr:new ce({x:.5,y:-.5,cursorStyleHandler:ii,actionHandler:Vi}),bl:new ce({x:-.5,y:.5,cursorStyleHandler:ii,actionHandler:Vi}),br:new ce({x:.5,y:.5,cursorStyleHandler:ii,actionHandler:Vi}),mtr:new ce({x:0,y:-.5,actionHandler:Mc,cursorStyleHandler:kc,offsetY:-40,withConnection:!0,actionName:er})}),jc=()=>({mr:new ce({x:.5,y:0,actionHandler:Pa,cursorStyleHandler:Os,actionName:Ys}),ml:new ce({x:-.5,y:0,actionHandler:Pa,cursorStyleHandler:Os,actionName:Ys})}),Bc=()=>w(w({},Ia()),jc());class ni extends Re{static getDefaults(){return w(w({},super.getDefaults()),ni.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),ni.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Ia()}}_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(Ti))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=Cs(e.x,e.y),i=es({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=gt(s,i),r=gt(t,n),o=gt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?ts(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const l=this._calculateCurrentDimensions(h),c={};return this.forEachControl(((u,d)=>{const f=u.positionHandler(l,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(lt(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=w({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=w({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=gt(r,this.calcTransformMatrix()),c=ts(l);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(lt(this.group?c.angle:this.angle)),o&&this.drawBorders(t,c,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=Ri(this.width,this.height,qs(e)),r=this.isStrokeAccountedForInDimensions()?ir:(this.strokeUniform?new C().scalarAdd(this.canvas?this.canvas.getZoom():1):new C(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=w({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl(((h,l)=>{if(h.getVisibility(this,l)){const c=this.oCoords[l];h.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(ni,"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 Et extends ni{}Na(Et,[ua]),F.setClass(Et),F.setClass(Et,"object");const ja=(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 Ba{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new C(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new C(1/this.options.scaleX,1/this.options.scaleY):new C(1,1)}createSideVector(t,e){const s=Bi(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 C(t);return e.y+=e.x*Math.tan(lt(this.options.skewY)),e.x+=e.y*Math.tan(lt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const Hc=new C;class Ds extends Ba{static getOrthogonalRotationFactor(t,e){const s=e?zi(t,e):xa(t);return Math.abs(s)<ze?-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 C(t),this.B=new C(e),this.C=new C(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=zi(this.AB,this.AC),this.bisector=Gi(yr(this.AB.eq(Hc)?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=_r(i),r=Ds.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%Pe==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?Hi(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Hi(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new C(Ds.getOrthogonalRotationFactor(this.bisector),Ds.getOrthogonalRotationFactor(new C(this.bisector.y,this.bisector.x)));return[new C(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new C(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach((n=>{wr(n,t,e)&&s.push(this.A.add(n))})),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:o,strokeUniform:h}=this.options,l=new C(Math.tan(lt(i)),Math.tan(lt(n))),c=this.strokeProjectionMagnitude,u=h?c/o/Math.sqrt(1/o**2+1/r**2*l.y**2):c/Math.sqrt(1+l.y**2),d=new C(Math.sqrt(Math.max(c**2-u**2,0)),u),f=h?c/Math.sqrt(1+l.x**2*(1/o)**2/(1/r+1/r*l.x*l.y)**2):c/Math.sqrt(1+l.x**2/(1+l.x*l.y)**2),g=new C(f,Math.sqrt(Math.max(c**2-f**2,0)));return[g,g.scalarMultiply(-1),d,d.scalarMultiply(-1)].map((p=>this.applySkew(h?p.multiply(this.strokeUniformScalar):p))).forEach((p=>{wr(p,t,e)&&s.push(this.applySkew(this.A).add(p))})),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Pe==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=ks(i,r)>0,h=o?i:n,l=o?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,l)):t.push(...this.projectRoundNoSkew(h,l)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map((t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector})))}}class Ha extends Ba{constructor(t,e,s){super(s),this.A=new C(t),this.T=new C(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(_r(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 C(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 Ds(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new C(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(Gi(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 C(r)),n)),[new C(a[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((o,h)=>{for(let l=o.length-1;l>=0;l--)if(h(o[l],l,o))return l;return-1})(i,(o=>!o.eq(n)));i.splice(r+1)}return i.forEach(((n,r,o)=>{let h,l;r===0?(l=o[1],h=e?n:o[o.length-1]):r===o.length-1?(h=o[r-1],l=e?n:o[0]):(h=o[r-1],l=o[r+1]),e&&o.length===1?s.push(...new Ha(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Ds(n,h,l,t).project()):s.push(...new Ha(n,r===0?l:h,t).project())})),s},Mr=a=>{const t={};return Object.keys(a).forEach((e=>{t[e]={},Object.keys(a[e]).forEach((s=>{t[e][s]=w({},a[e][s])}))})),t},Ga=a=>a.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">");let ri;const Ui=a=>{if(ri||ri||(ri="Intl"in Ws()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),ri){const t=ri.segment(a);return Array.from(t).map((e=>{let{segment:s}=e;return s}))}return zc(a)},zc=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=Gc(a,s))!==!1&&t.push(e);return t},Gc=(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 Vc=Object.freeze({__proto__:null,capitalize:function(a){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(a.charAt(0).toUpperCase()).concat(t?a.slice(1):a.slice(1).toLowerCase())},escapeXml:Ga,graphemeSplit:Ui});const Yi=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)},Va=(a,t)=>{const e=t.split(`
|
|
38
|
+
`),s=[];let i=-1,n={};a=Mr(a);for(let r=0;r<e.length;r++){const o=Ui(e[r]);if(a[r])for(let h=0;h<o.length;h++){i++;const l=a[r][h];l&&Object.keys(l).length>0&&(Yi(n,l,!0)?s.push({start:i,end:i+1,style:l}):s[s.length-1].end++),n=l||{}}else i+=o.length,n={}}return s},Xa=(a,t)=>{if(!Array.isArray(a))return Mr(a);const e=t.split(tr),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=Ui(e[r]);for(let h=0;h<o.length;h++)i++,a[n]&&a[n].start<=i&&i<a[n].end&&(s[r]=s[r]||{},s[r][h]=w({},a[n].style),i===a[n].end-1&&n++)}return s},Xe=["display","transform",bt,"fill-opacity","fill-rule","opacity",It,"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 Wa(a,t){const e=a.nodeName,s=a.getAttribute("class"),i=a.getAttribute("id"),n="(?![a-zA-Z\\-]+)";let r;if(r=new RegExp("^"+e,"i"),t=t.replace(r,""),i&&t.length&&(r=new RegExp("#"+i+n,"i"),t=t.replace(r,"")),s&&t.length){const o=s.split(" ");for(let h=o.length;h--;)r=new RegExp("\\."+o[h]+n,"i"),t=t.replace(r,"")}return t.length===0}function Xc(a,t){let e=!0;const s=Wa(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=Wa(i=i.parentElement,r);return n.length===0})(a,t)),s&&e&&t.length===0}const Wc=a=>{var t;return(t=hc[a])!==null&&t!==void 0?t:a},Uc=new RegExp("(".concat(le,")"),"gi"),Yc=a=>Fi(a.replace(Uc," $1 ").replace(/,/gi," "));var Ua,Ya,$a,qa,Ka,Ja,Za;const jt="(".concat(le,")"),$c=String.raw(Ua||(Ua=me(["(skewX)(",")"],["(skewX)\\(","\\)"])),jt),qc=String.raw(Ya||(Ya=me(["(skewY)(",")"],["(skewY)\\(","\\)"])),jt),Kc=String.raw($a||($a=me(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),jt,jt,jt),Jc=String.raw(qa||(qa=me(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),jt,jt),Zc=String.raw(Ka||(Ka=me(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),jt,jt),Qc=String.raw(Ja||(Ja=me(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),jt,jt,jt,jt,jt,jt),Pr="(?:".concat(Qc,"|").concat(Zc,"|").concat(Kc,"|").concat(Jc,"|").concat($c,"|").concat(qc,")"),tu="(?:".concat(Pr,"*)"),eu=String.raw(Za||(Za=me(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),tu),su=new RegExp(eu),iu=new RegExp(Pr),nu=new RegExp(Pr,"g");function $i(a){const t=[];if(!(a=Yc(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!su.test(a))return[...Rt];for(const e of a.matchAll(nu)){const s=iu.exec(e[0]);if(!s)continue;let i=Rt;const n=s.filter((g=>!!g)),[,r,...o]=n,[h,l,c,u,d,f]=o.map((g=>parseFloat(g)));switch(r){case"translate":i=Cs(h,l);break;case er:i=es({angle:h},{x:l,y:c});break;case Ti:i=Oi(h,l);break;case ws:i=or(h);break;case xs:i=ar(h);break;case"matrix":i=[h,l,c,u,d,f]}t.push(i)}return Pi(t)}function ru(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==bt&&a!==It||t!==Lt){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===Lt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?gt(e.transformMatrix,$i(t)):$i(t);else if(a==="visible")r=t!==Lt&&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"?Z:t==="end"?ft:X;else if(a==="charSpacing"||a===rs)n=Nt(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(bt),h=t.indexOf(It);r=bt,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=It)}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 ou(a,t){const e=a.match(ac);if(!e)return;const s=e[1],i=e[3],n=e[4],r=e[5],o=e[6];s&&(t.fontStyle=s),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),n&&(t.fontSize=Nt(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function Or(a,t){a.replace(/;\s*$/,"").split(";").forEach((e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()}))}function au(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?Or(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 hu={stroke:"strokeOpacity",fill:"fillOpacity"};function Le(a,t,e){if(!a)return{};let s,i={},n=Zn;a.parentNode&&ya.test(a.parentNode.nodeName)&&(i=Le(a.parentElement,t,e),i.fontSize&&(s=n=Nt(i.fontSize)));const r=w(w(w({},t.reduce(((l,c)=>{const u=a.getAttribute(c);return u&&(l[c]=u),l}),{})),(function(l){let c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const d in c)Xc(l,d.split(" "))&&(u=w(w({},u),c[d]));return u})(a,e)),au(a));r[vr]&&a.setAttribute(vr,r[vr]),r[br]&&(s=Nt(r[br],n),r[br]="".concat(s));const o={};for(const l in r){const c=Wc(l),u=ru(c,r[l],i,s);o[c]=u}o&&o.font&&ou(o.font,o);const h=w(w({},i),o);return ya.test(a.nodeName)?h:(function(l){const c=Et.getDefaults();return Object.entries(hu).forEach((u=>{let[d,f]=u;if(l[f]===void 0||l[d]==="")return;if(l[d]===void 0){if(!c[d])return;l[d]=c[d]}if(l[d].indexOf("url(")===0)return;const g=new tt(l[d]);l[d]=g.setAlpha(et(g.getAlpha()*l[f],2)).toRgba()})),l})(h)}const lu=["left","top","width","height","visible"],Qa=["rx","ry"];class Se extends Et{static getDefaults(){return w(w({},super.getDefaults()),Se.ownDefaults)}constructor(t){super(),Object.assign(this,Se.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){const{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){const{width:e,height:s}=this,i=-e/2,n=-s/2,r=this.rx?Math.min(this.rx,e/2):0,o=this.ry?Math.min(this.ry,s/2):0,h=r!==0||o!==0;t.beginPath(),t.moveTo(i+r,n),t.lineTo(i+e-r,n),h&&t.bezierCurveTo(i+e-Ge*r,n,i+e,n+Ge*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-Ge*o,i+e-Ge*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+Ge*r,n+s,i,n+s-Ge*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+Ge*o,i+Ge*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([...Qa,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:i}=this;return["<rect ","COMMON_PARTS",'x="'.concat(-t/2,'" y="').concat(-e/2,'" rx="').concat(s,'" ry="').concat(i,'" width="').concat(t,'" height="').concat(e,`" />
|
|
39
|
+
`)]}static async fromElement(t,e,s){const i=Le(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,c=it(i,lu);return new this(w(w(w({},e),c),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}x(Se,"type","Rect"),x(Se,"cacheProperties",[...De,...Qa]),x(Se,"ownDefaults",{rx:0,ry:0}),x(Se,"ATTRIBUTE_NAMES",[...Xe,"x","y","rx","ry","width","height"]),F.setClass(Se),F.setSVGClass(Se);const Fe="initialization",qi="added",Dr="removed",Ki="imperative",th=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?Qs(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),c=e&&l?ea(new C(s,s),void 0,a.calcTransformMatrix()):ir,u=!e&&l?s:0,d=Ri(i+u,n+u,Pi([o,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[h.subtract(d),h.add(d)]};class Ji{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===Fe||e===Ki||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Fe&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Ki&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=we(t.map((u=>th(i,u))).reduce(((u,d)=>u.concat(d)),[])),l=new C(o,h),c=new C(n,r).add(l.scalarDivide(2));if(s===Fe){const u=this.getInitialSize(e,{size:l,center:c});return{center:c,relativeCorrection:new C(0,0),size:u}}return{center:c.transform(i.calcOwnMatrix()),size:l}}}x(Ji,"type","strategy");class Rr extends Ji{shouldPerformLayout(t){return!0}}x(Rr,"type","fit-content"),F.setClass(Rr);const cu=["strategy"],uu=["target","strategy","bubbles","prevStrategy"],eh="layoutManager";class oi{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Rr;x(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=w(w({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[Ei,Ro,Ys,Lo,Ci,Fo,Ai,ql,Kl].map((i=>t.on(i,(n=>this.performLayout(i===Ei?{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===Fe||s===qi?this.subscribeTargets(t):s===Dr&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Ki&&t.deep){const n=it(t,cu);e.forEachObject((r=>r.layoutManager&&r.layoutManager.performLayout(w(w({},n),{},{bubbles:!1,target:r}))))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===Fe?new C:e.getRelativeCenterPoint(),{center:o,correction:h=new C,relativeCorrection:l=new C}=n,c=r.subtract(o).add(h).transform(i===Fe?Rt:Wt(e.calcOwnMatrix()),!0).add(l);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===Fe?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*vt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*vt(s.originY)}):(s.setPositionByOrigin(n,X,X),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject((i=>{i.group===s&&this.layoutObject(t,e,i)})),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:i}=e;s.set({left:s.left+i.x,top:s.top+i.y})}onAfterLayout(t,e){const{target:s,strategy:i,bubbles:n,prevStrategy:r}=t,o=it(t,uu),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;n&&l!=null&&l.layoutManager&&((o.path||(o.path=[])).push(s),l.layoutManager.performLayout(w(w({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach((e=>e.forEach((s=>s())))),t.clear()}toObject(){return{type:eh,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}F.setClass(oi,eh);const du=["type","objects","layoutManager"];class fu extends oi{performLayout(){}}class Jt extends Io(Et){static getDefaults(){return w(w({},super.getDefaults()),Jt.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,Jt.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 oi,this.layoutManager.performLayout({type:Fe,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(Me("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(Me("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(Dr,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&&Es(t,gt(Wt(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||(Es(t,gt(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=Et.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(...Wt(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(w({target:this,type:Ki},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 w(w(w({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject((t=>{this._watchObject(!1,t),t.dispose()})),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Se.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const i=e.join("");return t?t(i):i}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
|
|
40
40
|
`],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toSVG(t));return e.push(`</g>
|
|
41
|
-
`),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:i=[],layoutManager:n}=t,r=nt(t,Vd);return Promise.all([Rs(i,e),ai(r,e)]).then((o=>{let[h,l]=o;const c=new this(h,S(S(S({},r),l),{},{layoutManager:new Wd}));if(n){const d=I.getClass(n.type),u=I.getClass(n.strategy);c.layoutManager=new d(new u)}else c.layoutManager=new mi;return c.layoutManager.subscribeTargets({type:Ge,target:c,targets:c.getObjects()}),c.setCoords(),c}))}}C(te,"type","Group"),C(te,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),I.setClass(te);const Ch=(a,t)=>Math.min(t.width/a.width,t.height/a.height),Ah=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Kr="\\s*,?\\s*",yi="".concat(Kr,"(").concat(pe,")"),Ud="".concat(yi).concat(yi).concat(yi).concat(Kr,"([01])").concat(Kr,"([01])").concat(yi).concat(yi),Xd={m:"l",M:"L"},Yd=(a,t,e,s,i,n,r,o,h,l,c)=>{const d=de(a),u=ue(a),f=de(t),g=ue(t),p=e*i*f-s*n*g+r,y=s*i*f+e*n*g+o;return["C",l+h*(-e*i*u-s*n*d),c+h*(-s*i*u+e*n*d),p+h*(e*i*g+s*n*f),y+h*(s*i*g-e*n*f),p,y]},Th=(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 Jr(a,t,e,s,i,n,r,o){let h;if(q.cachesBoundsOfCurve&&(h=[...arguments].join(),si.boundsOfCurveCache[h]))return si.boundsOfCurveCache[h];const l=Math.sqrt,c=Math.abs,d=[],u=[[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 _=0;_<2;++_){if(_>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&&d.push(k);continue}const w=f*f-4*p*g;if(w<0)continue;const x=l(w),T=(-f+x)/(2*g);0<T&&T<1&&d.push(T);const A=(-f-x)/(2*g);0<A&&A<1&&d.push(A)}let y=d.length;const m=y,b=kh(a,t,e,s,i,n,r,o);for(;y--;){const{x:_,y:w}=b(d[y]);u[0][y]=_,u[1][y]=w}u[0][m]=a,u[1][m]=t,u[0][m+1]=r,u[1][m+1]=o;const v=[new E(Math.min(...u[0]),Math.min(...u[1])),new E(Math.max(...u[0]),Math.max(...u[1]))];return q.cachesBoundsOfCurve&&(si.boundsOfCurveCache[h]=v),v}const $d=(a,t,e)=>{let[s,i,n,r,o,h,l,c]=e;const d=((u,f,g,p,y,m,b)=>{if(g===0||p===0)return[];let v=0,_=0,w=0;const x=Math.PI,T=b*fr,A=ue(T),k=de(T),R=.5*(-k*u-A*f),D=.5*(-k*f+A*u),F=g**2,M=p**2,P=D**2,B=R**2,O=F*M-F*P-M*B;let L=Math.abs(g),H=Math.abs(p);if(O<0){const Le=Math.sqrt(1-O/(F*M));L*=Le,H*=Le}else w=(y===m?-1:1)*Math.sqrt(O/(F*P+M*B));const Z=w*L*D/H,ct=-w*H*R/L,Ut=k*Z-A*ct+.5*u,dt=A*Z+k*ct+.5*f;let it=Th(1,0,(R-Z)/L,(D-ct)/H),Xt=Th((R-Z)/L,(D-ct)/H,(-R-Z)/L,(-D-ct)/H);m===0&&Xt>0?Xt-=2*x:m===1&&Xt<0&&(Xt+=2*x);const ne=Math.ceil(Math.abs(Xt/x*2)),Lt=[],et=Xt/ne,Es=8/3*Math.sin(et/4)*Math.sin(et/4)/Math.sin(et/2);let Ii=it+et;for(let Le=0;Le<ne;Le++)Lt[Le]=Yd(it,Ii,k,A,L,H,Ut,dt,Es,v,_),v=Lt[Le][5],_=Lt[Le][6],it=Ii,Ii+=et;return Lt})(l-a,c-t,i,n,o,h,r);for(let u=0,f=d.length;u<f;u++)d[u][1]+=a,d[u][2]+=t,d[u][3]+=a,d[u][4]+=t,d[u][5]+=a,d[u][6]+=t;return d},Eh=a=>{let t=0,e=0,s=0,i=0;const n=[];let r,o=0,h=0;for(const l of a){const c=[...l];let d;switch(c[0]){case"l":c[1]+=t,c[2]+=e;case"L":t=c[1],e=c[2],d=["L",t,e];break;case"h":c[1]+=t;case"H":t=c[1],d=["L",t,e];break;case"v":c[1]+=e;case"V":e=c[1],d=["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],d=["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],h=c[4],t=c[5],e=c[6],d=["C",c[1],c[2],o,h,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,h=2*e-h):(o=t,h=e),t=c[3],e=c[4],d=["C",o,h,c[1],c[2],t,e],o=d[3],h=d[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":o=c[1],h=c[2],t=c[3],e=c[4],d=["Q",o,h,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":r==="Q"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=c[1],e=c[2],d=["Q",o,h,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":$d(t,e,c).forEach((u=>n.push(u))),t=c[6],e=c[7];break;case"z":case"Z":t=s,e=i,d=["Z"]}d?(n.push(d),r=d[0]):r=""}return n},fn=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),kh=(a,t,e,s,i,n,r,o)=>h=>{const l=h**3,c=(f=>3*f**2*(1-f))(h),d=(f=>3*f*(1-f)**2)(h),u=(f=>(1-f)**3)(h);return new E(r*l+i*c+e*d+a*u,o*l+n*c+s*d+t*u)},Mh=a=>a**2,Dh=a=>2*a*(1-a),Ph=a=>(1-a)**2,qd=(a,t,e,s,i,n,r,o)=>h=>{const l=Mh(h),c=Dh(h),d=Ph(h),u=3*(d*(e-a)+c*(i-e)+l*(r-i)),f=3*(d*(s-t)+c*(n-s)+l*(o-n));return Math.atan2(f,u)},Kd=(a,t,e,s,i,n)=>r=>{const o=Mh(r),h=Dh(r),l=Ph(r);return new E(i*o+e*h+a*l,n*o+s*h+t*l)},Jd=(a,t,e,s,i,n)=>r=>{const o=1-r,h=2*(o*(e-a)+r*(i-e)),l=2*(o*(s-t)+r*(n-s));return Math.atan2(l,h)},Oh=(a,t,e)=>{let s=new E(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=fn(s.x,s.y,r.x,r.y),s=r}return i},Zd=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=S({},n),o=.01,h=0;const l=a.iterator,c=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=fn(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return S(S({},r),{},{angle:c(h)})},Zr=a=>{let t,e,s=0,i=0,n=0,r=0,o=0;const h=[];for(const l of a){const c={x:i,y:n,command:l[0],length:0};switch(l[0]){case"M":e=c,e.x=r=i=l[1],e.y=o=n=l[2];break;case"L":e=c,e.length=fn(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=kh(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=c,e.iterator=t,e.angleFinder=qd(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=Oh(t,i,n),i=l[5],n=l[6];break;case"Q":t=Kd(i,n,l[1],l[2],l[3],l[4]),e=c,e.iterator=t,e.angleFinder=Jd(i,n,l[1],l[2],l[3],l[4]),e.length=Oh(t,i,n),i=l[3],n=l[4];break;case"Z":e=c,e.destX=r,e.destY=o,e.length=fn(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},Lh=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Zr(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 S(S({},new E(i.x,i.y).lerp(new E(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return S(S({},new E(i.x,i.y).lerp(new E(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return Zd(i,t)}},Qd=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Rh=new RegExp(Ud,"g"),tu=new RegExp(pe,"gi"),eu={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Fh=a=>{var t;const e=[],s=(t=a.match(Qd))!==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=eu[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){Rh.lastIndex=0;for(let h=null;h=Rh.exec(i);)o.push(...h.slice(1))}else o=i.match(tu)||[];for(let h=0;h<o.length;h+=r){const l=new Array(r),c=Xd[n];l[0]=h>0&&c?c:n;for(let d=0;d<r;d++)l[d+1]=parseFloat(o[h+d]);e.push(l)}}return e},su=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new E(a[0]),s=new E(a[1]),i=1,n=0;const r=[],o=a.length,h=o>2;let l;for(h&&(i=a[2].x<s.x?-1:a[2].x===s.x?0:1,n=a[2].y<s.y?-1:a[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),l=1;l<o;l++){if(!e.eq(s)){const c=e.midPointFrom(s);r.push(["Q",e.x,e.y,c.x,c.y])}e=a[l],l+1<a.length&&(s=a[l+1])}return h&&(i=e.x>a[l-2].x?1:e.x===a[l-2].x?0:-1,n=e.y>a[l-2].y?1:e.y===a[l-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},Ih=(a,t)=>a.map((e=>e.map(((s,i)=>i===0||t===void 0?s:st(s,t))).join(" "))).join(" ");function gn(a,t){const e=a.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach((s=>{let[i,n]=s;return e.setProperty(i,n)})))}const iu=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function Bh(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||ns,s=new(ei()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=ns};if(i&&i.aborted)throw new dr("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=ns)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const pn=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=os(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(It,i),s.set(Zt,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 nu=Object.freeze({__proto__:null,addTransformToObject:wa,animate:Gr,animateColor:Ja,applyTransformToObject:Is,calcAngleBetweenVectors:en,calcDimensionsMatrix:ri,calcPlaneChangeMatrix:li,calcVectorRotation:Wa,cancelAnimFrame:oa,capValue:us,composeMatrix:da,copyCanvasElement:a=>{var t;const e=Qt(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:de,createCanvasElement:Se,createImage:aa,createRotateMatrix:as,createScaleMatrix:Ui,createSkewXMatrix:xr,createSkewYMatrix:Sr,createTranslateMatrix:Ls,createVector:Qi,crossProduct:Bs,degreesToRadians:lt,dotProduct:Ua,ease:Uc,enlivenObjectEnlivables:ai,enlivenObjects:Rs,findScaleToCover:Ah,findScaleToFit:Ch,getBoundsOfCurve:Jr,getOrthonormalVector:Ir,getPathSegmentsInfo:Zr,getPointOnPath:Lh,getPointer:va,getRandomInt:iu,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-qe;a%2==0&&(s+=e/2);const i=new Array(a+1);for(let n=0;n<a;n++){const r=n*e+s,{x:o,y:h}=new E(de(r),ue(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:su,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:sn,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new te(a,t),hasStyleChanged:hn,invertTransform:$t,isBetweenVectors:Br,isIdentityMatrix:ha,isTouchEvent:Xi,isTransparent:oh,joinPath:Ih,loadImage:oi,magnitude:tn,makeBoundingBoxFromPoints:Ae,makePathSimpler:Eh,matrixToSVG:Fs,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),Er(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:gt,multiplyTransformMatrixArray:Wi,parsePath:Fh,parsePreserveAspectRatioAttribute:Dr,parseUnit:Nt,pick:hs,projectStrokeOnPoints:lh,qrDecompose:os,radiansToDegrees:Ce,removeFromArray:rs,removeTransformFromObject:(a,t)=>{const e=$t(t),s=gt(e,a.calcOwnMatrix());Is(a,s)},removeTransformMatrixForSvgParsing:pn,request:Bh,requestAnimFrame:ni,resetObjectTransform:xa,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:Fr,saveObjectTransform:Tr,sendObjectToPlane:Er,sendPointToPlane:cs,sendVectorToPlane:Sa,setStyle:gn,sin:ue,sizeAfterTransform:Yi,string:_d,stylesFromArray:uh,stylesToArray:dh,toBlob:wr,toDataURL:_r,toFixed:st,transformPath:(a,t,e)=>(e&&(t=gt(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}=Mt({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i}))),transformPoint:Mt});class ru extends ba{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),C(this,"upper",void 0),C(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,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=Se();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=Ms().createElement("div");return t.setAttribute("data-fabric","wrapper"),gn(t,{position:"relative"}),ya(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;gn(t,S(S({},s),{},{"touch-action":i?"manipulation":Ft})),ya(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;ma(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Ar(this.upper.el,t),Ar(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(),xe().dispose(this.upper.el),delete this.upper,delete this.container}}class mn extends hi{constructor(){super(...arguments),C(this,"targets",[]),C(this,"_hoveredTargets",[]),C(this,"_currentTransform",null),C(this,"_groupSelector",null),C(this,"contextTopDirty",!1)}static getDefaults(){return S(S({},super.getDefaults()),mn.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 ru(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 oh(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===Hi||e===It||e===Zt||e===ii?i=this.centeredScaling||t.centeredScaling:e===yr&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=ft:["mr","tr","br"].includes(e)&&(s.x=J),["tl","mt","tr"].includes(e)?s.y=pr:["bl","mb","br"].includes(e)&&(s.y=Yt)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?cs(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},h=s&&o?(i=o.getActionHandler(t,e,o))===null||i===void 0?void 0:i.bind(o):Fc,l=((f,g,p,y)=>{if(!g||!f)return"drag";const m=y.controls[g];return m.getActionName(p,m,y)})(s,r,t,e),c=t[this.centeredKey],d=this._shouldCenterTransform(e,l,c)?{x:U,y:U}:this._getOriginFromCorner(e,r),u={target:e,action:l,actionHandler:h,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:d.x,originY:d.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:lt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:c,original:S(S({},Tr(e)),{},{originX:d.x,originY:d.y})};this._currentTransform=u,this.fire("before:transform",{e:t,transform:u})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new E(e,s).transform(this.viewportTransform),o=new E(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=Math.min(r.x,o.x),c=Math.min(r.y,o.y),d=Math.max(r.x,o.x),u=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,c,d-l,u-c)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,c+=h,d-=h,u-=h,Dt.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,c,d-l,u-c))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,Xi(t))||i.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const n=this.targets;this.targets=[];const r=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&r&&r!==s?(this.targets=n,s):r}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,o,h,l]=s,c=Math.atan2(o.y-r.y,o.x-r.x),d=de(c)*n,u=ue(c)*n,f=d+u,g=d-u;s=[new E(r.x-g,r.y-f),new E(o.x+f,o.y-g),new E(h.x+g,h.y+f),new E(l.x-f,l.y+g)]}return at.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,cs(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const i=t[s];if(this._checkTarget(i,e)){if(Vi(i)&&i.subTargetCheck){const n=this._searchPossibleTargets(i._objects,e);n&&this.targets.push(n)}return i}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&Vi(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!Vi(r)||!r.interactive)return r}return i[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=va(t),r=i.width||0,o=i.height||0;r&&o||(Yt in i&&pr in i&&(o=Math.abs(i.top-i.bottom)),ft in i&&J 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=cs(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new E(1,1):new E(s.width/r,s.height/o);return n.multiply(l)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Se(),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 ls(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach((h=>{n.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),o.push(h))})),n.forEach((h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),r.push(h))})),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:o})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:o})),i&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),i=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),i}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,ls(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),ls(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(zi,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;ls(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&&ls(e)&&this._activeObject===e){const s=hs(t,["angle","flipX","flipY",J,It,Zt,Ds,Ps,Yt]);return wa(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}C(mn,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class ou{constructor(t){C(this,"targets",[]),C(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach((t=>{t.isEditing&&t.exitEditing()}))}add(t){this.targets.push(t)}remove(t){this.unregister(t),rs(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 au=["target","oldTarget","fireCanvas","e"],ee={passive:!1},Gs=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},Qe=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)},oe=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)},hu={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 Qr extends mn{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),C(this,"_isClick",void 0),C(this,"textEditingManager",new ou(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(Qe,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(pa(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,ee),t(s,"".concat(i,"out"),this._onMouseOut),t(s,"".concat(i,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,ee)}removeListeners(){this.addOrRemove(oe,"remove");const t=this._getEventPrefix(),e=fe(this.upperCanvasEl);oe(e,"".concat(t,"up"),this._onMouseUp),oe(e,"touchend",this._onTouchEnd,ee),oe(e,"".concat(t,"move"),this._onMouseMove,ee),oe(e,"touchmove",this._onMouseMove,ee),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=S({e:t},Gs(this,t));this.fire("mouse:out",S(S({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",S({},s)),this._hoveredTargets.forEach((i=>{this.fire("mouse:out",S(S({},s),{},{target:i})),i&&i.fire("mouseout",S({},s))})),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",S({e:t},Gs(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 Qe(this.upperCanvasEl,"drag",this._onDragProgress)}_a(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e?.clearContextTop(),s!==e&&s?.clearContextTop();const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),i=!0),s&&(r.save(),s.transform(r),s.renderDropTargetEffect(t),r.restore(),i=!0),r.restore(),i&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==Ft,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};oe(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let h=0;h<i.length;h++){const l=i[h];l.canDrop(t)&&(o=l),l.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",S({e:t,target:e,subTargets:s,dragSource:this._dragSource},Gs(this,t)));i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&_a(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=fe(i);Qe(r,"touchend",this._onTouchEnd,ee),e&&Qe(r,"touchmove",this._onMouseMove,ee),oe(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();oe(e,"".concat(s,"move"),this._onMouseMove,ee);const i=fe(e);Qe(i,"".concat(s,"up"),this._onMouseUp),Qe(i,"".concat(s,"move"),this._onMouseMove,ee)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=fe(this.upperCanvasEl);oe(s,"touchend",this._onTouchEnd,ee),oe(s,"touchmove",this._onMouseMove,ee),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((()=>{Qe(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0}),400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=fe(this.upperCanvasEl);oe(i,"".concat(s,"up"),this._onMouseUp),oe(i,"".concat(s,"move"),this._onMouseMove,ee),Qe(e,"".concat(s,"move"),this._onMouseMove,ee)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,n=this._target,{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o,h,l=!1;if(s&&(this._finalizeCurrentTransform(t),l=s.actionPerformed),!i){const c=n===this._activeObject;this.handleSelection(t),l||(l=this._shouldRender(n)||!c&&n===this._activeObject)}if(n){const c=n.findControl(this.getViewportPoint(t),Xi(t)),{key:d,control:u}=c||{};if(h=d,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),l=!0;else if(u){const f=u.getMouseUpHandler(t,n,u);f&&(o=this.getScenePoint(t),f.call(u,t,s,o.x,o.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const c=s.target&&s.target.controls[s.corner],d=c&&c.getMouseUpHandler(t,s.target,c);o=o||this.getScenePoint(t),d&&d.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),l?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e,s){const i=this._target,n=this.targets||[],r=S(S(S({e:t,target:i,subTargets:n},Gs(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let o=0;o<n.length;o++)n[o]!==i&&n[o].fire("mouse".concat(e),r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const o=this.getScenePoint(t);this._groupSelector={x:o.x,y:o.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const o=e.findControl(this.getViewportPoint(t),Xi(t));if(e===this._activeObject&&(o||!r)){this._setupCurrentTransform(t,e,s);const h=o?o.control:void 0,l=this.getScenePoint(t),c=h&&h.getMouseDownHandler(t,e,h);c&&c.call(h,t,this._currentTransform,l.x,l.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=cs(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let o=0;o<r;o++)n[o]===e||i[o]&&i[o]===s||this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",S(S({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",S(S({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=nt(e,au);const{targetIn:h,targetOut:l,canvasIn:c,canvasOut:d}=hu[t],u=i!==s;if(i&&u){const f=S(S({},o),{},{e:r,target:i,nextTarget:s},Gs(this,r));n&&this.fire(d,f),i.fire(l,f)}if(s&&u){const f=S(S({},o),{},{e:r,target:s,previousTarget:i},Gs(this,r));n&&this.fire(c,f),s.fire(h,f)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?cs(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=ls(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const r=n.control;this.setCursor(r.cursorStyleHandler(t,r,e))}else e.subTargetCheck&&this.targets.concat().reverse().map((r=>{s=r.hoverCursor||s})),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,i=ls(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||i)&&(i||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(i){const n=s.getObjects();if(e===s){const r=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(n,r)||this.searchPossibleTargets(this._objects,r))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(n,t)}else{s.isEditing&&s.exitEditing();const n=new(I.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(s,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new E(e,s),o=r.add(new E(i,n)),h=r.min(o),l=r.max(o).subtract(h),c=this.collectObjects({left:h.x,top:h.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),d=r.eq(o)?c[0]?[c[0]]:[]:c.length>1?c.filter((u=>!u.onSelect({e:t}))).reverse():c;if(d.length===1)this.setActiveObject(d[0],t);else if(d.length>1){const u=I.getClass("ActiveSelection");this.setActiveObject(new u(d,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const Nh={x1:0,y1:0,x2:0,y2:0},lu=S(S({},Nh),{},{r1:0,r2:0}),Vs=(a,t)=>isNaN(a)&&typeof t=="number"?t:a;function jh(a){return a&&/%$/.test(a)&&Number.isFinite(parseFloat(a))}function Hh(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(jh(a)?100:1):NaN;return us(0,Vs(e,t),1)}const cu=/\s*;\s*/,du=/\s*:\s*/;function uu(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[h,l]=r[o].split(du).map((c=>c.trim()));h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}const n=new Q(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Hh(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Vs(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function fu(a,t){const e=[],s=a.getElementsByTagName("stop"),i=Hh(t,1);for(let n=s.length;n--;)e.push(uu(s[n],i));return e}function zh(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Gh(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function ye(a,t){return a.getAttribute(t)}function gu(a,t){return(function(e,s){let i,{width:n,height:r,gradientUnits:o}=s;return Object.entries(e).reduce(((h,l)=>{let[c,d]=l;if(d==="Infinity")i=1;else if(d==="-Infinity")i=0;else{const u=typeof d=="string";i=u?parseFloat(d):d,u&&jh(d)&&(i*=.01,o==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(i*=n),c!=="y1"&&c!=="y2"||(i*=r)))}return h[c]=i,h}),{})})(zh(a)==="linear"?(function(e){return{x1:ye(e,"x1")||0,y1:ye(e,"y1")||0,x2:ye(e,"x2")||"100%",y2:ye(e,"y2")||0}})(a):(function(e){return{x1:ye(e,"fx")||ye(e,"cx")||"50%",y1:ye(e,"fy")||ye(e,"cy")||"50%",r1:0,x2:ye(e,"cx")||"50%",y2:ye(e,"cy")||"50%",r2:ye(e,"r")||"50%"}})(a),S(S({},t),{},{gradientUnits:Gh(a)}))}class bi{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:S(S({},e==="radial"?lu:Nh),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(Je()):Je()})}addColorStop(t){for(const e in t){const s=new Q(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return S(S({},hs(this,t)),{},{type:this.type,coords:S({},this.coords),colorStops:this.colorStops.map((e=>S({},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():Rt.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map((d=>S({},d))).sort(((d,u)=>d.offset-u.offset));let o=-this.offsetX,h=-this.offsetY;var l;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const c=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(Fs(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:d,y1:u,x2:f,y2:g}=this.coords;s.push("<linearGradient ",c,' x1="',d,'" y1="',u,'" x2="',f,'" y2="',g,`">
|
|
42
|
-
`)}else if(this.type==="radial"){const{x1:
|
|
43
|
-
`),m&&(r.reverse(),r.forEach((
|
|
41
|
+
`),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:i=[],layoutManager:n}=t,r=it(t,du);return Promise.all([As(i,e),Js(r,e)]).then((o=>{let[h,l]=o;const c=new this(h,w(w(w({},r),l),{},{layoutManager:new fu}));if(n){const u=F.getClass(n.type),d=F.getClass(n.strategy);c.layoutManager=new u(new d)}else c.layoutManager=new oi;return c.layoutManager.subscribeTargets({type:Fe,target:c,targets:c.getObjects()}),c.setCoords(),c}))}}x(Jt,"type","Group"),x(Jt,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),F.setClass(Jt);const sh=(a,t)=>Math.min(t.width/a.width,t.height/a.height),ih=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Lr="\\s*,?\\s*",ai="".concat(Lr,"(").concat(le,")"),gu="".concat(ai).concat(ai).concat(ai).concat(Lr,"([01])").concat(Lr,"([01])").concat(ai).concat(ai),pu={m:"l",M:"L"},mu=(a,t,e,s,i,n,r,o,h,l,c)=>{const u=re(a),d=oe(a),f=re(t),g=oe(t),p=e*i*f-s*n*g+r,b=s*i*f+e*n*g+o;return["C",l+h*(-e*i*d-s*n*u),c+h*(-s*i*d+e*n*u),p+h*(e*i*g+s*n*f),b+h*(s*i*g-e*n*f),p,b]},nh=(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 Fr(a,t,e,s,i,n,r,o){let h;if(K.cachesBoundsOfCurve&&(h=[...arguments].join(),Us.boundsOfCurveCache[h]))return Us.boundsOfCurveCache[h];const l=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 _=0;_<2;++_){if(_>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 O=-p/f;0<O&&O<1&&u.push(O);continue}const S=f*f-4*p*g;if(S<0)continue;const A=l(S),T=(-f+A)/(2*g);0<T&&T<1&&u.push(T);const E=(-f-A)/(2*g);0<E&&E<1&&u.push(E)}let b=u.length;const m=b,v=oh(a,t,e,s,i,n,r,o);for(;b--;){const{x:_,y:S}=v(u[b]);d[0][b]=_,d[1][b]=S}d[0][m]=a,d[1][m]=t,d[0][m+1]=r,d[1][m+1]=o;const y=[new C(Math.min(...d[0]),Math.min(...d[1])),new C(Math.max(...d[0]),Math.max(...d[1]))];return K.cachesBoundsOfCurve&&(Us.boundsOfCurveCache[h]=y),y}const bu=(a,t,e)=>{let[s,i,n,r,o,h,l,c]=e;const u=((d,f,g,p,b,m,v)=>{if(g===0||p===0)return[];let y=0,_=0,S=0;const A=Math.PI,T=v*Jn,E=oe(T),O=re(T),N=.5*(-O*d-E*f),D=.5*(-O*f+E*d),L=g**2,M=p**2,P=D**2,j=N**2,k=L*M-L*P-M*j;let R=Math.abs(g),G=Math.abs(p);if(k<0){const ke=Math.sqrt(1-k/(L*M));R*=ke,G*=ke}else S=(b===m?-1:1)*Math.sqrt(k/(L*P+M*j));const at=S*R*D/G,ct=-S*G*N/R,At=O*at-E*ct+.5*d,wt=E*at+O*ct+.5*f;let nt=nh(1,0,(N-at)/R,(D-ct)/G),Vt=nh((N-at)/R,(D-ct)/G,(-N-at)/R,(-D-ct)/G);m===0&&Vt>0?Vt-=2*A:m===1&&Vt<0&&(Vt+=2*A);const Ee=Math.ceil(Math.abs(Vt/A*2)),ut=[],Q=Vt/Ee,Je=8/3*Math.sin(Q/4)*Math.sin(Q/4)/Math.sin(Q/2);let Vs=nt+Q;for(let ke=0;ke<Ee;ke++)ut[ke]=mu(nt,Vs,O,E,R,G,At,wt,Je,y,_),y=ut[ke][5],_=ut[ke][6],nt=Vs,Vs+=Q;return ut})(l-a,c-t,i,n,o,h,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},rh=a=>{let t=0,e=0,s=0,i=0;const n=[];let r,o=0,h=0;for(const l of a){const c=[...l];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],h=c[4],t=c[5],e=c[6],u=["C",c[1],c[2],o,h,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,h=2*e-h):(o=t,h=e),t=c[3],e=c[4],u=["C",o,h,c[1],c[2],t,e],o=u[3],h=u[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":o=c[1],h=c[2],t=c[3],e=c[4],u=["Q",o,h,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":r==="Q"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=c[1],e=c[2],u=["Q",o,h,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":bu(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},Zi=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),oh=(a,t,e,s,i,n,r,o)=>h=>{const l=h**3,c=(f=>3*f**2*(1-f))(h),u=(f=>3*f*(1-f)**2)(h),d=(f=>(1-f)**3)(h);return new C(r*l+i*c+e*u+a*d,o*l+n*c+s*u+t*d)},ah=a=>a**2,hh=a=>2*a*(1-a),lh=a=>(1-a)**2,vu=(a,t,e,s,i,n,r,o)=>h=>{const l=ah(h),c=hh(h),u=lh(h),d=3*(u*(e-a)+c*(i-e)+l*(r-i)),f=3*(u*(s-t)+c*(n-s)+l*(o-n));return Math.atan2(f,d)},yu=(a,t,e,s,i,n)=>r=>{const o=ah(r),h=hh(r),l=lh(r);return new C(i*o+e*h+a*l,n*o+s*h+t*l)},_u=(a,t,e,s,i,n)=>r=>{const o=1-r,h=2*(o*(e-a)+r*(i-e)),l=2*(o*(s-t)+r*(n-s));return Math.atan2(l,h)},ch=(a,t,e)=>{let s=new C(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=Zi(s.x,s.y,r.x,r.y),s=r}return i},wu=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=w({},n),o=.01,h=0;const l=a.iterator,c=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=Zi(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return w(w({},r),{},{angle:c(h)})},Ir=a=>{let t,e,s=0,i=0,n=0,r=0,o=0;const h=[];for(const l of a){const c={x:i,y:n,command:l[0],length:0};switch(l[0]){case"M":e=c,e.x=r=i=l[1],e.y=o=n=l[2];break;case"L":e=c,e.length=Zi(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=oh(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=c,e.iterator=t,e.angleFinder=vu(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=ch(t,i,n),i=l[5],n=l[6];break;case"Q":t=yu(i,n,l[1],l[2],l[3],l[4]),e=c,e.iterator=t,e.angleFinder=_u(i,n,l[1],l[2],l[3],l[4]),e.length=ch(t,i,n),i=l[3],n=l[4];break;case"Z":e=c,e.destX=r,e.destY=o,e.length=Zi(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},uh=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ir(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 w(w({},new C(i.x,i.y).lerp(new C(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return w(w({},new C(i.x,i.y).lerp(new C(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return wu(i,t)}},xu=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),dh=new RegExp(gu,"g"),Su=new RegExp(le,"gi"),Cu={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},fh=a=>{var t;const e=[],s=(t=a.match(xu))!==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=Cu[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){dh.lastIndex=0;for(let h=null;h=dh.exec(i);)o.push(...h.slice(1))}else o=i.match(Su)||[];for(let h=0;h<o.length;h+=r){const l=new Array(r),c=pu[n];l[0]=h>0&&c?c:n;for(let u=0;u<r;u++)l[u+1]=parseFloat(o[h+u]);e.push(l)}}return e},Au=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new C(a[0]),s=new C(a[1]),i=1,n=0;const r=[],o=a.length,h=o>2;let l;for(h&&(i=a[2].x<s.x?-1:a[2].x===s.x?0:1,n=a[2].y<s.y?-1:a[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),l=1;l<o;l++){if(!e.eq(s)){const c=e.midPointFrom(s);r.push(["Q",e.x,e.y,c.x,c.y])}e=a[l],l+1<a.length&&(s=a[l+1])}return h&&(i=e.x>a[l-2].x?1:e.x===a[l-2].x?0:-1,n=e.y>a[l-2].y?1:e.y===a[l-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},gh=(a,t)=>a.map((e=>e.map(((s,i)=>i===0||t===void 0?s:et(s,t))).join(" "))).join(" ");function Qi(a,t){const e=a.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach((s=>{let[i,n]=s;return e.setProperty(i,n)})))}const Tu=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function ph(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||Ze,s=new(Ws()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=Ze};if(i&&i.aborted)throw new qn("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=Ze)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const tn=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=ts(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Ft,i),s.set(qt,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,X,X)};var Eu=Object.freeze({__proto__:null,addTransformToObject:Qo,animate:Tr,animateColor:Ma,applyTransformToObject:Es,calcAngleBetweenVectors:zi,calcDimensionsMatrix:qs,calcPlaneChangeMatrix:Qs,calcVectorRotation:xa,cancelAnimFrame:jo,capValue:os,composeMatrix:Vo,copyCanvasElement:a=>{var t;const e=Kt(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:re,createCanvasElement:ye,createImage:Bo,createRotateMatrix:es,createScaleMatrix:Oi,createSkewXMatrix:or,createSkewYMatrix:ar,createTranslateMatrix:Cs,createVector:Bi,crossProduct:ks,degreesToRadians:lt,dotProduct:Sa,ease:gc,enlivenObjectEnlivables:Js,enlivenObjects:As,findScaleToCover:ih,findScaleToFit:sh,getBoundsOfCurve:Fr,getOrthonormalVector:_r,getPathSegmentsInfo:Ir,getPointOnPath:uh,getPointer:Jo,getRandomInt:Tu,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-ze;a%2==0&&(s+=e/2);const i=new Array(a+1);for(let n=0;n<a;n++){const r=n*e+s,{x:o,y:h}=new C(re(r),oe(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:Au,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:Gi,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new Jt(a,t),hasStyleChanged:Yi,invertTransform:Wt,isBetweenVectors:wr,isIdentityMatrix:Ho,isTouchEvent:Di,isTransparent:ja,joinPath:gh,loadImage:Ks,magnitude:Hi,makeBoundingBoxFromPoints:we,makePathSimpler:rh,matrixToSVG:Ts,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 Jt([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:gt,multiplyTransformMatrixArray:Pi,parsePath:fh,parsePreserveAspectRatioAttribute:gr,parseUnit:Nt,pick:ss,projectStrokeOnPoints:za,qrDecompose:ts,radiansToDegrees:_e,removeFromArray:Qe,removeTransformFromObject:(a,t)=>{const e=Wt(t),s=gt(e,a.calcOwnMatrix());Es(a,s)},removeTransformMatrixForSvgParsing:tn,request:ph,requestAnimFrame:$s,resetObjectTransform:ta,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:yr,saveObjectTransform:cr,sendObjectToPlane:ur,sendPointToPlane:ns,sendVectorToPlane:ea,setStyle:Qi,sin:oe,sizeAfterTransform:Ri,string:Vc,stylesFromArray:Xa,stylesToArray:Va,toBlob:rr,toDataURL:nr,toFixed:et,transformPath:(a,t,e)=>(e&&(t=gt(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}=Tt({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i}))),transformPoint:Tt});class ku extends Ko{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=ye();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=_s().createElement("div");return t.setAttribute("data-fabric","wrapper"),Qi(t,{position:"relative"}),qo(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;Qi(t,w(w({},s),{},{"touch-action":i?"manipulation":Lt})),qo(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;$o(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),lr(this.upper.el,t),lr(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(),ve().dispose(this.upper.el),delete this.upper,delete this.container}}class en extends Zs{constructor(){super(...arguments),x(this,"targets",[]),x(this,"_hoveredTargets",[]),x(this,"_currentTransform",null),x(this,"_groupSelector",null),x(this,"contextTopDirty",!1)}static getDefaults(){return w(w({},super.getDefaults()),en.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 ku(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 ja(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===Ti||e===Ft||e===qt||e===Ys?i=this.centeredScaling||t.centeredScaling:e===er&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=ft:["mr","tr","br"].includes(e)&&(s.x=Z),["tl","mt","tr"].includes(e)?s.y=Qn:["bl","mb","br"].includes(e)&&(s.y=Xt)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?ns(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},h=s&&o?(i=o.getActionHandler(t,e,o))===null||i===void 0?void 0:i.bind(o):nc,l=((f,g,p,b)=>{if(!g||!f)return"drag";const m=b.controls[g];return m.getActionName(p,m,b)})(s,r,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,l,c)?{x:X,y:X}:this._getOriginFromCorner(e,r),d={target:e,action:l,actionHandler:h,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:u.x,originY:u.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:lt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:c,original:w(w({},cr(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new C(e,s).transform(this.viewportTransform),o=new C(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=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(l,c,u-l,d-c)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,c+=h,u-=h,d-=h,Et.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,c,u-l,d-c))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,Di(t))||i.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const n=this.targets;this.targets=[];const r=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&r&&r!==s?(this.targets=n,s):r}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,o,h,l]=s,c=Math.atan2(o.y-r.y,o.x-r.x),u=re(c)*n,d=oe(c)*n,f=u+d,g=u-d;s=[new C(r.x-g,r.y-f),new C(o.x+f,o.y-g),new C(h.x+g,h.y+f),new C(l.x-f,l.y+g)]}return ht.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,ns(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const i=t[s];if(this._checkTarget(i,e)){if(Mi(i)&&i.subTargetCheck){const n=this._searchPossibleTargets(i._objects,e);n&&this.targets.push(n)}return i}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&Mi(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!Mi(r)||!r.interactive)return r}return i[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=Jo(t),r=i.width||0,o=i.height||0;r&&o||(Xt in i&&Qn in i&&(o=Math.abs(i.top-i.bottom)),ft in i&&Z 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=ns(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new C(1,1):new C(s.width/r,s.height/o);return n.multiply(l)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=ye(),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 is(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach((h=>{n.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),o.push(h))})),n.forEach((h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),r.push(h))})),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:o})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:o})),i&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),i=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),i}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,is(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),is(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(Ei,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;is(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&&is(e)&&this._activeObject===e){const s=ss(t,["angle","flipX","flipY",Z,Ft,qt,ws,xs,Xt]);return Qo(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}x(en,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class Mu{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),Qe(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 Pu=["target","oldTarget","fireCanvas","e"],Zt={passive:!1},Rs=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},We=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)},se=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)},Ou={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 Nr extends en{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),x(this,"_isClick",void 0),x(this,"textEditingManager",new Mu(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(We,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Yo(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,Zt),t(s,"".concat(i,"out"),this._onMouseOut),t(s,"".concat(i,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,Zt)}removeListeners(){this.addOrRemove(se,"remove");const t=this._getEventPrefix(),e=ae(this.upperCanvasEl);se(e,"".concat(t,"up"),this._onMouseUp),se(e,"touchend",this._onTouchEnd,Zt),se(e,"".concat(t,"move"),this._onMouseMove,Zt),se(e,"touchmove",this._onMouseMove,Zt),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=w({e:t},Rs(this,t));this.fire("mouse:out",w(w({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",w({},s)),this._hoveredTargets.forEach((i=>{this.fire("mouse:out",w(w({},s),{},{target:i})),i&&i.fire("mouseout",w({},s))})),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",w({e:t},Rs(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 We(this.upperCanvasEl,"drag",this._onDragProgress)}Zo(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e?.clearContextTop(),s!==e&&s?.clearContextTop();const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),i=!0),s&&(r.save(),s.transform(r),s.renderDropTargetEffect(t),r.restore(),i=!0),r.restore(),i&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==Lt,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};se(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let h=0;h<i.length;h++){const l=i[h];l.canDrop(t)&&(o=l),l.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",w({e:t,target:e,subTargets:s,dragSource:this._dragSource},Rs(this,t)));i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&Zo(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=ae(i);We(r,"touchend",this._onTouchEnd,Zt),e&&We(r,"touchmove",this._onMouseMove,Zt),se(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();se(e,"".concat(s,"move"),this._onMouseMove,Zt);const i=ae(e);We(i,"".concat(s,"up"),this._onMouseUp),We(i,"".concat(s,"move"),this._onMouseMove,Zt)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=ae(this.upperCanvasEl);se(s,"touchend",this._onTouchEnd,Zt),se(s,"touchmove",this._onMouseMove,Zt),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((()=>{We(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0}),400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=ae(this.upperCanvasEl);se(i,"".concat(s,"up"),this._onMouseUp),se(i,"".concat(s,"move"),this._onMouseMove,Zt),We(e,"".concat(s,"move"),this._onMouseMove,Zt)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,n=this._target,{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o,h,l=!1;if(s&&(this._finalizeCurrentTransform(t),l=s.actionPerformed),!i){const c=n===this._activeObject;this.handleSelection(t),l||(l=this._shouldRender(n)||!c&&n===this._activeObject)}if(n){const c=n.findControl(this.getViewportPoint(t),Di(t)),{key:u,control:d}=c||{};if(h=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),l=!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!==h)){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),l?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e,s){const i=this._target,n=this.targets||[],r=w(w(w({e:t,target:i,subTargets:n},Rs(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let o=0;o<n.length;o++)n[o]!==i&&n[o].fire("mouse".concat(e),r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const o=this.getScenePoint(t);this._groupSelector={x:o.x,y:o.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const o=e.findControl(this.getViewportPoint(t),Di(t));if(e===this._activeObject&&(o||!r)){this._setupCurrentTransform(t,e,s);const h=o?o.control:void 0,l=this.getScenePoint(t),c=h&&h.getMouseDownHandler(t,e,h);c&&c.call(h,t,this._currentTransform,l.x,l.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=ns(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let o=0;o<r;o++)n[o]===e||i[o]&&i[o]===s||this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",w(w({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",w(w({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=it(e,Pu);const{targetIn:h,targetOut:l,canvasIn:c,canvasOut:u}=Ou[t],d=i!==s;if(i&&d){const f=w(w({},o),{},{e:r,target:i,nextTarget:s},Rs(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&d){const f=w(w({},o),{},{e:r,target:s,previousTarget:i},Rs(this,r));n&&this.fire(c,f),s.fire(h,f)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?ns(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=is(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const r=n.control;this.setCursor(r.cursorStyleHandler(t,r,e))}else e.subTargetCheck&&this.targets.concat().reverse().map((r=>{s=r.hoverCursor||s})),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,i=is(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||i)&&(i||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(i){const n=s.getObjects();if(e===s){const r=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(n,r)||this.searchPossibleTargets(this._objects,r))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(n,t)}else{s.isEditing&&s.exitEditing();const n=new(F.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 C(e,s),o=r.add(new C(i,n)),h=r.min(o),l=r.max(o).subtract(h),c=this.collectObjects({left:h.x,top:h.y,width:l.x,height:l.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=F.getClass("ActiveSelection");this.setActiveObject(new d(u,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const mh={x1:0,y1:0,x2:0,y2:0},Du=w(w({},mh),{},{r1:0,r2:0}),Ls=(a,t)=>isNaN(a)&&typeof t=="number"?t:a;function bh(a){return a&&/%$/.test(a)&&Number.isFinite(parseFloat(a))}function vh(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(bh(a)?100:1):NaN;return os(0,Ls(e,t),1)}const Ru=/\s*;\s*/,Lu=/\s*:\s*/;function Fu(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(Ru);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(Lu).map((c=>c.trim()));h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}const n=new tt(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:vh(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Ls(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function Iu(a,t){const e=[],s=a.getElementsByTagName("stop"),i=vh(t,1);for(let n=s.length;n--;)e.push(Fu(s[n],i));return e}function yh(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function _h(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function ue(a,t){return a.getAttribute(t)}function Nu(a,t){return(function(e,s){let i,{width:n,height:r,gradientUnits:o}=s;return Object.entries(e).reduce(((h,l)=>{let[c,u]=l;if(u==="Infinity")i=1;else if(u==="-Infinity")i=0;else{const d=typeof u=="string";i=d?parseFloat(u):u,d&&bh(u)&&(i*=.01,o==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(i*=n),c!=="y1"&&c!=="y2"||(i*=r)))}return h[c]=i,h}),{})})(yh(a)==="linear"?(function(e){return{x1:ue(e,"x1")||0,y1:ue(e,"y1")||0,x2:ue(e,"x2")||"100%",y2:ue(e,"y2")||0}})(a):(function(e){return{x1:ue(e,"fx")||ue(e,"cx")||"50%",y1:ue(e,"fy")||ue(e,"cy")||"50%",r1:0,x2:ue(e,"cx")||"50%",y2:ue(e,"cy")||"50%",r2:ue(e,"r")||"50%"}})(a),w(w({},t),{},{gradientUnits:_h(a)}))}class hi{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:w(w({},e==="radial"?Du:mh),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(Ve()):Ve()})}addColorStop(t){for(const e in t){const s=new tt(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return w(w({},ss(this,t)),{},{type:this.type,coords:w({},this.coords),colorStops:this.colorStops.map((e=>w({},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():Rt.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map((u=>w({},u))).sort(((u,d)=>u.offset-d.offset));let o=-this.offsetX,h=-this.offsetY;var l;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const c=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(Ts(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:d,x2:f,y2:g}=this.coords;s.push("<linearGradient ",c,' x1="',u,'" y1="',d,'" x2="',f,'" y2="',g,`">
|
|
42
|
+
`)}else if(this.type==="radial"){const{x1:u,y1:d,x2:f,y2:g,r1:p,r2:b}=this.coords,m=p>b;s.push("<radialGradient ",c,' cx="',m?u:f,'" cy="',m?d:g,'" r="',m?p:b,'" fx="',m?f:u,'" fy="',m?g:d,`">
|
|
43
|
+
`),m&&(r.reverse(),r.forEach((y=>{y.offset=1-y.offset})));const v=Math.min(p,b);if(v>0){const y=v/Math.max(p,b);r.forEach((_=>{_.offset+=y*(1-_.offset)}))}}return r.forEach((u=>{let{color:d,offset:f,opacity:g}=u;s.push("<stop ",'offset="',100*f+"%",'" style="stop-color:',d,g!==void 0?";stop-opacity: "+g:";",`"/>
|
|
44
44
|
`)})),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
|
|
45
|
-
`),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:o}=this.coords,h=this.type==="linear"?t.createLinearGradient(e,s,i,n):t.createRadialGradient(e,s,r,i,n,o);return this.colorStops.forEach((l=>{let{color:c,opacity:
|
|
46
|
-
`)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=
|
|
47
|
-
`)]}_getOffsetTransform(){const t=
|
|
48
|
-
`];{const{radius:e}=this,s=lt(this.startAngle),i=lt(this.endAngle),n=
|
|
49
|
-
`]}}static async fromElement(t,e,s){const i=
|
|
50
|
-
`)]}static async fromElement(t,e,s){const i=
|
|
51
|
-
`)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,
|
|
52
|
-
`)]}_render(t){const e=this.points.length,s=this.pathOffset.x,i=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-i);for(let n=0;n<e;n++){const r=this.points[n];t.lineTo(r.x-s,r.y-i)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(
|
|
53
|
-
`)}const Au=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let io;class Pt extends Xh{static getDefaults(){return S(S({},super.getDefaults()),Pt.ownDefaults)}constructor(t,e){super(),C(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=Zr(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(Te)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,o;for(let h=0,l=this._textLines.length;h<l;h++)if((this.textAlign===Te||h!==l-1&&!this.isEndOfWrapping(h))&&(i=0,n=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(o=this.textLines[h].match(this._reSpacesAndTabs)))){s=o.length,t=(this.width-e)/s;for(let c=0;c<=n.length;c++)r=this.__charBounds[h][c],this._reSpaceAndTab.test(n[c])?(r.width+=t,r.kernedWidth+=t,r.left+=i,i+=t):r.left+=i}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let i;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===Bt?(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=Yt;break;case"descender":t.textBaseline=pr}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,s,i,n,r){this._renderChars(t,e,s,i,n,r)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let i=this._getTopOffset();for(let n=0,r=this._textLines.length;n<r;n++){const o=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=o;continue}const h=this._textLines[n].length,l=this._getLineLeftOffset(n);let c,d,u=0,f=0,g=this.getValueOfPropertyAt(n,0,"textBackgroundColor");const p=this.getHeightOfLineImpl(n);for(let y=0;y<h;y++){const m=this.__charBounds[n][y];d=this.getValueOfPropertyAt(n,y,"textBackgroundColor"),this.path?(t.save(),t.translate(m.renderLeft,m.renderTop),t.rotate(m.angle),t.fillStyle=d,d&&t.fillRect(-m.width/2,-p*(1-this._fontSizeFraction),m.width,p),t.restore()):d!==g?(c=s+l+f,this.direction==="rtl"&&(c=this.width-c-u),t.fillStyle=g,g&&t.fillRect(c,i,u,p),f=m.left,u=m.width,g=d):u+=m.kernedWidth}d&&!this.path&&(c=s+l+f,this.direction==="rtl"&&(c=this.width-c-u),t.fillStyle=d,t.fillRect(c,i,u,p)),i+=o}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=si.getFontCache(e),r=this._getFontDeclaration(e),o=s+t,h=s&&r===this._getFontDeclaration(i),l=e.fontSize/this.CACHE_FONT_SIZE;let c,d,u,f;if(s&&n.has(s)&&(u=n.get(s)),n.has(t)&&(f=c=n.get(t)),h&&n.has(o)&&(d=n.get(o),f=d-u),c===void 0||u===void 0||d===void 0){const g=(function(){return io||(io=Qt({width:0,height:0}).getContext("2d")),io})();this._setTextStyles(g,e,!0),c===void 0&&(f=c=g.measureText(t).width,n.set(t,c)),u===void 0&&h&&s&&(u=g.measureText(s).width,n.set(s,u)),h&&d===void 0&&(d=g.measureText(o).width,n.set(o,d),f=d-u)}return{width:c*l,kernedWidth:f*l}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,i=0;const n=this.pathSide===ft,r=this.path,o=this._textLines[t],h=o.length,l=new Array(h);this.__charBounds[t]=l;for(let c=0;c<h;c++){const d=o[c];s=this._getGraphemeBox(d,t,c,e),l[c]=s,i+=s.kernedWidth,e=d}if(l[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let c=0;const d=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case J:c=n?d-i:0;break;case U:c=(d-i)/2;break;case ft:c=n?0:d-i}c+=this.pathStartOffset*(n?-1:1);for(let u=n?h-1:0;n?u>=0:u<h;n?u--:u++)s=l[u],c>d?c%=d:c<0&&(c+=d),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=Lh(i.path,s,i.segmentsInfo);e.renderLeft=n.x-i.pathOffset.x,e.renderTop=n.y-i.pathOffset.y,e.angle=n.angle+(this.pathSide===ft?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),o=i?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,r,i,o);let l,c=h.kernedWidth,d=h.width;this.charSpacing!==0&&(l=this._getWidthOfCharSpacing(),d+=l,c+=l);const u={width:d,left:0,height:r.fontSize,kernedWidth:c,deltaY:r.deltaY};if(s>0&&!n){const f=this.__charBounds[e][s-1];u.left=f.left+f.width+h.kernedWidth-h.width}return u}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==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const i=this._getLeftOffset(),n=this._getTopOffset();for(let r=0,o=this._textLines.length;r<o;r++)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(yt))&&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(Te),h=this.path,l=!o&&this.charSpacing===0&&this.isEmptyStyles(r)&&!h,c=this.direction==="ltr",d=this.direction==="ltr"?1:-1,u=e.direction;let f,g,p,y,m,b="",v=0;if(e.save(),u!==this.direction&&(e.canvas.setAttribute("dir",c?"ltr":"rtl"),e.direction=c?"ltr":"rtl",e.textAlign=c?J:ft),n-=this.getHeightOfLineImpl(r)*this._fontSizeFraction,l)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let _=0,w=s.length-1;_<=w;_++)y=_===w||this.charSpacing||h,b+=s[_],p=this.__charBounds[r][_],v===0?(i+=d*(p.kernedWidth-p.width),v+=p.width):v+=p.kernedWidth,o&&!y&&this._reSpaceAndTab.test(s[_])&&(y=!0),y||(f=f||this.getCompleteStyleDeclaration(r,_),g=this.getCompleteStyleDeclaration(r,_+1),y=hn(f,g,!1)),y&&(h?(e.save(),e.translate(p.renderLeft,p.renderTop),e.rotate(p.angle),this._renderChar(t,e,r,_,b,-v/2,0),e.restore()):(m=i,this._renderChar(t,e,r,_,b,m,n)),b="",f=g,i+=d*v,v=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=Qt({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 re(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(i=-this.width/2,n=-this.height/2,t.translate(i,n),t[e]=this._applyPatternGradientTransformText(s),{offsetX:i,offsetY:n}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:i}=e;return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,i,n,r,o){const h=this._getStyleDeclaration(s,i),l=this.getCompleteStyleDeclaration(s,i),c=t==="fillText"&&l.fill,d=t==="strokeText"&&l.stroke&&l.strokeWidth;if(d||c){if(e.save(),e.font=this._getFontDeclaration(l),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(o+=h.deltaY),c){const u=this._setFillStyles(e,l);e.fillText(n,r-u.offsetX,o-u.offsetY)}if(d){const u=this._setStrokeStyles(e,l);e.strokeText(n,r-u.offsetX,o-u.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===Te||i===ui&&!r||i===di&&!r||i===Zi&&!r?0:(i===U&&(o=s/2),i===ft&&(o=s),i===ui&&(o=s/2),i===di&&(o=s),n==="rtl"&&(i===ft||i===Te||i===di?o=0:i===J||i===Zi?o=-s:i!==U&&i!==ui||(o=-s/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var i;return(i=this._getStyleDeclaration(t,e)[s])!==null&&i!==void 0?i:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const i=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),o=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let l=0,c=this._textLines.length;l<c;l++){const d=this.getHeightOfLine(l);if(!this[e]&&!this.styleHas(e,l)){s+=d;continue}const u=this._textLines[l],f=d/this.lineHeight,g=this._getLineLeftOffset(l);let p=0,y=0,m=this.getValueOfPropertyAt(l,0,e),b=this.getValueOfPropertyAt(l,0,yt),v=this.getValueOfPropertyAt(l,0,ds),_=m,w=b,x=v;const T=s+f*(1-this._fontSizeFraction);let A=this.getHeightOfChar(l,0),k=this.getValueOfPropertyAt(l,0,"deltaY");for(let F=0,M=u.length;F<M;F++){const P=this.__charBounds[l][F];_=this.getValueOfPropertyAt(l,F,e),w=this.getValueOfPropertyAt(l,F,yt),x=this.getValueOfPropertyAt(l,F,ds);const B=this.getHeightOfChar(l,F),O=this.getValueOfPropertyAt(l,F,"deltaY");if(n&&_&&w){const L=this.fontSize*x/1e3;t.save(),t.fillStyle=b,t.translate(P.renderLeft,P.renderTop),t.rotate(P.angle),t.fillRect(-P.kernedWidth/2,h*B+O-o*L,P.kernedWidth,L),t.restore()}else if((_!==m||w!==b||B!==A||x!==v||O!==k)&&y>0){const L=this.fontSize*v/1e3;let H=i+g+p;this.direction==="rtl"&&(H=this.width-H-y),m&&b&&v&&(t.fillStyle=b,t.fillRect(H,T+h*A+k-o*L,y,L)),p=P.left,y=P.width,m=_,v=x,b=w,A=B,k=O}else y+=P.kernedWidth}let R=i+g+p;this.direction==="rtl"&&(R=this.width-R-y),t.fillStyle=w;const D=this.fontSize*x/1e3;_&&w&&x&&t.fillRect(R,T+h*A+k-o*D,y-r,D),s+=d}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||Pt.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return an(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
|
|
54
|
-
`];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return
|
|
55
|
-
`]}_getSVGTextAndBg(a,t){const e=[],s=[];let i,n=a;this.backgroundColor&&s.push(...so(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=q.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,a!==a.trim()||!!a.match(Su)),o=r?'style="'.concat(r,'"'):"",h=t.deltaY,l=h?' dy="'.concat(st(h,n),'" '):"",{angle:c,renderLeft:d,renderTop:u,width:f}=i;let g="";if(d!==void 0){const p=f/2;c&&(g=' rotate="'.concat(st(Ce(c),n),'"'));const y=as({angle:Ce(c)});y[4]=d,y[5]=u;const m=new E(-p,0).transform(y);e=m.x,s=m.y}return'<tspan x="'.concat(st(e,n),'" y="').concat(st(s,n),'" ').concat(l).concat(g).concat(o,">").concat(ch(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Te),r=this._textLines[t];let o,h,l,c,d,u="",f=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let g=0,p=r.length-1;g<=p;g++)d=g===p||this.charSpacing||this.path,u+=r[g],l=this.__charBounds[t][g],f===0?(e+=l.kernedWidth-l.width,f+=l.width):f+=l.kernedWidth,n&&!d&&this._reSpaceAndTab.test(r[g])&&(d=!0),d||(o=o||this.getCompleteStyleDeclaration(t,g),h=this.getCompleteStyleDeclaration(t,g+1),d=hn(o,h,!0)),d&&(c=this._getStyleDeclaration(t,g),a.push(this._createTextCharSpan(u,c,e,s,l)),u="",o=h,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(a,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,o=0,h=0,l=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let c=0;c<i.length;c++){const{left:d,width:u,kernedWidth:f}=this.__charBounds[t][c];r=this.getValueOfPropertyAt(t,c,"textBackgroundColor"),r!==l?(l&&a.push(...so(l,e+h,s,o,n)),h=d,o=u,l=r):o+=f}r&&a.push(...so(l,e+h,s,o,n))}_getSVGLineTopOffset(a){let t,e=0;for(t=0;t<a;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(a){return"".concat(super.getSvgStyles(a)," text-decoration-thickness: ").concat(st(this.textDecorationThickness*this.getObjectScaling().y/10,q.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(a,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:o,fontWeight:h,deltaY:l,textDecorationThickness:c,linethrough:d,overline:u,underline:f}=a,g=this.getSvgTextDecoration({underline:f??this.underline,overline:u??this.overline,linethrough:d??this.linethrough}),p=c||this.textDecorationThickness;return[i?ci(Bt,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",o?"font-style: ".concat(o,"; "):"",h?"font-weight: ".concat(h,"; "):"",g?"text-decoration: ".concat(g,"; text-decoration-thickness: ").concat(st(p*this.getObjectScaling().y/10,q.NUM_FRACTION_DIGITS),"%; "):"",n?ci(yt,n):"",l?"baseline-shift: ".concat(-l,"; "):"",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 Tu{constructor(t){C(this,"target",void 0),C(this,"__mouseDownInPlace",!1),C(this,"__dragStartFired",!1),C(this,"__isDraggingOver",!1),C(this,"__dragStartSelection",void 0),C(this,"__dragImageDisposer",void 0),C(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach((s=>s())),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,o=r.canvas,h=new E(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),c=new E(l.left+l.leftOffset,l.top+l.topOffset).multiply(h).transform(r.calcTransformMatrix()),d=o.getScenePoint(t).subtract(c),u=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),g=c.subtract(new E(f.left,f.top)),p=o.viewportTransform,y=g.add(d).transform(p,!0),m=r.backgroundColor,b=Ur(r.styles);r.backgroundColor="";const v={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(v,0,i),r.setSelectionStyles(v,n,r.text.length),r.dirty=!0;const _=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=m,r.styles=b,r.dirty=!0,gn(_,{position:"fixed",left:"".concat(-_.width,"px"),border:Ft,width:"".concat(_.width/u,"px"),height:"".concat(_.height/u,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{_.remove()},fe(t.target||this.target.hiddenTextarea).body.appendChild(_),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(_,y.x,y.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=S({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,o=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},c=n[Math.max(0,n.length-1)],d=0;if(this.__dragStartSelection){const u=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;h>u&&h<=f?h=u:h>f&&(h-=f-u),r.removeChars(u,f),delete this.__dragStartSelection}r._reNewline.test(c)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,l,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+d,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(ji,{index:h+d,action:"drop"}),o.fire("text:changed",{target:r}),o.contextTopDirty=!0,o.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:o}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||Ft;h===Ft?(i.selectionStart=r,i.selectionEnd=o,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),h==="move"&&(i.removeChars(r,o),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(ji,{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 Yh=/[ \n\.,;!\?\-]/;class Eu extends Pt{constructor(){super(...arguments),C(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return Gr({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||!mr.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!Yh.test(n);)i+=e,n=s[i];return e===-1&&Yh.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;fe(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&i!==n||i!==s&&n!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const i=s.slice(0,t),n=this.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=s.slice(t,e);return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,s){const i=s.slice(0,t).join("").length;return t===e?{selectionStart:i,selectionEnd:i}:{selectionStart:i,selectionEnd:i+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex,r=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,o=e.leftOffset,h=this.getCanvasRetinaScaling(),l=this.canvas.upperCanvasEl,c=l.width/h,d=l.height/h,u=c-r,f=d-r,g=new E(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new E(l.clientWidth/c,l.clientHeight/d));return g.x<0&&(g.x=0),g.x>u&&(g.x=u),g.y<0&&(g.y=0),g.y>f&&(g.y=f),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:"".concat(g.x,"px"),top:"".concat(g.y,"px"),fontSize:"".concat(r,"px"),charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(zi),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let o=i;o<this._unwrappedTextLines[s].length;o++)delete this.styles[s][o];if(this.styles[n])for(let o=r;o<this._unwrappedTextLines[n].length;o++){const h=this.styles[n][o];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=h)}for(let o=s+1;o<=n;o++)delete this.styles[o];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const o=this.styles[s],h=r-i;for(let l=i;l<r;l++)delete o[l];for(const l in this.styles[s]){const c=parseInt(l,10);c>=r&&(o[c-h]=o[l],delete o[l])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const d in this.styles[t]){const u=parseInt(d,10);u>=e&&(h=!0,n[u-e]=this.styles[t][d],o&&e===0||delete this.styles[t][d])}let c=!1;for(h&&!o&&(this.styles[t+s]=n,c=!0),(c||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:S({},i[s-1])}:l?this.styles[t+s]={0:S({},l)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?S({},n):{};s||(s=1);for(const h in r){const l=parseInt(h,10);l>=e&&(n[l+s]=r[l],r[l-s]||delete n[l])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=S({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=S({},o)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let h=0;h<t.length;h++)t[h]===`
|
|
56
|
-
`?(o++,n[o]=0):n[o]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),o&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],o),r=1;r<o;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=J:this._selectionDirection===ft&&(this._selectionDirection=J,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===ft?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=ft:this._selectionDirection===J&&(this._selectionDirection=ft,this.selectionStart=e),this.selectionEnd=s)}}class ku extends Eu{initHiddenTextarea(){const t=this.canvas&&fe(this.canvas.getElement())||Ms(),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,h]=r;return e.setAttribute(o,h)}));const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(i,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(n,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map((r=>{let[o,h]=r;return e.addEventListener(o,this[h].bind(this))})),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(ji),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const o=this._splitTextIntoLines(s).graphemeText,h=this._text.length,l=o.length,c=this.selectionStart,d=this.selectionEnd,u=c!==d;let f,g,p,y,m=l-h;const b=this.fromStringToGraphemeSelection(i,n,s),v=c>b.selectionStart;u?(g=this._text.slice(c,d),m+=d-c):l<h&&(g=v?this._text.slice(d+m,d):this._text.slice(c,c-m));const _=o.slice(b.selectionEnd-m,b.selectionEnd);if(g&&g.length&&(_.length&&(f=this.getSelectionStyles(c,c+1,!1),f=_.map((()=>f[0]))),u?(p=c,y=d):v?(p=d-g.length,y=d):(p=d,y=d+g.length),this.removeStyleFromTo(p,y)),_.length){const{copyPasteData:w}=xe();e&&_.join("")===w.copiedText&&!q.disableStyleCopyPaste&&(f=w.copiedTextStyle),this.insertNewStyleBlock(_,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}=xe();t.copiedText=this.getSelectedText(),q.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,r),c=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-l.length+(1-c)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,l=s.length;h<l;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const c=r-i,d=r,u=Math.abs(c-e);o=Math.abs(d-e)<u?h:h-1;break}return n||(o=s.length-1),o}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===ft);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=us(0,this.selectionStart,i),this.selectionEnd=us(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===J?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let i;if(t.altKey)i=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this["findLineBoundary".concat(s)](this[e])}return i!==void 0&&this[e]!==i&&(this[e]=i,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=J,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===ft&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=J,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===J&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=ft,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=ft,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const $h=a=>!!a.button;class Mu extends ku{constructor(){super(...arguments),C(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 Tu(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&&!$h(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||$h(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($t(this.calcTransformMatrix())).add(new E(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let l=0;l<this._textLines.length&&s<=e.y;l++)s+=this.getHeightOfLine(l),n=l,l>0&&(i+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));let r=Math.abs(this._getLineLeftOffset(n));const o=this._textLines[n].length,h=this.__charBounds[n];for(let l=0;l<o;l++){const c=r+h[l].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 bn="moveCursorUp",vn="moveCursorDown",_n="moveCursorLeft",wn="moveCursorRight",xn="exitEditing",qh=(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])},Du=S({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:xn,27:xn,33:bn,34:vn,35:wn,36:_n,37:_n,38:bn,39:wn,40:vn},keysMapRtl:{9:xn,27:xn,33:bn,34:vn,35:_n,36:wn,37:wn,38:bn,39:_n,40:vn},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class Ue extends Mu{static getDefaults(){return S(S({},super.getDefaults()),Ue.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,S(S({},Ue.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 Qr&&this.canvas.textEditingManager.remove(this),e instanceof Qr&&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=Qt(t.canvas),r=n.getContext("2d"),qh(r,this.canvas);const o=this.calcTransformMatrix();r.transform(o[0],o[1],o[2],o[3],o[4],o[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const o of s){const h=o.clipPath,l=Qt(t.canvas),c=l.getContext("2d");if(qh(c,this.canvas),!h.absolutePositioned){const d=o.calcTransformMatrix();c.transform(d[0],d[1],d[2],d[3],d[4],d[5])}h.transform(c),h.drawObject(c,!0,{}),this.drawClipPathOnCache(r,h,l)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:s,top:i,leftOffset:n.left,topOffset:n.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:i,lineIndex:n}=this.get2DCursorLocation(t);for(let l=0;l<n;l++)e+=this.getHeightOfLine(l);const r=this._getLineLeftOffset(n),o=this.__charBounds[n][i];o&&(s=o.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===ft||this.textAlign===Te||this.textAlign===di?h.left*=-1:this.textAlign===J||this.textAlign===Zi?h.left=r-(s>0?s:0):this.textAlign!==U&&this.textAlign!==ui||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/o,l=this.getValueOfPropertyAt(i,n,"deltaY"),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-h/2,top:c+e.top+l,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:o,width:h,height:l}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,h,l)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const i=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(Te),o=this.get2DCursorLocation(i),h=this.get2DCursorLocation(n),l=o.lineIndex,c=h.lineIndex,d=o.charIndex<0?0:o.charIndex,u=h.charIndex<0?0:h.charIndex;for(let f=l;f<=c;f++){const g=this._getLineLeftOffset(f)||0;let p=this.getHeightOfLine(f),y=0,m=0,b=0;if(f===l&&(m=this.__charBounds[l][d].left),f>=l&&f<c)b=r&&!this.isEndOfWrapping(f)?this.width:this.getLineWidth(f)||5;else if(f===c)if(u===0)b=this.__charBounds[c][u].left;else{const T=this._getWidthOfCharSpacing();b=this.__charBounds[c][u-1].left+this.__charBounds[c][u-1].width-T}y=p,(this.lineHeight<1||f===c&&this.lineHeight>1)&&(p/=this.lineHeight);let v=s.left+g+m,_=p,w=0;const x=b-m;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",_=1,w=p):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===ft||this.textAlign===Te||this.textAlign===di?v=this.width-v-x:this.textAlign===J||this.textAlign===Zi?v=s.left+g-b:this.textAlign!==U&&this.textAlign!==ui||(v=s.left+g-b)),t.fillRect(v,s.top+s.topOffset+w,x,_),s.topOffset+=y}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,yt)}_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()}}C(Ue,"ownDefaults",Du),C(Ue,"type","IText"),I.setClass(Ue),I.setClass(Ue,"i-text");class ms extends Ue{static getDefaults(){return S(S({},super.getDefaults()),ms.ownDefaults)}constructor(t,e){super(t,S(S({},ms.ownDefaults),e))}static createControls(){return{controls:md()}}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(Te)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,i=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)t.graphemeText[i]===`
|
|
57
|
-
`&&r>0?(s=0,i++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[i])&&r>0&&(s++,i++),n[r]={line:e,offset:s},i+=t.graphemeLines[r].length,s+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,i=t+1,n=!1;const r=this._styleMap[t],o=this._styleMap[t+1];r&&(t=r.line,s=r.offset),o&&(i=o.line,n=i===t,e=o.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const l in h)for(const c in h[l]){const d=parseInt(c,10);if(d>=s&&(!n||d<e))for(const u in h[l][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 h=e?this.graphemeSplit(n):this.wordSplit(n);return h.length===0?[{word:[],width:0}]:h.map((l=>{const c=e?[l]:this.graphemeSplit(l),d=this._measureWord(c,r,o);return i=Math.max(d,i),o+=c.length+s.length,{word:c,width:d}}))})),largestWordWidth:i}}_measureWord(t,e){let s,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,n=0;for(let r=0,o=t.length;r<o;r++)n+=this._getGraphemeBox(t[r],e,r+i,s,!0).kernedWidth,s=t[r];return n}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:i,wordsData:n}=s,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const o=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,l=[],c=h?"":" ";let d=0,u=[],f=0,g=0,p=!0;e-=r;const y=Math.max(e,i,this.dynamicMinWidth),m=n[t];let b;for(f=0,b=0;b<m.length;b++){const{word:v,width:_}=m[b];f+=v.length,d+=g+_-o,d>y&&!p?(l.push(u),u=[],d=_,p=!0):d+=o,p||h||u.push(c),u=u.concat(v),g=h?0:this._measureWord([c],t,f),f++,p=!1}return b&&l.push(u),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),l}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}C(ms,"type","Textbox"),C(ms,"textLayoutProperties",[...Ue.textLayoutProperties,"width"]),C(ms,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),I.setClass(ms);class Kh extends un{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}=Ae(xh(s,i)),h=new E(r,o);if(i.absolutePositioned)return{center:cs(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:h};{const l=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:c=new E,correction:d=new E}=this.calcBoundingBox(e,t)||{};return{center:c.add(l),correction:d.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}C(Kh,"type","clip-path"),I.setClass(Kh);class Jh extends un{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new E(s.width||i.x,s.height||i.y)}}C(Jh,"type","fixed"),I.setClass(Jh);class Pu extends mi{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 ys extends te{static getDefaults(){return S(S({},super.getDefaults()),ys.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,ys.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new Pu})}_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)))?(Ie("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===$r?s.forEach((i=>{i._onAfterObjectsChange(cn,e)})):s.forEach((i=>{i._set("dirty",!0)}))}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=S(S({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}C(ys,"type","ActiveSelection"),C(ys,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),I.setClass(ys),I.setClass(ys,"activeSelection");class Ou{constructor(){C(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const o={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach((l=>{l.applyTo(o)}));const{imageData:h}=o;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),o}}class Zh{constructor(){let{tileSize:t=q.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};C(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),C(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=Qt({width:t,height:e}),i=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});i&&(i.clearColor(0,0,0,0),this.canvas=s,this.gl=i)}applyFilters(t,e,s,i,n,r){const o=this.gl,h=n.getContext("2d");if(!o||!h)return;let l;r&&(l=this.getCachedTexture(r,e));const 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,l?void 0:e),targetTexture:this.createTexture(o,s,i),originalTexture:l||this.createTexture(o,s,i,l?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},d=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,d),t.forEach((u=>{u&&u.applyTo(c)})),(function(u){const f=u.targetCanvas,g=f.width,p=f.height,y=u.destinationWidth,m=u.destinationHeight;g===y&&p===m||(f.width=y,f.height=m)})(c),this.copyGLTo2D(o,c),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(c.sourceTexture),o.deleteTexture(c.targetTexture),o.deleteFramebuffer(d),h.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:h,UNSIGNED_BYTE:l,CLAMP_TO_EDGE:c,TEXTURE_MAG_FILTER:d,TEXTURE_MIN_FILTER:u,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:g}=t,p=t.createTexture();return t.bindTexture(o,p),t.texParameteri(o,d,n||r),t.texParameteri(o,u,n||r),t.texParameteri(o,f,c),t.texParameteri(o,g,c),i?t.texImage2D(o,0,h,h,l,i):t.texImage2D(o,0,h,e,s,0,h,l,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),h=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,o);const l=new ImageData(h,i,n);s.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let no;function Lu(){const{WebGLProbe:a}=xe();return a.queryWebGL(Se()),q.enableGLFiltering&&a.isSupported(q.textureSize)?new Zh({tileSize:q.textureSize}):new Ou}function ro(){return!no&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(no=Lu()),no}const Ru=["filters","resizeFilter","src","crossOrigin","type"],Qh=["cropX","cropY"];class Ot extends Dt{static getDefaults(){return S(S({},super.getDefaults()),Ot.ownDefaults)}constructor(t,e){super(),C(this,"_lastScaleX",1),C(this,"_lastScaleY",1),C(this,"_filterScalingX",1),C(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Ot.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(Je()),this.setElement(typeof t=="string"?(this.canvas&&fe(this.canvas.getElement())||Ms()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(Ot.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=ro(!1);e instanceof Zh&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach((t=>{const e=this[t];e&&xe().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())})),S(S({},super.toObject([...Qh,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,i=-this.height/2;let n=[],r=[],o="",h="";if(!e)return[];if(this.hasCrop()){const l=Je();n.push('<clipPath id="imageCrop_'+l+`">
|
|
45
|
+
`),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:o}=this.coords,h=this.type==="linear"?t.createLinearGradient(e,s,i,n):t.createRadialGradient(e,s,r,i,n,o);return this.colorStops.forEach((l=>{let{color:c,opacity:u,offset:d}=l;h.addColorStop(d,u!==void 0?new tt(c).setAlpha(u).toRgba():c)})),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(w(w({},t),{},{colorStops:e?e.map((i=>w({},i))):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=_h(t),n=e._findCenterFromElement();return new this(w({id:t.getAttribute("id")||void 0,type:yh(t),coords:Nu(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:Iu(t,s.opacity),gradientUnits:i,gradientTransform:$i(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}x(hi,"type","Gradient"),F.setClass(hi,"gradient"),F.setClass(hi,"linear"),F.setClass(hi,"radial");const ju=["type","source","patternTransform"];class jr{get type(){return"pattern"}set type(t){Me("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 w(w({},ss(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:et(this.offsetX,K.NUM_FRACTION_DIGITS),offsetY:et(this.offsetY,K.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=Ls(this.offsetX/e,0),h=Ls(this.offsetY/s,0),l=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):Ls(i.width/e,0),c=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):Ls(i.height/s,0);return['<pattern id="SVGID_'.concat(r,'" x="').concat(o,'" y="').concat(h,'" width="').concat(l,'" height="').concat(c,'">'),'<image x="0" y="0" width="'.concat(i.width,'" height="').concat(i.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
|
|
46
|
+
`)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=it(t,ju);const o=await Ks(i,w(w({},e),{},{crossOrigin:r.crossOrigin}));return new this(w(w({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}x(jr,"type","Pattern"),F.setClass(jr),F.setClass(jr,"pattern");const Bu=["path","left","top"],Hu=["d"];class as extends Et{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=it(e,Bu);super(),Object.assign(this,as.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(Z,i),typeof n=="number"&&this.set(Xt,n)}_setPath(t,e){this.path=rh(Array.isArray(t)?t:fh(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new C(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const i of this.path)switch(i[0]){case"L":t.lineTo(i[1]+e,i[2]+s);break;case"M":t.moveTo(i[1]+e,i[2]+s);break;case"C":t.bezierCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s,i[5]+e,i[6]+s);break;case"Q":t.quadraticCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),{},{path:this.path.map((e=>e.slice()))})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=gh(this.path,K.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
|
|
47
|
+
`)]}_getOffsetTransform(){const t=K.NUM_FRACTION_DIGITS;return" translate(".concat(et(-this.pathOffset.x,t),", ").concat(et(-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,X,X)}_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(...Fr(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(...Fr(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 we(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return w(w({},t),{},{pathOffset:new C(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,s){const i=Le(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,w(w(w({},it(i,Hu)),e),{},{left:void 0,top:void 0}))}}x(as,"type","Path"),x(as,"cacheProperties",[...De,"path","fillRule"]),x(as,"ATTRIBUTE_NAMES",[...Xe,"d"]),F.setClass(as),F.setSVGClass(as);const zu=["left","top","radius"],wh=["radius","startAngle","endAngle","counterClockwise"];class Ie extends Et{static getDefaults(){return w(w({},super.getDefaults()),Ie.ownDefaults)}constructor(t){super(),Object.assign(this,Ie.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,lt(this.startAngle),lt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(Ft)}getRadiusY(){return this.get("radius")*this.get(qt)}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([...wh,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
|
|
48
|
+
`];{const{radius:e}=this,s=lt(this.startAngle),i=lt(this.endAngle),n=re(s)*e,r=oe(s)*e,o=re(i)*e,h=oe(i)*e,l=t>180?1:0,c=this.counterClockwise?0:1;return['<path d="M '.concat(n," ").concat(r," A ").concat(e," ").concat(e," 0 ").concat(l," ").concat(c," ").concat(o," ").concat(h,'" '),"COMMON_PARTS",` />
|
|
49
|
+
`]}}static async fromElement(t,e,s){const i=Le(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(w(w({},it(i,zu)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}x(Ie,"type","Circle"),x(Ie,"cacheProperties",[...De,...wh]),x(Ie,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),x(Ie,"ATTRIBUTE_NAMES",["cx","cy","r",...Xe]),F.setClass(Ie),F.setSVGClass(Ie);const Gu=["x1","y1","x2","y2"],Vu=["x1","y1","x2","y2"],Br=["x1","x2","y1","y2"];class hs extends Et{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,hs.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(Z,r),typeof o=="number"&&this.set(Xt,o)}_setWidthHeight(){const{x1:t,y1:e,x2:s,y2:i}=this;this.width=Math.abs(s-t),this.height=Math.abs(i-e);const{left:n,top:r,width:o,height:h}=we([{x:t,y:e},{x:s,y:i}]),l=new C(n+o/2,r+h/2);this.setPositionByOrigin(l,X,X)}_set(t,e){return super._set(t,e),Br.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;ee(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 C((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:i,width:n,height:r}=this,o=t<=e?-1:1,h=s<=i?-1:1;return{x1:o*n/2,x2:o*-n/2,y1:h*r/2,y2:h*-r/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(i,`" />
|
|
50
|
+
`)]}static async fromElement(t,e,s){const i=Le(t,this.ATTRIBUTE_NAMES,s),{x1:n=0,y1:r=0,x2:o=0,y2:h=0}=i;return new this([n,r,o,h],it(i,Gu))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=it(t,Vu);return this._fromObject(w(w({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}x(hs,"type","Line"),x(hs,"cacheProperties",[...De,...Br]),x(hs,"ATTRIBUTE_NAMES",Xe.concat(Br)),F.setClass(hs),F.setSVGClass(hs);class ls extends Et{static getDefaults(){return w(w({},super.getDefaults()),ls.ownDefaults)}constructor(t){super(),Object.assign(this,ls.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}x(ls,"type","Triangle"),x(ls,"ownDefaults",{width:100,height:100}),F.setClass(ls),F.setSVGClass(ls);const xh=["rx","ry"];class Ne extends Et{static getDefaults(){return w(w({},super.getDefaults()),Ne.ownDefaults)}constructor(t){super(),Object.assign(this,Ne.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(Ft)}getRy(){return this.get("ry")*this.get(qt)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...xh,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
|
|
51
|
+
`)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Pe,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=Le(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function Xu(a){if(!a)return[];const t=a.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}x(Ne,"type","Ellipse"),x(Ne,"cacheProperties",[...De,...xh]),x(Ne,"ownDefaults",{rx:0,ry:0}),x(Ne,"ATTRIBUTE_NAMES",[...Xe,"cx","cy","rx","ry"]),F.setClass(Ne),F.setSVGClass(Ne);const Wu=["left","top"],Sh={exactBoundingBox:!1};class de extends Et{static getDefaults(){return w(w({},super.getDefaults()),de.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,de.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(Z,s),typeof i=="number"&&this.set(Xt,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return za(this.points,t,this.isOpen())}_calcDimensions(t){t=w({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map((l=>l.projectedPoint)):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new C,strokeOffset:new C,strokeDiff:new C};const s=we(e),i=qs(w(w({},t),{},{scaleX:1,scaleY:1})),n=we(this.points.map((l=>Tt(l,i,!0)))),r=new C(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(lt(this.skewX)),h-=o*Math.tan(lt(this.skewY))),w(w({},s),{},{pathOffset:new C(o,h),strokeOffset:new C(n.left,n.top).subtract(new C(s.left,s.top)).multiply(r),strokeDiff:new C(s.width,s.height).subtract(new C(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=we(this.points);return new C(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:s,width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}=this._calcDimensions();this.set({width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}),t&&this.setPositionByOrigin(new C(e+i/2,s+n/2),X,X)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new C(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let r;if(Object.keys(t).some((o=>this.strokeUniform||this.constructor.layoutProperties.includes(o)))){var e,s;const{width:o,height:h}=this._calcDimensions(t);r=new C((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new C((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new C(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===Ft||t===qt)&&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 w(w({},super.toObject(t)),{},{points:this.points.map((e=>{let{x:s,y:i}=e;return{x:s,y:i}}))})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,i=K.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(et(this.points[n].x-e,i),",",et(this.points[n].y-s,i)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
|
|
52
|
+
`)]}_render(t){const e=this.points.length,s=this.pathOffset.x,i=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-i);for(let n=0;n<e;n++){const r=this.points[n];t.lineTo(r.x-s,r.y-i)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(Xu(t.getAttribute("points")),w(w({},it(Le(t,this.ATTRIBUTE_NAMES,s),Wu)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}x(de,"ownDefaults",Sh),x(de,"type","Polyline"),x(de,"layoutProperties",[ws,xs,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),x(de,"cacheProperties",[...De,"points"]),x(de,"ATTRIBUTE_NAMES",[...Xe]),F.setClass(de),F.setSVGClass(de);class sn extends de{isOpen(){return!1}}x(sn,"ownDefaults",Sh),x(sn,"type","Polygon"),F.setClass(sn),F.setSVGClass(sn);class Ch extends Et{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const i in e[s])for(const n in e[s][i])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const i in s)for(const n in s[i])if(s[i][n][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,r=!0,o=0;for(const h in e){s=0;for(const l in e[h]){const c=e[h][l]||{};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[h][l]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)o+=this._textLines[h].length;r&&n===o&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],Object.keys(s[n]).length===0&&delete s[n];Object.keys(s).length===0&&delete e[i]}}_extendStyles(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const n=hr(w(w({},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 w(w({},ss(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(Ch,"_styleProperties",rc);const Uu=/ +/g,Yu=/"/g;function Hr(a,t,e,s,i){return" ".concat((function(n,r){let{left:o,top:h,width:l,height:c}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:K.NUM_FRACTION_DIGITS;const d=ti(bt,n,!1),[f,g,p,b]=[o,h,l,c].map((m=>et(m,u)));return"<rect ".concat(d,' x="').concat(f,'" y="').concat(g,'" width="').concat(p,'" height="').concat(b,'"></rect>')})(a,{left:t,top:e,width:s,height:i}),`
|
|
53
|
+
`)}const $u=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let zr;class kt extends Ch{static getDefaults(){return w(w({},super.getDefaults()),kt.ownDefaults)}constructor(t,e){super(),x(this,"__charBounds",[]),Object.assign(this,kt.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=Ir(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(xe)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,o;for(let h=0,l=this._textLines.length;h<l;h++)if((this.textAlign===xe||h!==l-1&&!this.isEndOfWrapping(h))&&(i=0,n=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(o=this.textLines[h].match(this._reSpacesAndTabs)))){s=o.length,t=(this.width-e)/s;for(let c=0;c<=n.length;c++)r=this.__charBounds[h][c],this._reSpaceAndTab.test(n[c])?(r.width+=t,r.kernedWidth+=t,r.left+=i,i+=t):r.left+=i}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let i;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===It?(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 X:t.textBaseline="middle";break;case"ascender":t.textBaseline=Xt;break;case"descender":t.textBaseline=Qn}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,s,i,n,r){this._renderChars(t,e,s,i,n,r)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let i=this._getTopOffset();for(let n=0,r=this._textLines.length;n<r;n++){const o=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=o;continue}const h=this._textLines[n].length,l=this._getLineLeftOffset(n);let c,u,d=0,f=0,g=this.getValueOfPropertyAt(n,0,"textBackgroundColor");const p=this.getHeightOfLineImpl(n);for(let b=0;b<h;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+l+f,this.direction==="rtl"&&(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+l+f,this.direction==="rtl"&&(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+t,h=s&&r===this._getFontDeclaration(i),l=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)),h&&n.has(o)&&(u=n.get(o),f=u-d),c===void 0||d===void 0||u===void 0){const g=(function(){return zr||(zr=Kt({width:0,height:0}).getContext("2d")),zr})();this._setTextStyles(g,e,!0),c===void 0&&(f=c=g.measureText(t).width,n.set(t,c)),d===void 0&&h&&s&&(d=g.measureText(s).width,n.set(s,d)),h&&u===void 0&&(u=g.measureText(o).width,n.set(o,u),f=u-d)}return{width:c*l,kernedWidth:f*l}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,i=0;const n=this.pathSide===ft,r=this.path,o=this._textLines[t],h=o.length,l=new Array(h);this.__charBounds[t]=l;for(let c=0;c<h;c++){const u=o[c];s=this._getGraphemeBox(u,t,c,e),l[c]=s,i+=s.kernedWidth,e=u}if(l[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let c=0;const u=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case Z:c=n?u-i:0;break;case X:c=(u-i)/2;break;case ft:c=n?0:u-i}c+=this.pathStartOffset*(n?-1:1);for(let d=n?h-1:0;n?d>=0:d<h;n?d--:d++)s=l[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=uh(i.path,s,i.segmentsInfo);e.renderLeft=n.x-i.pathOffset.x,e.renderTop=n.y-i.pathOffset.y,e.angle=n.angle+(this.pathSide===ft?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),o=i?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,r,i,o);let l,c=h.kernedWidth,u=h.width;this.charSpacing!==0&&(l=this._getWidthOfCharSpacing(),u+=l,c+=l);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+h.kernedWidth-h.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==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const i=this._getLeftOffset(),n=this._getTopOffset();for(let r=0,o=this._textLines.length;r<o;r++)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(bt))&&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(xe),h=this.path,l=!o&&this.charSpacing===0&&this.isEmptyStyles(r)&&!h,c=this.direction==="ltr",u=this.direction==="ltr"?1:-1,d=e.direction;let f,g,p,b,m,v="",y=0;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",c?"ltr":"rtl"),e.direction=c?"ltr":"rtl",e.textAlign=c?Z:ft),n-=this.getHeightOfLineImpl(r)*this._fontSizeFraction,l)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let _=0,S=s.length-1;_<=S;_++)b=_===S||this.charSpacing||h,v+=s[_],p=this.__charBounds[r][_],y===0?(i+=u*(p.kernedWidth-p.width),y+=p.width):y+=p.kernedWidth,o&&!b&&this._reSpaceAndTab.test(s[_])&&(b=!0),b||(f=f||this.getCompleteStyleDeclaration(r,_),g=this.getCompleteStyleDeclaration(r,_+1),b=Yi(f,g,!1)),b&&(h?(e.save(),e.translate(p.renderLeft,p.renderTop),e.rotate(p.angle),this._renderChar(t,e,r,_,v,-y/2,0),e.restore()):(m=i,this._renderChar(t,e,r,_,v,m,n)),v="",f=g,i+=u*y,y=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=Kt({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 ee(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(i=-this.width/2,n=-this.height/2,t.translate(i,n),t[e]=this._applyPatternGradientTransformText(s),{offsetX:i,offsetY:n}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:i}=e;return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,i,n,r,o){const h=this._getStyleDeclaration(s,i),l=this.getCompleteStyleDeclaration(s,i),c=t==="fillText"&&l.fill,u=t==="strokeText"&&l.stroke&&l.strokeWidth;if(u||c){if(e.save(),e.font=this._getFontDeclaration(l),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(o+=h.deltaY),c){const d=this._setFillStyles(e,l);e.fillText(n,r-d.offsetX,o-d.offsetY)}if(u){const d=this._setStrokeStyles(e,l);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===xe||i===si&&!r||i===ei&&!r||i===ji&&!r?0:(i===X&&(o=s/2),i===ft&&(o=s),i===si&&(o=s/2),i===ei&&(o=s),n==="rtl"&&(i===ft||i===xe||i===ei?o=0:i===Z||i===ji?o=-s:i!==X&&i!==si||(o=-s/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var i;return(i=this._getStyleDeclaration(t,e)[s])!==null&&i!==void 0?i:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const i=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),o=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let l=0,c=this._textLines.length;l<c;l++){const u=this.getHeightOfLine(l);if(!this[e]&&!this.styleHas(e,l)){s+=u;continue}const d=this._textLines[l],f=u/this.lineHeight,g=this._getLineLeftOffset(l);let p=0,b=0,m=this.getValueOfPropertyAt(l,0,e),v=this.getValueOfPropertyAt(l,0,bt),y=this.getValueOfPropertyAt(l,0,rs),_=m,S=v,A=y;const T=s+f*(1-this._fontSizeFraction);let E=this.getHeightOfChar(l,0),O=this.getValueOfPropertyAt(l,0,"deltaY");for(let L=0,M=d.length;L<M;L++){const P=this.__charBounds[l][L];_=this.getValueOfPropertyAt(l,L,e),S=this.getValueOfPropertyAt(l,L,bt),A=this.getValueOfPropertyAt(l,L,rs);const j=this.getHeightOfChar(l,L),k=this.getValueOfPropertyAt(l,L,"deltaY");if(n&&_&&S){const R=this.fontSize*A/1e3;t.save(),t.fillStyle=v,t.translate(P.renderLeft,P.renderTop),t.rotate(P.angle),t.fillRect(-P.kernedWidth/2,h*j+k-o*R,P.kernedWidth,R),t.restore()}else if((_!==m||S!==v||j!==E||A!==y||k!==O)&&b>0){const R=this.fontSize*y/1e3;let G=i+g+p;this.direction==="rtl"&&(G=this.width-G-b),m&&v&&y&&(t.fillStyle=v,t.fillRect(G,T+h*E+O-o*R,b,R)),p=P.left,b=P.width,m=_,y=A,v=S,E=j,O=k}else b+=P.kernedWidth}let N=i+g+p;this.direction==="rtl"&&(N=this.width-N-b),t.fillStyle=S;const D=this.fontSize*A/1e3;_&&S&&A&&t.fillRect(N,T+h*E+O-o*D,b-r,D),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(",")||kt.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return Ui(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
|
|
54
|
+
`];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject([...pa,...t])),{},{styles:Va(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=Le(t,kt.ATTRIBUTE_NAMES,s),n=w(w({},e),i),{textAnchor:r=Z,textDecoration:o="",dx:h=0,dy:l=0,top:c=0,left:u=0,fontSize:d=Zn,strokeWidth:f=1}=n,g=it(n,$u),p=new this(Fi(t.textContent||"").trim(),w({left:u+h,top:c+l,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:d},g)),b=p.getScaledHeight()/p.height,m=((p.height+p.strokeWidth)*p.lineHeight-p.height)*b,v=p.getScaledHeight()+m;let y=0;return r===X&&(y=p.getScaledWidth()/2),r===ft&&(y=p.getScaledWidth()),p.set({left:p.left-y,top:p.top-(v-p.fontSize*(.07+p._fontSizeFraction))/p.lineHeight,strokeWidth:f}),p}static fromObject(t){return this._fromObject(w(w({},t),{},{styles:Xa(t.styles||{},t.text)}),{extraParam:"text"})}}x(kt,"textLayoutProperties",ga),x(kt,"cacheProperties",[...De,...pa]),x(kt,"ownDefaults",oc),x(kt,"type","Text"),x(kt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),x(kt,"ATTRIBUTE_NAMES",Xe.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Na(kt,[class extends ua{_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:Ts(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(a){let{textBgRects:t,textSpans:e}=a;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ','font-family="'.concat(this.fontFamily.replace(Yu,"'"),'" '),'font-size="'.concat(this.fontSize,'" '),this.fontStyle?'font-style="'.concat(this.fontStyle,'" '):"",this.fontWeight?'font-weight="'.concat(this.fontWeight,'" '):"",s?'text-decoration="'.concat(s,'" '):"",this.direction==="rtl"?'direction="'.concat(this.direction,'" '):"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
|
|
55
|
+
`]}_getSVGTextAndBg(a,t){const e=[],s=[];let i,n=a;this.backgroundColor&&s.push(...Hr(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=K.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,a!==a.trim()||!!a.match(Uu)),o=r?'style="'.concat(r,'"'):"",h=t.deltaY,l=h?' dy="'.concat(et(h,n),'" '):"",{angle:c,renderLeft:u,renderTop:d,width:f}=i;let g="";if(u!==void 0){const p=f/2;c&&(g=' rotate="'.concat(et(_e(c),n),'"'));const b=es({angle:_e(c)});b[4]=u,b[5]=d;const m=new C(-p,0).transform(b);e=m.x,s=m.y}return'<tspan x="'.concat(et(e,n),'" y="').concat(et(s,n),'" ').concat(l).concat(g).concat(o,">").concat(Ga(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(xe),r=this._textLines[t];let o,h,l,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],l=this.__charBounds[t][g],f===0?(e+=l.kernedWidth-l.width,f+=l.width):f+=l.kernedWidth,n&&!u&&this._reSpaceAndTab.test(r[g])&&(u=!0),u||(o=o||this.getCompleteStyleDeclaration(t,g),h=this.getCompleteStyleDeclaration(t,g+1),u=Yi(o,h,!0)),u&&(c=this._getStyleDeclaration(t,g),a.push(this._createTextCharSpan(d,c,e,s,l)),d="",o=h,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(a,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,o=0,h=0,l=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let c=0;c<i.length;c++){const{left:u,width:d,kernedWidth:f}=this.__charBounds[t][c];r=this.getValueOfPropertyAt(t,c,"textBackgroundColor"),r!==l?(l&&a.push(...Hr(l,e+h,s,o,n)),h=u,o=d,l=r):o+=f}r&&a.push(...Hr(l,e+h,s,o,n))}_getSVGLineTopOffset(a){let t,e=0;for(t=0;t<a;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(a){return"".concat(super.getSvgStyles(a)," text-decoration-thickness: ").concat(et(this.textDecorationThickness*this.getObjectScaling().y/10,K.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(a,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:o,fontWeight:h,deltaY:l,textDecorationThickness:c,linethrough:u,overline:d,underline:f}=a,g=this.getSvgTextDecoration({underline:f??this.underline,overline:d??this.overline,linethrough:u??this.linethrough}),p=c||this.textDecorationThickness;return[i?ti(It,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",o?"font-style: ".concat(o,"; "):"",h?"font-weight: ".concat(h,"; "):"",g?"text-decoration: ".concat(g,"; text-decoration-thickness: ").concat(et(p*this.getObjectScaling().y/10,K.NUM_FRACTION_DIGITS),"%; "):"",n?ti(bt,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter((t=>a[t.replace("-","")])).join(" ")}}]),F.setClass(kt),F.setSVGClass(kt);class qu{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,h=new C(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),c=new C(l.left+l.leftOffset,l.top+l.topOffset).multiply(h).transform(r.calcTransformMatrix()),u=o.getScenePoint(t).subtract(c),d=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),g=c.subtract(new C(f.left,f.top)),p=o.viewportTransform,b=g.add(u).transform(p,!0),m=r.backgroundColor,v=Mr(r.styles);r.backgroundColor="";const y={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(y,0,i),r.setSelectionStyles(y,n,r.text.length),r.dirty=!0;const _=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=m,r.styles=v,r.dirty=!0,Qi(_,{position:"fixed",left:"".concat(-_.width,"px"),border:Lt,width:"".concat(_.width/d,"px"),height:"".concat(_.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{_.remove()},ae(t.target||this.target.hiddenTextarea).body.appendChild(_),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(_,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=w({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,o=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},c=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const d=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;h>d&&h<=f?h=d:h>f&&(h-=f-d),r.removeChars(d,f),delete this.__dragStartSelection}r._reNewline.test(c)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,l,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+u,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(Ai,{index:h+u,action:"drop"}),o.fire("text:changed",{target:r}),o.contextTopDirty=!0,o.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:o}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||Lt;h===Lt?(i.selectionStart=r,i.selectionEnd=o,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),h==="move"&&(i.removeChars(r,o),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(Ai,{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 Ah=/[ \n\.,;!\?\-]/;class Ku extends kt{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 Tr({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||!tr.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!Ah.test(n);)i+=e,n=s[i];return e===-1&&Ah.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;ae(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&i!==n||i!==s&&n!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const i=s.slice(0,t),n=this.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=s.slice(t,e);return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,s){const i=s.slice(0,t).join("").length;return t===e?{selectionStart:i,selectionEnd:i}:{selectionStart:i,selectionEnd:i+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex,r=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,o=e.leftOffset,h=this.getCanvasRetinaScaling(),l=this.canvas.upperCanvasEl,c=l.width/h,u=l.height/h,d=c-r,f=u-r,g=new C(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new C(l.clientWidth/c,l.clientHeight/u));return g.x<0&&(g.x=0),g.x>d&&(g.x=d),g.y<0&&(g.y=0),g.y>f&&(g.y=f),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:"".concat(g.x,"px"),top:"".concat(g.y,"px"),fontSize:"".concat(r,"px"),charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(Ei),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let o=i;o<this._unwrappedTextLines[s].length;o++)delete this.styles[s][o];if(this.styles[n])for(let o=r;o<this._unwrappedTextLines[n].length;o++){const h=this.styles[n][o];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=h)}for(let o=s+1;o<=n;o++)delete this.styles[o];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const o=this.styles[s],h=r-i;for(let l=i;l<r;l++)delete o[l];for(const l in this.styles[s]){const c=parseInt(l,10);c>=r&&(o[c-h]=o[l],delete o[l])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const d=parseInt(u,10);d>=e&&(h=!0,n[d-e]=this.styles[t][u],o&&e===0||delete this.styles[t][u])}let c=!1;for(h&&!o&&(this.styles[t+s]=n,c=!0),(c||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:w({},i[s-1])}:l?this.styles[t+s]={0:w({},l)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?w({},n):{};s||(s=1);for(const h in r){const l=parseInt(h,10);l>=e&&(n[l+s]=r[l],r[l-s]||delete n[l])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=w({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=w({},o)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let h=0;h<t.length;h++)t[h]===`
|
|
56
|
+
`?(o++,n[o]=0):n[o]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),o&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],o),r=1;r<o;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=Z:this._selectionDirection===ft&&(this._selectionDirection=Z,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===ft?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=ft:this._selectionDirection===Z&&(this._selectionDirection=ft,this.selectionStart=e),this.selectionEnd=s)}}class Ju extends Ku{initHiddenTextarea(){const t=this.canvas&&ae(this.canvas.getElement())||_s(),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,h]=r;return e.setAttribute(o,h)}));const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(i,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(n,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map((r=>{let[o,h]=r;return e.addEventListener(o,this[h].bind(this))})),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(Ai),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const o=this._splitTextIntoLines(s).graphemeText,h=this._text.length,l=o.length,c=this.selectionStart,u=this.selectionEnd,d=c!==u;let f,g,p,b,m=l-h;const v=this.fromStringToGraphemeSelection(i,n,s),y=c>v.selectionStart;d?(g=this._text.slice(c,u),m+=u-c):l<h&&(g=y?this._text.slice(u+m,u):this._text.slice(c,c-m));const _=o.slice(v.selectionEnd-m,v.selectionEnd);if(g&&g.length&&(_.length&&(f=this.getSelectionStyles(c,c+1,!1),f=_.map((()=>f[0]))),d?(p=c,b=u):y?(p=u-g.length,b=u):(p=u,b=u+g.length),this.removeStyleFromTo(p,b)),_.length){const{copyPasteData:S}=ve();e&&_.join("")===S.copiedText&&!K.disableStyleCopyPaste&&(f=S.copiedTextStyle),this.insertNewStyleBlock(_,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}=ve();t.copiedText=this.getSelectedText(),K.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,r),c=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-l.length+(1-c)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,l=s.length;h<l;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const c=r-i,u=r,d=Math.abs(c-e);o=Math.abs(u-e)<d?h:h-1;break}return n||(o=s.length-1),o}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===ft);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=os(0,this.selectionStart,i),this.selectionEnd=os(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===Z?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let i;if(t.altKey)i=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this["findLineBoundary".concat(s)](this[e])}return i!==void 0&&this[e]!==i&&(this[e]=i,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=Z,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===ft&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=Z,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===Z&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=ft,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=ft,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const Th=a=>!!a.button;class Zu extends Ju{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 qu(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&&!Th(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||Th(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(Wt(this.calcTransformMatrix())).add(new C(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let l=0;l<this._textLines.length&&s<=e.y;l++)s+=this.getHeightOfLine(l),n=l,l>0&&(i+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));let r=Math.abs(this._getLineLeftOffset(n));const o=this._textLines[n].length,h=this.__charBounds[n];for(let l=0;l<o;l++){const c=r+h[l].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 nn="moveCursorUp",rn="moveCursorDown",on="moveCursorLeft",an="moveCursorRight",hn="exitEditing",Eh=(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])},Qu=w({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:nn,34:rn,35:an,36:on,37:on,38:nn,39:an,40:rn},keysMapRtl:{9:hn,27:hn,33:nn,34:rn,35:on,36:an,37:an,38:nn,39:on,40:rn},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class je extends Zu{static getDefaults(){return w(w({},super.getDefaults()),je.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,w(w({},je.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 Nr&&this.canvas.textEditingManager.remove(this),e instanceof Nr&&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=Kt(t.canvas),r=n.getContext("2d"),Eh(r,this.canvas);const o=this.calcTransformMatrix();r.transform(o[0],o[1],o[2],o[3],o[4],o[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const o of s){const h=o.clipPath,l=Kt(t.canvas),c=l.getContext("2d");if(Eh(c,this.canvas),!h.absolutePositioned){const u=o.calcTransformMatrix();c.transform(u[0],u[1],u[2],u[3],u[4],u[5])}h.transform(c),h.drawObject(c,!0,{}),this.drawClipPathOnCache(r,h,l)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:s,top:i,leftOffset:n.left,topOffset:n.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:i,lineIndex:n}=this.get2DCursorLocation(t);for(let l=0;l<n;l++)e+=this.getHeightOfLine(l);const r=this._getLineLeftOffset(n),o=this.__charBounds[n][i];o&&(s=o.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===ft||this.textAlign===xe||this.textAlign===ei?h.left*=-1:this.textAlign===Z||this.textAlign===ji?h.left=r-(s>0?s:0):this.textAlign!==X&&this.textAlign!==si||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/o,l=this.getValueOfPropertyAt(i,n,"deltaY"),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-h/2,top:c+e.top+l,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:o,width:h,height:l}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,h,l)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const i=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(xe),o=this.get2DCursorLocation(i),h=this.get2DCursorLocation(n),l=o.lineIndex,c=h.lineIndex,u=o.charIndex<0?0:o.charIndex,d=h.charIndex<0?0:h.charIndex;for(let f=l;f<=c;f++){const g=this._getLineLeftOffset(f)||0;let p=this.getHeightOfLine(f),b=0,m=0,v=0;if(f===l&&(m=this.__charBounds[l][u].left),f>=l&&f<c)v=r&&!this.isEndOfWrapping(f)?this.width:this.getLineWidth(f)||5;else if(f===c)if(d===0)v=this.__charBounds[c][d].left;else{const T=this._getWidthOfCharSpacing();v=this.__charBounds[c][d-1].left+this.__charBounds[c][d-1].width-T}b=p,(this.lineHeight<1||f===c&&this.lineHeight>1)&&(p/=this.lineHeight);let y=s.left+g+m,_=p,S=0;const A=v-m;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",_=1,S=p):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===ft||this.textAlign===xe||this.textAlign===ei?y=this.width-y-A:this.textAlign===Z||this.textAlign===ji?y=s.left+g-v:this.textAlign!==X&&this.textAlign!==si||(y=s.left+g-v)),t.fillRect(y,s.top+s.topOffset+S,A,_),s.topOffset+=b}}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,bt)}_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(je,"ownDefaults",Qu),x(je,"type","IText"),F.setClass(je),F.setClass(je,"i-text");class cs extends je{static getDefaults(){return w(w({},super.getDefaults()),cs.ownDefaults)}constructor(t,e){super(t,w(w({},cs.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(xe)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,i=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)t.graphemeText[i]===`
|
|
57
|
+
`&&r>0?(s=0,i++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[i])&&r>0&&(s++,i++),n[r]={line:e,offset:s},i+=t.graphemeLines[r].length,s+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,i=t+1,n=!1;const r=this._styleMap[t],o=this._styleMap[t+1];r&&(t=r.line,s=r.offset),o&&(i=o.line,n=i===t,e=o.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const l in h)for(const c in h[l]){const u=parseInt(c,10);if(u>=s&&(!n||u<e))for(const d in h[l][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 h=e?this.graphemeSplit(n):this.wordSplit(n);return h.length===0?[{word:[],width:0}]:h.map((l=>{const c=e?[l]:this.graphemeSplit(l),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(),h=this.splitByGrapheme,l=[],c=h?"":" ";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:y,width:_}=m[v];f+=y.length,u+=g+_-o,u>b&&!p?(l.push(d),d=[],u=_,p=!0):u+=o,p||h||d.push(c),d=d.concat(y),g=h?0:this._measureWord([c],t,f),f++,p=!1}return v&&l.push(d),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),l}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}x(cs,"type","Textbox"),x(cs,"textLayoutProperties",[...je.textLayoutProperties,"width"]),x(cs,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),F.setClass(cs);class kh extends Ji{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}=we(th(s,i)),h=new C(r,o);if(i.absolutePositioned)return{center:ns(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:h};{const l=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:c=new C,correction:u=new C}=this.calcBoundingBox(e,t)||{};return{center:c.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}x(kh,"type","clip-path"),F.setClass(kh);class Mh extends Ji{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new C(s.width||i.x,s.height||i.y)}}x(Mh,"type","fixed"),F.setClass(Mh);class td extends oi{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 us extends Jt{static getDefaults(){return w(w({},super.getDefaults()),us.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,us.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new td})}_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)))?(Me("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===Dr?s.forEach((i=>{i._onAfterObjectsChange(qi,e)})):s.forEach((i=>{i._set("dirty",!0)}))}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=w(w({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(us,"type","ActiveSelection"),x(us,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),F.setClass(us),F.setClass(us,"activeSelection");class ed{constructor(){x(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const o={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach((l=>{l.applyTo(o)}));const{imageData:h}=o;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),o}}class Ph{constructor(){let{tileSize:t=K.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=Kt({width:t,height:e}),i=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});i&&(i.clearColor(0,0,0,0),this.canvas=s,this.gl=i)}applyFilters(t,e,s,i,n,r){const o=this.gl,h=n.getContext("2d");if(!o||!h)return;let l;r&&(l=this.getCachedTexture(r,e));const 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,l?void 0:e),targetTexture:this.createTexture(o,s,i),originalTexture:l||this.createTexture(o,s,i,l?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),t.forEach((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),h.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:h,UNSIGNED_BYTE:l,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,h,h,l,i):t.texImage2D(o,0,h,e,s,0,h,l,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),h=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,o);const l=new ImageData(h,i,n);s.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let Gr;function sd(){const{WebGLProbe:a}=ve();return a.queryWebGL(ye()),K.enableGLFiltering&&a.isSupported(K.textureSize)?new Ph({tileSize:K.textureSize}):new ed}function Vr(){return!Gr&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(Gr=sd()),Gr}const id=["filters","resizeFilter","src","crossOrigin","type"],Oh=["cropX","cropY"];class Mt extends Et{static getDefaults(){return w(w({},super.getDefaults()),Mt.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,Mt.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(Ve()),this.setElement(typeof t=="string"?(this.canvas&&ae(this.canvas.getElement())||_s()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(Mt.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=Vr(!1);e instanceof Ph&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach((t=>{const e=this[t];e&&ve().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())})),w(w({},super.toObject([...Oh,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,i=-this.height/2;let n=[],r=[],o="",h="";if(!e)return[];if(this.hasCrop()){const l=Ve();n.push('<clipPath id="imageCrop_'+l+`">
|
|
58
58
|
`,' <rect x="'+s+'" y="'+i+'" width="'+this.width+'" height="'+this.height+`" />
|
|
59
59
|
`,`</clipPath>
|
|
60
60
|
`),o=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(h=' image-rendering="optimizeSpeed"'),t.push(" <image ","COMMON_PARTS",'xlink:href="'.concat(this.getSvgSrc(!0),'" x="').concat(s-this.cropX,'" y="').concat(i-this.cropY,'" width="').concat(e.width||e.naturalWidth,'" height="').concat(e.height||e.naturalHeight,'"').concat(h).concat(o,`></image>
|
|
61
61
|
`)),this.stroke||this.strokeDashArray){const l=this.fill;this.fill=null,r=[' <rect x="'.concat(s,'" y="').concat(i,'" width="').concat(this.width,'" height="').concat(this.height,'" style="').concat(this.getSvgStyles(),`" />
|
|
62
|
-
`)],this.fill=l}return n=this.paintFirst!==yt?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 oi(t,{crossOrigin:e,signal:s}).then((i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)}))}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),i=s.x,n=s.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||i>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=i,void(this._lastScaleY=n);const o=Qt(r),{width:h,height:l}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,ro().applyFilters([t],r,h,l,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter((n=>n&&!n.isNeutralState())),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){const n=Qt({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);ro().applyFilters(t,this._originalElement,s,i,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,i=this._filterScalingY,n=this.width,r=this.height,o=Math.max(this.cropX,0),h=Math.max(this.cropY,0),l=e.naturalWidth||e.width,c=e.naturalHeight||e.height,d=o*s,u=h*i,f=Math.min(n*s,l-d),g=Math.min(r*i,c-u),p=-n/2,y=-r/2,m=Math.min(n,l/s-o),b=Math.min(r,c/i-h);e&&t.drawImage(e,d,u,f,g,p,y,m,b)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=Dr(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,o=this._element.height,h=1,l=1,c=0,d=0,u=0,f=0;return!t||t.alignX===Ft&&t.alignY===Ft?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=Ch(this._element,i),n=(e-r*h)/2,t.alignX==="Min"&&(c=-n),t.alignX==="Max"&&(c=n),n=(s-o*l)/2,t.alignY==="Min"&&(d=-n),t.alignY==="Max"&&(d=n)),t.meetOrSlice==="slice"&&(h=l=Ah(this._element,i),n=r-e/h,t.alignX==="Mid"&&(u=n/2),t.alignX==="Max"&&(u=n),n=o-s/l,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/h,o=s/l)),{width:r,height:o,scaleX:h,scaleY:l,offsetLeft:c,offsetTop:d,cropX:u,cropY:f}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:o}=t,h=nt(t,Ru);return Promise.all([oi(n,S(S({},e),{},{crossOrigin:r})),s&&Rs(s,e),i&&Rs([i],e),ai(h,e)]).then((l=>{let[c,d=[],[u]=[],f={}]=l;return new this(c,S(S({},h),{},{src:n,filters:d,resizeFilter:u},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 oi(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=ze(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch((n=>(Ie("log","Unable to parse Image",n),null)))}}function oo(a){if(!zc.test(a.nodeName))return{};const t=a.getAttribute("viewBox");let e,s,i=1,n=1,r=0,o=0;const h=a.getAttribute("width"),l=a.getAttribute("height"),c=a.getAttribute("x")||0,d=a.getAttribute("y")||0,u=!(t&&Ga.test(t)),f=!h||!l||h==="100%"||l==="100%";let g="",p=0,y=0;if(u&&(c||d)&&a.parentNode&&a.parentNode.nodeName!=="#document"&&(g=" translate("+Nt(c||"0")+" "+Nt(d||"0")+") ",e=(a.getAttribute("transform")||"")+g,a.setAttribute("transform",e),a.removeAttribute("x"),a.removeAttribute("y")),u&&f)return{width:0,height:0};const m={width:0,height:0};if(u)return m.width=Nt(h),m.height=Nt(l),m;const b=t.match(Ga);r=-parseFloat(b[1]),o=-parseFloat(b[2]);const v=parseFloat(b[3]),_=parseFloat(b[4]);m.minX=r,m.minY=o,m.viewBoxWidth=v,m.viewBoxHeight=_,f?(m.width=v,m.height=_):(m.width=Nt(h),m.height=Nt(l),i=m.width/v,n=m.height/_);const w=Dr(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-v*i,y=m.height-_*i,w.alignX==="Mid"&&(p/=2),w.alignY==="Mid"&&(y/=2),w.alignX==="Min"&&(p=0),w.alignY==="Min"&&(y=0)),i===1&&n===1&&r===0&&o===0&&c===0&&d===0)return m;if((c||d)&&a.parentNode.nodeName!=="#document"&&(g=" translate("+Nt(c||"0")+" "+Nt(d||"0")+") "),e=g+" matrix("+i+" 0 0 "+n+" "+(r*i+p)+" "+(o*n+y)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(Or,"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}C(Ot,"type","Image"),C(Ot,"cacheProperties",[...je,...Qh]),C(Ot,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),C(Ot,"CSS_CANVAS","canvas-img"),C(Ot,"ATTRIBUTE_NAMES",[...Ze,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),I.setClass(Ot),I.setSVGClass(Ot);const Sn=a=>a.tagName.replace("svg:",""),Fu=Ji(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function tl(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 Iu=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],ao="xlink:href";function el(a,t){var e;const s=((e=t.getAttribute(ao))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(ao)&&el(a,i),i&&(Iu.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(ao)}const Bu=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function Nu(a){const t=a.getElementsByTagName("style"),e={};for(let s=0;s<t.length;s++){const i=(t[s].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");i.trim()!==""&&i.split("}").filter(((n,r,o)=>o.length>1&&n.trim())).forEach((n=>{if((n.match(/{/g)||[]).length>1&&n.trim().startsWith("@"))return;const r=n.split("{"),o={},h=r[1].trim().split(";").filter((function(l){return l.trim()}));for(let l=0;l<h.length;l++){const c=h[l].split(":"),d=c[0].trim(),u=c[1].trim();o[d]=u}(n=r[0].trim()).split(",").forEach((l=>{(l=l.replace(/^svg/i,"").trim())!==""&&(e[l]=S(S({},e[l]||{}),o))}))}))}return e}const sl=a=>I.getSVGClass(Sn(a).toLowerCase());class ju{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=tl(r,Bu),h={};let l=o.length;for(;l--;){const c=o[l];c.getAttribute("xlink:href")&&el(r,c);const d=c.getAttribute("id");d&&(h[d]=c)}return h})(i),this.cssRules=Nu(i)}parse(){return Promise.all(this.elements.map((t=>this.createObject(t))))}async createObject(t){const e=sl(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,yt),this.resolveGradient(s,t,Bt),s instanceof Ot&&s._originalElement?pn(s,s.parsePreserveAspectRatioAttribute()):pn(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=bi.fromElement(i,t,S(S({},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=$t(t.calcTransformMatrix()),r=i[0].parentElement;let o=e;for(;!s&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const h=ln("".concat(o.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const l=await Promise.all(i.map((b=>sl(b).fromElement(b,this.options,this.cssRules).then((v=>(pn(v),v.fillRule=v.clipRule,delete v.clipRule,v)))))),c=l.length===1?l[0]:new te(l),d=gt(n,c.calcTransformMatrix());c.clipPath&&await this.resolveClipPath(c,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:u,scaleY:f,angle:g,skewX:p,translateX:y,translateY:m}=os(d);c.set({flipX:!1,flipY:!1}),c.set({scaleX:u,scaleY:f,angle:g,skewX:p,skewY:0}),c.setPositionByOrigin(new E(y,m),U,U),t.clipPath=c}else delete t.clipPath}}const il=a=>Hc.test(Sn(a)),ho=()=>({objects:[],elements:[],options:{},allElements:[]});async function Hu(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return Ie("log",new dr("parseSVGDocument")),ho();const i=a.documentElement;(function(c){const d=tl(c,["use","svg:use"]),u=["x","y","xlink:href","href","transform"];for(const f of d){const g=f.attributes,p={};for(const k of g)k.value&&(p[k.name]=k.value);const y=(p["xlink:href"]||p.href||"").slice(1);if(y==="")return;const m=c.getElementById(y);if(m===null)return;let b=m.cloneNode(!0);const v=b.attributes,_={};for(const k of v)k.value&&(_[k.name]=k.value);const{x:w=0,y:x=0,transform:T=""}=p,A="".concat(T," ").concat(_.transform||""," translate(").concat(w,", ").concat(x,")");if(oo(b),/^svg$/i.test(b.nodeName)){const k=b.ownerDocument.createElementNS(Or,"g");Object.entries(_).forEach((R=>{let[D,F]=R;return k.setAttributeNS(Or,D,F)})),k.append(...b.childNodes),b=k}for(const k of g){if(!k)continue;const{name:R,value:D}=k;if(!u.includes(R))if(R==="style"){const F={};Yr(D,F),Object.entries(_).forEach((P=>{let[B,O]=P;F[B]=O})),Yr(_.style||"",F);const M=Object.entries(F).map((P=>P.join(":"))).join(";");b.setAttribute(R,M)}else!_[R]&&b.setAttribute(R,D)}b.setAttribute("transform",A),b.setAttribute("instantiated_by_use","1"),b.removeAttribute("id"),f.parentNode.replaceChild(b,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=S(S({},oo(i)),{},{crossOrigin:e,signal:s}),o=n.filter((c=>(oo(c),il(c)&&!(function(d){let u=d;for(;u&&(u=u.parentElement);)if(u&&u.nodeName&&Fu.test(Sn(u))&&!u.getAttribute("instantiated_by_use"))return!0;return!1})(c))));if(!o||o&&!o.length)return S(S({},ho()),{},{options:r,allElements:n});const h={};return n.filter((c=>Sn(c)==="clipPath")).forEach((c=>{c.setAttribute("originalTransform",c.getAttribute("transform")||"");const d=c.getAttribute("id");h[d]=Array.from(c.getElementsByTagName("*")).filter((u=>il(u)))})),{objects:await new ju(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function zu(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise(((s,i)=>{Bh(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})})).then((s=>Hu(s,t,e))).catch((()=>ho()))}const Cn=a=>a.webgl!==void 0,lo="precision highp float",Gu=`
|
|
63
|
-
`.concat(
|
|
62
|
+
`)],this.fill=l}return n=this.paintFirst!==bt?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 Ks(t,{crossOrigin:e,signal:s}).then((i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)}))}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),i=s.x,n=s.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||i>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=i,void(this._lastScaleY=n);const o=Kt(r),{width:h,height:l}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,Vr().applyFilters([t],r,h,l,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter((n=>n&&!n.isNeutralState())),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){const n=Kt({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),h=Math.max(this.cropY,0),l=e.naturalWidth||e.width,c=e.naturalHeight||e.height,u=o*s,d=h*i,f=Math.min(n*s,l-u),g=Math.min(r*i,c-d),p=-n/2,b=-r/2,m=Math.min(n,l/s-o),v=Math.min(r,c/i-h);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=gr(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,o=this._element.height,h=1,l=1,c=0,u=0,d=0,f=0;return!t||t.alignX===Lt&&t.alignY===Lt?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=sh(this._element,i),n=(e-r*h)/2,t.alignX==="Min"&&(c=-n),t.alignX==="Max"&&(c=n),n=(s-o*l)/2,t.alignY==="Min"&&(u=-n),t.alignY==="Max"&&(u=n)),t.meetOrSlice==="slice"&&(h=l=ih(this._element,i),n=r-e/h,t.alignX==="Mid"&&(d=n/2),t.alignX==="Max"&&(d=n),n=o-s/l,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/h,o=s/l)),{width:r,height:o,scaleX:h,scaleY:l,offsetLeft:c,offsetTop:u,cropX:d,cropY:f}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:o}=t,h=it(t,id);return Promise.all([Ks(n,w(w({},e),{},{crossOrigin:r})),s&&As(s,e),i&&As([i],e),Js(h,e)]).then((l=>{let[c,u=[],[d]=[],f={}]=l;return new this(c,w(w({},h),{},{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 Ks(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=Le(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch((n=>(Me("log","Unable to parse Image",n),null)))}}function Xr(a){if(!cc.test(a.nodeName))return{};const t=a.getAttribute("viewBox");let e,s,i=1,n=1,r=0,o=0;const h=a.getAttribute("width"),l=a.getAttribute("height"),c=a.getAttribute("x")||0,u=a.getAttribute("y")||0,d=!(t&&_a.test(t)),f=!h||!l||h==="100%"||l==="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(h),m.height=Nt(l),m;const v=t.match(_a);r=-parseFloat(v[1]),o=-parseFloat(v[2]);const y=parseFloat(v[3]),_=parseFloat(v[4]);m.minX=r,m.minY=o,m.viewBoxWidth=y,m.viewBoxHeight=_,f?(m.width=y,m.height=_):(m.width=Nt(h),m.height=Nt(l),i=m.width/y,n=m.height/_);const S=gr(a.getAttribute("preserveAspectRatio")||"");if(S.alignX!==Lt&&(S.meetOrSlice==="meet"&&(n=i=i>n?n:i),S.meetOrSlice==="slice"&&(n=i=i>n?i:n),p=m.width-y*i,b=m.height-_*i,S.alignX==="Mid"&&(p/=2),S.alignY==="Mid"&&(b/=2),S.alignX==="Min"&&(p=0),S.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(mr,"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(Mt,"type","Image"),x(Mt,"cacheProperties",[...De,...Oh]),x(Mt,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),x(Mt,"CSS_CANVAS","canvas-img"),x(Mt,"ATTRIBUTE_NAMES",[...Xe,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),F.setClass(Mt),F.setSVGClass(Mt);const ln=a=>a.tagName.replace("svg:",""),nd=Ni(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function Dh(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 rd=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Wr="xlink:href";function Rh(a,t){var e;const s=((e=t.getAttribute(Wr))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(Wr)&&Rh(a,i),i&&(rd.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(Wr)}const od=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function ad(a){const t=a.getElementsByTagName("style"),e={};for(let s=0;s<t.length;s++){const i=(t[s].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");i.trim()!==""&&i.split("}").filter(((n,r,o)=>o.length>1&&n.trim())).forEach((n=>{if((n.match(/{/g)||[]).length>1&&n.trim().startsWith("@"))return;const r=n.split("{"),o={},h=r[1].trim().split(";").filter((function(l){return l.trim()}));for(let l=0;l<h.length;l++){const c=h[l].split(":"),u=c[0].trim(),d=c[1].trim();o[u]=d}(n=r[0].trim()).split(",").forEach((l=>{(l=l.replace(/^svg/i,"").trim())!==""&&(e[l]=w(w({},e[l]||{}),o))}))}))}return e}const Lh=a=>F.getSVGClass(ln(a).toLowerCase());class hd{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=Dh(r,od),h={};let l=o.length;for(;l--;){const c=o[l];c.getAttribute("xlink:href")&&Rh(r,c);const u=c.getAttribute("id");u&&(h[u]=c)}return h})(i),this.cssRules=ad(i)}parse(){return Promise.all(this.elements.map((t=>this.createObject(t))))}async createObject(t){const e=Lh(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,bt),this.resolveGradient(s,t,It),s instanceof Mt&&s._originalElement?tn(s,s.parsePreserveAspectRatioAttribute()):tn(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=hi.fromElement(i,t,w(w({},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=Wt(t.calcTransformMatrix()),r=i[0].parentElement;let o=e;for(;!s&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const h=$i("".concat(o.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const l=await Promise.all(i.map((v=>Lh(v).fromElement(v,this.options,this.cssRules).then((y=>(tn(y),y.fillRule=y.clipRule,delete y.clipRule,y)))))),c=l.length===1?l[0]:new Jt(l),u=gt(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}=ts(u);c.set({flipX:!1,flipY:!1}),c.set({scaleX:d,scaleY:f,angle:g,skewX:p,skewY:0}),c.setPositionByOrigin(new C(b,m),X,X),t.clipPath=c}else delete t.clipPath}}const Fh=a=>lc.test(ln(a)),Ur=()=>({objects:[],elements:[],options:{},allElements:[]});async function ld(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return Me("log",new qn("parseSVGDocument")),Ur();const i=a.documentElement;(function(c){const u=Dh(c,["use","svg:use"]),d=["x","y","xlink:href","href","transform"];for(const f of u){const g=f.attributes,p={};for(const O of g)O.value&&(p[O.name]=O.value);const 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 y=v.attributes,_={};for(const O of y)O.value&&(_[O.name]=O.value);const{x:S=0,y:A=0,transform:T=""}=p,E="".concat(T," ").concat(_.transform||""," translate(").concat(S,", ").concat(A,")");if(Xr(v),/^svg$/i.test(v.nodeName)){const O=v.ownerDocument.createElementNS(mr,"g");Object.entries(_).forEach((N=>{let[D,L]=N;return O.setAttributeNS(mr,D,L)})),O.append(...v.childNodes),v=O}for(const O of g){if(!O)continue;const{name:N,value:D}=O;if(!d.includes(N))if(N==="style"){const L={};Or(D,L),Object.entries(_).forEach((P=>{let[j,k]=P;L[j]=k})),Or(_.style||"",L);const M=Object.entries(L).map((P=>P.join(":"))).join(";");v.setAttribute(N,M)}else!_[N]&&v.setAttribute(N,D)}v.setAttribute("transform",E),v.setAttribute("instantiated_by_use","1"),v.removeAttribute("id"),f.parentNode.replaceChild(v,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=w(w({},Xr(i)),{},{crossOrigin:e,signal:s}),o=n.filter((c=>(Xr(c),Fh(c)&&!(function(u){let d=u;for(;d&&(d=d.parentElement);)if(d&&d.nodeName&&nd.test(ln(d))&&!d.getAttribute("instantiated_by_use"))return!0;return!1})(c))));if(!o||o&&!o.length)return w(w({},Ur()),{},{options:r,allElements:n});const h={};return n.filter((c=>ln(c)==="clipPath")).forEach((c=>{c.setAttribute("originalTransform",c.getAttribute("transform")||"");const u=c.getAttribute("id");h[u]=Array.from(c.getElementsByTagName("*")).filter((d=>Fh(d)))})),{objects:await new hd(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function cd(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise(((s,i)=>{ph(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})})).then((s=>ld(s,t,e))).catch((()=>Ur()))}const cn=a=>a.webgl!==void 0,Yr="precision highp float",ud=`
|
|
63
|
+
`.concat(Yr,`;
|
|
64
64
|
varying vec2 vTexCoord;
|
|
65
65
|
uniform sampler2D uTexture;
|
|
66
66
|
void main() {
|
|
67
67
|
gl_FragColor = texture2D(uTexture, vTexCoord);
|
|
68
|
-
}`),
|
|
68
|
+
}`),dd=["type"],fd=["type"],gd=new RegExp(Yr,"g");class xt{get type(){return this.constructor.type}constructor(){let t=it(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},dd);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return ud}getVertexSource(){return`
|
|
69
69
|
attribute vec2 aPosition;
|
|
70
70
|
varying vec2 vTexCoord;
|
|
71
71
|
void main() {
|
|
72
72
|
vTexCoord = aPosition;
|
|
73
73
|
gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
|
|
74
|
-
}`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:i="highp"}}=
|
|
74
|
+
}`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:i="highp"}}=ve();i!=="highp"&&(e=e.replace(gd,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 be("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new be("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new be("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(r)));if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new be('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(o)));const h=this.getUniformLocations(t,o)||{};return h.uStepW=t.getUniformLocation(o,"uStepW"),h.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:h}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const s=this.constructor.uniformLocations,i={};for(let n=0;n<s.length;n++)i[s[n]]=t.getUniformLocation(e,s[n]);return i}sendAttributeData(t,e,s){const i=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const s=t.destinationWidth,i=t.destinationHeight;t.sourceWidth===s&&t.sourceHeight===i||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,s,i)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){cn(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=Kt({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return w({type:this.type},t.reduce(((e,s)=>(e[s]=this[s],e)),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(it(t,fd))}}x(xt,"type","BaseFilter"),x(xt,"uniformLocations",[]);const pd={multiply:`gl_FragColor.rgb *= uColor.rgb;
|
|
75
75
|
`,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
|
|
76
76
|
`,add:`gl_FragColor.rgb += uColor.rgb;
|
|
77
77
|
`,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
|
|
@@ -98,7 +98,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
98
98
|
`,tint:`
|
|
99
99
|
gl_FragColor.rgb *= (1.0 - uColor.a);
|
|
100
100
|
gl_FragColor.rgb += uColor.rgb;
|
|
101
|
-
`};class
|
|
101
|
+
`};class un extends xt{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
|
|
102
102
|
precision highp float;
|
|
103
103
|
uniform sampler2D uTexture;
|
|
104
104
|
uniform vec4 uColor;
|
|
@@ -107,10 +107,10 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
107
107
|
vec4 color = texture2D(uTexture, vTexCoord);
|
|
108
108
|
gl_FragColor = color;
|
|
109
109
|
if (color.a > 0.0) {
|
|
110
|
-
`.concat(
|
|
110
|
+
`.concat(pd[this.mode],`
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
|
-
`)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new
|
|
113
|
+
`)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new tt(this.color).getSource(),i=this.alpha,n=s[0]*i,r=s[1]*i,o=s[2]*i,h=1-i;for(let l=0;l<e.length;l+=4){const c=e[l],u=e[l+1],d=e[l+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*h,g=r+u*h,p=o+d*h}e[l]=f,e[l+1]=g,e[l+2]=p}}sendUniformData(t,e){const s=new tt(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(un,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),x(un,"type","BlendColor"),x(un,"uniformLocations",["uColor"]),F.setClass(un);const md={multiply:`
|
|
114
114
|
precision highp float;
|
|
115
115
|
uniform sampler2D uTexture;
|
|
116
116
|
uniform sampler2D uImage;
|
|
@@ -136,7 +136,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
136
136
|
color.a = color2.a;
|
|
137
137
|
gl_FragColor = color;
|
|
138
138
|
}
|
|
139
|
-
`}
|
|
139
|
+
`},bd=["type","image"];class dn extends xt{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return md[this.mode]}getVertexSource(){return`
|
|
140
140
|
attribute vec2 aPosition;
|
|
141
141
|
varying vec2 vTexCoord;
|
|
142
142
|
varying vec2 vTexCoord2;
|
|
@@ -146,7 +146,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
146
146
|
vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
|
|
147
147
|
gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
|
|
148
148
|
}
|
|
149
|
-
`}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:i},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=
|
|
149
|
+
`}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:i},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=ye());const o=n.blendImage,h=o.getContext("2d");o.width!==s||o.height!==i?(o.width=s,o.height=i):h.clearRect(0,0,s,i),h.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),h.drawImage(r.getElement(),0,0,s,i);const l=h.getImageData(0,0,s,i).data;for(let c=0;c<e.length;c+=4){const u=e[c],d=e[c+1],f=e[c+2],g=e[c+3],p=l[c],b=l[c+1],m=l[c+2],v=l[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 w(w({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=it(t,bd);return Mt.fromObject(i,e).then((r=>new this(w(w({},n),{},{image:r}))))}}x(dn,"type","BlendImage"),x(dn,"defaults",{mode:"multiply",alpha:1}),x(dn,"uniformLocations",["uTransformMatrix","uImage"]),F.setClass(dn);class fn extends xt{getFragmentSource(){return`
|
|
150
150
|
precision highp float;
|
|
151
151
|
uniform sampler2D uTexture;
|
|
152
152
|
uniform vec2 uDelta;
|
|
@@ -175,7 +175,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
175
175
|
gl_FragColor.rgb = color.rgb / totalC;
|
|
176
176
|
gl_FragColor.a = color.a / totalA;
|
|
177
177
|
}
|
|
178
|
-
`}applyTo(t){
|
|
178
|
+
`}applyTo(t){cn(t)?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;this.aspectRatio=s/i,this.horizontal=!0;let n=this.getBlurValue()*s;const r=new Uint8ClampedArray(e),o=15,h=4*s;for(let l=0;l<e.length;l+=4){let c=0,u=0,d=0,f=0,g=0;const p=l-l%h,b=p+h;for(let m=-14;m<o;m++){const v=m/o,y=4*Math.floor(n*v),_=1-Math.abs(v);let S=l+y;S<p?S=p:S>b&&(S=b);const A=e[S+3]*_;c+=e[S]*A,u+=e[S+1]*A,d+=e[S+2]*A,f+=A,g+=_}r[l]=c/f,r[l+1]=u/f,r[l+2]=d/f,r[l+3]=f/g}this.horizontal=!1,n=this.getBlurValue()*i;for(let l=0;l<r.length;l+=4){let c=0,u=0,d=0,f=0,g=0;const p=l%h,b=r.length-h+p;for(let m=-14;m<o;m++){const v=m/o,y=Math.floor(n*v)*h,_=1-Math.abs(v);let S=l+y;S<p?S=p:S>b&&(S=b);const A=r[S+3]*_;c+=r[S]*A,u+=r[S+1]*A,d+=r[S+2]*A,f+=A,g+=_}e[l]=c/f,e[l+1]=u/f,e[l+2]=d/f,e[l+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(fn,"type","Blur"),x(fn,"defaults",{blur:0}),x(fn,"uniformLocations",["uDelta"]),F.setClass(fn);class gn extends xt{getFragmentSource(){return`
|
|
179
179
|
precision highp float;
|
|
180
180
|
uniform sampler2D uTexture;
|
|
181
181
|
uniform float uBrightness;
|
|
@@ -185,7 +185,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
185
185
|
color.rgb += uBrightness;
|
|
186
186
|
gl_FragColor = color;
|
|
187
187
|
}
|
|
188
|
-
`}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)}}
|
|
188
|
+
`}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(gn,"type","Brightness"),x(gn,"defaults",{brightness:0}),x(gn,"uniformLocations",["uBrightness"]),F.setClass(gn);const Ih={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Fs extends xt{getFragmentSource(){return`
|
|
189
189
|
precision highp float;
|
|
190
190
|
uniform sampler2D uTexture;
|
|
191
191
|
varying vec2 vTexCoord;
|
|
@@ -196,7 +196,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
196
196
|
color *= uColorMatrix;
|
|
197
197
|
color += uConstants;
|
|
198
198
|
gl_FragColor = color;
|
|
199
|
-
}`}applyTo2d(t){const e=t.imageData.data,s=this.matrix,i=this.colorsOnly;for(let n=0;n<e.length;n+=4){const r=e[n],o=e[n+1],h=e[n+2];if(e[n]=r*s[0]+o*s[1]+h*s[2]+255*s[4],e[n+1]=r*s[5]+o*s[6]+h*s[7]+255*s[9],e[n+2]=r*s[10]+o*s[11]+h*s[12]+255*s[14],!i){const l=e[n+3];e[n]+=l*s[3],e[n+1]+=l*s[8],e[n+2]+=l*s[13],e[n+3]=r*s[15]+o*s[16]+h*s[17]+l*s[18]+255*s[19]}}}sendUniformData(t,e){const s=this.matrix,i=[s[0],s[1],s[2],s[3],s[5],s[6],s[7],s[8],s[10],s[11],s[12],s[13],s[15],s[16],s[17],s[18]],n=[s[4],s[9],s[14],s[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,i),t.uniform4fv(e.uConstants,n)}toObject(){return
|
|
199
|
+
}`}applyTo2d(t){const e=t.imageData.data,s=this.matrix,i=this.colorsOnly;for(let n=0;n<e.length;n+=4){const r=e[n],o=e[n+1],h=e[n+2];if(e[n]=r*s[0]+o*s[1]+h*s[2]+255*s[4],e[n+1]=r*s[5]+o*s[6]+h*s[7]+255*s[9],e[n+2]=r*s[10]+o*s[11]+h*s[12]+255*s[14],!i){const l=e[n+3];e[n]+=l*s[3],e[n+1]+=l*s[8],e[n+2]+=l*s[13],e[n+3]=r*s[15]+o*s[16]+h*s[17]+l*s[18]+255*s[19]}}}sendUniformData(t,e){const s=this.matrix,i=[s[0],s[1],s[2],s[3],s[5],s[6],s[7],s[8],s[10],s[11],s[12],s[13],s[15],s[16],s[17],s[18]],n=[s[4],s[9],s[14],s[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,i),t.uniform4fv(e.uConstants,n)}toObject(){return w(w({},super.toObject()),{},{matrix:[...this.matrix]})}}function ds(a,t){var e;const s=(x(e=class extends Fs{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",a),x(e,"defaults",{colorsOnly:!1,matrix:t}),e);return F.setClass(s,a),s}x(Fs,"type","ColorMatrix"),x(Fs,"defaults",Ih),x(Fs,"uniformLocations",["uColorMatrix","uConstants"]),F.setClass(Fs),ds("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),ds("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),ds("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),ds("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),ds("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),ds("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),ds("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 Nh extends xt{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){cn(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=>F.getClass(s.type).fromObject(s,e)))).then((s=>new this({subFilters:s})))}}x(Nh,"type","Composed"),F.setClass(Nh);class pn extends xt{getFragmentSource(){return`
|
|
200
200
|
precision highp float;
|
|
201
201
|
uniform sampler2D uTexture;
|
|
202
202
|
uniform float uContrast;
|
|
@@ -206,7 +206,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
206
206
|
float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
|
|
207
207
|
color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
|
|
208
208
|
gl_FragColor = color;
|
|
209
|
-
}`}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)}}
|
|
209
|
+
}`}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(pn,"type","Contrast"),x(pn,"defaults",{contrast:0}),x(pn,"uniformLocations",["uContrast"]),F.setClass(pn);const vd={Convolute_3_1:`
|
|
210
210
|
precision highp float;
|
|
211
211
|
uniform sampler2D uTexture;
|
|
212
212
|
uniform float uMatrix[9];
|
|
@@ -350,7 +350,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
350
350
|
gl_FragColor = color;
|
|
351
351
|
gl_FragColor.a = alpha;
|
|
352
352
|
}
|
|
353
|
-
`};class
|
|
353
|
+
`};class mn extends xt{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return vd[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,s=e.data,i=this.matrix,n=Math.round(Math.sqrt(i.length)),r=Math.floor(n/2),o=e.width,h=e.height,l=t.ctx.createImageData(o,h),c=l.data,u=this.opaque?1:0;let d,f,g,p,b,m,v,y,_,S,A,T,E;for(A=0;A<h;A++)for(S=0;S<o;S++){for(b=4*(A*o+S),d=0,f=0,g=0,p=0,E=0;E<n;E++)for(T=0;T<n;T++)v=A+E-r,m=S+T-r,v<0||v>=h||m<0||m>=o||(y=4*(v*o+m),_=i[E*n+T],d+=s[y]*_,f+=s[y+1]*_,g+=s[y+2]*_,u||(p+=s[y+3]*_));c[b]=d,c[b+1]=f,c[b+2]=g,c[b+3]=u?s[b+3]:p}t.imageData=l}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return w(w({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}x(mn,"type","Convolute"),x(mn,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),x(mn,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),F.setClass(mn);const jh="Gamma";class bn extends xt{getFragmentSource(){return`
|
|
354
354
|
precision highp float;
|
|
355
355
|
uniform sampler2D uTexture;
|
|
356
356
|
uniform vec3 uGamma;
|
|
@@ -364,7 +364,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
364
364
|
gl_FragColor = color;
|
|
365
365
|
gl_FragColor.rgb *= color.a;
|
|
366
366
|
}
|
|
367
|
-
`}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.gamma,i=1/s[0],n=1/s[1],r=1/s[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const o=this.rgbValues;for(let h=0;h<256;h++)o.r[h]=255*Math.pow(h/255,i),o.g[h]=255*Math.pow(h/255,n),o.b[h]=255*Math.pow(h/255,r);for(let h=0;h<e.length;h+=4)e[h]=o.r[e[h]],e[h+1]=o.g[e[h+1]],e[h+2]=o.b[e[h+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return t[0]===1&&t[1]===1&&t[2]===1}toObject(){return{type:
|
|
367
|
+
`}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.gamma,i=1/s[0],n=1/s[1],r=1/s[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const o=this.rgbValues;for(let h=0;h<256;h++)o.r[h]=255*Math.pow(h/255,i),o.g[h]=255*Math.pow(h/255,n),o.b[h]=255*Math.pow(h/255,r);for(let h=0;h<e.length;h+=4)e[h]=o.r[e[h]],e[h+1]=o.g[e[h+1]],e[h+2]=o.b[e[h+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return t[0]===1&&t[1]===1&&t[2]===1}toObject(){return{type:jh,gamma:this.gamma.concat()}}}x(bn,"type",jh),x(bn,"defaults",{gamma:[1,1,1]}),x(bn,"uniformLocations",["uGamma"]),F.setClass(bn);const yd={average:`
|
|
368
368
|
precision highp float;
|
|
369
369
|
uniform sampler2D uTexture;
|
|
370
370
|
varying vec2 vTexCoord;
|
|
@@ -393,7 +393,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
393
393
|
float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
|
|
394
394
|
gl_FragColor = vec4(average, average, average, col.a);
|
|
395
395
|
}
|
|
396
|
-
`};class
|
|
396
|
+
`};class vn extends xt{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2];switch(this.mode){case"average":s=(n+r+o)/3;break;case"lightness":s=(Math.min(n,r,o)+Math.max(n,r,o))/2;break;case"luminosity":s=.21*n+.72*r+.07*o}e[i+2]=e[i+1]=e[i]=s}}getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return yd[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}x(vn,"type","Grayscale"),x(vn,"defaults",{mode:"average"}),x(vn,"uniformLocations",["uMode"]),F.setClass(vn);const _d=w(w({},Ih),{},{rotation:0});class $r extends Fs{calculateMatrix(){const t=this.rotation*Math.PI,e=re(t),s=oe(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($r,"type","HueRotation"),x($r,"defaults",_d),F.setClass($r);class yn extends xt{applyTo2d(t){let{imageData:{data:e}}=t;for(let s=0;s<e.length;s+=4)e[s]=255-e[s],e[s+1]=255-e[s+1],e[s+2]=255-e[s+2],this.alpha&&(e[s+3]=255-e[s+3])}getFragmentSource(){return`
|
|
397
397
|
precision highp float;
|
|
398
398
|
uniform sampler2D uTexture;
|
|
399
399
|
uniform int uInvert;
|
|
@@ -411,7 +411,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
411
411
|
gl_FragColor = color;
|
|
412
412
|
}
|
|
413
413
|
}
|
|
414
|
-
`}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}
|
|
414
|
+
`}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}x(yn,"type","Invert"),x(yn,"defaults",{alpha:!1,invert:!0}),x(yn,"uniformLocations",["uInvert","uAlpha"]),F.setClass(yn);class _n extends xt{getFragmentSource(){return`
|
|
415
415
|
precision highp float;
|
|
416
416
|
uniform sampler2D uTexture;
|
|
417
417
|
uniform float uStepH;
|
|
@@ -426,7 +426,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
426
426
|
color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
|
|
427
427
|
gl_FragColor = color;
|
|
428
428
|
}
|
|
429
|
-
`}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}}
|
|
429
|
+
`}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(_n,"type","Noise"),x(_n,"defaults",{noise:0}),x(_n,"uniformLocations",["uNoise","uSeed"]),F.setClass(_n);class wn extends xt{applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;for(let n=0;n<i;n+=this.blocksize)for(let r=0;r<s;r+=this.blocksize){const o=4*n*s+4*r,h=e[o],l=e[o+1],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]=h,e[g+1]=l,e[g+2]=c,e[g+3]=u}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
|
|
430
430
|
precision highp float;
|
|
431
431
|
uniform sampler2D uTexture;
|
|
432
432
|
uniform float uBlocksize;
|
|
@@ -444,7 +444,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
444
444
|
vec4 color = texture2D(uTexture, squareCoords);
|
|
445
445
|
gl_FragColor = color;
|
|
446
446
|
}
|
|
447
|
-
`}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}
|
|
447
|
+
`}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}x(wn,"type","Pixelate"),x(wn,"defaults",{blocksize:4}),x(wn,"uniformLocations",["uBlocksize"]),F.setClass(wn);class xn extends xt{getFragmentSource(){return`
|
|
448
448
|
precision highp float;
|
|
449
449
|
uniform sampler2D uTexture;
|
|
450
450
|
uniform vec4 uLow;
|
|
@@ -456,7 +456,7 @@ void main() {
|
|
|
456
456
|
gl_FragColor.a = 0.0;
|
|
457
457
|
}
|
|
458
458
|
}
|
|
459
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new
|
|
459
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new tt(this.color).getSource(),n=[i[0]-s,i[1]-s,i[2]-s],r=[i[0]+s,i[1]+s,i[2]+s];for(let o=0;o<e.length;o+=4){const h=e[o],l=e[o+1],c=e[o+2];h>n[0]&&l>n[1]&&c>n[2]&&h<r[0]&&l<r[1]&&c<r[2]&&(e[o+3]=0)}}sendUniformData(t,e){const s=new tt(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(xn,"type","RemoveColor"),x(xn,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),x(xn,"uniformLocations",["uLow","uHigh"]),F.setClass(xn);class Sn extends xt{sendUniformData(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)}getFilterWindow(){const t=this.tempScale;return Math.ceil(this.lanczosLobes/t)}getCacheKey(){const t=this.getFilterWindow();return"".concat(this.type,"_").concat(t)}getFragmentSource(){const t=this.getFilterWindow();return this.generateShader(t)}getTaps(){const t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,s=this.getFilterWindow(),i=new Array(s);for(let n=1;n<=s;n++)i[n-1]=t(n*e);return i}generateShader(t){const e=new Array(t);for(let s=1;s<=t;s++)e[s-1]="".concat(s,".0 * uDelta");return`
|
|
460
460
|
precision highp float;
|
|
461
461
|
uniform sampler2D uTexture;
|
|
462
462
|
uniform vec2 uDelta;
|
|
@@ -472,7 +472,7 @@ void main() {
|
|
|
472
472
|
`),`
|
|
473
473
|
gl_FragColor = color / sum;
|
|
474
474
|
}
|
|
475
|
-
`)}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){
|
|
475
|
+
`)}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){cn(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<11920929e-14&&e>-11920929e-14)return 1;const s=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(s)/s}}applyTo2d(t){const e=t.imageData,s=this.scaleX,i=this.scaleY;this.rcpScaleX=1/s,this.rcpScaleY=1/i;const n=e.width,r=e.height,o=Math.round(n*s),h=Math.round(r*i);let l;l=this.resizeType==="sliceHack"?this.sliceByTwo(t,n,r,o,h):this.resizeType==="hermite"?this.hermiteFastResize(t,n,r,o,h):this.resizeType==="bilinear"?this.bilinearFiltering(t,n,r,o,h):this.resizeType==="lanczos"?this.lanczosResize(t,n,r,o,h):new ImageData(o,h),t.imageData=l}sliceByTwo(t,e,s,i,n){const r=t.imageData,o=.5;let h=!1,l=!1,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=ye());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);!h||!l;)e=c,s=u,i<Math.floor(c*o)?c=Math.floor(c*o):(c=i,h=!0),n<Math.floor(u*o)?u=Math.floor(u*o):(u=n,l=!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),h=o.data,l=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 S,A,T,E,O,N,D,L,M,P,j;for(m.x=(_+.5)*c,v.x=Math.floor(m.x),S=0;S<n;S++){for(m.y=(S+.5)*u,v.y=Math.floor(m.y),O=0,N=0,D=0,L=0,M=0,A=v.x-g;A<=v.x+g;A++)if(!(A<0||A>=e)){P=Math.floor(1e3*Math.abs(A-m.x)),b[P]||(b[P]={});for(let k=v.y-p;k<=v.y+p;k++)k<0||k>=s||(j=Math.floor(1e3*Math.abs(k-m.y)),b[P][j]||(b[P][j]=l(Math.sqrt(Math.pow(P*d,2)+Math.pow(j*f,2))/1e3)),T=b[P][j],T>0&&(E=4*(k*e+A),O+=T,N+=T*r[E],D+=T*r[E+1],L+=T*r[E+2],M+=T*r[E+3]))}E=4*(S*i+_),h[E]=N/O,h[E+1]=D/O,h[E+2]=L/O,h[E+3]=M/O}return++_<i?y(_):o})(0)}bilinearFiltering(t,e,s,i,n){let r,o,h,l,c,u,d,f,g,p,b,m,v,y=0;const _=this.rcpScaleX,S=this.rcpScaleY,A=4*(e-1),T=t.imageData.data,E=t.ctx.createImageData(i,n),O=E.data;for(d=0;d<n;d++)for(f=0;f<i;f++)for(c=Math.floor(_*f),u=Math.floor(S*d),g=_*f-c,p=S*d-u,v=4*(u*e+c),b=0;b<4;b++)r=T[v+b],o=T[v+4+b],h=T[v+A+b],l=T[v+A+4+b],m=r*(1-g)*(1-p)+o*g*(1-p)+h*p*(1-g)+l*g*p,O[y++]=m;return E}hermiteFastResize(t,e,s,i,n){const r=this.rcpScaleX,o=this.rcpScaleY,h=Math.ceil(r/2),l=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,y=0,_=0,S=0,A=0;const T=(f+.5)*o;for(let E=Math.floor(f*o);E<(f+1)*o;E++){const O=Math.abs(T-(E+.5))/l,N=(g+.5)*r,D=O*O;for(let L=Math.floor(g*r);L<(g+1)*r;L++){let M=Math.abs(N-(L+.5))/h;const P=Math.sqrt(D+M*M);P>1&&P<-1||(b=2*P*P*P-3*P*P+1,b>0&&(M=4*(L+E*e),A+=b*c[M+3],v+=b,c[M+3]<255&&(b=b*c[M+3]/250),y+=b*c[M],_+=b*c[M+1],S+=b*c[M+2],m+=b))}}d[p]=y/m,d[p+1]=_/m,d[p+2]=S/m,d[p+3]=A/v}return u}}x(Sn,"type","Resize"),x(Sn,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),x(Sn,"uniformLocations",["uDelta","uTaps"]),F.setClass(Sn);class Cn extends xt{getFragmentSource(){return`
|
|
476
476
|
precision highp float;
|
|
477
477
|
uniform sampler2D uTexture;
|
|
478
478
|
uniform float uSaturation;
|
|
@@ -486,7 +486,7 @@ void main() {
|
|
|
486
486
|
color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
|
|
487
487
|
gl_FragColor = color;
|
|
488
488
|
}
|
|
489
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o);e[i]+=h!==n?(h-n)*s:0,e[i+1]+=h!==r?(h-r)*s:0,e[i+2]+=h!==o?(h-o)*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}
|
|
489
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o);e[i]+=h!==n?(h-n)*s:0,e[i+1]+=h!==r?(h-r)*s:0,e[i+2]+=h!==o?(h-o)*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}x(Cn,"type","Saturation"),x(Cn,"defaults",{saturation:0}),x(Cn,"uniformLocations",["uSaturation"]),F.setClass(Cn);class An extends xt{getFragmentSource(){return`
|
|
490
490
|
precision highp float;
|
|
491
491
|
uniform sampler2D uTexture;
|
|
492
492
|
uniform float uVibrance;
|
|
@@ -501,15 +501,15 @@ void main() {
|
|
|
501
501
|
color.b += max != color.b ? (max - color.b) * amt : 0.00;
|
|
502
502
|
gl_FragColor = color;
|
|
503
503
|
}
|
|
504
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o),l=(n+r+o)/3,c=2*Math.abs(h-l)/255*s;e[i]+=h!==n?(h-n)*c:0,e[i+1]+=h!==r?(h-r)*c:0,e[i+2]+=h!==o?(h-o)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}C(jn,"type","Vibrance"),C(jn,"defaults",{vibrance:0}),C(jn,"uniformLocations",["uVibrance"]),I.setClass(jn);const Ht=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),uo=[.001,0,0,.001,0,0],fo=1.35,se={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},ts={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},al="pdfjs_internal_editor_",V={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},$={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_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},Zu={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},At={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Hn={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},vt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},Us={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},zn={ERRORS:0,WARNINGS:1,INFOS:5},vi={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,rawFillPath:94},Gn={moveTo:0,lineTo:1,curveTo:2,closePath:3},Qu={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Vn=zn.WARNINGS;function tf(a){Number.isInteger(a)&&(Vn=a)}function ef(){return Vn}function Wn(a){Vn>=zn.INFOS&&console.log(`Info: ${a}`)}function W(a){Vn>=zn.WARNINGS&&console.log(`Warning: ${a}`)}function tt(a){throw new Error(a)}function _t(a,t){a||tt(t)}function sf(a){switch(a?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function hl(a,t=null,e=null){if(!a)return null;if(e&&typeof a=="string"&&(e.addDefaultProtocol&&a.startsWith("www.")&&a.match(/\./g)?.length>=2&&(a=`http://${a}`),e.tryConvertEncoding))try{a=hf(a)}catch{}const s=t?URL.parse(a,t):URL.parse(a);return sf(s)?s:null}function ll(a,t,e=!1){const s=URL.parse(a);return s?(s.hash=t,s.href):e&&hl(a,"http://example.com")?a.split("#",1)[0]+`${t?`#${t}`:""}`:""}function Y(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const vs=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class cl extends vs{constructor(t,e){super(t,"PasswordException"),this.code=e}}class go extends vs{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class po extends vs{constructor(t){super(t,"InvalidPDFException")}}class Un extends vs{constructor(t,e,s){super(t,"ResponseException"),this.status=e,this.missing=s}}class nf extends vs{constructor(t){super(t,"FormatError")}}class es extends vs{constructor(t){super(t,"AbortException")}}function dl(a){(typeof a!="object"||a?.length===void 0)&&tt("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 _i(a){typeof a!="string"&&tt("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 rf(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function of(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function af(){try{return new Function(""),!0}catch{return!1}}class Tt{static get isLittleEndian(){return Y(this,"isLittleEndian",of())}static get isEvalSupported(){return Y(this,"isEvalSupported",af())}static get isOffscreenCanvasSupported(){return Y(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Y(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){const{platform:t,userAgent:e}=navigator;return Y(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return Y(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const mo=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class j{static makeHexColor(t,e,s){return`#${mo[t]}${mo[e]}${mo[s]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}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 multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,s=0){const i=t[s],n=t[s+1];t[s]=i*e[0]+n*e[2]+e[4],t[s+1]=i*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,s=0){const i=e[0],n=e[1],r=e[2],o=e[3],h=e[4],l=e[5];for(let c=0;c<6;c+=2){const d=t[s+c],u=t[s+c+1];t[s+c]=d*i+u*r+h,t[s+c+1]=d*n+u*o+l}}static applyInverseTransform(t,e){const s=t[0],i=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(s*e[3]-i*e[2]+e[2]*e[5]-e[4]*e[3])/n,t[1]=(-s*e[1]+i*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,s){const i=e[0],n=e[1],r=e[2],o=e[3],h=e[4],l=e[5],c=t[0],d=t[1],u=t[2],f=t[3];let g=i*c+h,p=g,y=i*u+h,m=y,b=o*d+l,v=b,_=o*f+l,w=_;if(n!==0||r!==0){const x=n*c,T=n*u,A=r*d,k=r*f;g+=A,m+=A,y+=k,p+=k,b+=x,w+=x,_+=T,v+=T}s[0]=Math.min(s[0],g,y,p,m),s[1]=Math.min(s[1],b,_,v,w),s[2]=Math.max(s[2],g,y,p,m),s[3]=Math.max(s[3],b,_,v,w)}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,e){const s=t[0],i=t[1],n=t[2],r=t[3],o=s**2+i**2,h=s*n+i*r,l=n**2+r**2,c=(o+l)/2,d=Math.sqrt(c**2-(o*l-h**2));e[0]=Math.sqrt(c+d||1),e[1]=Math.sqrt(c-d||1)}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 pointBoundingBox(t,e,s){s[0]=Math.min(s[0],t),s[1]=Math.min(s[1],e),s[2]=Math.max(s[2],t),s[3]=Math.max(s[3],e)}static rectBoundingBox(t,e,s,i,n){n[0]=Math.min(n[0],t,s),n[1]=Math.min(n[1],e,i),n[2]=Math.max(n[2],t,s),n[3]=Math.max(n[3],e,i)}static#t(t,e,s,i,n,r,o,h,l,c){if(l<=0||l>=1)return;const d=1-l,u=l*l,f=u*l,g=d*(d*(d*t+3*l*e)+3*u*s)+f*i,p=d*(d*(d*n+3*l*r)+3*u*o)+f*h;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,h,l,c,d,u){if(Math.abs(l)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,o,h,-d/c,u);return}const f=c**2-4*d*l;if(f<0)return;const g=Math.sqrt(f),p=2*l;this.#t(t,e,s,i,n,r,o,h,(-c+g)/p,u),this.#t(t,e,s,i,n,r,o,h,(-c-g)/p,u)}static bezierBoundingBox(t,e,s,i,n,r,o,h,l){l[0]=Math.min(l[0],t,o),l[1]=Math.min(l[1],e,h),l[2]=Math.max(l[2],t,o),l[3]=Math.max(l[3],e,h),this.#e(t,s,n,o,e,i,r,h,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),l),this.#e(t,s,n,o,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),l)}}function hf(a){return decodeURIComponent(escape(a))}let yo=null,ul=null;function lf(a){return yo||(yo=/([\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,ul=new Map([["ſt","ſt"]])),a.replaceAll(yo,(t,e,s)=>e?e.normalize("NFKC"):ul.get(s))}function fl(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const a=new Uint8Array(32);return crypto.getRandomValues(a),dl(a)}const bo="pdfjs_internal_id_";function cf(a,t,e){if(!Array.isArray(e)||e.length<2)return!1;const[s,i,...n]=e;if(!a(s)&&!Number.isInteger(s)||!t(i))return!1;const r=n.length;let o=!0;switch(i.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return r===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(r!==4)return!1;o=!1;break;default:return!1}for(const h of n)if(!(typeof h=="number"||o&&h===null))return!1;return!0}function zt(a,t,e){return Math.min(Math.max(a,t),e)}function gl(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(dl(a))}function df(a){return Uint8Array.fromBase64?Uint8Array.fromBase64(a):_i(atob(a))}typeof Promise.try!="function"&&(Promise.try=function(a,...t){return new Promise(e=>{e(a(...t))})}),typeof Math.sumPrecise!="function"&&(Math.sumPrecise=function(a){return a.reduce((t,e)=>t+e,0)});const Xe="http://www.w3.org/2000/svg";class Xs{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function wi(a,t="text"){if(Si(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 xi{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const h=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let c,d,u,f;switch(i%=360,i<0&&(i+=360),i){case 180:c=-1,d=0,u=0,f=1;break;case 90:c=0,d=1,u=1,f=0;break;case 270:c=0,d=-1,u=-1,f=0;break;case 0:c=1,d=0,u=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}o&&(u=-u,f=-f);let g,p,y,m;c===0?(g=Math.abs(l-t[1])*s+n,p=Math.abs(h-t[0])*s+r,y=(t[3]-t[1])*s,m=(t[2]-t[0])*s):(g=Math.abs(h-t[0])*s+n,p=Math.abs(l-t[1])*s+r,y=(t[2]-t[0])*s,m=(t[3]-t[1])*s),this.transform=[c*s,d*s,u*s,f*s,g-c*s*h-u*s*l,p-d*s*h-f*s*l],this.width=y,this.height=m}get rawDims(){const t=this.viewBox;return Y(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new xi({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){const s=[t,e];return j.applyTransform(s,this.transform),s}convertToViewportRectangle(t){const e=[t[0],t[1]];j.applyTransform(e,this.transform);const s=[t[2],t[3]];return j.applyTransform(s,this.transform),[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){const s=[t,e];return j.applyInverseTransform(s,this.transform),s}}class vo extends vs{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Xn(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function _o(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function uf(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function ff(a,t="document.pdf"){if(typeof a!="string")return t;if(Xn(a))return W('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const s=(o=>{try{return new URL(o)}catch{try{return new URL(decodeURIComponent(o))}catch{try{return new URL(o,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(o),"https://foo.bar")}catch{return null}}}}})(a);if(!s)return t;const i=o=>{try{let h=decodeURIComponent(o);return h.includes("/")?(h=h.split("/").at(-1),h.test(/^\.pdf$/i)?h:o):h}catch{return o}},n=/\.pdf$/i,r=s.pathname.split("/").at(-1);if(n.test(r))return i(r);if(s.searchParams.size>0){const o=Array.from(s.searchParams.values()).reverse();for(const l of o)if(n.test(l))return i(l);const h=Array.from(s.searchParams.keys()).reverse();for(const l of h)if(n.test(l))return i(l)}if(s.hash){const h=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(s.hash);if(h)return i(h[0])}return t}class pl{started=Object.create(null);times=[];time(t){t in this.started&&W(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||W(`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
|
|
505
|
-
`);return t.join("")}}function Si(a,t){const e=t?URL.parse(a,t):URL.parse(a);return e?.protocol==="http:"||e?.protocol==="https:"}function ae(a){a.preventDefault()}function wt(a){a.preventDefault(),a.stopPropagation()}function gf(a){console.log("Deprecated API usage: "+a)}class wo{static#t;static toDateObject(t){if(t instanceof Date)return 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 h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const l=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,l==="-"?(r+=c,o+=d):l==="+"&&(r-=c,o-=d),new Date(Date.UTC(s,i,n,r,o,h))}}function pf(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new xi({viewBox:n,userUnit:1,scale:t,rotation:e})}function Yn(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):(W(`Not a valid color format: "${a}"`),[0,0,0])}function mf(a){const t=document.createElement("span");t.style.visibility="hidden",t.style.colorScheme="only light",document.body.append(t);for(const e of a.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;a.set(e,Yn(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 ke(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 _s(a,t,e=!1,s=!0){if(t instanceof xi){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Tt.isCSSRoundSupported,h=`var(--total-scale-factor) * ${i}px`,l=`var(--total-scale-factor) * ${n}px`,c=o?`round(down, ${h}, var(--scale-round-x))`:`calc(${h})`,d=o?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=c,r.height=d):(r.width=d,r.height=c)}s&&a.setAttribute("data-main-rotation",t.rotation)}class Me{constructor(){const{pixelRatio:t}=Me;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,s,i,n=-1){let r=1/0,o=1/0,h=1/0;s=Me.capPixels(s,n),s>0&&(r=Math.sqrt(s/(t*e))),i!==-1&&(o=i/t,h=i/e);const l=Math.min(r,o,h);return this.sx>l||this.sy>l?(this.sx=l,this.sy=l,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const s=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,s):s}return t}}const xo=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class Ci{#t=null;#e=null;#s;#i=null;#r=null;#n=null;#o=null;static#a=null;constructor(t){this.#s=t,Ci.#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",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",ae,{signal:e}),t.addEventListener("pointerdown",Ci.#h,{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 t}get div(){return this.#t}static#h(t){t.stopPropagation()}#l(t){this.#s._focusEventsAllowed=!1,wt(t)}#u(t){this.#s._focusEventsAllowed=!0,wt(t)}#c(t){const e=this.#s._uiManager._signal;return!(e instanceof AbortSignal)||e.aborted?!1:(t.addEventListener("focusin",this.#l.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ae,{signal:e}),!0)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown(),this.#n?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.classList.add("basic","deleteButton"),s.tabIndex=0,s.setAttribute("data-l10n-id",Ci.#a[t]),this.#c(s)&&s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#f(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#c(e),this.#i.append(e,this.#f),this.#r=t}addComment(t){if(this.#n)return;const e=t.render();e&&(this.#c(e),this.#i.append(e,this.#f),this.#n=t,t.toolbar=this)}addColorPicker(t){if(this.#e)return;this.#e=t;const e=t.renderButton();this.#c(e),this.#i.append(e,this.#f)}async addEditSignatureButton(t){const e=this.#o=await t.renderEditButton(this.#s);this.#c(e),this.#i.append(e,this.#f)}async addButton(t,e){switch(t){case"colorPicker":this.addColorPicker(e);break;case"altText":await this.addAltText(e);break;case"editSignature":await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":this.addComment(e);break}}updateEditSignatureButton(t){this.#o&&(this.#o.title=t)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class yf{#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");const e=this.#s._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",ae,{signal:e});const s=this.#t=document.createElement("div");return s.className="buttons",t.append(s),this.#s.hasCommentManager()&&this.#n("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#s.commentSelection("floating_button")}),this.#n("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#s.highlightSelection("floating_button")}),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(t,e,s,i){const n=document.createElement("button");n.classList.add("basic",t),n.tabIndex=0,n.setAttribute("data-l10n-id",e);const r=document.createElement("span");n.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",s);const o=this.#s._signal;o instanceof AbortSignal&&!o.aborted&&(n.addEventListener("contextmenu",ae,{signal:o}),n.addEventListener("click",i,{signal:o})),this.#t.append(n)}}function ml(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class bf{#t=0;get id(){return`${al}${this.#t++}`}}class So{#t=fl();#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 Y(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 wi(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=So._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((l,c)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,l()},r.onload=async()=>{const d=s.svgUrl=r.result;o.src=await n?`${d}#svgView(preserveAspectRatio(none))`:d},o.onerror=r.onerror=c});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){W(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 vf{#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 h={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(h);return}if(r&&this.#t[this.#i].type===n){o&&(h.undo=this.#t[this.#i].undo),this.#t[this.#i]=h;return}const l=this.#i+1;l===this.#s?this.#t.splice(0,1):(this.#i=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(h)}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 Ai{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Tt.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||wt(e))}}class Co{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return mf(t),Y(this,"_colors",t)}convert(t){const e=Yn(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 Co._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?j.makeHexColor(...e):t}}class ss{#t=new AbortController;#e=null;#s=null;#i=new Map;#r=new Map;#n=null;#o=null;#a=null;#h=new vf;#l=null;#u=null;#c=null;#f=0;#p=new Set;#g=null;#d=null;#m=new Set;_editorUndoBar=null;#v=!1;#y=!1;#w=!1;#x=null;#b=null;#S=null;#k=null;#T=!1;#C=null;#O=new bf;#E=!1;#M=!1;#F=!1;#L=null;#R=null;#I=null;#P=null;#j=null;#A=V.NONE;#_=new Set;#H=null;#z=null;#V=null;#$=null;#X=null;#Y={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#B=[0,0];#W=null;#U=null;#Z=null;#Q=null;#N=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=ss.prototype,e=r=>r.#U.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:h}=o;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return Y(this,"_keyboardManager",new Ai([[["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.#U.contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#U.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,h,l,c,d,u,f,g,p,y){const m=this._signal=this.#t.signal;this.#U=t,this.#Z=e,this.#Q=s,this.#n=i,this.#l=n,this.#z=r,this.#X=h,this._eventBus=o,o._on("editingaction",this.onEditingAction.bind(this),{signal:m}),o._on("pagechanging",this.onPageChanging.bind(this),{signal:m}),o._on("scalechanging",this.onScaleChanging.bind(this),{signal:m}),o._on("rotationchanging",this.onRotationChanging.bind(this),{signal:m}),o._on("setpreference",this.onSetPreference.bind(this),{signal:m}),o._on("switchannotationeditorparams",b=>this.updateParams(b.type,b.value),{signal:m}),window.addEventListener("pointerdown",()=>{this.#M=!0},{capture:!0,signal:m}),window.addEventListener("pointerup",()=>{this.#M=!1},{capture:!0,signal:m}),this.#ht(),this.#ut(),this.#et(),this.#o=h.annotationStorage,this.#x=h.filterFactory,this.#V=l,this.#k=c||null,this.#v=d,this.#y=u,this.#w=f,this.#j=g||null,this.viewParameters={realScale:Xs.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=p||null,this._supportsPinchToZoom=y!==!1}destroy(){this.#N?.resolve(),this.#N=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#r.values())t.destroy();this.#r.clear(),this.#i.clear(),this.#m.clear(),this.#P?.clear(),this.#e=null,this.#_.clear(),this.#h.destroy(),this.#n?.destroy(),this.#l?.destroy(),this.#z?.destroy(),this.#C?.hide(),this.#C=null,this.#I?.destroy(),this.#I=null,this.#s=null,this.#b&&(clearTimeout(this.#b),this.#b=null),this.#W&&(clearTimeout(this.#W),this.#W=null),this._editorUndoBar?.destroy(),this.#X=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#j}get useNewAltTextFlow(){return this.#y}get useNewAltTextWhenAddingImage(){return this.#w}get hcmFilter(){return Y(this,"hcmFilter",this.#V?this.#x.addHCMFilter(this.#V.foreground,this.#V.background):"none")}get direction(){return Y(this,"direction",getComputedStyle(this.#U).direction)}get _highlightColors(){return Y(this,"_highlightColors",this.#k?new Map(this.#k.split(",").map(t=>(t=t.split("=").map(e=>e.trim()),t[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return Y(this,"highlightColors",null);const e=new Map,s=!!this.#V;for(const[i,n]of t){const r=i.endsWith("_HCM");if(s&&r){e.set(i.replace("_HCM",""),n);continue}!s&&!r&&e.set(i,n)}return Y(this,"highlightColors",e)}get highlightColorNames(){return Y(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#c=t}setMainHighlightColorPicker(t){this.#I=t}editAltText(t,e=!1){this.#n?.editAltText(this,t,e)}hasCommentManager(){return!!this.#l}editComment(t,e){this.#l?.open(this,t,e)}getSignature(t){this.#z?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#z}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":this.#w=e;break}}onPageChanging({pageNumber:t}){this.#f=t-1}focusMainContainer(){this.#U.focus()}findParent(t,e){for(const s of this.#r.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.#Z.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#m.add(t)}removeShouldRescale(t){this.#m.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Xs.PDF_TO_CSS_UNITS;for(const e of this.#m)e.onScaleChanging();this.#c?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#J({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#tt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#r.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t="",e=!1){const s=document.getSelection();if(!s||s.isCollapsed)return;const{anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:o}=s,h=s.toString(),c=this.#J(s).closest(".textLayer"),d=this.getSelectionBoxes(c);if(!d)return;s.empty();const u=this.#tt(c),f=this.#A===V.NONE,g=()=>{const p=u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:d,anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:o,text:h});f&&this.showAllEditors("highlight",!0,!0),e&&p?.editComment()};if(f){this.switchToMode(V.HIGHLIGHT,g);return}g()}commentSelection(t=""){this.highlightSelection(t,!0)}#ot(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#J(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#C||=new yf(this),this.#C.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#o&&!this.#o.has(t.id)&&this.#o.setValue(t.id,t)}a11yAlert(t,e=null){const s=this.#Q;s&&(s.setAttribute("data-l10n-id",t),e?s.setAttribute("data-l10n-args",JSON.stringify(e)):s.removeAttribute("data-l10n-args"))}#at(){const t=document.getSelection();if(!t||t.isCollapsed){this.#H&&(this.#C?.hide(),this.#H=null,this.#D({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#H)return;const i=this.#J(t).closest(".textLayer");if(!i){this.#H&&(this.#C?.hide(),this.#H=null,this.#D({hasSelectedText:!1}));return}if(this.#C?.hide(),this.#H=e,this.#D({hasSelectedText:!0}),!(this.#A!==V.HIGHLIGHT&&this.#A!==V.NONE)&&(this.#A===V.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#T=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#A===V.HIGHLIGHT?this.#tt(i):null;if(n?.toggleDrawing(),this.#M){const r=new AbortController,o=this.combinedSignal(r),h=l=>{l.type==="pointerup"&&l.button!==0||(r.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#q("main_toolbar"))};window.addEventListener("pointerup",h,{signal:o}),window.addEventListener("blur",h,{signal:o})}else n?.toggleDrawing(!0),this.#q("main_toolbar")}}#q(t=""){this.#A===V.HIGHLIGHT?this.highlightSelection(t):this.#v&&this.#ot()}#ht(){document.addEventListener("selectionchange",this.#at.bind(this),{signal:this._signal})}#lt(){if(this.#S)return;this.#S=new AbortController;const t=this.combinedSignal(this.#S);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#ct(){this.#S?.abort(),this.#S=null}blur(){if(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#q("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#_)if(e.div.contains(t)){this.#R=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#R)return;const[t,e]=this.#R;this.#R=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#et(){if(this.#L)return;this.#L=new AbortController;const t=this.combinedSignal(this.#L);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#dt(){this.#L?.abort(),this.#L=null}#st(){if(this.#u)return;this.#u=new AbortController;const t=this.combinedSignal(this.#u);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})}#it(){this.#u?.abort(),this.#u=null}#ut(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#et(),this.#st()}removeEditListeners(){this.#dt(),this.#it()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#d)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.#d)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.#_){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.#d)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){W(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)this.#nt(h);this.#rt(n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){W(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#A!==V.NONE&&!this.isEditorHandlingKeyboard&&ss._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#q("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;case"commentSelection":this.commentSelection("context_menu");break}}#D(t){Object.entries(t).some(([s,i])=>this.#Y[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#Y,t)}),this.#A===V.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#G([[$.HIGHLIGHT_FREE,!0]]))}#G(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#lt(),this.#st(),this.#D({isEditing:this.#A!==V.NONE,isEmpty:this.#K(),hasSomethingToUndo:this.#h.hasSomethingToUndo(),hasSomethingToRedo:this.#h.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#ct(),this.#it(),this.#D({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#d){this.#d=t;for(const e of this.#d)this.#G(e.defaultPropertiesToUpdate)}}getId(){return this.#O.id}get currentLayer(){return this.#r.get(this.#f)}getLayer(t){return this.#r.get(t)}get currentPageIndex(){return this.#f}addLayer(t){this.#r.set(t.pageIndex,t),this.#E?t.enable():t.disable()}removeLayer(t){this.#r.delete(t.pageIndex)}async updateMode(t,e=null,s=!1,i=!1,n=!1){if(this.#A!==t&&!(this.#N&&(await this.#N.promise,!this.#N))){if(this.#N=Promise.withResolvers(),this.#c?.commitOrRemove(),this.#A===V.POPUP&&this.#l?.hideSidebar(),this.#A=t,t===V.NONE){this.setEditingState(!1),this.#gt(),this._editorUndoBar?.hide(),this.#N.resolve();return}t===V.SIGNATURE&&await this.#z?.loadSignatures(),t===V.POPUP&&(this.#s||=await this.#X.getAnnotationsByType(new Set(this.#d.map(r=>r._editorType))),this.#l?.showSidebar(this.#s)),this.setEditingState(!0),await this.#ft(),this.unselectAll();for(const r of this.#r.values())r.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#N.resolve();return}for(const r of this.#i.values())r.annotationElementId===e||r.id===e?(this.setSelected(r),n?r.editComment():i&&r.enterInEditMode()):r.unselect();this.#N.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#A&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#d){switch(t){case $.CREATE:this.currentLayer.addNewEditor(e);return;case $.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#$||=new Map).set(t,e),this.showAllEditors("highlight",e);break}if(this.hasSelection)for(const s of this.#_)s.updateParams(t,e);else for(const s of this.#d)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#i.values())n.editorType===t&&n.show(e);(this.#$?.get($.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#G([[$.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#F!==t){this.#F=t;for(const e of this.#r.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#ft(){if(!this.#E){this.#E=!0;const t=[];for(const e of this.#r.values())t.push(e.enable());await Promise.all(t);for(const e of this.#i.values())e.enable()}}#gt(){if(this.unselectAll(),this.#E){this.#E=!1;for(const t of this.#r.values())t.disable();for(const t of this.#i.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#i.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#i.get(t)}addEditor(t){this.#i.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.focusMainContainer(),this.#b=null},0)),this.#i.delete(t.id),t.annotationElementId&&this.#P?.delete(t.annotationElementId),this.unselect(t),(!t.annotationElementId||!this.#p.has(t.annotationElementId))&&this.#o?.remove(t.id)}addDeletedAnnotationElement(t){this.#p.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#p.has(t)}removeDeletedAnnotationElement(t){this.#p.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#nt(t){const e=this.#r.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#G(t.propertiesToUpdate))}get#pt(){let t=null;for(t of this.#_);return t}updateUI(t){this.#pt===t&&this.#G(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#G(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#_.has(t)){this.#_.delete(t),t.unselect(),this.#D({hasSelectedEditor:this.hasSelection});return}this.#_.add(t),t.select(),this.#G(t.propertiesToUpdate),this.#D({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.id}),this.#c?.commitOrRemove();for(const e of this.#_)e!==t&&e.unselect();this.#_.clear(),this.#_.add(t),t.select(),this.#G(t.propertiesToUpdate),this.#D({hasSelectedEditor:!0})}isSelected(t){return this.#_.has(t)}get firstSelectedEditor(){return this.#_.values().next().value}unselect(t){t.unselect(),this.#_.delete(t),this.#D({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#_.size!==0}get isEnterHandled(){return this.#_.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#h.undo(),this.#D({hasSomethingToUndo:this.#h.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#K()}),this._editorUndoBar?.hide()}redo(){this.#h.redo(),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:this.#h.hasSomethingToRedo(),isEmpty:this.#K()})}addCommands(t){this.#h.add(t),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#K()})}cleanUndoStack(t){this.#h.cleanType(t)}#K(){if(this.#i.size===0)return!0;if(this.#i.size===1)for(const t of this.#i.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.#_],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.#nt(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#rt(t){for(const e of this.#_)e.unselect();this.#_.clear();for(const e of t)e.isEmpty()||(this.#_.add(e),e.select());this.#D({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#_)t.commit();this.#rt(this.#i.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#A!==V.NONE))&&!this.#c?.commitOrRemove()&&this.hasSelection){for(const t of this.#_)t.unselect();this.#_.clear(),this.#D({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#B[0]+=t,this.#B[1]+=e;const[i,n]=this.#B,r=[...this.#_],o=1e3;this.#W&&clearTimeout(this.#W),this.#W=setTimeout(()=>{this.#W=null,this.#B[0]=this.#B[1]=0,this.addCommands({cmd:()=>{for(const h of r)this.#i.has(h.id)&&(h.translateInPage(i,n),h.translationDone())},undo:()=>{for(const h of r)this.#i.has(h.id)&&(h.translateInPage(-i,-n),h.translationDone())},mustExec:!1})},o);for(const h of r)h.translateInPage(t,e),h.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#g=new Map;for(const t of this.#_)this.#g.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#g)return!1;this.disableUserSelect(!1);const t=this.#g;this.#g=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.#i.has(i.id)){const h=this.#r.get(o);h?i._setParentAndPosition(h,n,r):(i.pageIndex=o,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:o}]of t)s(i,n,r,o)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:o}]of t)s(i,n,r,o)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#g)for(const s of this.#g.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.#_.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#A}get imageManager(){return Y(this,"imageManager",new So)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,c=e.rangeCount;l<c;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(l,c,d,u)=>({x:(c-i)/r,y:1-(l+d-s)/n,width:u/r,height:d/n});break;case"180":o=(l,c,d,u)=>({x:1-(l+d-s)/n,y:1-(c+u-i)/r,width:d/n,height:u/r});break;case"270":o=(l,c,d,u)=>({x:1-(c+u-i)/r,y:(l-s)/n,width:u/r,height:d/n});break;default:o=(l,c,d,u)=>({x:(l-s)/n,y:(c-i)/r,width:d/n,height:u/r});break}const h=[];for(let l=0,c=e.rangeCount;l<c;l++){const d=e.getRangeAt(l);if(!d.collapsed)for(const{x:u,y:f,width:g,height:p}of d.getClientRects())g===0||p===0||h.push(o(u,f,g,p))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#a||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#a?.delete(t)}renderAnnotationElement(t){const e=this.#a?.get(t.data.id);if(!e)return;const s=this.#o.getRawValue(e);s&&(this.#A===V.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}setMissingCanvas(t,e,s){const i=this.#P?.get(t);i&&(i.setCanvas(e,s),this.#P.delete(t))}addMissingCanvas(t,e){(this.#P||=new Map).set(t,e)}}class De{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#o=!1;#a=null;#h=null;#l=null;#u=null;#c=!1;static#f=null;static _l10n=null;constructor(t){this.#h=t,this.#c=t._uiManager.useNewAltTextFlow,De.#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){De._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.#c?(t.classList.add("new"),t.setAttribute("data-l10n-id",De.#f.missing),e.setAttribute("data-l10n-id",De.#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.#h._uiManager._signal;t.addEventListener("contextmenu",ae,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#h._uiManager.editAltText(this.#h),this.#c&&this.#h._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#p}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#o=!0,i(n))},{signal:s}),await this.#g(),t}get#p(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#c?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#c?this.#t!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#t===null&&(this.#l=t,this.#u=await De._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#c||this.#t){this.#a?.remove(),this.#a=null;return}if(!this.#a){const e=this.#a=document.createElement("div");e.className="noAltTextBadge",this.#h.div.append(e)}this.#a.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#l===e&&(e=this.#u),{altText:e,decorative:this.#e,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#l=s,this.#u=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.#h._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#p}})}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.#c){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",De.#f[this.#p]),this.#i?.setAttribute("data-l10n-id",De.#f[`${this.#p}-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.#h.id}`;const i=100,n=this.#h._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.#h._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.#h.getElementForAltText()?.setAttribute("aria-describedby",e.id)}}class $n{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#o=!1;constructor(t){this.#s=t,this.toolbar=null}render(){if(!this.#s._uiManager.hasCommentManager())return null;const t=this.#t=document.createElement("button");t.className="comment",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-button");const e=this.#s._uiManager._signal;if(!(e instanceof AbortSignal)||e.aborted)return t;t.addEventListener("contextmenu",ae,{signal:e}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:e});const s=i=>{i.preventDefault(),this.edit()};return t.addEventListener("click",s,{capture:!0,signal:e}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(this.#e=!0,s(i))},{signal:e}),t}edit(){const{bottom:t,left:e,right:s}=this.#s.getClientDimensions(),i={top:t};this.#s._uiManager.direction==="ltr"?i.right=s:i.left=e,this.#s._uiManager.editComment(this.#s,i)}finish(){this.#t&&(this.#t.focus({focusVisible:this.#e}),this.#e=!1)}isDeleted(){return this.#o||this.#r===""}hasBeenEdited(){return this.isDeleted()||this.#r!==this.#i}serialize(){return this.data}get data(){return{text:this.#r,date:this.#n,deleted:this.#o}}set data(t){if(t===null){this.#r="",this.#o=!0;return}this.#r=t,this.#n=new Date,this.#o=!1}setInitialText(t){this.#i=t,this.data=t}toggle(t=!1){this.#t&&(this.#t.disabled=!t)}shown(){}destroy(){this.#t?.remove(),this.#t=null,this.#r="",this.#n=null,this.#s=null,this.#e=!1,this.#o=!1}}class qn{#t;#e=!1;#s=null;#i;#r;#n;#o;#a=null;#h;#l=null;#u;#c=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.#o=r,this.#u=new AbortController,this.#h=AbortSignal.any([o,this.#u.signal]),t.addEventListener("touchstart",this.#f.bind(this),{passive:!1,signal:this.#h})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Me.pixelRatio}#f(t){if(this.#i?.())return;if(t.touches.length===1){if(this.#a)return;const i=this.#a=new AbortController,n=AbortSignal.any([this.#h,i.signal]),r=this.#t,o={capture:!0,signal:n,passive:!1},h=l=>{l.pointerType==="touch"&&(this.#a?.abort(),this.#a=null)};r.addEventListener("pointerdown",l=>{l.pointerType==="touch"&&(wt(l),h(l))},o),r.addEventListener("pointerup",h,o),r.addEventListener("pointercancel",h,o);return}if(!this.#c){this.#c=new AbortController;const i=AbortSignal.any([this.#h,this.#c.signal]),n=this.#t,r={signal:i,capture:!1,passive:!1};n.addEventListener("touchmove",this.#p.bind(this),r);const o=this.#g.bind(this);n.addEventListener("touchend",o,r),n.addEventListener("touchcancel",o,r),r.capture=!0,n.addEventListener("pointerdown",wt,r),n.addEventListener("pointermove",wt,r),n.addEventListener("pointercancel",wt,r),n.addEventListener("pointerup",wt,r),this.#r?.()}if(wt(t),t.touches.length!==2||this.#s?.()){this.#l=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#l={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#p(t){if(!this.#l||t.touches.length!==2)return;wt(t);let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:o}=s,h=this.#l,{touch0X:l,touch0Y:c,touch1X:d,touch1Y:u}=h,f=d-l,g=u-c,p=r-i,y=o-n,m=Math.hypot(p,y)||1,b=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(b-m)<=qn.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=o,!this.#e){this.#e=!0;return}const v=[(i+r)/2,(n+o)/2];this.#n?.(v,b,m)}#g(t){t.touches.length>=2||(this.#c&&(this.#c.abort(),this.#c=null,this.#o?.()),this.#l&&(wt(t),this.#l=null,this.#e=!1))}destroy(){this.#u?.abort(),this.#u=null,this.#a?.abort(),this.#a=null}}class z{#t=null;#e=null;#s=null;#i=null;#r=!1;#n=null;#o="";#a=!1;#h=null;#l=null;#u=null;#c=null;#f="";#p=!1;#g=null;#d=!1;#m=!1;#v=!1;#y=null;#w=0;#x=0;#b=null;#S=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#k=!1;#T=z._zIndex++;static _borderLineWidth=-1;static _colorManager=new Co;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=z.prototype._resizeWithKeyboard,e=ss.TRANSLATE_SMALL,s=ss.TRANSLATE_BIG;return Y(this,"_resizerKeyboardManager",new Ai([[["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"],z.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,this.annotationElementId=t.annotationElementId||null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return Y(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new _f({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(z._l10n??=t,z._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"}),z._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);z._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){tt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#k}set _isDraggable(t){this.#k=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.#T}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#B(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#p?this.#p=!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.isInEditMode()&&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()}_moveAfterPaste(t,e){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i),this._onTranslated()}#C([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.#C(this.parentDimensions,t,e)}translateInPage(t,e){this.#g||=[this.x,this.y,this.width,this.height],this.#C(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#g||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:d,y:u}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,u)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[h,l]=this.getBaseTranslation();r+=h,o+=l;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.#g&&(this.#g[0]!==this.x||this.#g[1]!==this.y)}get _hasBeenResized(){return!!this.#g&&(this.#g[2]!==this.width||this.#g[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=z,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=zt(n,0,s-o),r=zt(r,0,i-h);break;case 90:n=zt(n,0,s-h),r=zt(r,o,i);break;case 180:n=zt(n,o,s),r=zt(r,h,i);break;case 270:n=zt(n,h,s),r=zt(r,0,i-o);break}this.x=n/=s,this.y=r/=i;const[l,c]=this.getBaseTranslation();n+=l,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#O(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 z.#O(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return z.#O(t,e,360-this.parentRotation)}#E(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.#a||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#a&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#a&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#M(){if(this.#h)return;this.#h=document.createElement("div"),this.#h.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.#h.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#F.bind(this,s),{signal:e}),i.addEventListener("contextmenu",ae,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#h)}#F(t,e){e.preventDefault();const{isMac:s}=Tt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#l=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#I.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",wt,{passive:!1,signal:r}),window.addEventListener("contextmenu",ae,{signal:r}),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,this.#R()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{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(){}#R(){if(!this.#u)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#u;this.#u=null;const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:this.#L.bind(this,n,r,o,h),undo:this.#L.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#I(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=z.MIN_SIZE/s,c=z.MIN_SIZE/i,d=this.#E(this.rotation),u=(O,L)=>[d[0]*O+d[2]*L,d[1]*O+d[3]*L],f=this.#E(360-this.rotation),g=(O,L)=>[f[0]*O+f[2]*L,f[1]*O+f[3]*L];let p,y,m=!1,b=!1;switch(t){case"topLeft":m=!0,p=(O,L)=>[0,0],y=(O,L)=>[O,L];break;case"topMiddle":p=(O,L)=>[O/2,0],y=(O,L)=>[O/2,L];break;case"topRight":m=!0,p=(O,L)=>[O,0],y=(O,L)=>[0,L];break;case"middleRight":b=!0,p=(O,L)=>[O,L/2],y=(O,L)=>[0,L/2];break;case"bottomRight":m=!0,p=(O,L)=>[O,L],y=(O,L)=>[0,0];break;case"bottomMiddle":p=(O,L)=>[O/2,L],y=(O,L)=>[O/2,0];break;case"bottomLeft":m=!0,p=(O,L)=>[0,L],y=(O,L)=>[O,0];break;case"middleLeft":b=!0,p=(O,L)=>[0,L/2],y=(O,L)=>[O,L/2];break}const v=p(o,h),_=y(o,h);let w=u(..._);const x=z._round(n+w[0]),T=z._round(r+w[1]);let A=1,k=1,R,D;if(e.fromKeyboard)({deltaX:R,deltaY:D}=e);else{const{screenX:O,screenY:L}=e,[H,Z]=this.#l;[R,D]=this.screenToPageTranslation(O-H,L-Z),this.#l[0]=O,this.#l[1]=L}if([R,D]=g(R/s,D/i),m){const O=Math.hypot(o,h);A=k=Math.max(Math.min(Math.hypot(_[0]-v[0]-R,_[1]-v[1]-D)/O,1/o,1/h),l/o,c/h)}else b?A=zt(Math.abs(_[0]-v[0]-R),l,1)/o:k=zt(Math.abs(_[1]-v[1]-D),c,1)/h;const F=z._round(o*A),M=z._round(h*k);w=u(...y(F,M));const P=x-w[0],B=T-w[1];this.#g||=[this.x,this.y,this.width,this.height],this.width=F,this.height=M,this.x=P,this.y=B,this.setDims(s*F,i*M),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#m)return this._editToolbar;this._editToolbar=new Ci(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,s]of t)await this._editToolbar.addButton(e,s);return this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),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()}createAltText(){return this.#s||(De.initialize(z._l10n),this.#s=new De(this),this.#t&&(this.#s.data=this.#t,this.#t=null)),this.#s}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}addCommentButton(){return this.#i?this.#i:this.#i=new $n(this)}get commentColor(){return null}get comment(){const t=this.#i;return{text:t.data.text,date:t.data.date,deleted:t.isDeleted(),color:this.commentColor}}set comment(t){this.#i||(this.#i=new $n(this)),this.#i.data=t}setCommentData(t){this.#i||(this.#i=new $n(this)),this.#i.setInitialText(t)}get hasEditedComment(){return this.#i?.hasBeenEdited()}async editComment(){this.#i||(this.#i=new $n(this)),this.#i.edit()}addComment(t){if(this.hasEditedComment){const[,,,i]=t.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,o=r+n+1,h=i-100,l=o+180;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[o,h,l,i]}}}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#r?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#z();const[e,s]=this.parentDimensions;this.parentRotation%180!==0&&(t.style.maxWidth=`${(100*s/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/s).toFixed(2)}%`);const[i,n]=this.getInitialTranslation();return this.translate(i,n),ml(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new qn({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#P.bind(this),onPinching:this.#j.bind(this),onPinchEnd:this.#A.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),t}#P(){this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#j(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#E(this.rotation),o=(x,T)=>[r[0]*x+r[2]*T,r[1]*x+r[3]*T],[h,l]=this.parentDimensions,c=this.x,d=this.y,u=this.width,f=this.height,g=z.MIN_SIZE/h,p=z.MIN_SIZE/l;n=Math.max(Math.min(n,1/u,1/f),g/u,p/f);const y=z._round(u*n),m=z._round(f*n);if(y===u&&m===f)return;this.#g||=[c,d,u,f];const b=o(u/2,f/2),v=z._round(c+b[0]),_=z._round(d+b[1]),w=o(y/2,m/2);this.x=v-w[0],this.y=_-w[1],this.width=y,this.height=m,this.setDims(h*y,l*m),this.fixAndSetPosition(),this._onResizing()}#A(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#R()}pointerdown(t){const{isMac:e}=Tt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#p=!0,this._isDraggable){this.#H(t);return}this.#_(t)}#_(t){const{isMac:e}=Tt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#H(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=l=>{i.abort(),this.#n=null,this.#p=!1,this._uiManager.endDragSession()||this.#_(l),s&&this._onStopDragging()};e&&(this.#w=t.clientX,this.#x=t.clientY,this.#n=t.pointerId,this.#o=t.pointerType,window.addEventListener("pointermove",l=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:d,pointerId:u}=l;if(u!==this.#n){wt(l);return}const[f,g]=this.screenToPageTranslation(c-this.#w,d-this.#x);this.#w=c,this.#x=d,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",wt,r),window.addEventListener("pointerdown",l=>{l.pointerType===this.#o&&(this.#S||l.isPrimary)&&o(l),wt(l)},r));const h=l=>{if(!this.#n||this.#n===l.pointerId){o(l);return}wt(l)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.#y=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,h]=this.pageTranslation,l=t/i,c=e/i,d=this.x*n,u=this.y*r,f=this.width*n,g=this.height*r;switch(s){case 0:return[d+l+o,r-u-c-g+h,d+l+f+o,r-u-c+h];case 90:return[d+c+o,r-u+l+h,d+c+g+o,r-u+l+f+h];case 180:return[d-l-f+o,r-u+c+h,d-l+o,r-u+c+g+h];case 270:return[d-c-g+o,r-u-l-f+h,d-c+o,r-u-l+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,o,h];case 90:return[s,e-i,h,o];case 180:return[n,e-i,o,h];case 270:return[n,e-r,h,o];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return this.isInEditMode()?!1:(this.parent.setEditingState(!1),this.#m=!0,!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),this.#m=!1,!0):!1}isInEditMode(){return this.#m}shouldGetKeyboardEvents(){return this.#v}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}#z(){if(this.#c||!this.div)return;this.#c=new AbortController;const t=this._uiManager.combinedSignal(this.#c);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#z()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){tt("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s,annotationElementId:t.annotationElementId});i.rotation=t.rotation,i.#t=t.accessibilityData,i._isCopy=t.isCopy||!1;const[n,r]=i.pageDimensions,[o,h,l,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#c?.abort(),this.#c=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#y&&(clearTimeout(this.#y),this.#y=null),this.#B(),this.removeEditToolbar(),this.#b){for(const t of this.#b.values())clearTimeout(t);this.#b=null}this.parent=null,this.#S?.destroy(),this.#S=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#M(),this.#h.classList.remove("hidden"))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#h.children;if(!this.#e){this.#e=Array.from(e);const r=this.#V.bind(this),o=this.#$.bind(this),h=this._uiManager._signal;for(const l of this.#e){const c=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:h}),l.addEventListener("blur",o,{signal:h}),l.addEventListener("focus",this.#X.bind(this,c),{signal:h}),l.setAttribute("data-l10n-id",z._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.#h.append(this.#h.firstChild);else if(n>i)for(let o=0;o<n-i;o++)this.#h.firstChild.before(this.#h.lastChild);let r=0;for(const o of e){const l=this.#e[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",z._l10nResizer[l])}}this.#Y(0),this.#v=!0,this.#h.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#V(t){z._resizerKeyboardManager.exec(this,t)}#$(t){this.#v&&t.relatedTarget?.parentNode!==this.#h&&this.#B()}#X(t){this.#f=this.#v?t:""}#Y(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#v&&this.#I(this.#f,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#v=!1,this.#Y(-1),this.#R()}_stopResizingWithKeyboard(){this.#B(),this.div.focus()}select(){if(!(this.isSelected&&this._editToolbar)){if(this.isSelected=!0,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.isSelected&&(this.isSelected=!1,this.#h?.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(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.id})}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#d}set isEditing(t){this.#d=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#a=!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.#b||=new Map;const{action:s}=t;let i=this.#b.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#b.delete(s),this.#b.size===0&&(this.#b=null)},z._telemetryTimeout),this.#b.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.#r=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#r=!0}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;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 _f extends z{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const yl=3285377520,he=4294901760,Pe=65535;class bl{constructor(t){this.h1=t?t&4294967295:yl,this.h2=t?t&4294967295:yl}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,y=t.length;p<y;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,h=0,l=this.h1,c=this.h2;const d=3432918353,u=461845907,f=d&Pe,g=u&Pe;for(let p=0;p<i;p++)p&1?(o=r[p],o=o*d&he|o*f&Pe,o=o<<15|o>>>17,o=o*u&he|o*g&Pe,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[p],h=h*d&he|h*f&Pe,h=h<<15|h>>>17,h=h*u&he|h*g&Pe,c^=h,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*d&he|o*f&Pe,o=o<<15|o>>>17,o=o*u&he|o*g&Pe,i&1?l^=o:c^=o}this.h1=l,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&he|t*36045&Pe,e=e*4283543511&he|((e<<16|t>>>16)*2950163797&he)>>>16,t^=e>>>1,t=t*444984403&he|t*60499&Pe,e=e*3301882366&he|((e<<16|t>>>16)*3120437893&he)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Ao=Object.freeze({map:null,hash:"",transfer:void 0});class To{#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 z)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 z&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}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 vl(this)}get serializable(){if(this.#s.size===0)return Ao;const t=new Map,e=new bl,s=[],i=Object.create(null);let n=!1;for(const[r,o]of this.#s){const h=o instanceof z?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||=!!h.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Ao}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof z))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,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const c=l.get(h)??0;l.set(h,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 z)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#s.entries()}}class vl extends To{#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(){tt("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return Y(this,"modifiedIds",{ids:new Set,hash:""})}}class wf{#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,disableFontFace:e,_inspectFont:s}){if(!(!t||this.#t.has(t.loadedName))){if(_t(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:n,style:r}=t,o=new FontFace(i,n,r);this.addNativeFontFace(o);try{await o.load(),this.#t.add(i),s?.(t)}catch{W(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(o)}return}tt("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 W(`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 Y(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){return Y(this,"isSyncFontLoadingSupported",Ht||Tt.platform.isFirefox)}_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 Y(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(_,w){return _.charCodeAt(w)<<24|_.charCodeAt(w+1)<<16|_.charCodeAt(w+2)<<8|_.charCodeAt(w+3)&255}function i(_,w,x,T){const A=_.substring(0,w),k=_.substring(w+x);return A+T+k}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function c(_,w){if(++l>30){W("Load test font never loaded."),w();return}if(h.font="30px "+_,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){w();return}setTimeout(c.bind(null,_,w))}const d=`lt${Date.now()}${this.loadTestFontId++}`;let u=this._loadTestFont;u=i(u,976,d.length,d);const g=16,p=1482184792;let y=s(u,g);for(n=0,r=d.length-3;n<r;n+=4)y=y-p+s(d,n)|0;n<d.length&&(y=y-p+s(d+"XXX",n)|0),u=i(u,g,4,rf(y));const m=`url(data:font/opentype;base64,${btoa(u)});`,b=`@font-face {font-family:"${d}";src:${m}}`;this.insertRule(b);const v=this._document.createElement("div");v.style.visibility="hidden",v.style.width=v.style.height="10px",v.style.position="absolute",v.style.top=v.style.left="0px";for(const _ of[t.loadedName,d]){const w=this._document.createElement("span");w.textContent="Hi",w.style.fontFamily=_,v.append(w)}this._document.body.append(v),c(d,()=>{v.remove(),e.complete()})}}class xf{constructor(t,e=null){this.compiledGlyphs=Object.create(null);for(const s in t)this[s]=t[s];this._inspectFont=e}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,${gl(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){W(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}function Sf(a){if(a instanceof URL)return a.href;if(typeof a=="string"){if(Ht)return a;const t=URL.parse(a,window.location);if(t)return t.href}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Cf(a){if(Ht&&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 _i(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 Kn(a){if(typeof a!="string")return null;if(a.endsWith("/"))return a;throw new Error(`Invalid factory url: "${a}" must include trailing slash.`)}const Eo=a=>typeof a=="object"&&Number.isInteger(a?.num)&&a.num>=0&&Number.isInteger(a?.gen)&&a.gen>=0,Af=a=>typeof a=="object"&&typeof a?.name=="string",Tf=cf.bind(null,Eo,Af);class Ef{#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){W("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 Jn={DATA:1,ERROR:2},xt={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function _l(){}function qt(a){if(a instanceof es||a instanceof po||a instanceof cl||a instanceof Un||a instanceof go)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||tt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new es(a.message);case"InvalidPDFException":return new po(a.message);case"PasswordException":return new cl(a.message,a.code);case"ResponseException":return new Un(a.message,a.status,a.missing);case"UnknownErrorException":return new go(a.message,a.details)}return new go(a.message,a.toString())}class Ti{#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(qt(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:qt(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,h=this.comObj;return new ReadableStream({start:l=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),c.promise},pull:l=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,h.postMessage({sourceName:r,targetName:o,stream:xt.PULL,streamId:n,desiredSize:l.desiredSize}),c.promise},cancel:l=>{_t(l instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:xt.CANCEL,streamId:n,reason:qt(l)}),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],h={enqueue(l,c=1,d){if(this.isCancelled)return;const u=this.desiredSize;this.desiredSize-=c,u>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:xt.ENQUEUE,streamId:e,chunk:l},d)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:xt.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){_t(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:xt.ERROR,streamId:e,reason:qt(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,Promise.try(o,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:xt.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:xt.START_COMPLETE,streamId:e,reason:qt(l)})})}#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 xt.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(qt(t.reason));break;case xt.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(qt(t.reason));break;case xt.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:xt.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:xt.PULL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:xt.PULL_COMPLETE,streamId:e,reason:qt(l)})});break;case xt.ENQUEUE:if(_t(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case xt.CLOSE:if(_t(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case xt.ERROR:_t(r,"error should have stream controller"),r.controller.error(qt(t.reason)),this.#r(r,e);break;case xt.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(qt(t.reason)),this.#r(r,e);break;case xt.CANCEL:if(!o)break;const h=qt(t.reason);Promise.try(o.onCancel||_l,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:xt.CANCEL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:xt.CANCEL_COMPLETE,streamId:e,reason:qt(l)})}),o.sinkCapability.reject(h),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 wl{#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){tt("Abstract method `_createCanvas` called.")}}class kf extends wl{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 xl{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){tt("Abstract method `_fetch` called.")}}class Sl extends xl{async _fetch(t){const e=await wi(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):_i(e)}}class Cl{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 Mf extends Cl{#t;#e;#s;#i;#r;#n;#o=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#a(){return this.#e||=new Map}get#h(){return this.#n||=new Map}get#l(){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(Xe,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(Xe,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#u(t){if(t.length===1){const h=t[0],l=new Array(256);for(let d=0;d<256;d++)l[d]=h[d]/255;const c=l.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),o=new Array(256);for(let h=0;h<256;h++)n[h]=e[h]/255,r[h]=s[h]/255,o[h]=i[h]/255;return[n.join(","),r.join(","),o.join(",")]}#c(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Xn(e)?W('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=ll(e,""))}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.#u(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.#o++}`,h=this.#c(o);this.#a.set(t,h),this.#a.set(r,h);const l=this.#g(o);return this.#m(s,i,n,l),h}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#h.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.#h.set(i,n)),!t||!e))return n.url;const r=this.#y(t);t=j.makeHexColor(...r);const o=this.#y(e);if(e=j.makeHexColor(...o),this.#l.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const h=new Array(256);for(let f=0;f<=255;f++){const g=f/255;h[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const l=h.join(","),c=`g_${this.#i}_hcm_filter`,d=n.filter=this.#g(c);this.#m(l,l,l,d),this.#p(d);const u=(f,g)=>{const p=r[f]/255,y=o[f]/255,m=new Array(g+1);for(let b=0;b<=g;b++)m[b]=p+b/g*(y-p);return m.join(",")};return this.#m(u(0,5),u(1,5),u(2,5),d),n.url=this.#c(c),n.url}addAlphaFilter(t){let e=this.#a.get(t);if(e)return e;const[s]=this.#u([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.#o++}`,r=this.#c(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#v(s,o),r}addLuminosityFilter(t){let e=this.#a.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#u([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.#o++}`,r=this.#c(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#f(o),t&&this.#v(s,o),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let o=this.#h.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.#h.set(t,o)),!e||!s))return o.url;const[h,l]=[e,s].map(this.#y.bind(this));let c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[u,f]=[i,n].map(this.#y.bind(this));d<c&&([c,d,u,f]=[d,c,f,u]),this.#l.style.color="";const g=(m,b,v)=>{const _=new Array(256),w=(d-c)/v,x=m/255,T=(b-m)/(255*v);let A=0;for(let k=0;k<=v;k++){const R=Math.round(c+k*w),D=x+k*T;for(let F=A;F<=R;F++)_[F]=D;A=R+1}for(let k=A;k<256;k++)_[k]=_[A-1];return _.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,y=o.filter=this.#g(p);return this.#p(y),this.#m(g(u[0],f[0],5),g(u[1],f[1],5),g(u[2],f[2],5),y),o.url=this.#c(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.#o=0)}#f(t){const e=this.#r.createElementNS(Xe,"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)}#p(t){const e=this.#r.createElementNS(Xe,"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(Xe,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#l.append(e),e}#d(t,e,s){const i=this.#r.createElementNS(Xe,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#m(t,e,s,i){const n=this.#r.createElementNS(Xe,"feComponentTransfer");i.append(n),this.#d(n,"feFuncR",t),this.#d(n,"feFuncG",e),this.#d(n,"feFuncB",s)}#v(t,e){const s=this.#r.createElementNS(Xe,"feComponentTransfer");e.append(s),this.#d(s,"feFuncA",t)}#y(t){return this.#l.style.color=t,Yn(getComputedStyle(this.#l).getPropertyValue("color"))}}class Al{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){tt("Abstract method `_fetch` called.")}}class Tl extends Al{async _fetch(t){const e=await wi(t,"arraybuffer");return new Uint8Array(e)}}class El{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load wasm data at: ${e}`)})}async _fetch(t){tt("Abstract method `_fetch` called.")}}class kl extends El{async _fetch(t){const e=await wi(t,"arraybuffer");return new Uint8Array(e)}}Ht&&W("Please use the `legacy` build in Node.js environments.");async function ko(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class Df extends Cl{}class Pf extends wl{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ut&&ut.tagName.toUpperCase()==="SCRIPT"&&ut.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class Of extends xl{async _fetch(t){return ko(t)}}class Lf extends Al{async _fetch(t){return ko(t)}}class Rf extends El{async _fetch(t){return ko(t)}}const Ys="__forcedDependency";class Ff{#t={__proto__:null};#e={__proto__:null,transform:[],moveText:[],sameLineText:[],[Ys]:[]};#s=new Map;#i=[];#r=[];#n=[[1,0,0,1,0,0]];#o=[-1/0,-1/0,1/0,1/0];#a=new Float64Array([1/0,1/0,-1/0,-1/0]);#h=-1;#l=new Set;#u=new Map;#c=new Map;#f;#p;constructor(t){this.#f=t.width,this.#p=t.height}save(t){return this.#t={__proto__:this.#t},this.#e={__proto__:this.#e,transform:{__proto__:this.#e.transform},moveText:{__proto__:this.#e.moveText},sameLineText:{__proto__:this.#e.sameLineText},[Ys]:{__proto__:this.#e[Ys]}},this.#o={__proto__:this.#o},this.#i.push([t,null]),this}restore(t){const e=Object.getPrototypeOf(this.#t);if(e===null)return this;this.#t=e,this.#e=Object.getPrototypeOf(this.#e),this.#o=Object.getPrototypeOf(this.#o);const s=this.#i.pop();return s!==void 0&&(s[1]=t),this}recordOpenMarker(t){return this.#i.push([t,null]),this}getOpenMarker(){return this.#i.length===0?null:this.#i.at(-1)[0]}recordCloseMarker(t){const e=this.#i.pop();return e!==void 0&&(e[1]=t),this}beginMarkedContent(t){return this.#r.push([t,null]),this}endMarkedContent(t){const e=this.#r.pop();return e!==void 0&&(e[1]=t),this}pushBaseTransform(t){return this.#n.push(j.multiplyByDOMMatrix(this.#n.at(-1),t.getTransform())),this}popBaseTransform(){return this.#n.length>1&&this.#n.pop(),this}recordSimpleData(t,e){return this.#t[t]=e,this}recordIncrementalData(t,e){return this.#e[t].push(e),this}resetIncrementalData(t,e){return this.#e[t].length=0,this}recordNamedData(t,e){return this.#s.set(t,e),this}recordFutureForcedDependency(t,e){return this.recordIncrementalData(Ys,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#t&&this.recordFutureForcedDependency(e,this.#t[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#l)this.recordFutureForcedDependency(Ys,t);return this}resetBBox(t){return this.#h=t,this.#a[0]=1/0,this.#a[1]=1/0,this.#a[2]=-1/0,this.#a[3]=-1/0,this}get hasPendingBBox(){return this.#h!==-1}recordClipBox(t,e,s,i,n,r){const o=j.multiplyByDOMMatrix(this.#n.at(-1),e.getTransform()),h=[1/0,1/0,-1/0,-1/0];j.axialAlignedBoundingBox([s,n,i,r],o,h);const l=j.intersect(this.#o,h);return l?(this.#o[0]=l[0],this.#o[1]=l[1],this.#o[2]=l[2],this.#o[3]=l[3]):(this.#o[0]=this.#o[1]=1/0,this.#o[2]=this.#o[3]=-1/0),this}recordBBox(t,e,s,i,n,r){const o=this.#o;if(o[0]===1/0)return this;const h=j.multiplyByDOMMatrix(this.#n.at(-1),e.getTransform());if(o[0]===-1/0)return j.axialAlignedBoundingBox([s,n,i,r],h,this.#a),this;const l=[1/0,1/0,-1/0,-1/0];return j.axialAlignedBoundingBox([s,n,i,r],h,l),this.#a[0]=Math.min(this.#a[0],Math.max(l[0],o[0])),this.#a[1]=Math.min(this.#a[1],Math.max(l[1],o[1])),this.#a[2]=Math.max(this.#a[2],Math.min(l[2],o[2])),this.#a[3]=Math.max(this.#a[3],Math.min(l[3],o[3])),this}recordCharacterBBox(t,e,s,i=1,n=0,r=0,o){const h=s.bbox;let l,c;if(h&&(l=h[2]!==h[0]&&h[3]!==h[1]&&this.#c.get(s),l!==!1&&(c=[0,0,0,0],j.axialAlignedBoundingBox(h,s.fontMatrix,c),(i!==1||n!==0||r!==0)&&j.scaleMinMax([i,0,0,-i,n,r],c),l)))return this.recordBBox(t,e,c[0],c[2],c[1],c[3]);if(!o)return this.recordFullPageBBox(t);const d=o();return h&&c&&l===void 0&&(l=c[0]<=n-d.actualBoundingBoxLeft&&c[2]>=n+d.actualBoundingBoxRight&&c[1]<=r-d.actualBoundingBoxAscent&&c[3]>=r+d.actualBoundingBoxDescent,this.#c.set(s,l),l)?this.recordBBox(t,e,c[0],c[2],c[1],c[3]):this.recordBBox(t,e,n-d.actualBoundingBoxLeft,n+d.actualBoundingBoxRight,r-d.actualBoundingBoxAscent,r+d.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#a[0]=Math.max(0,this.#o[0]),this.#a[1]=Math.max(0,this.#o[1]),this.#a[2]=Math.min(this.#f,this.#o[2]),this.#a[3]=Math.min(this.#p,this.#o[3]),this}getSimpleIndex(t){return this.#t[t]}recordDependencies(t,e){const s=this.#l,i=this.#t,n=this.#e;for(const r of e)r in this.#t?s.add(i[r]):r in n&&n[r].forEach(s.add,s);return this}copyDependenciesFromIncrementalOperation(t,e){const s=this.#u,i=this.#l;for(const n of this.#e[e])s.get(n).dependencies.forEach(i.add,i.add(n));return this}recordNamedDependency(t,e){return this.#s.has(e)&&this.#l.add(this.#s.get(e)),this}recordOperation(t,e=!1){this.recordDependencies(t,[Ys]);const s=new Set(this.#l),i=this.#i.concat(this.#r),n=this.#h===t?{minX:this.#a[0],minY:this.#a[1],maxX:this.#a[2],maxY:this.#a[3]}:null;return this.#u.set(t,{bbox:n,pairs:i,dependencies:s}),e||(this.#h=-1),this.#l.clear(),this}bboxToClipBoxDropOperation(t){return this.#h!==-1&&(this.#h=-1,this.#o[0]=Math.max(this.#o[0],this.#a[0]),this.#o[1]=Math.max(this.#o[1],this.#a[1]),this.#o[2]=Math.min(this.#o[2],this.#a[2]),this.#o[3]=Math.min(this.#o[3],this.#a[3])),this.#l.clear(),this}_takePendingDependencies(){const t=this.#l;return this.#l=new Set,t}_extractOperation(t){const e=this.#u.get(t);return this.#u.delete(t),e}_pushPendingDependencies(t){for(const e of t)this.#l.add(e)}take(){return this.#c.clear(),Array.from(this.#u,([t,{bbox:e,pairs:s,dependencies:i}])=>(s.forEach(n=>n.forEach(i.add,i)),i.delete(t),{minX:(e?.minX??0)/this.#f,maxX:(e?.maxX??this.#f)/this.#f,minY:(e?.minY??0)/this.#p,maxY:(e?.maxY??this.#p)/this.#p,dependencies:Array.from(i).sort((n,r)=>n-r),idx:t}))}}class Zn{#t;#e;#s=0;#i;#r=0;constructor(t,e){if(t instanceof Zn)return t;this.#t=t,this.#i=t._takePendingDependencies(),this.#e=e}save(t){return this.#r++,this.#t.save(this.#e),this}restore(t){return this.#r>0&&(this.#t.restore(this.#e),this.#r--),this}recordOpenMarker(t){return this.#s++,this}getOpenMarker(){return this.#s>0?this.#e:this.#t.getOpenMarker()}recordCloseMarker(t){return this.#s--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#t.pushBaseTransform(t),this}popBaseTransform(){return this.#t.popBaseTransform(),this}recordSimpleData(t,e){return this.#t.recordSimpleData(t,this.#e),this}recordIncrementalData(t,e){return this.#t.recordIncrementalData(t,this.#e),this}resetIncrementalData(t,e){return this.#t.resetIncrementalData(t,this.#e),this}recordNamedData(t,e){return this}recordFutureForcedDependency(t,e){return this.#t.recordFutureForcedDependency(t,this.#e),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#t.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#t.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#t.hasPendingBBox||this.#t.resetBBox(this.#e),this}get hasPendingBBox(){return this.#t.hasPendingBBox}recordClipBox(t,e,s,i,n,r){return this.#t.recordClipBox(this.#e,e,s,i,n,r),this}recordBBox(t,e,s,i,n,r){return this.#t.recordBBox(this.#e,e,s,i,n,r),this}recordCharacterBBox(t,e,s,i,n,r,o){return this.#t.recordCharacterBBox(this.#e,e,s,i,n,r,o),this}recordFullPageBBox(t){return this.#t.recordFullPageBBox(this.#e),this}getSimpleIndex(t){return this.#t.getSimpleIndex(t)}recordDependencies(t,e){return this.#t.recordDependencies(this.#e,e),this}copyDependenciesFromIncrementalOperation(t,e){return this.#t.copyDependenciesFromIncrementalOperation(this.#e,e),this}recordNamedDependency(t,e){return this.#t.recordNamedDependency(this.#e,e),this}recordOperation(t){this.#t.recordOperation(this.#e,!0);const e=this.#t._extractOperation(this.#e);for(const s of e.dependencies)this.#i.add(s);return this.#i.delete(this.#e),this.#i.delete(null),this}bboxToClipBoxDropOperation(t){return this.#t.bboxToClipBoxDropOperation(this.#e),this}recordNestedDependencies(){this.#t._pushPendingDependencies(this.#i)}take(){throw new Error("Unreachable")}}const le={stroke:["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],fill:["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],imageXObject:["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],rawFillPath:["filter","fillColor","fillAlpha"],showText:["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation"],transform:["transform"],transformAndFill:["transform","fillColor"]},Et={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Mo(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 Do{isModifyingCurrentTransform(){return!1}getPattern(){tt("Abstract method `getPattern` called.")}}class If extends Do{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===Et.STROKE||i===Et.FILL){const r=e.current.getClippedPathBoundingBox(i,ht(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),c=l.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=j.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),Mo(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(s);n.setTransform(d)}else Mo(t,this._bbox),n=this._createGradient(t);return n}}function Po(a,t,e,s,i,n,r,o){const h=t.coords,l=t.colors,c=a.data,d=a.width*4;let u;h[e+1]>h[s+1]&&(u=e,e=s,s=u,u=n,n=r,r=u),h[s+1]>h[i+1]&&(u=s,s=i,i=u,u=r,r=o,o=u),h[e+1]>h[s+1]&&(u=e,e=s,s=u,u=n,n=r,r=u);const f=(h[e]+t.offsetX)*t.scaleX,g=(h[e+1]+t.offsetY)*t.scaleY,p=(h[s]+t.offsetX)*t.scaleX,y=(h[s+1]+t.offsetY)*t.scaleY,m=(h[i]+t.offsetX)*t.scaleX,b=(h[i+1]+t.offsetY)*t.scaleY;if(g>=b)return;const v=l[n],_=l[n+1],w=l[n+2],x=l[r],T=l[r+1],A=l[r+2],k=l[o],R=l[o+1],D=l[o+2],F=Math.round(g),M=Math.round(b);let P,B,O,L,H,Z,ct,Ut;for(let dt=F;dt<=M;dt++){if(dt<y){const et=dt<g?0:(g-dt)/(g-y);P=f-(f-p)*et,B=v-(v-x)*et,O=_-(_-T)*et,L=w-(w-A)*et}else{let et;dt>b?et=1:y===b?et=0:et=(y-dt)/(y-b),P=p-(p-m)*et,B=x-(x-k)*et,O=T-(T-R)*et,L=A-(A-D)*et}let it;dt<g?it=0:dt>b?it=1:it=(g-dt)/(g-b),H=f-(f-m)*it,Z=v-(v-k)*it,ct=_-(_-R)*it,Ut=w-(w-D)*it;const Xt=Math.round(Math.min(P,H)),ne=Math.round(Math.max(P,H));let Lt=d*dt+Xt*4;for(let et=Xt;et<=ne;et++)it=(P-et)/(P-H),it<0?it=0:it>1&&(it=1),c[Lt++]=B-(B-Z)*it|0,c[Lt++]=O-(O-ct)*it|0,c[Lt++]=L-(L-Ut)*it|0,c[Lt++]=255}}function Bf(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,h=Math.floor(s.length/o)-1,l=o-1;for(n=0;n<h;n++){let c=n*o;for(let d=0;d<l;d++,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 Nf extends Do{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null}_createMeshCanvas(t,e,s){const o=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-o,c=Math.ceil(this._bounds[3])-h,d=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),u=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=l/d,g=c/u,p={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/f,scaleY:1/g},y=d+4,m=u+4,b=s.getCanvas("mesh",y,m),v=b.context,_=v.createImageData(d,u);if(e){const x=_.data;for(let T=0,A=x.length;T<A;T+=4)x[T]=e[0],x[T+1]=e[1],x[T+2]=e[2],x[T+3]=255}for(const x of this._figures)Bf(_,x,p);return v.putImageData(_,2,2),{canvas:b.canvas,offsetX:o-2*f,offsetY:h-2*g,scaleX:f,scaleY:g}}isModifyingCurrentTransform(){return!0}getPattern(t,e,s,i){Mo(t,this._bbox);const n=new Float32Array(2);if(i===Et.SHADING)j.singularValueDecompose2dScale(ht(t),n);else if(this.matrix){j.singularValueDecompose2dScale(this.matrix,n);const[o,h]=n;j.singularValueDecompose2dScale(e.baseTransform,n),n[0]*=o,n[1]*=h}else j.singularValueDecompose2dScale(e.baseTransform,n);const r=this._createMeshCanvas(n,i===Et.SHADING?null:this._background,e.cachedCanvases);return i!==Et.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 jf extends Do{getPattern(){return"hotpink"}}function Hf(a){switch(a[0]){case"RadialAxial":return new If(a);case"Mesh":return new Nf(a);case"Dummy":return new jf}throw new Error(`Unknown IR type: ${a[0]}`)}const Ml={COLORED:1,UNCOLORED:2};class Oo{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i){this.color=t[1],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.ctx=e,this.canvasGraphicsFactory=s,this.baseTransform=i}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),Wn("TilingType: "+n);const c=e[0],d=e[1],u=e[2],f=e[3],g=u-c,p=f-d,y=new Float32Array(2);j.singularValueDecompose2dScale(this.matrix,y);const[m,b]=y;j.singularValueDecompose2dScale(this.baseTransform,y);const v=m*y[0],_=b*y[1];let w=g,x=p,T=!1,A=!1;const k=Math.ceil(h*v),R=Math.ceil(l*_),D=Math.ceil(g*v),F=Math.ceil(p*_);k>=D?w=h:T=!0,R>=F?x=l:A=!0;const M=this.getSizeAndScale(w,this.ctx.canvas.width,v),P=this.getSizeAndScale(x,this.ctx.canvas.height,_),B=t.cachedCanvases.getCanvas("pattern",M.size,P.size),O=B.context,L=o.createCanvasGraphics(O);if(L.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(L,i,r),O.translate(-M.scale*c,-P.scale*d),L.transform(0,M.scale,0,0,P.scale,0,0),O.save(),L.dependencyTracker?.save(),this.clipBbox(L,c,d,u,f),L.baseTransform=ht(L.ctx),L.executeOperatorList(s),L.endDrawing(),L.dependencyTracker?.restore().recordNestedDependencies?.(),O.restore(),T||A){const H=B.canvas;T&&(w=h),A&&(x=l);const Z=this.getSizeAndScale(w,this.ctx.canvas.width,v),ct=this.getSizeAndScale(x,this.ctx.canvas.height,_),Ut=Z.size,dt=ct.size,it=t.cachedCanvases.getCanvas("pattern-workaround",Ut,dt),Xt=it.context,ne=T?Math.floor(g/h):0,Lt=A?Math.floor(p/l):0;for(let et=0;et<=ne;et++)for(let Es=0;Es<=Lt;Es++)Xt.drawImage(H,Ut*et,dt*Es,Ut,dt,0,0,Ut,dt);return{canvas:it.canvas,scaleX:Z.scale,scaleY:ct.scale,offsetX:c,offsetY:d}}return{canvas:B.canvas,scaleX:M.scale,scaleY:P.scale,offsetX:c,offsetY:d}}getSizeAndScale(t,e,s){const i=Math.max(Oo.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),j.axialAlignedBoundingBox([e,s,i,n],ht(t.ctx),t.current.minMax),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case Ml.COLORED:const{fillStyle:r,strokeStyle:o}=this.ctx;i.fillStyle=n.fillColor=r,i.strokeStyle=n.strokeColor=o;break;case Ml.UNCOLORED:i.fillStyle=i.strokeStyle=s,n.fillColor=n.strokeColor=s;break;default:throw new nf(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,s,i){let n=s;i!==Et.SHADING&&(n=j.transform(n,e.baseTransform),this.matrix&&(n=j.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let o=new DOMMatrix(n);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(o),h}}function zf({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Tt.isLittleEndian?4278190080:255,[h,l]=r?[n,o]:[o,n],c=s>>3,d=s&7,u=a.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const y=t+c;t<y;t++){const m=t<u?a[t]:255;e[f++]=m&128?l:h,e[f++]=m&64?l:h,e[f++]=m&32?l:h,e[f++]=m&16?l:h,e[f++]=m&8?l:h,e[f++]=m&4?l:h,e[f++]=m&2?l:h,e[f++]=m&1?l:h}if(d===0)continue;const p=t<u?a[t++]:255;for(let y=0;y<d;y++)e[f++]=p&1<<7-y?l:h}return{srcPos:t,destPos:f}}const Dl=16,Pl=100,Gf=15,Ol=10,Kt=16,Lo=new DOMMatrix,ie=new Float32Array(2),$s=new Float32Array([1/0,1/0,-1/0,-1/0]);function Vf(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(e,s){t.translate(e,s),this.__originalTranslate(e,s)},a.scale=function(e,s){t.scale(e,s),this.__originalScale(e,s)},a.transform=function(e,s,i,n,r,o){t.transform(e,s,i,n,r,o),this.__originalTransform(e,s,i,n,r,o)},a.setTransform=function(e,s,i,n,r,o){t.setTransform(e,s,i,n,r,o),this.__originalSetTransform(e,s,i,n,r,o)},a.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},a.rotate=function(e){t.rotate(e),this.__originalRotate(e)},a.clip=function(e){t.clip(e),this.__originalClip(e)},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 Wf{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 Qn(a,t,e,s,i,n,r,o,h,l){const[c,d,u,f,g,p]=ht(a);if(d===0&&u===0){const b=r*c+g,v=Math.round(b),_=o*f+p,w=Math.round(_),x=(r+h)*c+g,T=Math.abs(Math.round(x)-v)||1,A=(o+l)*f+p,k=Math.abs(Math.round(A)-w)||1;return a.setTransform(Math.sign(c),0,0,Math.sign(f),v,w),a.drawImage(t,e,s,i,n,0,0,T,k),a.setTransform(c,d,u,f,g,p),[T,k]}if(c===0&&f===0){const b=o*u+g,v=Math.round(b),_=r*d+p,w=Math.round(_),x=(o+l)*u+g,T=Math.abs(Math.round(x)-v)||1,A=(r+h)*d+p,k=Math.abs(Math.round(A)-w)||1;return a.setTransform(0,Math.sign(d),Math.sign(u),0,v,w),a.drawImage(t,e,s,i,n,0,0,k,T),a.setTransform(c,d,u,f,g,p),[k,T]}a.drawImage(t,e,s,i,n,r,o,h,l);const y=Math.hypot(c,d),m=Math.hypot(u,f);return[y*h,m*l]}class Ll{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=uo;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=At.FILL;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e,s){s?.(this),this.clipBox=new Float32Array([0,0,t,e]),this.minMax=$s.slice()}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t}getPathBoundingBox(t=Et.FILL,e=null){const s=this.minMax.slice();if(t===Et.STROKE){e||tt("Stroke bounding box must include transform."),j.singularValueDecompose2dScale(e,ie);const i=ie[0]*this.lineWidth/2,n=ie[1]*this.lineWidth/2;s[0]-=i,s[1]-=n,s[2]+=i,s[3]+=n}return s}updateClipFromPath(){const t=j.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set($s,0)}getClippedPathBoundingBox(t=Et.FILL,e=null){return j.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Rl(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Kt,n=(e-i)/Kt,r=i===0?n:n+1,o=a.createImageData(s,Kt);let h=0,l;const c=t.data,d=o.data;let u,f,g,p;if(t.kind===Hn.GRAYSCALE_1BPP){const y=c.byteLength,m=new Uint32Array(d.buffer,0,d.byteLength>>2),b=m.length,v=s+7>>3,_=4294967295,w=Tt.isLittleEndian?4278190080:255;for(u=0;u<r;u++){for(g=u<n?Kt:i,l=0,f=0;f<g;f++){const x=y-h;let T=0;const A=x>v?s:x*8-7,k=A&-8;let R=0,D=0;for(;T<k;T+=8)D=c[h++],m[l++]=D&128?_:w,m[l++]=D&64?_:w,m[l++]=D&32?_:w,m[l++]=D&16?_:w,m[l++]=D&8?_:w,m[l++]=D&4?_:w,m[l++]=D&2?_:w,m[l++]=D&1?_:w;for(;T<A;T++)R===0&&(D=c[h++],R=128),m[l++]=D&R?_:w,R>>=1}for(;l<b;)m[l++]=0;a.putImageData(o,0,u*Kt)}}else if(t.kind===Hn.RGBA_32BPP){for(f=0,p=s*Kt*4,u=0;u<n;u++)d.set(c.subarray(h,h+p)),h+=p,a.putImageData(o,0,f),f+=Kt;u<r&&(p=s*i*4,d.set(c.subarray(h,h+p)),a.putImageData(o,0,f))}else if(t.kind===Hn.RGB_24BPP)for(g=Kt,p=s*g,u=0;u<r;u++){for(u>=n&&(g=i,p=s*g),l=0,f=p;f--;)d[l++]=c[h++],d[l++]=c[h++],d[l++]=c[h++],d[l++]=255;a.putImageData(o,0,u*Kt)}else throw new Error(`bad image kind: ${t.kind}`)}function Fl(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Kt,n=(e-i)/Kt,r=i===0?n:n+1,o=a.createImageData(s,Kt);let h=0;const l=t.data,c=o.data;for(let d=0;d<r;d++){const u=d<n?Kt:i;({srcPos:h}=zf({src:l,srcPos:h,dest:c,width:s,height:u,nonBlackColor:0})),a.putImageData(o,0,d*Kt)}}function Ei(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 tr(a){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);const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}function Il(a,t){if(t)return!0;j.singularValueDecompose2dScale(a,ie);const e=Math.fround(Me.pixelRatio*Xs.PDF_TO_CSS_UNITS);return ie[0]<=e&&ie[1]<=e}const Uf=["butt","round","square"],Xf=["miter","round","bevel"],Yf={},Bl={};class qs{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l,c){this.ctx=t,this.current=new Ll(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.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 Wf(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=c??null}getObject(t,e,s=null){return typeof e=="string"?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):s}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...ht(this.compositeCtx))}this.ctx.save(),tr(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,n){const r=t.argsArray,o=t.fnArray;let h=e||0;const l=r.length;if(l===h)return h;const c=l-h>Ol&&typeof s=="function",d=c?Date.now()+Gf:0;let u=0;const f=this.commonObjs,g=this.objs;let p,y;for(;;){if(i!==void 0&&h===i.nextBreakPoint)return i.breakIt(h,s),h;if(!n||n.has(h))if(p=o[h],y=r[h]??null,p!==vi.dependency)y===null?this[p](h):this[p](h,...y);else for(const m of y){this.dependencyTracker?.recordNamedData(m,h);const b=m.startsWith("g_")?f:g;if(!b.has(m))return b.get(m,s),h}if(h++,h===l)return h;if(c&&++u>Ol){if(Date.now()>d)return s(),h;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,h=i,l="prescale1",c,d;for(;n>2&&o>1||r>2&&h>1;){let u=o,f=h;n>2&&o>1&&(u=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/u),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),c=this.cachedCanvases.getCanvas(l,u,f),d=c.context,d.clearRect(0,0,u,f),d.drawImage(t,0,0,o,h,0,0,u,f),t=c.canvas,o=u,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t,e){const s=this.ctx,{width:i,height:n}=e,r=this.current.fillColor,o=this.current.patternFill,h=ht(s);let l,c,d,u;if((e.bitmap||e.data)&&e.count>1){const R=e.bitmap||e.data.buffer;c=JSON.stringify(o?h:[h.slice(0,4),r]),l=this._cachedBitmapsMap.get(R),l||(l=new Map,this._cachedBitmapsMap.set(R,l));const D=l.get(c);if(D&&!o){const F=Math.round(Math.min(h[0],h[2])+h[4]),M=Math.round(Math.min(h[1],h[3])+h[5]);return this.dependencyTracker?.recordDependencies(t,le.transformAndFill),{canvas:D,offsetX:F,offsetY:M}}d=D}d||(u=this.cachedCanvases.getCanvas("maskCanvas",i,n),Fl(u.context,e));let f=j.transform(h,[1/i,0,0,-1/n,0,0]);f=j.transform(f,[1,0,0,1,0,-n]);const g=$s.slice();j.axialAlignedBoundingBox([0,0,i,n],f,g);const[p,y,m,b]=g,v=Math.round(m-p)||1,_=Math.round(b-y)||1,w=this.cachedCanvases.getCanvas("fillCanvas",v,_),x=w.context,T=p,A=y;x.translate(-T,-A),x.transform(...f),d||(d=this._scaleImage(u.canvas,ke(x)),d=d.img,l&&o&&l.set(c,d)),x.imageSmoothingEnabled=Il(ht(x),e.interpolate),Qn(x,d,0,0,d.width,d.height,0,0,i,n),x.globalCompositeOperation="source-in";const k=j.transform(ke(x),[1,0,0,1,-T,-A]);return x.fillStyle=o?r.getPattern(s,this,k,Et.FILL):r,x.fillRect(0,0,i,n),l&&!o&&(this.cachedCanvases.delete("fillCanvas"),l.set(c,w.canvas)),this.dependencyTracker?.recordDependencies(t,le.transformAndFill),{canvas:w.canvas,offsetX:Math.round(T),offsetY:Math.round(A)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Uf[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Xf[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,s){this.dependencyTracker?.recordSimpleData("dash",t);const i=this.ctx;i.setLineDash!==void 0&&(i.setLineDash(e),i.lineDashOffset=s)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[s,i]of e)switch(s){case"LW":this.setLineWidth(t,i);break;case"LC":this.setLineCap(t,i);break;case"LJ":this.setLineJoin(t,i);break;case"ML":this.setMiterLimit(t,i);break;case"D":this.setDash(t,i[0],i[1]);break;case"RI":this.setRenderingIntent(t,i);break;case"FL":this.setFlatness(t,i);break;case"Font":this.setFont(t,i[0],i[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=i;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=i;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=i;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,s=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,n=this.cachedCanvases.getCanvas(i,e,s);this.suspendedCtx=this.ctx;const r=this.ctx=n.context;r.setTransform(this.suspendedCtx.getTransform()),Ei(this.suspendedCtx,r),Vf(r,this.suspendedCtx),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Ei(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;o===0||h===0||(this.genericComposeSMask(e.context,s,o,h,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,o,h,l,c,d){let u=t.canvas,f=h-c,g=l-d;if(r)if(f<0||g<0||f+s>u.width||g+i>u.height){const y=this.cachedCanvases.getCanvas("maskExtension",s,i),m=y.context;m.drawImage(u,-f,-g),m.globalCompositeOperation="destination-atop",m.fillStyle=r,m.fillRect(0,0,s,i),m.globalCompositeOperation="source-over",u=y.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const y=new Path2D;y.rect(f,g,s,i),t.clip(y),t.globalCompositeOperation="destination-atop",t.fillStyle=r,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(h,l,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(u,f,g,s,i,h,l,s,i),e.restore()}save(t){this.inSMaskMode&&Ei(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){if(this.dependencyTracker?.restore(t),this.stateStack.length===0){this.inSMaskMode&&this.endSMaskMode();return}this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&Ei(this.suspendedCtx,this.ctx),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}transform(t,e,s,i,n,r,o){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,s,i,n,r,o),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s,i){let[n]=s;if(!i){n||=s[0]=new Path2D,this[e](t,n);return}if(this.dependencyTracker!==null){const r=e===vi.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,i[0]-r,i[2]+r,i[1]-r,i[3]+r).recordDependencies(t,["transform"])}if(!(n instanceof Path2D)){const r=s[0]=new Path2D;for(let o=0,h=n.length;o<h;)switch(n[o++]){case Gn.moveTo:r.moveTo(n[o++],n[o++]);break;case Gn.lineTo:r.lineTo(n[o++],n[o++]);break;case Gn.curveTo:r.bezierCurveTo(n[o++],n[o++],n[o++],n[o++],n[o++],n[o++]);break;case Gn.closePath:r.closePath();break;default:W(`Unrecognized drawing path operator: ${n[o-1]}`);break}n=r}j.axialAlignedBoundingBox(i,ht(this.ctx),this.current.minMax),this[e](t,n),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,s=!0){const i=this.ctx,n=this.current.strokeColor;if(i.globalAlpha=this.current.strokeAlpha,this.contentVisible)if(typeof n=="object"&&n?.getPattern){const r=n.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.strokeStyle=n.getPattern(i,this,ke(i),Et.STROKE),r){const o=new Path2D;o.addPath(e,i.getTransform().invertSelf().multiplySelf(r)),e=o}this.rescaleAndStroke(e,!1),i.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,le.stroke),s&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(Et.STROKE,ht(this.ctx))),i.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,s=!0){const i=this.ctx,n=this.current.fillColor,r=this.current.patternFill;let o=!1;if(r){const l=n.isModifyingCurrentTransform()?i.getTransform():null;if(this.dependencyTracker?.save(t),i.save(),i.fillStyle=n.getPattern(i,this,ke(i),Et.FILL),l){const c=new Path2D;c.addPath(e,i.getTransform().invertSelf().multiplySelf(l)),e=c}o=!0}const h=this.current.getClippedPathBoundingBox();this.contentVisible&&h!==null&&(this.pendingEOFill?(i.fill(e,"evenodd"),this.pendingEOFill=!1):i.fill(e)),this.dependencyTracker?.recordDependencies(t,le.fill),o&&(i.restore(),this.dependencyTracker?.restore(t)),s&&this.consumePath(t,e,h)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,le.rawFillPath).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Yf}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Bl}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,s=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;e!==void 0&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t),i.recordCloseMarker(t)}if(e!==void 0){const i=new Path2D,n=s.getTransform().invertSelf();for(const{transform:r,x:o,y:h,fontSize:l,path:c}of e)c&&i.addPath(c,new DOMMatrix(r).preMultiplySelf(n).translate(o,h).scale(l,-l));s.clip(i)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,s){this.dependencyTracker?.recordSimpleData("font",t).recordNamedDependency(t,e);const i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error(`Can't find font for ${e}`);if(n.fontMatrix=i.fontMatrix||uo,(n.fontMatrix[0]===0||n.fontMatrix[3]===0)&&W("Invalid font matrix for font "+e),s<0?(s=-s,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=s,i.isType3Font)return;const r=i.loadedName||"sans-serif",o=i.systemFontInfo?.css||`"${r}", ${i.fallbackName}`;let h="normal";i.black?h="900":i.bold&&(h="bold");const l=i.italic?"italic":"normal";let c=s;s<Dl?c=Dl:s>Pl&&(c=Pl),this.current.fontSizeScale=s/c,this.ctx.font=`${l} ${h} ${c}px ${o}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,s){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=s}setLeadingMoveText(t,e,s){this.setLeading(t,-s),this.moveText(t,e,s)}setTextMatrix(t,e){this.dependencyTracker?.recordSimpleData("textMatrix",t);const{current:s}=this;s.textMatrix=e,s.textMatrixScale=Math.hypot(e[0],e[1]),s.x=s.lineX=0,s.y=s.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#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,r){const o=this.ctx,h=this.current,l=h.font,c=h.textRenderingMode,d=h.fontSize/h.fontSizeScale,u=c&At.FILL_STROKE_MASK,f=!!(c&At.ADD_TO_PATH_FLAG),g=h.patternFill&&!l.missingFile,p=h.patternStroke&&!l.missingFile;let y;if((l.disableFontFace||f||g||p)&&!l.missingFile&&(y=l.getPathGenerator(this.commonObjs,e)),y&&(l.disableFontFace||g||p)){o.save(),o.translate(s,i),o.scale(d,-d),this.dependencyTracker?.recordCharacterBBox(t,o,l);let m;if(u===At.FILL||u===At.FILL_STROKE)if(n){m=o.getTransform(),o.setTransform(...n);const b=this.#s(y,m,n);o.fill(b)}else o.fill(y);if(u===At.STROKE||u===At.FILL_STROKE)if(r){m||=o.getTransform(),o.setTransform(...r);const{a:b,b:v,c:_,d:w}=m,x=j.inverseTransform(r),T=j.transform([b,v,_,w,0,0],x);j.singularValueDecompose2dScale(T,ie),o.lineWidth*=Math.max(ie[0],ie[1])/d,o.stroke(this.#s(y,m,r))}else o.lineWidth/=d,o.stroke(y);o.restore()}else(u===At.FILL||u===At.FILL_STROKE)&&(o.fillText(e,s,i),this.dependencyTracker?.recordCharacterBBox(t,o,l,d,s,i,()=>o.measureText(e))),(u===At.STROKE||u===At.FILL_STROKE)&&(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,o,l,d,s,i,()=>o.measureText(e)).recordDependencies(t,le.stroke),o.strokeText(e,s,i));f&&((this.pendingTextPaths||=[]).push({transform:ht(o),x:s,y:i,fontSize:d,path:y}),this.dependencyTracker?.recordCharacterBBox(t,o,l,d,s,i))}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 Y(this,"isFontSubpixelAAEnabled",s)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,le.showText).copyDependenciesFromIncrementalOperation(t,"sameLineText").resetBBox(t),this.current.textRenderingMode&At.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const s=this.current,i=s.font;if(i.isType3Font){this.showType3Text(t,e),this.dependencyTracker?.recordOperation(t).recordIncrementalData("sameLineText",t);return}const n=s.fontSize;if(n===0){this.dependencyTracker?.recordOperation(t);return}const r=this.ctx,o=s.fontSizeScale,h=s.charSpacing,l=s.wordSpacing,c=s.fontDirection,d=s.textHScale*c,u=e.length,f=i.vertical,g=f?1:-1,p=i.defaultVMetrics,y=n*s.fontMatrix[0],m=s.textRenderingMode===At.FILL&&!i.disableFontFace&&!s.patternFill;r.save(),s.textMatrix&&r.transform(...s.textMatrix),r.translate(s.x,s.y+s.textRise),c>0?r.scale(d,-1):r.scale(d,1);let b,v;if(s.patternFill){r.save();const A=s.fillColor.getPattern(r,this,ke(r),Et.FILL);b=ht(r),r.restore(),r.fillStyle=A}if(s.patternStroke){r.save();const A=s.strokeColor.getPattern(r,this,ke(r),Et.STROKE);v=ht(r),r.restore(),r.strokeStyle=A}let _=s.lineWidth;const w=s.textMatrixScale;if(w===0||_===0){const A=s.textRenderingMode&At.FILL_STROKE_MASK;(A===At.STROKE||A===At.FILL_STROKE)&&(_=this.getSinglePixelWidth())}else _/=w;if(o!==1&&(r.scale(o,o),_/=o),r.lineWidth=_,i.isInvalidPDFjsFont){const A=[];let k=0;for(const D of e)A.push(D.unicode),k+=D.width;const R=A.join("");if(r.fillText(R,0,0),this.dependencyTracker!==null){const D=r.measureText(R);this.dependencyTracker.recordBBox(t,this.ctx,-D.actualBoundingBoxLeft,D.actualBoundingBoxRight,-D.actualBoundingBoxAscent,D.actualBoundingBoxDescent).recordOperation(t).recordIncrementalData("sameLineText",t)}s.x+=k*y*d,r.restore(),this.compose();return}let x=0,T;for(T=0;T<u;++T){const A=e[T];if(typeof A=="number"){x+=g*A*n/1e3;continue}let k=!1;const R=(A.isSpace?l:0)+h,D=A.fontChar,F=A.accent;let M,P,B=A.width;if(f){const H=A.vmetric||p,Z=-(A.vmetric?H[1]:B*.5)*y,ct=H[2]*y;B=H?-H[0]:B,M=Z/o,P=(x+ct)/o}else M=x/o,P=0;let O;if(i.remeasure&&B>0){O=r.measureText(D);const H=O.width*1e3/n*o;if(B<H&&this.isFontSubpixelAAEnabled){const Z=B/H;k=!0,r.save(),r.scale(Z,1),M/=Z}else B!==H&&(M+=(B-H)/2e3*n/o)}if(this.contentVisible&&(A.isInFont||i.missingFile)){if(m&&!F)r.fillText(D,M,P),this.dependencyTracker?.recordCharacterBBox(t,r,O?{bbox:null}:i,n/o,M,P,()=>O??r.measureText(D));else if(this.paintChar(t,D,M,P,b,v),F){const H=M+n*F.offset.x/o,Z=P-n*F.offset.y/o;this.paintChar(t,F.fontChar,H,Z,b,v)}}const L=f?B*y-R*c:B*y+R*c;x+=L,k&&r.restore()}f?s.y-=x:s.x+=x*d,r.restore(),this.compose(),this.dependencyTracker?.recordOperation(t).recordIncrementalData("sameLineText",t)}showType3Text(t,e){const s=this.ctx,i=this.current,n=i.font,r=i.fontSize,o=i.fontDirection,h=n.vertical?1:-1,l=i.charSpacing,c=i.wordSpacing,d=i.textHScale*o,u=i.fontMatrix||uo,f=e.length,g=i.textRenderingMode===At.INVISIBLE;let p,y,m,b;if(g||r===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,s.save(),i.textMatrix&&s.transform(...i.textMatrix),s.translate(i.x,i.y+i.textRise),s.scale(d,o);const v=this.dependencyTracker;for(this.dependencyTracker=v?new Zn(v,t):null,p=0;p<f;++p){if(y=e[p],typeof y=="number"){b=h*y*r/1e3,this.ctx.translate(b,0),i.x+=b*d;continue}const _=(y.isSpace?c:0)+l,w=n.charProcOperatorList[y.operatorListId];w?this.contentVisible&&(this.save(),s.scale(r,r),s.transform(...u),this.executeOperatorList(w),this.restore()):W(`Type3 character "${y.operatorListId}" is not available.`);const x=[y.width,0];j.applyTransform(x,u),m=x[0]*r+_,s.translate(m,0),i.x+=m*d}s.restore(),v&&(this.dependencyTracker.recordNestedDependencies(),this.dependencyTracker=v)}setCharWidth(t,e,s){}setCharWidthAndBounds(t,e,s,i,n,r,o){const h=new Path2D;h.rect(i,n,r-i,o-n),this.ctx.clip(h),this.dependencyTracker?.recordBBox(t,this.ctx,i,r,n,o).recordClipBox(t,this.ctx,i,r,n,o),this.endPath(t)}getColorN_Pattern(t,e){let s;if(e[0]==="TilingPattern"){const i=this.baseTransform||ht(this.ctx),n={createCanvasGraphics:r=>new qs(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new Zn(this.dependencyTracker,t):null)};s=new Oo(e,this.ctx,n,i)}else s=this._getPattern(t,e[1],e[2]);return s}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.current.fillColor=this.getColorN_Pattern(t,e),this.current.patternFill=!0}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e,s=null){let i;return this.cachedPatterns.has(e)?i=this.cachedPatterns.get(e):(i=Hf(this.getObject(t,e)),this.cachedPatterns.set(e,i)),s&&(i.matrix=s),i}shadingFill(t,e){if(!this.contentVisible)return;const s=this.ctx;this.save(t);const i=this._getPattern(t,e);s.fillStyle=i.getPattern(s,this,ke(s),Et.SHADING);const n=ke(s);if(n){const{width:r,height:o}=s.canvas,h=$s.slice();j.axialAlignedBoundingBox([0,0,r,o],n,h);const[l,c,d,u]=h;this.ctx.fillRect(l,c,d-l,u-c)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,le.transform).recordDependencies(t,le.fill).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t)}beginInlineImage(){tt("Should not call beginInlineImage")}beginImageData(){tt("Should not call beginImageData")}paintFormXObjectBegin(t,e,s){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=ht(this.ctx),s)){j.axialAlignedBoundingBox(s,this.baseTransform,this.current.minMax);const[i,n,r,o]=s,h=new Path2D;h.rect(i,n,r-i,o-n),this.ctx.clip(h),this.dependencyTracker?.recordClipBox(t,this.ctx,i,r,n,o),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const s=this.ctx;e.isolated||Wn("TODO: Support non-isolated groups."),e.knockout&&W("Knockout groups not supported.");const i=ht(s);if(e.matrix&&s.transform(...e.matrix),!e.bbox)throw new Error("Bounding box is required.");let n=$s.slice();j.axialAlignedBoundingBox(e.bbox,ht(s),n);const r=[0,0,s.canvas.width,s.canvas.height];n=j.intersect(n,r)||[0,0,0,0];const o=Math.floor(n[0]),h=Math.floor(n[1]),l=Math.max(Math.ceil(n[2])-o,1),c=Math.max(Math.ceil(n[3])-h,1);this.current.startNewPathAndClipBox([0,0,l,c]);let d="groupAt"+this.groupLevel;e.smask&&(d+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(d,l,c),f=u.context;f.translate(-o,-h),f.transform(...i);let g=new Path2D;const[p,y,m,b]=e.bbox;if(g.rect(p,y,m-p,b-y),e.matrix){const v=new Path2D;v.addPath(g,new DOMMatrix(e.matrix)),g=v}f.clip(g),e.smask&&this.smaskStack.push({canvas:u.canvas,context:f,offsetX:o,offsetY:h,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}),(!e.smask||this.dependencyTracker)&&(s.setTransform(1,0,0,1,0,0),s.translate(o,h),s.save()),Ei(s,f),this.ctx=f,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(s),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(s),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const s=this.ctx,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&this.ctx.restore();else{this.ctx.restore();const n=ht(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...n);const r=$s.slice();j.axialAlignedBoundingBox([0,0,s.canvas.width,s.canvas.height],n,r),this.ctx.drawImage(s.canvas,0,0),this.ctx.restore(),this.compose(r)}}beginAnnotation(t,e,s,i,n,r){if(this.#t(),tr(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),s){const o=s[2]-s[0],h=s[3]-s[1];if(r&&this.annotationCanvasMap){i=i.slice(),i[4]-=s[0],i[5]-=s[1],s=s.slice(),s[0]=s[1]=0,s[2]=o,s[3]=h,j.singularValueDecompose2dScale(ht(this.ctx),ie);const{viewportScale:l}=this,c=Math.ceil(o*this.outputScaleX*l),d=Math.ceil(h*this.outputScaleY*l);this.annotationCanvas=this.canvasFactory.create(c,d);const{canvas:u,context:f}=this.annotationCanvas;this.annotationCanvasMap.set(e,u),this.annotationCanvas.savedCtx=this.ctx,this.ctx=f,this.ctx.save(),this.ctx.setTransform(ie[0],0,0,-ie[1],0,h*ie[1]),tr(this.ctx)}else{tr(this.ctx),this.endPath(t);const l=new Path2D;l.rect(s[0],s[1],o,h),this.ctx.clip(l)}}this.current=new Ll(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(t,...i),this.transform(t,...n)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const s=e.count;e=this.getObject(t,e.data,e),e.count=s;const i=this.ctx,n=this._createMaskCanvas(t,e),r=n.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(r,n.offsetX,n.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,n.offsetX,n.offsetX+r.width,n.offsetY,n.offsetY+r.height).recordOperation(t),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s,i=0,n=0,r,o){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const h=this.ctx;h.save();const l=ht(h);h.transform(s,i,n,r,0,0);const c=this._createMaskCanvas(t,e);h.setTransform(1,0,0,1,c.offsetX-l[4],c.offsetY-l[5]),this.dependencyTracker?.resetBBox(t);for(let d=0,u=o.length;d<u;d+=2){const f=j.transform(l,[s,i,n,r,o[d],o[d+1]]);h.drawImage(c.canvas,f[4],f[5]),this.dependencyTracker?.recordBBox(t,this.ctx,f[4],f[4]+c.canvas.width,f[5],f[5]+c.canvas.height)}h.restore(),this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx,i=this.current.fillColor,n=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,le.transformAndFill);for(const r of e){const{data:o,width:h,height:l,transform:c}=r,d=this.cachedCanvases.getCanvas("maskCanvas",h,l),u=d.context;u.save();const f=this.getObject(t,o,r);Fl(u,f),u.globalCompositeOperation="source-in",u.fillStyle=n?i.getPattern(u,this,ke(s),Et.FILL):i,u.fillRect(0,0,h,l),u.restore(),s.save(),s.transform(...c),s.scale(1,-1),Qn(s,d.canvas,0,0,h,l,0,-1,1,1),this.dependencyTracker?.recordBBox(t,s,0,h,0,l),s.restore()}this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageXObject(t,e){if(!this.contentVisible)return;const s=this.getObject(t,e);if(!s){W("Dependent image isn't ready yet");return}this.paintInlineImageXObject(t,s)}paintImageXObjectRepeat(t,e,s,i,n){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r){W("Dependent image isn't ready yet");return}const o=r.width,h=r.height,l=[];for(let c=0,d=n.length;c<d;c+=2)l.push({transform:[s,0,0,i,n[c],n[c+1]],x:0,y:0,w:o,h});this.paintInlineImageXObjectGroup(t,r,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,e){if(!this.contentVisible)return;const s=e.width,i=e.height,n=this.ctx;this.save(t);const{filter:r}=n;r!=="none"&&r!==""&&(n.filter="none"),n.scale(1/s,-1/i);let o;if(e.bitmap)o=this.applyTransferMapsToBitmap(e);else if(typeof HTMLElement=="function"&&e instanceof HTMLElement||!e.data)o=e;else{const c=this.cachedCanvases.getCanvas("inlineImage",s,i).context;Rl(c,e),o=this.applyTransferMapsToCanvas(c)}const h=this._scaleImage(o,ke(n));n.imageSmoothingEnabled=Il(ht(n),e.interpolate),this.dependencyTracker?.resetBBox(t).recordBBox(t,n,0,s,-i,0).recordDependencies(t,le.imageXObject).recordOperation(t),Qn(n,h.img,0,0,h.paintWidth,h.paintHeight,0,-i,s,i),this.compose(),this.restore(t)}paintInlineImageXObjectGroup(t,e,s){if(!this.contentVisible)return;const i=this.ctx;let n;if(e.bitmap)n=e.bitmap;else{const r=e.width,o=e.height,l=this.cachedCanvases.getCanvas("inlineImage",r,o).context;Rl(l,e),n=this.applyTransferMapsToCanvas(l)}this.dependencyTracker?.resetBBox(t);for(const r of s)i.save(),i.transform(...r.transform),i.scale(1,-1),Qn(i,n,r.x,r.y,r.w,r.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,i,0,1,-1,0),i.restore();this.dependencyTracker?.recordOperation(t),this.compose()}paintSolidColorImageMask(t){this.contentVisible&&(this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,le.fill).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t,e){}markPointProps(t,e,s){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,s){this.dependencyTracker?.beginMarkedContent(t),e==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(s)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,s){const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(s);const n=this.ctx;this.pendingClip?(i||(this.pendingClip===Bl?n.clip(e,"evenodd"):n.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}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 h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const c=h*t;r=o=c<1?1/c:1}else if(t===0)r=1/h,o=1/l;else{const c=h*t,d=l*t;r=c<1?1/c:1,o=d<1?1/d:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/h,o=l/h;else{const d=t*h;r=c>d?c/d:1,o=l>d?l/d:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:s,current:{lineWidth:i}}=this,[n,r]=this.getScaleForStroking();if(n===r){s.lineWidth=(i||1)*n,s.stroke(t);return}const o=s.getLineDash();e&&s.save(),s.scale(n,r),Lo.a=1/n,Lo.d=1/r;const h=new Path2D;if(h.addPath(t,Lo),o.length>0){const l=Math.max(n,r);s.setLineDash(o.map(c=>c/l)),s.lineDashOffset/=l}s.lineWidth=i||1,s.stroke(h),e&&s.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 vi)qs.prototype[a]!==void 0&&(qs.prototype[vi[a]]=qs.prototype[a]);class Ks{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 $f{#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}[Symbol.iterator](){return this.#t.entries()}}const Js=Symbol("INTERNAL");class qf{#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!==Js&&tt("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class Kf{#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 qf(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(Js,!1);for(const s of t.on)this.#e.get(s)._setVisible(Js,!0);for(const s of t.off)this.#e.get(s)._setVisible(Js,!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 W(`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 Wn("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(W(`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 W(`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 W(`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 W(`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 W(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return W(`Unknown optional content policy ${t.policy}.`),!0}return W(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){W(`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(Js,!1,!0);i._setVisible(Js,!!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}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new bl;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}[Symbol.iterator](){return this.#e.entries()}}class Jf{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 h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,l)=>{this._onReceiveData({begin:h,chunk:l})}),t.addProgressListener((h,l)=>{this._onProgress({loaded:h,total:l})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});_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 Zf(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Qf(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 Zf{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=_o(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 Qf{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 tg(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let c=o(e);return c=unescape(c),c=h(c),c=l(c),n(c)}if(e=r(a),e){const c=l(e);return n(c)}if(e=s("filename","i").exec(a),e){e=e[1];let c=o(e);return c=l(c),n(c)}function s(c,d){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',d)}function i(c,d){if(c){if(!/^[\x00-\xFF]+$/.test(d))return d;try{const u=new TextDecoder(c,{fatal:!0}),f=_i(d);d=u.decode(f),t=!1}catch{}}return d}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 d=[];let u;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(u=f.exec(c))!==null;){let[,p,y,m]=u;if(p=parseInt(p,10),p in d){if(p===0)break;continue}d[p]=[y,m]}const g=[];for(let p=0;p<d.length&&p in d;++p){let[y,m]=d[p];m=o(m),y&&(m=unescape(m),p===0&&(m=h(m))),g.push(m)}return g.join("")}function o(c){if(c.startsWith('"')){const d=c.slice(1).split('\\"');for(let u=0;u<d.length;++u){const f=d[u].indexOf('"');f!==-1&&(d[u]=d[u].slice(0,f),d.length=u+1),d[u]=d[u].replaceAll(/\\(.)/g,"$1")}c=d.join('"')}return c}function h(c){const d=c.indexOf("'");if(d===-1)return c;const u=c.slice(0,d),g=c.slice(d+1).replace(/^[^']*'/,"");return i(u,g)}function l(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(d,u,f,g){if(f==="q"||f==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,y){return String.fromCharCode(parseInt(y,16))}),i(u,g);try{g=atob(g)}catch{}return i(u,g)})}return""}function Nl(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 er(a){return URL.parse(a)?.origin??null}function jl({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 Hl(a){const t=a.get("Content-Disposition");if(t){let e=tg(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(_o(e))return e}return null}function ki(a,t){return new Un(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a,a===404||a===0&&t.startsWith("file:"))}function zl(a){return a===200||a===206}function Gl(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function Vl(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(W(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class eg{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=Nl(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 sg(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new ig(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 sg{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,Gl(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=er(n.url),!zl(n.status))throw ki(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=jl({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=Hl(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new es("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:Vl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class ig{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,Gl(n,this._withCredentials,this._abortController)).then(o=>{const h=er(o.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!zl(o.status))throw ki(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:Vl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const Ro=200,Fo=206;function ng(a){const t=a.response;return typeof t!="string"?t:_i(t).buffer}class rg{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Nl(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=Fo):i.expectedStatus=Ro,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||Ro;if(!(n===Ro&&s.expectedStatus===Fo)&&n!==s.expectedStatus){s.onError(i.status);return}const o=ng(i);if(n===Fo){const h=i.getResponseHeader("Content-Range"),l=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);l?s.onDone({begin:parseInt(l[1],10),chunk:o}):(W('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 og{constructor(t){this._source=t,this._manager=new rg(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 ag(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new hg(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 ag{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=er(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[h,...l]=o.split(": ");return[h,l.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=jl({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=Hl(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=ki(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 hg{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=er(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??=ki(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 lg=/^[a-z][a-z0-9\-+.]+:/i;function cg(a){if(lg.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class dg{constructor(t){this.source=t,this.url=cg(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 ug(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new fg(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 ug{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=ki(0,this._url.href)),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 es("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class fg{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 Mi=Symbol("INITIAL_DATA");class Wl{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:Mi}}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===Mi)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!==Mi}delete(t){const e=this.#t[t];return!e||e.data===Mi?!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!==Mi&&(yield[t,e])}}}const gg=1e5,Ul=30;class Gt{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#o=0;#a=0;#h=null;#l=null;#u=0;#c=0;#f=Object.create(null);#p=[];#g=null;#d=[];#m=new WeakMap;#v=null;static#y=new Map;static#w=new Map;static#x=new WeakMap;static#b=null;static#S=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(h){h.enqueue(t),h.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#l=e,this.#c=s.scale*Me.pixelRatio,this.#u=s.rotation,this.#n={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;this.#v=[1,0,0,-1,-r,o+n],this.#a=i,this.#o=n,Gt.#M(),_s(e,s),this.#t.promise.finally(()=>{Gt.#S.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Tt.platform;return Y(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#h.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#r??=e.lang,Object.assign(this.#f,e.styles),this.#k(e.items),t()},this.#t.reject)};return this.#h=this.#g.getReader(),Gt.#S.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*Me.pixelRatio,i=t.rotation;if(i!==this.#u&&(e?.(),this.#u=i,_s(this.#l,{rotation:i})),s!==this.#c){e?.(),this.#c=s;const n={div:null,properties:null,ctx:Gt.#O(this.#r)};for(const r of this.#d)n.properties=this.#m.get(r),n.div=r,this.#C(n)}}cancel(){const t=new es("TextLayer task cancelled.");this.#h?.cancel(t).catch(()=>{}),this.#h=null,this.#t.reject(t)}get textDivs(){return this.#d}get textContentItemsStr(){return this.#p}#k(t){if(this.#s)return;this.#n.ctx??=Gt.#O(this.#r);const e=this.#d,s=this.#p;for(const i of t){if(e.length>gg){W("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&&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.#T(i)}}#T(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#d.push(e);const i=j.transform(this.#v,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let o=this.#i&&r.fontSubstitution||r.fontFamily;o=Gt.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*Gt.#F(o,r,this.#r);let c,d;n===0?(c=i[4],d=i[5]-l):(c=i[4]+l*Math.sin(n),d=i[5]-l*Math.cos(n));const u="calc(var(--total-scale-factor) *",f=e.style;this.#e===this.#l?(f.left=`${(100*c/this.#a).toFixed(2)}%`,f.top=`${(100*d/this.#o).toFixed(2)}%`):(f.left=`${u}${c.toFixed(2)}px)`,f.top=`${u}${d.toFixed(2)}px)`),f.fontSize=`${u}${(Gt.#b*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,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]),y=Math.abs(t.transform[3]);p!==y&&Math.max(p,y)/Math.min(p,y)>1.5&&(g=!0)}if(g&&(s.canvasWidth=r.vertical?t.height:t.width),this.#m.set(e,s),this.#n.div=e,this.#n.properties=s,this.#C(this.#n),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#C(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(Gt.#b>1&&(r=`scale(${1/Gt.#b})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:o}=n,{canvasWidth:h,fontSize:l}=s;Gt.#E(i,l*this.#c,o);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${h*this.#c/c}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#S.size>0)){this.#y.clear();for(const{canvas:t}of this.#w.values())t.remove();this.#w.clear()}}static#O(t=null){let e=this.#w.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.#w.set(t,e),this.#x.set(e,{size:0,family:""})}return e}static#E(t,e,s){const i=this.#x.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#M(){if(this.#b!==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.#b=t.getBoundingClientRect().height,t.remove()}static#F(t,e,s){const i=this.#y.get(t);if(i)return i;const n=this.#O(s);n.canvas.width=n.canvas.height=Ul,this.#E(n,Ul,t);const r=n.measureText(""),o=r.fontBoundingBoxAscent,h=Math.abs(r.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let l=.8;return o?l=o/(o+h):(Tt.platform.isFirefox&&W("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#y.set(t,l),l}}class Di{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(Di.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 h of n.children)i(h)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const pg=100;function Xl(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new Io,{docId:e}=t,s=a.url?Sf(a.url):null,i=a.data?Cf(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof Yl?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:2**16;let c=a.worker instanceof Pi?a.worker:null;const d=a.verbosity,u=typeof a.docBaseUrl=="string"&&!Xn(a.docBaseUrl)?a.docBaseUrl:null,f=Kn(a.cMapUrl),g=a.cMapPacked!==!1,p=a.CMapReaderFactory||(Ht?Of:Sl),y=Kn(a.iccUrl),m=Kn(a.standardFontDataUrl),b=a.StandardFontDataFactory||(Ht?Lf:Tl),v=Kn(a.wasmUrl),_=a.WasmFactory||(Ht?Rf:kl),w=a.stopAtErrors!==!0,x=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,T=a.isEvalSupported!==!1,A=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Ht,k=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Ht&&(Tt.platform.isFirefox||!globalThis.chrome),R=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,D=typeof a.disableFontFace=="boolean"?a.disableFontFace:Ht,F=a.fontExtraProperties===!0,M=a.enableXfa===!0,P=a.ownerDocument||globalThis.document,B=a.disableRange===!0,O=a.disableStream===!0,L=a.disableAutoFetch===!0,H=a.pdfBug===!0,Z=a.CanvasFactory||(Ht?Pf:kf),ct=a.FilterFactory||(Ht?Df:Mf),Ut=a.enableHWA===!0,dt=a.useWasm!==!1,it=h?h.length:a.length??NaN,Xt=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Ht&&!D,ne=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:!!(p===Sl&&b===Tl&&_===kl&&f&&m&&v&&Si(f,document.baseURI)&&Si(m,document.baseURI)&&Si(v,document.baseURI)),Lt=null;tf(d);const et={canvasFactory:new Z({ownerDocument:P,enableHWA:Ut}),filterFactory:new ct({docId:e,ownerDocument:P}),cMapReaderFactory:ne?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:ne?null:new b({baseUrl:m}),wasmFactory:ne?null:new _({baseUrl:v})};c||(c=Pi.create({verbosity:d,port:Ks.workerPort}),t._worker=c);const Es={docId:e,apiVersion:"5.4.149",data:i,password:o,disableAutoFetch:L,rangeChunkSize:l,length:it,docBaseUrl:u,enableXfa:M,evaluatorOptions:{maxImageSize:x,disableFontFace:D,ignoreErrors:w,isEvalSupported:T,isOffscreenCanvasSupported:A,isImageDecoderSupported:k,canvasMaxAreaInBytes:R,fontExtraProperties:F,useSystemFonts:Xt,useWasm:dt,useWorkerFetch:ne,cMapUrl:f,iccUrl:y,standardFontDataUrl:m,wasmUrl:v}},Ii={ownerDocument:P,pdfBug:H,styleElement:Lt,loadingParams:{disableAutoFetch:L,enableXfa:M}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const Le=c.messageHandler.sendWithPromise("GetDocRequest",Es,i?[i.buffer]:null);let $o;if(h)$o=new Jf(h,{disableRange:B,disableStream:O});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");const qo=Si(s)?eg:Ht?dg:og;$o=new qo({url:s,length:it,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:B,disableStream:O})}return Le.then(qo=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const gc=new Ti(e,qo,c.port),up=new bg(gc,t,$o,Ii,et,Ut);t._transport=up,gc.send("Ready",null)})}).catch(t._capability.reject),t}class Io{static#t=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId=`d${Io.#t++}`;destroyed=!1;onPassword=null;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}async getData(){return this._transport.getData()}}class Yl{#t=Promise.withResolvers();#e=[];#s=[];#i=[];#r=[];constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i}addRangeListener(t){this.#r.push(t)}addProgressListener(t){this.#i.push(t)}addProgressiveReadListener(t){this.#s.push(t)}addProgressiveDoneListener(t){this.#e.push(t)}onDataRange(t,e){for(const s of this.#r)s(t,e)}onDataProgress(t,e){this.#t.promise.then(()=>{for(const s of this.#i)s(t,e)})}onDataProgressiveRead(t){this.#t.promise.then(()=>{for(const e of this.#s)e(t)})}onDataProgressiveDone(){this.#t.promise.then(()=>{for(const t of this.#e)t()})}transportReady(){this.#t.resolve()}requestDataRange(t,e){tt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class mg{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 Y(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()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}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 yg{#t=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new pl:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new Wl,this._intentStates=new Map,this.destroyed=!1,this.recordedGroups=null}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 xi({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 Y(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:s,intent:i="display",annotationMode:n=ts.ENABLE,transform:r=null,background:o=null,optionalContentConfigPromise:h=null,annotationCanvasMap:l=null,pageColors:c=null,printAnnotationStorage:d=null,isEditing:u=!1,recordOperations:f=!1,filteredOperationIndexes:g=null}){this._stats?.time("Overall");const p=this._transport.getRenderingIntent(i,n,d,u),{renderingIntent:y,cacheKey:m}=p;this.#t=!1,h||=this._transport.getOptionalContentConfig(y);let b=this._intentStates.get(m);b||(b=Object.create(null),this._intentStates.set(m,b)),b.streamReaderCancelTimeout&&(clearTimeout(b.streamReaderCancelTimeout),b.streamReaderCancelTimeout=null);const v=!!(y&se.PRINT);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(p));const _=!this.recordedGroups&&(f||this._pdfBug&&globalThis.StepperManager?.enabled),w=A=>{if(b.renderTasks.delete(x),_){const k=x.gfx?.dependencyTracker.take();k?(x.stepper?.setOperatorGroups(k),f&&(this.recordedGroups=k)):f&&(this.recordedGroups=[])}v&&(this.#t=!0),this.#e(),A?(x.capability.reject(A),this._abortOperatorList({intentState:b,reason:A instanceof Error?A:new Error(A)})):x.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},x=new Zs({callback:w,params:{canvas:e,canvasContext:t,dependencyTracker:_?new Ff(e):null,viewport:s,transform:r,background:o},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:c,enableHWA:this._transport.enableHWA,filteredOperationIndexes:g});(b.renderTasks||=new Set).add(x);const T=x.task;return Promise.all([b.displayReadyCapability.promise,h]).then(([A,k])=>{if(this.destroyed){w();return}if(this._stats?.time("Rendering"),!(k.renderingIntent&y))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");x.initializeGraphics({transparency:A,optionalContentConfig:k}),x.operatorListChanged()}).catch(w),T}getOperatorList({intent:t="display",annotationMode:e=ts.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let o=this._intentStates.get(r.cacheKey);o||(o=Object.create(null),this._intentStates.set(r.cacheKey,o));let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(h),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=>Di.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:l}){if(l){s(o);return}o.lang??=h.lang,Object.assign(o.styles,h.styles),o.items.push(...h.items),n()},i)}const r=e.getReader(),o={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#t=!1,Promise.all(t)}cleanup(t=!1){this.#t=!0;const e=this.#e();return t&&e&&(this._stats&&=new pl),e}#e(){if(!this.#t||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#t=!1,!0}_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.#e()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),l=this._intentStates.get(e);l.streamReader=h;const c=()=>{h.read().then(({value:d,done:u})=>{if(u){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(d,l),c())},d=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const u of l.renderTasks)u.operatorListChanged();this.#e()}if(l.displayReadyCapability)l.displayReadyCapability.reject(d);else if(l.opListReadCapability)l.opListReadCapability.reject(d);else throw d}})};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 vo){let i=pg;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 es(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}}const rt=class rt{constructor({name:t=null,port:e=null,verbosity:s=ef()}={}){Re(this,Wt);Re(this,is,Promise.withResolvers());Re(this,ve,null);Re(this,$e,null);Re(this,Cs,null);if(this.name=t,this.destroyed=!1,this.verbosity=s,e){if(ot(rt,Ts).has(e))throw new Error("Cannot use more than one PDFWorker per port.");ot(rt,Ts).set(e,this),Fe(this,Wt,yc).call(this,e)}else Fe(this,Wt,bc).call(this)}get promise(){return ot(this,is).promise}get port(){return ot(this,$e)}get messageHandler(){return ot(this,ve)}destroy(){this.destroyed=!0,ot(this,Cs)?.terminate(),Jt(this,Cs,null),ot(rt,Ts).delete(ot(this,$e)),Jt(this,$e,null),ot(this,ve)?.destroy(),Jt(this,ve,null)}static create(t){const e=ot(this,Ts).get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new rt(t)}static get workerSrc(){if(Ks.workerSrc)return Ks.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Y(this,"_setupFakeWorkerGlobal",(async()=>ot(this,ti,lr)?ot(this,ti,lr):(await import(this.workerSrc)).WorkerMessageHandler)())}};is=new WeakMap,ve=new WeakMap,$e=new WeakMap,Cs=new WeakMap,or=new WeakMap,As=new WeakMap,Ts=new WeakMap,Wt=new WeakSet,hr=function(){ot(this,is).resolve(),ot(this,ve).send("configure",{verbosity:this.verbosity})},yc=function(t){Jt(this,$e,t),Jt(this,ve,new Ti("main","worker",t)),ot(this,ve).on("ready",()=>{}),Fe(this,Wt,hr).call(this)},bc=function(){if(ot(rt,As)||ot(rt,ti,lr)){Fe(this,Wt,Bi).call(this);return}let{workerSrc:t}=rt;try{rt._isSameOrigin(window.location,t)||(t=rt._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new Ti("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?ot(this,is).reject(new Error("Worker was destroyed")):Fe(this,Wt,Bi).call(this)},n=new AbortController;e.addEventListener("error",()=>{ot(this,Cs)||i()},{signal:n.signal}),s.on("test",o=>{if(n.abort(),this.destroyed||!o){i();return}Jt(this,ve,s),Jt(this,$e,e),Jt(this,Cs,e),Fe(this,Wt,hr).call(this)}),s.on("ready",o=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{Fe(this,Wt,Bi).call(this)}});const r=()=>{const o=new Uint8Array;s.send("test",o,[o.buffer])};r();return}catch{Wn("The worker has been disabled.")}Fe(this,Wt,Bi).call(this)},Bi=function(){ot(rt,As)||(W("Setting up fake worker."),Jt(rt,As,!0)),rt._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){ot(this,is).reject(new Error("Worker was destroyed"));return}const e=new Ef;Jt(this,$e,e);const s=`fake${mc(rt,or)._++}`,i=new Ti(s+"_worker",s,e);t.setup(i,e),Jt(this,ve,new Ti(s,s+"_worker",e)),Fe(this,Wt,hr).call(this)}).catch(t=>{ot(this,is).reject(new Error(`Setting up fake worker failed: "${t.message}".`))})},ti=new WeakSet,lr=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},Re(rt,ti),Re(rt,or,0),Re(rt,As,!1),Re(rt,Ts,new WeakMap),Ht&&(Jt(rt,As,!0),Ks.workerSrc||="./pdf.worker.mjs"),rt._isSameOrigin=(t,e)=>{const s=URL.parse(t);if(!s?.origin||s.origin==="null")return!1;const i=new URL(e,s);return s.origin===i.origin},rt._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))},rt.fromPort=t=>{if(gf("`PDFWorker.fromPort` - please use `PDFWorker.create` instead."),!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return rt.create(t)};let Pi=rt;class bg{#t=new Map;#e=new Map;#s=new Map;#i=new Map;#r=null;constructor(t,e,s,i,n,r){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new Wl,this.fontLoader=new wf({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.wasmFactory=n.wasmFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.enableHWA=r,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 Y(this,"annotationStorage",new To)}getRenderingIntent(t,e=ts.ENABLE,s=null,i=!1,n=!1){let r=se.DISPLAY,o=Ao;switch(t){case"any":r=se.ANY;break;case"display":break;case"print":r=se.PRINT;break;default:W(`getRenderingIntent - invalid intent: ${t}`)}const h=r&se.PRINT&&s instanceof vl?s:this.annotationStorage;switch(e){case ts.DISABLE:r+=se.ANNOTATIONS_DISABLE;break;case ts.ENABLE:break;case ts.ENABLE_FORMS:r+=se.ANNOTATIONS_FORMS;break;case ts.ENABLE_STORAGE:r+=se.ANNOTATIONS_STORAGE,o=h.serializable;break;default:W(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=se.IS_EDITING),n&&(r+=se.OPLIST);const{ids:l,hash:c}=h.modifiedIds,d=[r,o.hash,c];return{renderingIntent:r,cacheKey:d.join("_"),annotationStorageSerializable:o,modifiedIds:l}}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(),Gt.cleanup(),this._networkStream?.cancelAllRequests(new es("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 mg(s,this))}),t.on("DocException",s=>{e._capability.reject(qt(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw qt(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":if("error"in n){const l=n.error;W(`Error during font loading: ${l}`),this.commonObjs.resolve(s,l);break}const r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(l,c)=>globalThis.FontInspector.fontAdded(l,c):null,o=new xf(n,r);this.fontLoader.bind(o).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!o.fontExtraProperties&&o.data&&(o.data=null),this.commonObjs.resolve(s,o)});break;case"CopyLocalImage":const{imageRef:h}=n;_t(h,"The imageRef must be defined.");for(const l of this.#e.values())for(const[,c]of l.objs)if(c?.ref===h)return c.dataLen?(this.commonObjs.resolve(s,structuredClone(c)),c.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":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("FetchBinaryData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");const i=this[s.type];if(!i)throw new Error(`${s.type} not initialized, see the \`useWorkerFetch\` parameter.`);return i.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&W("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 yg(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return Eo(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)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}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 Kf(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 $f(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),Gt.cleanup()}}cachedPageNumber(t){if(!Eo(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}class vg{#t=null;onContinue=null;onError=null;constructor(t){this.#t=t}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 Zs{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:l,useRequestAnimationFrame:c=!1,pdfBug:d=!1,pageColors:u=null,enableHWA:f=!1,filteredOperationIndexes:g=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=h,this.filterFactory=l,this._pdfBug=d,this.pageColors=u,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 vg(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.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=f,this._dependencyTracker=e.dependencyTracker,this._filteredOperationIndexes=g}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Zs.#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.");Zs.#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{viewport:s,transform:i,background:n,dependencyTracker:r}=this.params,o=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new qs(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,r),this.gfx.beginDrawing({transform:i,viewport:s,transparency:t,background:n}),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),Zs.#e.delete(this._canvas),t||=new vo(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}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._filteredOperationIndexes),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Zs.#e.delete(this._canvas),this.callback())))}}const $l="5.4.149",_g="9e2e9e209";class ce{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#o=null;#a;#h=null;#l=null;static#u=null;static get _keyboardManager(){return Y(this,"_keyboardManager",new Ai([[["Escape","mac+Escape"],ce.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ce.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ce.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ce.prototype._moveToPrevious],[["Home","mac+Home"],ce.prototype._moveToBeginning],[["End","mac+End"],ce.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#o=t):this.#n=!0,this.#l=t?._uiManager||e,this.#a=this.#l._eventBus,this.#s=t?.color?.toUpperCase()||this.#l?.highlightColors.values().next().value||"#FFFF98",ce.#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.ariaHasPopup="true",this.#o&&(t.ariaControls=`${this.#o.id}_colorpicker_dropdown`);const e=this.#l._signal;t.addEventListener("click",this.#g.bind(this),{signal:e}),t.addEventListener("keydown",this.#p.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.ariaHidden="true",s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#c();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#c(){const t=document.createElement("div"),e=this.#l._signal;t.addEventListener("contextmenu",ae,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#o&&(t.id=`${this.#o.id}_colorpicker_dropdown`);for(const[s,i]of this.#l.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",ce.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.ariaSelected=i===this.#s,n.addEventListener("click",this.#f.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#p.bind(this),{signal:e}),t}#f(t,e){e.stopPropagation(),this.#a.dispatch("switchannotationeditorparams",{source:this,type:$.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#g(t);return}const e=t.target.getAttribute("data-color");e&&this.#f(e,t)}_moveToNext(t){if(!this.#m){this.#g(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.#m&&this._hideDropdownFromKeyboard();return}this.#m||this.#g(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#m){this.#g(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#m){this.#g(t);return}this.#i.lastChild?.focus()}#p(t){ce._keyboardManager.exec(this,t)}#g(t){if(this.#m){this.hideDropdown();return}if(this.#r=t.detail===0,this.#h||(this.#h=new AbortController,window.addEventListener("pointerdown",this.#d.bind(this),{signal:this.#l.combinedSignal(this.#h)})),this.#t.ariaExpanded="true",this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#c();this.#t.append(e)}#d(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#t.ariaExpanded="false",this.#h?.abort(),this.#h=null}get#m(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#m){this.#o?.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.#l.highlightColors.values();for(const s of this.#i.children)s.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class Oi{#t=null;#e=null;#s=null;static#i=null;constructor(t){this.#e=t,this.#s=t._uiManager,Oi.#i||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#t)return this.#t;const{editorType:t,colorType:e,colorValue:s}=this.#e,i=this.#t=document.createElement("input");return i.type="color",i.value=s||"#000000",i.className="basicColorPicker",i.tabIndex=0,i.setAttribute("data-l10n-id",Oi.#i[t]),i.addEventListener("input",()=>{this.#s.updateParams(e,i.value)},{signal:this.#s._signal}),i}update(t){this.#t&&(this.#t.value=t)}destroy(){this.#t?.remove(),this.#t=null}hideDropdown(){}}function ql(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function Li(a){return Math.max(0,Math.min(255,255*a))}class Kl{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=Li(t),[t,t,t]}static G_HTML([t]){const e=ql(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(Li)}static RGB_HTML(t){return`#${t.map(ql).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[Li(1-Math.min(1,t+i)),Li(1-Math.min(1,s+i)),Li(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 wg{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){tt("Abstract method `_createSVG` called.")}}class sr extends wg{_createSVG(t){return document.createElementNS(Xe,t)}}class Jl{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",o=>{i.setValue(e,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const o of s.children)o.attributes.value===r.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const h=o.target.options,l=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,o=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,l]of Object.entries(r))if(l!=null)switch(h){case"class":l.length&&t.setAttribute(h,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,l)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const o=n!=="richText",h=t.div;if(h.append(r),t.viewport){const d=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=d}o&&h.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const d=document.createTextNode(i.value);r.append(d),o&&Di.shouldBuildText(i.name)&&l.push(d)}return{textDivs:l}}const c=[[i,-1,r]];for(;c.length>0;){const[d,u,f]=c.at(-1);if(u+1===d.children.length){c.pop();continue}const g=d.children[++c.at(-1)[1]];if(g===null)continue;const{name:p}=g;if(p==="#text"){const m=document.createTextNode(g.value);l.push(m),f.append(m);continue}const y=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(y),g.attributes&&this.setAttributes({html:y,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,y]);else if(g.value){const m=document.createTextNode(g.value);o&&Di.shouldBuildText(p)&&l.push(m),y.append(m)}}for(const d of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))d.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const xg=9,ws=new WeakSet,Sg=new Date().getTimezoneOffset()*60*1e3;class Zl{static create(t){switch(t.data.annotationType){case vt.LINK:return new Bo(t);case vt.TEXT:return new Cg(t);case vt.WIDGET:switch(t.data.fieldType){case"Tx":return new Ag(t);case"Btn":return t.data.radioButton?new Ql(t):t.data.checkBox?new Eg(t):new kg(t);case"Ch":return new Mg(t);case"Sig":return new Tg(t)}return new xs(t);case vt.POPUP:return new No(t);case vt.FREETEXT:return new tc(t);case vt.LINE:return new Pg(t);case vt.SQUARE:return new Og(t);case vt.CIRCLE:return new Lg(t);case vt.POLYLINE:return new ec(t);case vt.CARET:return new Fg(t);case vt.INK:return new jo(t);case vt.POLYGON:return new Rg(t);case vt.HIGHLIGHT:return new sc(t);case vt.UNDERLINE:return new Ig(t);case vt.SQUIGGLY:return new Bg(t);case vt.STRIKEOUT:return new Ng(t);case vt.STAMP:return new ic(t);case vt.FILEATTACHMENT:return new jg(t);default:return new pt(t)}}}class pt{#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.enableComment=t.enableComment,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({contentsObj:t,richText:e}){return!!(t?.str||e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return pt._hasPopupData(this.data)}get hasCommentButton(){return this.enableComment&&this._isEditable&&this.hasPopupElement}get commentButtonPosition(){const{quadPoints:t,rect:e}=this.data;let s=-1/0,i=-1/0;if(t?.length>=8){for(let n=0;n<t.length;n+=8)t[n+1]>i?(i=t[n+1],s=t[n+2]):t[n+1]===i&&(s=Math.max(s,t[n+2]));return[s,i]}return e?[e[2],e[3]]:null}get commentButtonColor(){if(!this.data.color)return null;const[t,e,s]=this.data.color,n=255*(1-(this.data.opacity??1));return this.#i(Math.min(t+n,255),Math.min(e+n,255),Math.min(s+n,255))}#i(t,e,s){t/=255,e/=255,s/=255;const i=Math.max(t,e,s),n=Math.min(t,e,s),r=(i+n)/2,o=((1+Math.sqrt(r))/2*100).toFixed(2);if(i===n)return`hsl(0, 0%, ${o}%)`;const h=i-n;let l;i===t?l=(e-s)/h+(e<s?6:0):i===e?l=(s-t)/h+2:l=(t-e)/h+4,l=(l*60).toFixed(2);const c=(h/(1-Math.abs(2*r-1))*100).toFixed(2);return`hsl(${l}, ${c}%, ${o}%)`}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-n)/s,t[1]=100*(t[1]-r)/i,t}updateEdited(t){if(!this.container)return;t.rect&&(this.#t||={rect:this.data.rect.slice(0)});const{rect:e,popup:s}=t;e&&this.#r(e);let i=this.#s?.popup||this.popup;!i&&s?.text&&(this._createPopup(s),i=this.#s.popup),i&&(i.updateEdited(t),s?.deleted&&(i.remove(),this.#s=null,this.popup=null))}resetEdited(){this.#t&&(this.#r(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#r(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}}}=this;s?.splice(0,4,...t),e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*(t[2]-t[0])/n}%`,e.height=`${100*(t[3]-t[1])/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 xs)&&!(this instanceof Bo)&&(n.tabIndex=0);const{style:r}=n;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof No){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:o,height:h}=this;if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,y=e.borderStyle.verticalCornerRadius;if(p>0||y>0){const b=`calc(${p}px * var(--total-scale-factor)) / calc(${y}px * var(--total-scale-factor))`;r.borderRadius=b}else if(this instanceof Ql){const b=`calc(${o}px * var(--total-scale-factor)) / calc(${h}px * var(--total-scale-factor))`;r.borderRadius=b}switch(e.borderStyle.style){case Us.SOLID:r.borderStyle="solid";break;case Us.DASHED:r.borderStyle="dashed";break;case Us.BEVELED:W("Unimplemented border style: beveled");break;case Us.INSET:W("Unimplemented border style: inset");break;case Us.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=j.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const l=j.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:d,pageX:u,pageY:f}=i.rawDims;r.left=`${100*(l[0]-u)/c}%`,r.top=`${100*(l[1]-f)/d}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*o/c}%`,r.height=`${100*h/d}%`):this.setRotation(g,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims;let{width:n,height:r}=this;t%180!==0&&([n,r]=[r,n]),e.style.width=`${100*n/s}%`,e.style.height=`${100*r/i}%`,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]=Kl[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:Kl[`${r}_rgb`](o)})};return Y(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,y,m,b]=t.subarray(2,6);if(i===p&&n===y&&e===m&&s===b)return}const{style:r}=this.container;let o;if(this.#e){const{borderColor:p,borderWidth:y}=r;r.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${p}" stroke-width="${y}">`],this.container.classList.add("hasBorder")}const h=i-e,l=n-s,{svgFactory:c}=this,d=c.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0),d.role="none";const u=c.createElement("defs");d.append(u);const f=c.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),u.append(f);for(let p=2,y=t.length;p<y;p+=8){const m=t[p],b=t[p+1],v=t[p+2],_=t[p+3],w=c.createElement("rect"),x=(v-e)/h,T=(n-b)/l,A=(m-v)/h,k=(b-_)/l;w.setAttribute("x",x),w.setAttribute("y",T),w.setAttribute("width",A),w.setAttribute("height",k),f.append(w),o?.push(`<rect vector-effect="non-scaling-stroke" x="${x}" y="${T}" width="${A}" height="${k}"/>`)}this.#e&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(d),this.container.style.clipPath=`url(#${g})`}_createPopup(t=null){const{data:e}=this;let s,i;t?(s={str:t.text},i=t.date):(s=e.contentsObj,i=e.modificationDate);const n=this.#s=new No({data:{color:e.color,titleObj:e.titleObj,modificationDate:i,contentsObj:s,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]});this.parent.div.append(n.render())}get hasPopupElement(){return!!(this.#s||this.popup||this.data.popupRef)}render(){tt("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:o}of i){if(n===-1||r===e)continue;const h=typeof o=="string"?o:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!ws.has(l)){W(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&ws.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,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class Bo extends pt{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,t.overlaidText),i=!0):t.attachment?(this.#e(s,t.attachment,t.overlaidText,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState,t.overlaidText),i=!0):t.dest?(this._bindLink(s,t.dest,t.overlaidText),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,s=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t(),s&&(t.title=s)}_bindNamedAction(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),s&&(t.title=s),this.#t()}#e(t,e,s="",i=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:s&&(t.title=s),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#t()}#s(t,e,s=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),s&&(t.title=s),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))}e.overlaidText&&(t.title=e.overlaidText),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){W('_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 d of i){const u=this._fieldObjects[d]||[];for(const{id:f}of u)c.add(f)}for(const d of Object.values(this._fieldObjects))for(const u of d)c.has(u.id)===r&&o.push(u)}else for(const c of Object.values(this._fieldObjects))o.push(...c);const h=this.annotationStorage,l=[];for(const c of o){const{id:d}=c;switch(l.push(d),c.type){case"text":{const f=c.defaultValue||"";h.setValue(d,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;h.setValue(d,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";h.setValue(d,{value:f});break}default:continue}const u=document.querySelector(`[data-element-id="${d}"]`);if(u){if(!ws.has(u)){W(`_bindResetFormAction - element not allowed: ${d}`);continue}}else continue;u.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}}),!1}}}class Cg extends pt{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 xs extends pt{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Tt.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":j.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||xg,n=t.style;let r;const o=2,h=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o),c=Math.round(l/(fo*i))||1,d=l/c;r=Math.min(i,h(d/fo))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/fo))}n.fontSize=`calc(${r}px * var(--total-scale-factor))`,n.color=j.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 Ag extends xs{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(`
|
|
506
|
-
`)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,""));const h={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=this.data.password?"password":"text",s.setAttribute("value",o??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),ws.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=0;const{datetimeFormat:l,datetimeType:c,timeStep:d}=this.data,u=!!c&&this.enableScripting;l&&(s.title=l),this._setRequired(s,this.data.required),r&&(s.maxLength=r),s.addEventListener("input",g=>{t.setValue(e,{value:g.target.value}),this.setPropertyOnSiblings(s,"value",g.target.value,"value"),h.formattedValue=null}),s.addEventListener("resetform",g=>{const p=this.data.defaultFieldValue??"";s.value=h.userValue=p,h.formattedValue=null});let f=g=>{const{formattedValue:p}=h;p!=null&&(g.target.value=p),g.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",p=>{if(h.focused)return;const{target:y}=p;if(u&&(y.type=c,d&&(y.step=d)),h.userValue){const m=h.userValue;if(u)if(c==="time"){const b=new Date(m),v=[b.getHours(),b.getMinutes(),b.getSeconds()];y.value=v.map(_=>_.toString().padStart(2,"0")).join(":")}else y.value=new Date(m-Sg).toISOString().split(c==="date"?"T":".",1)[0];else y.value=m}h.lastCommittedValue=y.value,h.commitKey=1,this.data.actions?.Focus||(h.focused=!0)}),s.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const y={value(m){h.userValue=m.detail.value??"",u||t.setValue(e,{value:h.userValue.toString()}),m.target.value=h.userValue},formattedValue(m){const{formattedValue:b}=m.detail;h.formattedValue=b,b!=null&&m.target!==document.activeElement&&(m.target.value=b);const v={formattedValue:b};u&&(v.value=b),t.setValue(e,v)},selRange(m){m.target.setSelectionRange(...m.detail.selRange)},charLimit:m=>{const{charLimit:b}=m.detail,{target:v}=m;if(b===0){v.removeAttribute("maxLength");return}v.setAttribute("maxLength",b);let _=h.userValue;!_||_.length<=b||(_=_.slice(0,b),v.value=h.userValue=_,t.setValue(e,{value:_}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:_,willCommit:!0,commitKey:1,selStart:v.selectionStart,selEnd:v.selectionEnd}}))}};this._dispatchEventFromSandbox(y,p)}),s.addEventListener("keydown",p=>{h.commitKey=1;let y=-1;if(p.key==="Escape"?y=0:p.key==="Enter"&&!this.data.multiLine?y=2:p.key==="Tab"&&(h.commitKey=3),y===-1)return;const{value:m}=p.target;h.lastCommittedValue!==m&&(h.lastCommittedValue=m,h.userValue=m,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:m,willCommit:!0,commitKey:y,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const g=f;f=null,s.addEventListener("blur",p=>{if(!h.focused||!p.relatedTarget)return;this.data.actions?.Blur||(h.focused=!1);const{target:y}=p;let{value:m}=y;if(u){if(m&&c==="time"){const b=m.split(":").map(v=>parseInt(v,10));m=new Date(2e3,0,1,b[0],b[1],b[2]||0).valueOf(),y.step=""}else m=new Date(m).valueOf();y.type="text"}h.userValue=m,h.lastCommittedValue!==m&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:m,willCommit:!0,commitKey:h.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}),g(p)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",p=>{h.lastCommittedValue=null;const{data:y,target:m}=p,{value:b,selectionStart:v,selectionEnd:_}=m;let w=v,x=_;switch(p.inputType){case"deleteWordBackward":{const T=b.substring(0,v).match(/\w*[^\w]*$/);T&&(w-=T[0].length);break}case"deleteWordForward":{const T=b.substring(v).match(/^[^\w]*\w*/);T&&(x+=T[0].length);break}case"deleteContentBackward":v===_&&(w-=1);break;case"deleteContentForward":v===_&&(x+=1);break}p.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:b,change:y||"",willCommit:!1,selStart:w,selEnd:x}})}),this._setEventListeners(s,h,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(f&&s.addEventListener("blur",f),this.data.comb){const p=(this.data.rect[2]-this.data.rect[0])/r;s.classList.add("comb"),s.style.letterSpacing=`calc(${p}px * var(--total-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 Tg extends xs{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class Eg extends xs{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 ws.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=0,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s)){const c=h&&l.exportValue===e.exportValue;l.domElement&&(l.domElement.checked=c),t.setValue(l.id,{value:c})}t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue||"Off";r.target.checked=o===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const o={value(h){h.target.checked=h.detail.value!=="Off",t.setValue(s,{value:h.target.checked})}};this._dispatchEventFromSandbox(o,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ql extends xs{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(ws.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=0,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s))t.setValue(l.id,{value:!1});t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue;r.target.checked=o!=null&&o===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",o=>{const h={value:l=>{const c=r===l.detail.value;for(const d of this._getElementsByName(l.target.name)){const u=c&&d.id===s;d.domElement&&(d.domElement.checked=u),t.setValue(d.id,{value:u})}}};this._dispatchEventFromSandbox(h,o)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class kg extends Bo{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 Mg extends xs{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");ws.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=0;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 d=this.data.defaultFieldValue;for(const u of i.options)u.selected=u.value===d});for(const c of this.data.options){const d=document.createElement("option");d.textContent=c.displayValue,d.value=c.exportValue,s.value.includes(c.exportValue)&&(d.setAttribute("selected",!0),n=!1),i.append(d)}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 d=c?"value":"textContent",{options:u,multiple:f}=i;return f?Array.prototype.filter.call(u,g=>g.selected).map(g=>g[d]):u.selectedIndex===-1?null:u[u.selectedIndex][d]};let h=o(!1);const l=c=>{const d=c.target.options;return Array.prototype.map.call(d,u=>({displayValue:u.textContent,exportValue:u.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",c=>{const d={value(u){r?.();const f=u.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)}),h=o(!1)},multipleSelection(u){i.multiple=!0},remove(u){const f=i.options,g=u.detail.remove;f[g].selected=!1,i.remove(g),f.length>0&&Array.prototype.findIndex.call(f,y=>y.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:o(!0),items:l(u)}),h=o(!1)},clear(u){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),h=o(!1)},insert(u){const{index:f,displayValue:g,exportValue:p}=u.detail.insert,y=i.children[f],m=document.createElement("option");m.textContent=g,m.value=p,y?y.before(m):i.append(m),t.setValue(e,{value:o(!0),items:l(u)}),h=o(!1)},items(u){const{items:f}=u.detail;for(;i.length!==0;)i.remove(0);for(const g of f){const{displayValue:p,exportValue:y}=g,m=document.createElement("option");m.textContent=p,m.value=y,i.append(m)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:o(!0),items:l(u)}),h=o(!1)},indices(u){const f=new Set(u.detail.indices);for(const g of u.target.options)g.selected=f.has(g.index);t.setValue(e,{value:o(!0)}),h=o(!1)},editable(u){u.target.disabled=!u.detail.editable}};this._dispatchEventFromSandbox(d,c)}),i.addEventListener("input",c=>{const d=o(!0),u=o(!1);t.setValue(e,{value:d}),c.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:h,change:u,changeEx:d,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],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 No extends pt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:pt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=new Dg({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,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,eventBus:this.linkService.eventBus}),s=[];for(const i of this.elements)i.popup=e,i.container.ariaHasPopup="dialog",s.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",s.map(i=>`${bo}${i}`).join(",")),this.container}}class Dg{#t=this.#R.bind(this);#e=this.#A.bind(this);#s=this.#j.bind(this);#i=this.#P.bind(this);#r=null;#n=null;#o=null;#a=null;#h=null;#l=null;#u=null;#c=null;#f=!1;#p=null;#g=null;#d=null;#m=null;#v=null;#y=null;#w=null;#x=null;#b=null;#S=null;#k=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:o,parent:h,rect:l,parentRect:c,open:d,eventBus:u=null}){this.#n=t,this.#b=i,this.#o=r,this.#x=o,this.#u=h,this.#r=e,this.#w=l,this.#c=c,this.#h=s,this.#l=u,this.#a=wo.toDateObject(n),this.trigger=s.flatMap(f=>f.getElementsToTriggerPopup()),this.#T(),this.#n.hidden=!0,d&&this.#P()}#T(){if(this.#g)return;this.#g=new AbortController;const{signal:t}=this.#g;for(const e of this.trigger)e.addEventListener("click",this.#i,{signal:t}),e.addEventListener("mouseenter",this.#s,{signal:t}),e.addEventListener("mouseleave",this.#e,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#h)e.container?.addEventListener("keydown",this.#t,{signal:t});this.#O()}#C(){const t=this.#h.find(e=>e.hasCommentButton);t&&(this.#v=t._normalizePoint(t.commentButtonPosition),this.#y=t.commentButtonColor)}#O(){if(this.#m||(this.#v||this.#C(),!this.#v))return;const t=this.#m=document.createElement("button");t.className="annotationCommentButton";const e=this.#h[0].container;t.style.zIndex=e.style.zIndex+1,t.tabIndex=0;const{signal:s}=this.#g;t.addEventListener("hover",this.#i,{signal:s}),t.addEventListener("keydown",this.#t,{signal:s}),t.addEventListener("click",()=>{const[{data:{id:n},annotationEditorType:r}]=this.#h;this.#l?.dispatch("switchannotationeditormode",{source:this,editId:n,mode:r,editComment:!0})},{signal:s});const{style:i}=t;i.left=`calc(${this.#v[0]}%)`,i.top=`calc(${this.#v[1]}% - var(--comment-button-dim))`,this.#y&&(i.backgroundColor=this.#y),e.after(t)}render(){if(this.#p)return;const t=this.#p=document.createElement("div");if(t.className="popup",this.#r){const i=t.style.outlineColor=j.makeHexColor(...this.#r);t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#b?.str){const i=document.createElement("span");i.className="title",e.append(i),{dir:i.dir,str:i.textContent}=this.#b}if(t.append(e),this.#a){const i=document.createElement("time");i.className="popupDate",i.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),i.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#a.valueOf()})),i.dateTime=this.#a.toISOString(),e.append(i)}const s=this.#E;if(s)Jl.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(this.#o);t.append(i)}this.#n.append(t)}get#E(){const t=this.#x,e=this.#o;return t?.str&&(!e?.str||e.str===t.str)&&this.#x.html||null}get#M(){return this.#E?.attributes?.style?.fontSize||0}get#F(){return this.#E?.attributes?.style?.color||null}#L(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#F,fontSize:this.#M?`calc(${this.#M}px * var(--total-scale-factor))`:""}};for(const n of t.split(`
|
|
507
|
-
`))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}#R(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#f)&&this.#P()}updateEdited({rect:t,popup:e,deleted:s}){if(s||e?.deleted){this.remove();return}this.#T(),this.#S||={contentsObj:this.#o,richText:this.#x},t&&(this.#d=null),e&&(this.#x=this.#L(e.text),this.#a=wo.toDateObject(e.date),this.#o=null),this.#p?.remove(),this.#p=null}resetEdited(){this.#S&&({contentsObj:this.#o,richText:this.#x}=this.#S,this.#S=null,this.#p?.remove(),this.#p=null,this.#d=null)}remove(){this.#g?.abort(),this.#g=null,this.#p?.remove(),this.#p=null,this.#k=!1,this.#f=!1;for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#I(){if(this.#d!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#u;let r=!!this.#c,o=r?this.#c:this.#w;for(const g of this.#h)if(!o||j.intersect(g.data.rect,o)!==null){o=g.data.rect,r=!0;break}const h=j.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,d=h[0]+c,u=h[1];this.#d=[100*(d-i)/e,100*(u-n)/s];const{style:f}=this.#n;f.left=`${this.#d[0]}%`,f.top=`${this.#d[1]}%`}#P(){this.#f=!this.#f,this.#f?(this.#j(),this.#n.addEventListener("click",this.#i),this.#n.addEventListener("keydown",this.#t)):(this.#A(),this.#n.removeEventListener("click",this.#i),this.#n.removeEventListener("keydown",this.#t))}#j(){this.#p||this.render(),this.isVisible?this.#f&&this.#n.classList.add("focused"):(this.#I(),this.#n.hidden=!1,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)+1e3)}#A(){this.#n.classList.remove("focused"),!(this.#f||!this.isVisible)&&(this.#n.hidden=!0,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)-1e3)}forceHide(){this.#k=this.isVisible,this.#k&&(this.#n.hidden=!0)}maybeShow(){this.#T(),this.#k&&(this.#p||this.#j(),this.#k=!1,this.#n.hidden=!1)}get isVisible(){return this.#n.hidden===!1}}class tc extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=V.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 Pg extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:s}=this,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 Og extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:s}=this,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 Lg extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:s}=this,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 ec extends pt{#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},width:n,height:r}=this;if(!e)return this.container;const o=this.svgFactory.create(n,r,!0);let h=[];for(let c=0,d=e.length;c<d;c+=2){const u=e[c]-t[0],f=t[3]-e[c+1];h.push(`${u},${f}`)}h=h.join(" ");const l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",h),l.setAttribute("stroke-width",s.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Rg extends ec{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Fg extends pt{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 jo extends pt{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?V.HIGHLIGHT:V.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:h}=this.#s(e,t),l=this.svgFactory.create(o,h,!0),c=this.#t=this.svgFactory.createElement("svg:g");l.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 d=0,u=s.length;d<u;d++){const f=this.svgFactory.createElement(this.svgElementName);this.#e.push(f),f.setAttribute("points",s[d].join(",")),c.append(f)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(l),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:h}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${o} ${h}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}get commentButtonPosition(){const{inkLists:t,rect:e}=this.data;if(t?.length>=1){let s=-1/0,i=-1/0;for(const n of t)for(let r=0,o=n.length;r<o;r+=2)n[r+1]>i?(i=n[r+1],s=n[r]):n[r+1]===i&&(s=Math.max(s,n[r]));if(s!==1/0)return[s,i]}return e?[e[2],e[3]]:null}}class sc extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=V.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const s=document.createElement("mark");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Ig extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),t){const s=document.createElement("u");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Bg extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),t){const s=document.createElement("u");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class Ng extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),t){const s=document.createElement("s");s.classList.add("overlaidText"),s.textContent=t,this.container.append(s)}return this.container}}class ic extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=V.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 jg extends pt{#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}=Tt.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 Ho{#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,s){const i=t.firstChild||t,n=i.id=`${bo}${e}`,r=await this.#i?.getAriaAttributes(n);if(r)for(const[o,h]of r)i.setAttribute(o,h);s?s.at(-1).container.after(t):(this.div.append(t),this.#t?.moveElementInDOM(this.div,t,i,!1))}async render(t){const{annotations:e}=t,s=this.div;_s(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 sr,annotationStorage:t.annotationStorage||new To,enableComment:t.enableComment===!0,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===vt.POPUP;if(o){const c=i.get(r.id);if(!c)continue;n.elements=c}else if(r.rect[2]===r.rect[0]||r.rect[3]===r.rect[1])continue;n.data=r;const h=Zl.create(n);if(!h.isRenderable)continue;if(!o&&r.popupRef){const c=i.get(r.popupRef);c?c.push(h):i.set(r.popupRef,[h])}const l=h.render();r.hidden&&(l.style.visibility="hidden"),await this.#r(l,r.id,n.elements),h._isEditable&&(this.#s.set(h.data.id,h),this._annotationEditorUIManager?.renderAnnotationElement(h))}this.#n()}async addLinkAnnotations(t,e){const s={data:null,layer:this.div,linkService:e,svgFactory:new sr,parent:this};for(const i of t){i.borderStyle||=Ho._defaultBorderStyle,s.data=i;const n=Zl.create(s);if(!n.isRenderable)continue;const r=n.render();await this.#r(r,i.id,null)}}update({viewport:t}){const e=this.div;this.viewport=t,_s(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);const r=this.#s.get(e);r&&(r._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,i.id,s),r._hasNoCanvas=!1):r.canvas=s)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(t){return this.#s.get(t)}static get _defaultBorderStyle(){return Y(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:Us.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const ir=/\r\n?|\n/g;class Ct extends z{#t;#e="";#s=`${this.id}-editor`;#i=null;#r;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Ct.prototype,e=n=>n.isEmpty(),s=ss.TRANSLATE_SMALL,i=ss.TRANSLATE_BIG;return Y(this,"_keyboardManager",new Ai([[["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=V.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||Ct._defaultColor||z._defaultLineColor,this.#r=t.fontSize||Ct._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert")}static initialize(t,e){z.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case $.FREETEXT_SIZE:Ct._defaultFontSize=e;break;case $.FREETEXT_COLOR:Ct._defaultColor=e;break}}updateParams(t,e){switch(t){case $.FREETEXT_SIZE:this.#n(e);break;case $.FREETEXT_COLOR:this.#o(e);break}}static get defaultPropertiesToUpdate(){return[[$.FREETEXT_SIZE,Ct._defaultFontSize],[$.FREETEXT_COLOR,Ct._defaultColor||z._defaultLineColor]]}get propertiesToUpdate(){return[[$.FREETEXT_SIZE,this.#r],[$.FREETEXT_COLOR,this.#t]]}get toolbarButtons(){return this._colorPicker||=new Oi(this),[["colorPicker",this._colorPicker]]}get colorType(){return $.FREETEXT_COLOR}get colorValue(){return this.#t}#n(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--total-scale-factor))`,this.translate(0,-(i-this.#r)*this.parentScale),this.#r=i,this.#h()},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:$.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#o(t){const e=i=>{this.#t=this.editorDiv.style.color=i,this._colorPicker?.update(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:$.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Ct._internalPadding*t,-(Ct._internalPadding+this.#r)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;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);return 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}),!0}disableEditMode(){return 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"),!0):!1}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(Ct.#l(s)),e=s);return t.join(`
|
|
508
|
-
`)}#
|
|
504
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o),l=(n+r+o)/3,c=2*Math.abs(h-l)/255*s;e[i]+=h!==n?(h-n)*c:0,e[i+1]+=h!==r?(h-r)*c:0,e[i+2]+=h!==o?(h-o)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}x(An,"type","Vibrance"),x(An,"defaults",{vibrance:0}),x(An,"uniformLocations",["uVibrance"]),F.setClass(An);var li={};li.d=(a,t)=>{for(var e in t)li.o(t,e)&&!li.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},li.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var V=globalThis.pdfjsLib={};li.d(V,{AbortException:()=>$e,AnnotationEditorLayer:()=>He,AnnotationEditorParamsType:()=>q,AnnotationEditorType:()=>U,AnnotationEditorUIManager:()=>qe,AnnotationLayer:()=>mg,AnnotationMode:()=>Ue,ColorPicker:()=>ne,DOMSVGFactory:()=>yo,DrawLayer:()=>zt,FeatureTest:()=>Bt,GlobalWorkerOptions:()=>vi,ImageKind:()=>Tn,InvalidPDFException:()=>Zr,MissingPDFException:()=>ui,OPS:()=>fe,OutputScale:()=>oo,PDFDataRangeTransport:()=>_l,PDFDateString:()=>Xh,PDFWorker:()=>Bs,PasswordResponses:()=>Cd,PermissionFlag:()=>Sd,PixelsPerInch:()=>Is,RenderingCancelledException:()=>io,TextLayer:()=>Ht,TouchManager:()=>Fn,UnexpectedResponseException:()=>Pn,Util:()=>B,VerbosityLevel:()=>En,XfaLayer:()=>Cl,build:()=>Kf,createValidAbsoluteUrl:()=>kd,fetchData:()=>Dn,getDocument:()=>zf,getFilenameFromUrl:()=>Nd,getPdfFilenameFromUrl:()=>jd,getXfaPageViewport:()=>Bd,isDataScheme:()=>Rn,isPdfFile:()=>no,noContextMenu:()=>ge,normalizeUnicode:()=>Ld,setLayerDimensions:()=>fs,shadow:()=>$,stopEvent:()=>te,version:()=>qf});const Pt=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Bh=[1,0,0,1,0,0],qr=[.001,0,0,.001,0,0],wd=1e7,Kr=1.35,Qt={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Ue={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},xd="pdfjs_internal_editor_",U={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},q={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},Sd={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Ot={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Tn={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},St={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},ci={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},En={ERRORS:0,WARNINGS:1,INFOS:5},fe={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},Cd={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let kn=En.WARNINGS;function Ad(a){Number.isInteger(a)&&(kn=a)}function Td(){return kn}function Mn(a){kn>=En.INFOS&&console.log(`Info: ${a}`)}function Y(a){kn>=En.WARNINGS&&console.log(`Warning: ${a}`)}function st(a){throw new Error(a)}function yt(a,t){a||st(t)}function Ed(a){switch(a?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function kd(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=Rd(a)}catch{}const s=t?new URL(a,t):new URL(a);if(Ed(s))return s}catch{}return null}function $(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const Ye=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class Hh extends Ye{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Jr extends Ye{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Zr extends Ye{constructor(t){super(t,"InvalidPDFException")}}class ui extends Ye{constructor(t){super(t,"MissingPDFException")}}class Pn extends Ye{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Md extends Ye{constructor(t){super(t,"FormatError")}}class $e extends Ye{constructor(t){super(t,"AbortException")}}function zh(a){(typeof a!="object"||a?.length===void 0)&&st("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 On(a){typeof a!="string"&&st("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 Pd(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function Qr(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function Od(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function Dd(){try{return new Function(""),!0}catch{return!1}}class Bt{static get isLittleEndian(){return $(this,"isLittleEndian",Od())}static get isEvalSupported(){return $(this,"isEvalSupported",Dd())}static get isOffscreenCanvasSupported(){return $(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return $(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?$(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):$(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return $(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const to=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class B{static makeHexColor(t,e,s){return`#${to[t]}${to[e]}${to[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],r[0]),Math.min(s[1],i[1],n[1],r[1]),Math.max(s[0],i[0],n[0],r[0]),Math.max(s[1],i[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],o=(s+r)/2,h=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,l=o+h||1,c=o-h||1;return[Math.sqrt(l),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,h,l,c){if(l<=0||l>=1)return;const u=1-l,d=l*l,f=d*l,g=u*(u*(u*t+3*l*e)+3*d*s)+f*i,p=u*(u*(u*n+3*l*r)+3*d*o)+f*h;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,h,l,c,u,d){if(Math.abs(l)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,o,h,-u/c,d);return}const f=c**2-4*u*l;if(f<0)return;const g=Math.sqrt(f),p=2*l;this.#t(t,e,s,i,n,r,o,h,(-c+g)/p,d),this.#t(t,e,s,i,n,r,o,h,(-c-g)/p,d)}static bezierBoundingBox(t,e,s,i,n,r,o,h,l){return l?(l[0]=Math.min(l[0],t,o),l[1]=Math.min(l[1],e,h),l[2]=Math.max(l[2],t,o),l[3]=Math.max(l[3],e,h)):l=[Math.min(t,o),Math.min(e,h),Math.max(t,o),Math.max(e,h)],this.#e(t,s,n,o,e,i,r,h,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),l),this.#e(t,s,n,o,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),l),l}}function Rd(a){return decodeURIComponent(escape(a))}let eo=null,Gh=null;function Ld(a){return eo||(eo=/([\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,Gh=new Map([["ſt","ſt"]])),a.replaceAll(eo,(t,e,s)=>e?e.normalize("NFKC"):Gh.get(s))}function Fd(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const a=new Uint8Array(32);return crypto.getRandomValues(a),zh(a)}const so="pdfjs_internal_id_";function Id(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(zh(a))}typeof Promise.try!="function"&&(Promise.try=function(a,...t){return new Promise(e=>{e(a(...t))})});const Be="http://www.w3.org/2000/svg";class Is{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Dn(a,t="text"){if(fi(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 di{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const h=(t[2]+t[0])/2,l=(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(l-t[1])*s+n,p=Math.abs(h-t[0])*s+r,b=(t[3]-t[1])*s,m=(t[2]-t[0])*s):(g=Math.abs(h-t[0])*s+n,p=Math.abs(l-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*h-d*s*l,p-u*s*h-f*s*l],this.width=b,this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return $(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new di({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return B.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=B.applyTransform([t[0],t[1]],this.transform),s=B.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return B.applyInverseTransform([t,e],this.transform)}}class io extends Ye{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Rn(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function no(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function Nd(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function jd(a,t="document.pdf"){if(typeof a!="string")return t;if(Rn(a))return Y('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 Vh{started=Object.create(null);times=[];time(t){t in this.started&&Y(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||Y(`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
|
|
505
|
+
`);return t.join("")}}function fi(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function ge(a){a.preventDefault()}function te(a){a.preventDefault(),a.stopPropagation()}class Xh{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 h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const l=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,l==="-"?(r+=c,o+=u):l==="+"&&(r-=c,o-=u),new Date(Date.UTC(s,i,n,r,o,h))}}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 di({viewBox:n,userUnit:1,scale:t,rotation:e})}function ro(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):(Y(`Not a valid color format: "${a}"`),[0,0,0])}function Hd(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,ro(s))}t.remove()}function rt(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function Ce(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 fs(a,t,e=!1,s=!0){if(t instanceof di){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Bt.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,c=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=c,r.height=u):(r.width=u,r.height=c)}s&&a.setAttribute("data-main-rotation",t.rotation)}class oo{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 gi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,gi.#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",ge,{signal:e}),t.addEventListener("pointerdown",gi.#h,{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#h(t){t.stopPropagation()}#a(t){this.#s._focusEventsAllowed=!1,te(t)}#c(t){this.#s._focusEventsAllowed=!0,te(t)}#l(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",ge,{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",gi.#n[t]),this.#l(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.#l(e),this.#i.prepend(e,this.#u),this.#r=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#l(e),this.#i.prepend(e,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class zd{#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",ge,{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",ge,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function Ln(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class Gd{#t=0;get id(){return`${xd}${this.#t++}`}}class ao{#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 $(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 Dn(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=ao._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((l,c)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,l()},r.onload=async()=>{const u=s.svgUrl=r.result;o.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},o.onerror=r.onerror=c});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){Y(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 Vd{#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 h={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(h);return}if(r&&this.#t[this.#i].type===n){o&&(h.undo=this.#t[this.#i].undo),this.#t[this.#i]=h;return}const l=this.#i+1;l===this.#s?this.#t.splice(0,1):(this.#i=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(h)}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 pi{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Bt.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||te(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 Hd(t),$(this,"_colors",t)}convert(t){const e=ro(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?B.makeHexColor(...e):t}}class qe{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#h=null;#a=new Vd;#c=null;#l=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 Gd;#x=!1;#k=!1;#T=null;#O=null;#L=null;#I=null;#C=U.NONE;#y=new Set;#R=null;#z=null;#G=null;#V={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#N=[0,0];#F=null;#j=null;#X=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=qe.prototype,e=r=>r.#j.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:h}=o;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return $(this,"_keyboardManager",new pi([[["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.#j.contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.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,h,l,c,u,d,f){const g=this._signal=this.#t.signal;this.#j=t,this.#X=e,this.#r=s,this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:g}),this.#et(),this.#rt(),this.#$(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#z=r,this.#S=o||null,this.#m=h,this.#p=l,this.#b=c,this.#I=u||null,this.viewParameters={realScale:Is.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 $(this,"hcmFilter",this.#z?this.#_.addHCMFilter(this.#z.foreground,this.#z.background):"none")}get direction(){return $(this,"direction",getComputedStyle(this.#j).direction)}get highlightColors(){return $(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return $(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.#l=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}){switch(t){case"enableNewAltTextWhenAddingImage":this.#b=e;break}}onPageChanging({pageNumber:t}){this.#d=t-1}focusMainContainer(){this.#j.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.#X.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*Is.PDF_TO_CSS_UNITS;for(const e of this.#g)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#B({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Y(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#i.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,o=e.toString(),l=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(l);if(!c)return;e.empty();const u=this.#Y(l),d=this.#C===U.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(U.HIGHLIGHT,f);return}f()}#Q(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#B(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#E||=new zd(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!==U.HIGHLIGHT&&this.#C!==U.NONE)&&(this.#C===U.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===U.HIGHLIGHT?this.#Y(i):null;n?.toggleDrawing();const r=new AbortController,o=this.combinedSignal(r),h=l=>{l.type==="pointerup"&&l.button!==0||(r.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#U("main_toolbar"))};window.addEventListener("pointerup",h,{signal:o}),window.addEventListener("blur",h,{signal:o})}}#U(t=""){this.#C===U.HIGHLIGHT?this.highlightSelection(t):this.#m&&this.#Q()}#et(){document.addEventListener("selectionchange",this.#tt.bind(this),{signal:this._signal})}#st(){if(this.#w)return;this.#w=new AbortController;const t=this.combinedSignal(this.#w);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#it(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#y)if(e.div.contains(t)){this.#O=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;const[t,e]=this.#O;this.#O=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#$(){if(this.#T)return;this.#T=new AbortController;const t=this.combinedSignal(this.#T);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#nt(){this.#T?.abort(),this.#T=null}#q(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#K(){this.#c?.abort(),this.#c=null}#rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#$(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#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){Y(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)this.#J(h);this.#Z(n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){Y(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==U.NONE&&!this.isEditorHandlingKeyboard&&qe._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}#P(t){Object.entries(t).some(([s,i])=>this.#V[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#V,t)}),this.#C===U.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#H([[q.HIGHLIGHT_FREE,!0]]))}#H(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#P({isEditing:this.#C!==U.NONE,isEmpty:this.#W(),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.#H(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===U.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 q.CREATE:this.currentLayer.addNewEditor();return;case q.HIGHLIGHT_DEFAULT_COLOR:this.#L?.updateColor(e);break;case q.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#G||=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.#G?.get(q.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#H([[q.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}#J(t){const e=this.#i.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#H(t.propertiesToUpdate))}get#ht(){let t=null;for(t of this.#y);return t}updateUI(t){this.#ht===t&&this.#H(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#H(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#P({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}setSelected(t){this.#l?.commitOrRemove();for(const e of this.#y)e!==t&&e.unselect();this.#y.clear(),this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#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.#W()}),this._editorUndoBar?.hide()}redo(){this.#a.redo(),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:this.#a.hasSomethingToRedo(),isEmpty:this.#W()})}addCommands(t){this.#a.add(t),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#W()})}cleanUndoStack(t){this.#a.cleanType(t)}#W(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#y],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#J(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Z(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.#Z(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==U.NONE))&&!this.#l?.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.#N[0]+=t,this.#N[1]+=e;const[i,n]=this.#N,r=[...this.#y],o=1e3;this.#F&&clearTimeout(this.#F),this.#F=setTimeout(()=>{this.#F=null,this.#N[0]=this.#N[1]=0,this.addCommands({cmd:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(-i,-n)},mustExec:!1})},o);for(const h of r)h.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),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 h=this.#i.get(o);h?i._setParentAndPosition(h,n,r):(i.pageIndex=o,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:o}]of t)s(i,n,r,o)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:o}]of t)s(i,n,r,o)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(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 $(this,"imageManager",new ao)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,c=e.rangeCount;l<c;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(l,c,u,d)=>({x:(c-i)/r,y:1-(l+u-s)/n,width:d/r,height:u/n});break;case"180":o=(l,c,u,d)=>({x:1-(l+u-s)/n,y:1-(c+d-i)/r,width:u/n,height:d/r});break;case"270":o=(l,c,u,d)=>({x:1-(c+d-i)/r,y:(l-s)/n,width:d/r,height:u/n});break;default:o=(l,c,u,d)=>({x:(l-s)/n,y:(c-i)/r,width:u/n,height:d/r});break}const h=[];for(let l=0,c=e.rangeCount;l<c;l++){const u=e.getRangeAt(l);if(!u.collapsed)for(const{x:d,y:f,width:g,height:p}of u.getClientRects())g===0||p===0||h.push(o(d,f,g,p))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#h||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#h?.delete(t)}renderAnnotationElement(t){const e=this.#h?.get(t.data.id);if(!e)return;const s=this.#n.getRawValue(e);s&&(this.#C===U.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Ae{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#h=!1;#a=null;#c=null;#l=null;#d=null;#u=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#u=t._uiManager.useNewAltTextFlow,Ae.#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){Ae._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",Ae.#f.missing),e.setAttribute("data-l10n-id",Ae.#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",ge,{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.#h=!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.#h}),this.#h=!1)}isEmpty(){return this.#u?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#u?this.#t!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#t===null&&(this.#l=t,this.#d=await Ae._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.#l===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#l,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.#l=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",Ae.#f[this.#o]),this.#i?.setAttribute("data-l10n-id",Ae.#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 Fn{#t;#e=!1;#s=null;#i;#r;#n;#h;#a;#c=null;#l;#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.#h=r,this.#l=new AbortController,this.#a=AbortSignal.any([o,this.#l.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#a})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return $(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(te(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,h=this.#c,{touch0X:l,touch0Y:c,touch1X:u,touch1Y:d}=h,f=u-l,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)<=Fn.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=o,t.preventDefault(),!this.#e){this.#e=!0;return}const y=[(i+r)/2,(n+o)/2];this.#n?.(y,v,m)}#o(t){this.#d.abort(),this.#d=null,this.#h?.(),this.#c&&(t.preventDefault(),this.#c=null,this.#e=!1)}destroy(){this.#l?.abort(),this.#l=null}}class H{#t=null;#e=null;#s=null;#i=!1;#r=null;#n="";#h=!1;#a=null;#c=null;#l=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=H._zIndex++;static _borderLineWidth=-1;static _colorManager=new ho;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=H.prototype._resizeWithKeyboard,e=qe.TRANSLATE_SMALL,s=qe.TRANSLATE_BIG;return $(this,"_resizerKeyboardManager",new pi([[["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"],H.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,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return $(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(H._l10n??=t,H._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"}),H._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);H._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){st("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[h,l]=this.getBaseTranslation();r+=h,o+=l;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}=H,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-o,n)),r=Math.max(0,Math.min(i-h,r));break;case 90:n=Math.max(0,Math.min(s-h,n)),r=Math.min(i,Math.max(o,r));break;case 180:n=Math.min(s,Math.max(o,n)),r=Math.min(i,Math.max(h,r));break;case 270:n=Math.min(s,Math.max(h,n)),r=Math.max(0,Math.min(i-o,r));break}this.x=n/=s,this.y=r/=i;const[l,c]=this.getBaseTranslation();n+=l,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 H.#x(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return H.#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.#h||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#h&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#h&&!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",ge,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#a)}#O(t,e){e.preventDefault();const{isMac:s}=Bt.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",te,{passive:!1,signal:r}),window.addEventListener("contextmenu",ge,{signal:r}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,this.#I()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{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.#l)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#l;this.#l=null;const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:this.#L.bind(this,n,r,o,h),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,h=this.height,l=H.MIN_SIZE/s,c=H.MIN_SIZE/i,u=this.#k(this.rotation),d=(k,R)=>[u[0]*k+u[2]*R,u[1]*k+u[3]*R],f=this.#k(360-this.rotation),g=(k,R)=>[f[0]*k+f[2]*R,f[1]*k+f[3]*R];let p,b,m=!1,v=!1;switch(t){case"topLeft":m=!0,p=(k,R)=>[0,0],b=(k,R)=>[k,R];break;case"topMiddle":p=(k,R)=>[k/2,0],b=(k,R)=>[k/2,R];break;case"topRight":m=!0,p=(k,R)=>[k,0],b=(k,R)=>[0,R];break;case"middleRight":v=!0,p=(k,R)=>[k,R/2],b=(k,R)=>[0,R/2];break;case"bottomRight":m=!0,p=(k,R)=>[k,R],b=(k,R)=>[0,0];break;case"bottomMiddle":p=(k,R)=>[k/2,R],b=(k,R)=>[k/2,0];break;case"bottomLeft":m=!0,p=(k,R)=>[0,R],b=(k,R)=>[k,0];break;case"middleLeft":v=!0,p=(k,R)=>[0,R/2],b=(k,R)=>[k,R/2];break}const y=p(o,h),_=b(o,h);let S=d(..._);const A=H._round(n+S[0]),T=H._round(r+S[1]);let E=1,O=1,N,D;if(e.fromKeyboard)({deltaX:N,deltaY:D}=e);else{const{screenX:k,screenY:R}=e,[G,at]=this.#c;[N,D]=this.screenToPageTranslation(k-G,R-at),this.#c[0]=k,this.#c[1]=R}if([N,D]=g(N/s,D/i),m){const k=Math.hypot(o,h);E=O=Math.max(Math.min(Math.hypot(_[0]-y[0]-N,_[1]-y[1]-D)/k,1/o,1/h),l/o,c/h)}else v?E=Math.max(l,Math.min(1,Math.abs(_[0]-y[0]-N)))/o:O=Math.max(c,Math.min(1,Math.abs(_[1]-y[1]-D)))/h;const L=H._round(o*E),M=H._round(h*O);S=d(...b(L,M));const P=A-S[0],j=T-S[1];this.#o||=[this.x,this.y,this.width,this.height],this.width=L,this.height=M,this.x=P,this.y=j,this.setDims(s*L,i*M),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new gi(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||(Ae.initialize(H._l10n),this.#s=new Ae(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.#N();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),Ln(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new Fn({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#z.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#y(){this.#l={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=(A,T)=>[r[0]*A+r[2]*T,r[1]*A+r[3]*T],[h,l]=this.parentDimensions,c=this.x,u=this.y,d=this.width,f=this.height,g=H.MIN_SIZE/h,p=H.MIN_SIZE/l;n=Math.max(Math.min(n,1/d,1/f),g/d,p/f);const b=H._round(d*n),m=H._round(f*n);if(b===d&&m===f)return;this.#o||=[c,u,d,f];const v=o(d/2,f/2),y=H._round(c+v[0]),_=H._round(u+v[1]),S=o(b/2,m/2);this.x=y-S[0],this.y=_-S[1],this.width=b,this.height=m,this.setDims(h*b,l*m),this.fixAndSetPosition(),this._onResizing()}#z(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=Bt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#V(t);return}this.#G(t)}get isSelected(){return this._uiManager.isSelected(this)}#G(t){const{isMac:e}=Bt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#V(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=l=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#G(l),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#v=t.clientY,this.#r=t.pointerId,this.#n=t.pointerType,window.addEventListener("pointermove",l=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:u,pointerId:d}=l;if(d!==this.#r){te(l);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",te,r),window.addEventListener("pointerdown",l=>{l.pointerType===this.#n&&(this.#S||l.isPrimary)&&o(l),te(l)},r));const h=l=>{if(!this.#r||this.#r===l.pointerId){o(l);return}te(l)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{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,h]=this.pageTranslation,l=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+l+o,r-d-c-g+h,u+l+f+o,r-d-c+h];case 90:return[u+c+o,r-d+l+h,u+c+g+o,r-d+l+f+h];case 180:return[u-l-f+o,r-d+c+h,u-l+o,r-d+c+g+h];case 270:return[u-c-g+o,r-d-l-f+h,u-c+o,r-d-l+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,o,h];case 90:return[s,e-i,h,o];case 180:return[n,e-i,o,h];case 270:return[n,e-r,h,o];default:throw new Error("Invalid rotation")}}onceAdded(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}#N(){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.#N()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){st("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,h,l,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/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"),Ln(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};const e=this.#a.children;if(!this.#e){this.#e=Array.from(e);const r=this.#F.bind(this),o=this.#j.bind(this),h=this._uiManager._signal;for(const l of this.#e){const c=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:h}),l.addEventListener("blur",o,{signal:h}),l.addEventListener("focus",this.#X.bind(this,c),{signal:h}),l.setAttribute("data-l10n-id",H._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 l=this.#e[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",H._l10nResizer[l])}}this.#D(0),this.#p=!0,this.#a.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#F(t){H._resizerKeyboardManager.exec(this,t)}#j(t){this.#p&&t.relatedTarget?.parentNode!==this.#a&&this.#B()}#X(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.#h=!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)},H._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 H{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Wh=3285377520,ie=4294901760,Te=65535;class Uh{constructor(t){this.h1=t?t&4294967295:Wh,this.h2=t?t&4294967295:Wh}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,h=0,l=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&Te,g=d&Te;for(let p=0;p<i;p++)p&1?(o=r[p],o=o*u&ie|o*f&Te,o=o<<15|o>>>17,o=o*d&ie|o*g&Te,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[p],h=h*u&ie|h*f&Te,h=h<<15|h>>>17,h=h*d&ie|h*g&Te,c^=h,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&ie|o*f&Te,o=o<<15|o>>>17,o=o*d&ie|o*g&Te,i&1?l^=o:c^=o}this.h1=l,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&ie|t*36045&Te,e=e*4283543511&ie|((e<<16|t>>>16)*2950163797&ie)>>>16,t^=e>>>1,t=t*444984403&ie|t*60499&Te,e=e*3301882366&ie|((e<<16|t>>>16)*3120437893&ie)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const lo=Object.freeze({map:null,hash:"",transfer:void 0});class co{#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 H)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 H&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?Qr(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 Yh(this)}get serializable(){if(this.#s.size===0)return lo;const t=new Map,e=new Uh,s=[],i=Object.create(null);let n=!1;for(const[r,o]of this.#s){const h=o instanceof H?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||=!!h.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:lo}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof H))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,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const c=l.get(h)??0;l.set(h,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 H)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Yh extends co{#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(){st("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return $(this,"modifiedIds",{ids:new Set,hash:""})}}class Wd{#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(yt(!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{Y(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}st("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 Y(`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 $(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Pt||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),$(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(yt(!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 $(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(_,S){return _.charCodeAt(S)<<24|_.charCodeAt(S+1)<<16|_.charCodeAt(S+2)<<8|_.charCodeAt(S+3)&255}function i(_,S,A,T){const E=_.substring(0,S),O=_.substring(S+A);return E+T+O}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function c(_,S){if(++l>30){Y("Load test font never loaded."),S();return}if(h.font="30px "+_,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){S();return}setTimeout(c.bind(null,_,S))}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,Pd(b));const m=`url(data:font/opentype;base64,${btoa(d)});`,v=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(v);const y=this._document.createElement("div");y.style.visibility="hidden",y.style.width=y.style.height="10px",y.style.position="absolute",y.style.top=y.style.left="0px";for(const _ of[t.loadedName,u]){const S=this._document.createElement("span");S.textContent="Hi",S.style.fontFamily=_,y.append(S)}this._document.body.append(y),c(u,()=>{y.remove(),e.complete()})}}class Ud{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,${Id(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){Y(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const In={DATA:1,ERROR:2},_t={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function $h(){}function Ut(a){if(a instanceof $e||a instanceof Zr||a instanceof ui||a instanceof Hh||a instanceof Pn||a instanceof Jr)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||st('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new $e(a.message);case"InvalidPDFException":return new Zr(a.message);case"MissingPDFException":return new ui(a.message);case"PasswordException":return new Hh(a.message,a.code);case"UnexpectedResponseException":return new Pn(a.message,a.status);case"UnknownErrorException":return new Jr(a.message,a.details)}return new Jr(a.message,a.toString())}class mi{#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===In.DATA)i.resolve(t.data);else if(t.callback===In.ERROR)i.reject(Ut(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:In.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:In.ERROR,callbackId:t.callbackId,reason:Ut(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,h=this.comObj;return new ReadableStream({start:l=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),c.promise},pull:l=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,h.postMessage({sourceName:r,targetName:o,stream:_t.PULL,streamId:n,desiredSize:l.desiredSize}),c.promise},cancel:l=>{yt(l instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:_t.CANCEL,streamId:n,reason:Ut(l)}),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],h={enqueue(l,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:_t.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:_t.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){yt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:_t.ERROR,streamId:e,reason:Ut(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,Promise.try(o,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.START_COMPLETE,streamId:e,reason:Ut(l)})})}#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 _t.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Ut(t.reason));break;case _t.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Ut(t.reason));break;case _t.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||$h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,reason:Ut(l)})});break;case _t.ENQUEUE:if(yt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case _t.CLOSE:if(yt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case _t.ERROR:yt(r,"error should have stream controller"),r.controller.error(Ut(t.reason)),this.#r(r,e);break;case _t.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Ut(t.reason)),this.#r(r,e);break;case _t.CANCEL:if(!o)break;const h=Ut(t.reason);Promise.try(o.onCancel||$h,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.CANCEL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.CANCEL_COMPLETE,streamId:e,reason:Ut(l)})}),o.sinkCapability.reject(h),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 qh{#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){st("Abstract method `_createCanvas` called.")}}class Yd extends qh{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 Kh{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){st("Abstract method `_fetch` called.")}}class Jh extends Kh{async _fetch(t){const e=await Dn(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):On(e)}}class Zh{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 $d extends Zh{#t;#e;#s;#i;#r;#n;#h=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#l(){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(Be,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(Be,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#d(t){if(t.length===1){const h=t[0],l=new Array(256);for(let u=0;u<256;u++)l[u]=h[u]/255;const c=l.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),o=new Array(256);for(let h=0;h<256;h++)n[h]=e[h]/255,r[h]=s[h]/255,o[h]=i[h]/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&&(Rn(e)?Y('#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.#h++}`,h=this.#u(o);this.#a.set(t,h),this.#a.set(r,h);const l=this.#g(o);return this.#p(s,i,n,l),h}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=B.makeHexColor(...r);const o=this.#_(e);if(e=B.makeHexColor(...o),this.#l.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const h=new Array(256);for(let f=0;f<=255;f++){const g=f/255;h[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const l=h.join(","),c=`g_${this.#i}_hcm_filter`,u=n.filter=this.#g(c);this.#p(l,l,l,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.#h++}`,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.#h++}`,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[h,l]=[e,s].map(this.#_.bind(this));let c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),u=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,f]=[i,n].map(this.#_.bind(this));u<c&&([c,u,d,f]=[u,c,f,d]),this.#l.style.color="";const g=(m,v,y)=>{const _=new Array(256),S=(u-c)/y,A=m/255,T=(v-m)/(255*y);let E=0;for(let O=0;O<=y;O++){const N=Math.round(c+O*S),D=A+O*T;for(let L=E;L<=N;L++)_[L]=D;E=N+1}for(let O=E;O<256;O++)_[O]=_[E-1];return _.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.#h=0)}#f(t){const e=this.#r.createElementNS(Be,"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(Be,"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(Be,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#l.append(e),e}#m(t,e,s){const i=this.#r.createElementNS(Be,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(Be,"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(Be,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#l.style.color=t,ro(getComputedStyle(this.#l).getPropertyValue("color"))}}class Qh{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){st("Abstract method `_fetch` called.")}}class tl extends Qh{async _fetch(t){const e=await Dn(t,"arraybuffer");return new Uint8Array(e)}}Pt&&Y("Please use the `legacy` build in Node.js environments.");async function el(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class qd extends Zh{}class Kd extends qh{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:dt&&dt.tagName.toUpperCase()==="SCRIPT"&&dt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class Jd extends Kh{async _fetch(t){return el(t)}}class Zd extends Qh{async _fetch(t){return el(t)}}const Dt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function uo(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 fo{getPattern(){st("Abstract method `getPattern` called.")}}class Qd extends fo{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===Dt.STROKE||i===Dt.FILL){const r=e.current.getClippedPathBoundingBox(i,rt(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),c=l.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=B.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),uo(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(l.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else uo(t,this._bbox),n=this._createGradient(t);return n}}function go(a,t,e,s,i,n,r,o){const h=t.coords,l=t.colors,c=a.data,u=a.width*4;let d;h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d),h[s+1]>h[i+1]&&(d=s,s=i,i=d,d=r,r=o,o=d),h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d);const f=(h[e]+t.offsetX)*t.scaleX,g=(h[e+1]+t.offsetY)*t.scaleY,p=(h[s]+t.offsetX)*t.scaleX,b=(h[s+1]+t.offsetY)*t.scaleY,m=(h[i]+t.offsetX)*t.scaleX,v=(h[i+1]+t.offsetY)*t.scaleY;if(g>=v)return;const y=l[n],_=l[n+1],S=l[n+2],A=l[r],T=l[r+1],E=l[r+2],O=l[o],N=l[o+1],D=l[o+2],L=Math.round(g),M=Math.round(v);let P,j,k,R,G,at,ct,At;for(let wt=L;wt<=M;wt++){if(wt<b){const Q=wt<g?0:(g-wt)/(g-b);P=f-(f-p)*Q,j=y-(y-A)*Q,k=_-(_-T)*Q,R=S-(S-E)*Q}else{let Q;wt>v?Q=1:b===v?Q=0:Q=(b-wt)/(b-v),P=p-(p-m)*Q,j=A-(A-O)*Q,k=T-(T-N)*Q,R=E-(E-D)*Q}let nt;wt<g?nt=0:wt>v?nt=1:nt=(g-wt)/(g-v),G=f-(f-m)*nt,at=y-(y-O)*nt,ct=_-(_-N)*nt,At=S-(S-D)*nt;const Vt=Math.round(Math.min(P,G)),Ee=Math.round(Math.max(P,G));let ut=u*wt+Vt*4;for(let Q=Vt;Q<=Ee;Q++)nt=(P-Q)/(P-G),nt<0?nt=0:nt>1&&(nt=1),c[ut++]=j-(j-at)*nt|0,c[ut++]=k-(k-ct)*nt|0,c[ut++]=R-(R-At)*nt|0,c[ut++]=255}}function tf(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,h=Math.floor(s.length/o)-1,l=o-1;for(n=0;n<h;n++){let c=n*o;for(let u=0;u<l;u++,c++)go(a,e,s[c],s[c+1],s[c+o],i[c],i[c+1],i[c+o]),go(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)go(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 ef extends fo{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const o=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-o,c=Math.ceil(this._bounds[3])-h,u=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),d=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=l/u,g=c/d,p={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/f,scaleY:1/g},b=u+4,m=d+4,v=s.getCanvas("mesh",b,m),y=v.context,_=y.createImageData(u,d);if(e){const A=_.data;for(let T=0,E=A.length;T<E;T+=4)A[T]=e[0],A[T+1]=e[1],A[T+2]=e[2],A[T+3]=255}for(const A of this._figures)tf(_,A,p);return y.putImageData(_,2,2),{canvas:v.canvas,offsetX:o-2*f,offsetY:h-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){uo(t,this._bbox);let n;if(i===Dt.SHADING)n=B.singularValueDecompose2dScale(rt(t));else if(n=B.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=B.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Dt.SHADING?null:this._background,e.cachedCanvases);return i!==Dt.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 sf extends fo{getPattern(){return"hotpink"}}function nf(a){switch(a[0]){case"RadialAxial":return new Qd(a);case"Mesh":return new ef(a);case"Dummy":return new sf}throw new Error(`Unknown IR type: ${a[0]}`)}const sl={COLORED:1,UNCOLORED:2};class po{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:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),Mn("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,b=B.singularValueDecompose2dScale(this.matrix),m=B.singularValueDecompose2dScale(this.baseTransform),v=b[0]*m[0],y=b[1]*m[1];let _=g,S=p,A=!1,T=!1;const E=Math.ceil(h*v),O=Math.ceil(l*y),N=Math.ceil(g*v),D=Math.ceil(p*y);E>=N?_=h:A=!0,O>=D?S=l:T=!0;const L=this.getSizeAndScale(_,this.ctx.canvas.width,v),M=this.getSizeAndScale(S,this.ctx.canvas.height,y),P=t.cachedCanvases.getCanvas("pattern",L.size,M.size),j=P.context,k=o.createCanvasGraphics(j);if(k.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(k,i,r),j.translate(-L.scale*c,-M.scale*u),k.transform(L.scale,0,0,M.scale,0,0),j.save(),this.clipBbox(k,c,u,d,f),k.baseTransform=rt(k.ctx),k.executeOperatorList(s),k.endDrawing(),j.restore(),A||T){const R=P.canvas;A&&(_=h),T&&(S=l);const G=this.getSizeAndScale(_,this.ctx.canvas.width,v),at=this.getSizeAndScale(S,this.ctx.canvas.height,y),ct=G.size,At=at.size,wt=t.cachedCanvases.getCanvas("pattern-workaround",ct,At),nt=wt.context,Vt=A?Math.floor(g/h):0,Ee=T?Math.floor(p/l):0;for(let ut=0;ut<=Vt;ut++)for(let Q=0;Q<=Ee;Q++)nt.drawImage(R,ct*ut,At*Q,ct,At,0,0,ct,At);return{canvas:wt.canvas,scaleX:G.scale,scaleY:at.scale,offsetX:c,offsetY:u}}return{canvas:P.canvas,scaleX:L.scale,scaleY:M.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(po.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(rt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case sl.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case sl.UNCOLORED:const o=B.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new Md(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Dt.SHADING&&(n=B.transform(n,e.baseTransform),this.matrix&&(n=B.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let o=new DOMMatrix(n);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(o),h}}function rf({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Bt.isLittleEndian?4278190080:255,[h,l]=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?l:h,e[f++]=m&64?l:h,e[f++]=m&32?l:h,e[f++]=m&16?l:h,e[f++]=m&8?l:h,e[f++]=m&4?l:h,e[f++]=m&2?l:h,e[f++]=m&1?l:h}if(u===0)continue;const p=t<d?a[t++]:255;for(let b=0;b<u;b++)e[f++]=p&1<<7-b?l:h}return{srcPos:t,destPos:f}}const il=16,nl=100,of=15,rl=10,ol=1e3,Yt=16;function af(a,t){if(a._removeMirroring)throw new Error("Context is already forwarding operations.");a.__originalSave=a.save,a.__originalRestore=a.restore,a.__originalRotate=a.rotate,a.__originalScale=a.scale,a.__originalTranslate=a.translate,a.__originalTransform=a.transform,a.__originalSetTransform=a.setTransform,a.__originalResetTransform=a.resetTransform,a.__originalClip=a.clip,a.__originalMoveTo=a.moveTo,a.__originalLineTo=a.lineTo,a.__originalBezierCurveTo=a.bezierCurveTo,a.__originalRect=a.rect,a.__originalClosePath=a.closePath,a.__originalBeginPath=a.beginPath,a._removeMirroring=()=>{a.save=a.__originalSave,a.restore=a.__originalRestore,a.rotate=a.__originalRotate,a.scale=a.__originalScale,a.translate=a.__originalTranslate,a.transform=a.__originalTransform,a.setTransform=a.__originalSetTransform,a.resetTransform=a.__originalResetTransform,a.clip=a.__originalClip,a.moveTo=a.__originalMoveTo,a.lineTo=a.__originalLineTo,a.bezierCurveTo=a.__originalBezierCurveTo,a.rect=a.__originalRect,a.closePath=a.__originalClosePath,a.beginPath=a.__originalBeginPath,delete a._removeMirroring},a.save=function(){t.save(),this.__originalSave()},a.restore=function(){t.restore(),this.__originalRestore()},a.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},a.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},a.transform=function(s,i,n,r,o,h){t.transform(s,i,n,r,o,h),this.__originalTransform(s,i,n,r,o,h)},a.setTransform=function(s,i,n,r,o,h){t.setTransform(s,i,n,r,o,h),this.__originalSetTransform(s,i,n,r,o,h)},a.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},a.rotate=function(s){t.rotate(s),this.__originalRotate(s)},a.clip=function(s){t.clip(s),this.__originalClip(s)},a.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},a.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},a.bezierCurveTo=function(e,s,i,n,r,o){t.bezierCurveTo(e,s,i,n,r,o),this.__originalBezierCurveTo(e,s,i,n,r,o)},a.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},a.closePath=function(){t.closePath(),this.__originalClosePath()},a.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class hf{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,h,l){const[c,u,d,f,g,p]=rt(a);if(u===0&&d===0){const v=r*c+g,y=Math.round(v),_=o*f+p,S=Math.round(_),A=(r+h)*c+g,T=Math.abs(Math.round(A)-y)||1,E=(o+l)*f+p,O=Math.abs(Math.round(E)-S)||1;return a.setTransform(Math.sign(c),0,0,Math.sign(f),y,S),a.drawImage(t,e,s,i,n,0,0,T,O),a.setTransform(c,u,d,f,g,p),[T,O]}if(c===0&&f===0){const v=o*d+g,y=Math.round(v),_=r*u+p,S=Math.round(_),A=(o+l)*d+g,T=Math.abs(Math.round(A)-y)||1,E=(r+h)*u+p,O=Math.abs(Math.round(E)-S)||1;return a.setTransform(0,Math.sign(u),Math.sign(d),0,y,S),a.drawImage(t,e,s,i,n,0,0,O,T),a.setTransform(c,u,d,f,g,p),[O,T]}a.drawImage(t,e,s,i,n,r,o,h,l);const b=Math.hypot(c,u),m=Math.hypot(d,f);return[b*h,m*l]}function lf(a){const{width:t,height:e}=a;if(t>ol||e>ol)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),o,h,l;const 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),h=1;h<t;h++)u[d]!==u[d+1]&&(r[h]=u[d]?2:1,++f),d++;for(u[d]!==0&&(r[h]=2,++f),o=1;o<e;o++){d=o*c,l=o*n,u[d-c]!==u[d]&&(r[l]=u[d]?1:8,++f);let m=(u[d]?4:0)+(u[d-c]?8:0);for(h=1;h<t;h++)m=(m>>2)+(u[d+1]?4:0)+(u[d-c+1]?8:0),i[m]&&(r[l+h]=i[m],++f),d++;if(u[d-c]!==u[d]&&(r[l+h]=u[d]?2:4,++f),f>s)return null}for(d=c*(e-1),l=o*n,u[d]!==0&&(r[l]=8,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[l+h]=u[d]?4:8,++f),d++;if(u[d]!==0&&(r[l+h]=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 y=m;let _=r[m];do{const S=g[_];do m+=S;while(!r[m]);const A=r[m];A!==5&&A!==10?(_=A,r[m]=0):(_=A&51*_>>4,r[m]&=_>>2|_<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(y!==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 al{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Bh,this.textMatrixScale=1,this.fontMatrix=qr,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=Ot.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]=B.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=B.applyTransform(e,t),i=B.applyTransform(e.slice(2),t),n=B.applyTransform([e[0],e[3]],t),r=B.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){B.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,o,h,l,c){const u=B.bezierBoundingBox(e,s,i,n,r,o,h,l,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Dt.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Dt.STROKE){e||st("Stroke bounding box must include transform.");const i=B.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=B.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=Dt.FILL,e=null){return B.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function hl(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Yt,n=(e-i)/Yt,r=i===0?n:n+1,o=a.createImageData(s,Yt);let h=0,l;const c=t.data,u=o.data;let d,f,g,p;if(t.kind===Tn.GRAYSCALE_1BPP){const b=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),v=m.length,y=s+7>>3,_=4294967295,S=Bt.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?Yt:i,l=0,f=0;f<g;f++){const A=b-h;let T=0;const E=A>y?s:A*8-7,O=E&-8;let N=0,D=0;for(;T<O;T+=8)D=c[h++],m[l++]=D&128?_:S,m[l++]=D&64?_:S,m[l++]=D&32?_:S,m[l++]=D&16?_:S,m[l++]=D&8?_:S,m[l++]=D&4?_:S,m[l++]=D&2?_:S,m[l++]=D&1?_:S;for(;T<E;T++)N===0&&(D=c[h++],N=128),m[l++]=D&N?_:S,N>>=1}for(;l<v;)m[l++]=0;a.putImageData(o,0,d*Yt)}}else if(t.kind===Tn.RGBA_32BPP){for(f=0,p=s*Yt*4,d=0;d<n;d++)u.set(c.subarray(h,h+p)),h+=p,a.putImageData(o,0,f),f+=Yt;d<r&&(p=s*i*4,u.set(c.subarray(h,h+p)),a.putImageData(o,0,f))}else if(t.kind===Tn.RGB_24BPP)for(g=Yt,p=s*g,d=0;d<r;d++){for(d>=n&&(g=i,p=s*g),l=0,f=p;f--;)u[l++]=c[h++],u[l++]=c[h++],u[l++]=c[h++],u[l++]=255;a.putImageData(o,0,d*Yt)}else throw new Error(`bad image kind: ${t.kind}`)}function ll(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Yt,n=(e-i)/Yt,r=i===0?n:n+1,o=a.createImageData(s,Yt);let h=0;const l=t.data,c=o.data;for(let u=0;u<r;u++){const d=u<n?Yt:i;({srcPos:h}=rf({src:l,srcPos:h,dest:c,width:s,height:d,nonBlackColor:0})),a.putImageData(o,0,u*Yt)}}function bi(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 jn(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),!Pt){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function cl(a,t){if(t)return!0;const e=B.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*Is.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const cf=["butt","round","square"],uf=["miter","round","bevel"],df={},ul={};class Ns{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){this.ctx=t,this.current=new al(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 hf(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...rt(this.compositeCtx))}this.ctx.save(),jn(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=rt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>rl&&typeof s=="function",c=l?Date.now()+of: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!==fe.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===h)return o;if(l&&++u>rl){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,h=i,l="prescale1",c,u;for(;n>2&&o>1||r>2&&h>1;){let d=o,f=h;n>2&&o>1&&(d=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/d),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),c=this.cachedCanvases.getCanvas(l,d,f),u=c.context,u.clearRect(0,0,d,f),u.drawImage(t,0,0,o,h,0,0,d,f),t=c.canvas,o=d,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=rt(e);let h,l,c,u;if((t.bitmap||t.data)&&t.count>1){const E=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(E),h||(h=new Map,this._cachedBitmapsMap.set(E,h));const O=h.get(l);if(O&&!r){const N=Math.round(Math.min(o[0],o[2])+o[4]),D=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:O,offsetX:N,offsetY:D}}c=O}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),ll(u.context,t));let d=B.transform(o,[1/s,0,0,-1/i,0,0]);d=B.transform(d,[1,0,0,1,0,-i]);const[f,g,p,b]=B.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,v=Math.round(b-g)||1,y=this.cachedCanvases.getCanvas("fillCanvas",m,v),_=y.context,S=f,A=g;_.translate(-S,-A),_.transform(...d),c||(c=this._scaleImage(u.canvas,Ce(_)),c=c.img,h&&r&&h.set(l,c)),_.imageSmoothingEnabled=cl(rt(_),t.interpolate),Nn(_,c,0,0,c.width,c.height,0,0,s,i),_.globalCompositeOperation="source-in";const T=B.transform(Ce(_),[1,0,0,1,-S,-A]);return _.fillStyle=r?n.getPattern(e,this,T,Dt.FILL):n,_.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,y.canvas)),{canvas:y.canvas,offsetX:Math.round(S),offsetY:Math.round(A)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=cf[t]}setLineJoin(t){this.ctx.lineJoin=uf[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(...rt(this.suspendedCtx)),bi(this.suspendedCtx,n),af(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(),bi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;o===0||h===0||(this.genericComposeSMask(e.context,s,o,h,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,o,h,l,c,u){let d=t.canvas,f=h-c,g=l-u;if(r){const b=B.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(h,l,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(d,f,g,s,i,h,l,s,i),e.restore()}save(){this.inSMaskMode?(bi(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(),bi(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const c=rt(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 fe.rectangle:r=e[g++],o=e[g++];const b=e[g++],m=e[g++],v=r+b,y=o+m;i.moveTo(r,o),b===0||m===0?i.lineTo(v,y):(i.lineTo(v,o),i.lineTo(v,y),i.lineTo(r,y)),u||n.updateRectMinMax(c,[r,o,v,y]),i.closePath();break;case fe.moveTo:r=e[g++],o=e[g++],i.moveTo(r,o),u||n.updatePathMinMax(c,r,o);break;case fe.lineTo:r=e[g++],o=e[g++],i.lineTo(r,o),u||n.updatePathMinMax(c,r,o);break;case fe.curveTo:h=r,l=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,h,l,e[g],e[g+1],e[g+2],e[g+3],r,o,d),g+=6;break;case fe.curveTo2:h=r,l=o,i.bezierCurveTo(r,o,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,h,l,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 fe.curveTo3:h=r,l=o,r=e[g+2],o=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,o,r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],r,o,r,o,d),g+=4;break;case fe.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,Ce(e),Dt.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,Ce(e),Dt.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=df}eoClip(){this.pendingClip=ul}beginText(){this.current.textMatrix=Bh,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:o,fontSize:h,path:l}of t)s.addPath(l,new DOMMatrix(n).preMultiplySelf(i).translate(r,o).scale(h,-h));e.clip(s),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){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||qr,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&Y("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 h=s.italic?"italic":"normal";let l=e;e<il?l=il:e>nl&&(l=nl),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#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,h=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,u=l&Ot.FILL_STROKE_MASK,d=!!(l&Ot.ADD_TO_PATH_FLAG),f=o.patternFill&&!h.missingFile,g=o.patternStroke&&!h.missingFile;let p;if((h.disableFontFace||d||f||g)&&(p=h.getPathGenerator(this.commonObjs,t)),h.disableFontFace||f||g){if(r.save(),r.translate(e,s),r.scale(c,-c),u===Ot.FILL||u===Ot.FILL_STROKE)if(i){const b=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,b,i))}else r.fill(p);if(u===Ot.STROKE||u===Ot.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===Ot.FILL||u===Ot.FILL_STROKE)&&r.fillText(t,e,s),(u===Ot.STROKE||u===Ot.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:rt(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 $(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,c=e.textHScale*l,u=t.length,d=s.vertical,f=d?1:-1,g=s.defaultVMetrics,p=i*e.fontMatrix[0],b=e.textRenderingMode===Ot.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(c,-1):n.scale(c,1);let m,v;if(e.patternFill){n.save();const T=e.fillColor.getPattern(n,this,Ce(n),Dt.FILL);m=rt(n),n.restore(),n.fillStyle=T}if(e.patternStroke){n.save();const T=e.strokeColor.getPattern(n,this,Ce(n),Dt.STROKE);v=rt(n),n.restore(),n.strokeStyle=T}let y=e.lineWidth;const _=e.textMatrixScale;if(_===0||y===0){const T=e.textRenderingMode&Ot.FILL_STROKE_MASK;(T===Ot.STROKE||T===Ot.FILL_STROKE)&&(y=this.getSinglePixelWidth())}else y/=_;if(r!==1&&(n.scale(r,r),y/=r),n.lineWidth=y,s.isInvalidPDFjsFont){const T=[];let E=0;for(const O of t)T.push(O.unicode),E+=O.width;n.fillText(T.join(""),0,0),e.x+=E*p*c,n.restore(),this.compose();return}let S=0,A;for(A=0;A<u;++A){const T=t[A];if(typeof T=="number"){S+=f*T*i/1e3;continue}let E=!1;const O=(T.isSpace?h:0)+o,N=T.fontChar,D=T.accent;let L,M,P=T.width;if(d){const k=T.vmetric||g,R=-(T.vmetric?k[1]:P*.5)*p,G=k[2]*p;P=k?-k[0]:P,L=R/r,M=(S+G)/r}else L=S/r,M=0;if(s.remeasure&&P>0){const k=n.measureText(N).width*1e3/i*r;if(P<k&&this.isFontSubpixelAAEnabled){const R=P/k;E=!0,n.save(),n.scale(R,1),L/=R}else P!==k&&(L+=(P-k)/2e3*i/r)}if(this.contentVisible&&(T.isInFont||s.missingFile)){if(b&&!D)n.fillText(N,L,M);else if(this.paintChar(N,L,M,m,v),D){const k=L+i*D.offset.x/r,R=M-i*D.offset.y/r;this.paintChar(D.fontChar,k,R,m,v)}}const j=d?P*p-O*l:P*p+O*l;S+=j,E&&n.restore()}d?e.y-=S:e.x+=S*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,h=s.charSpacing,l=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||qr,d=t.length,f=s.textRenderingMode===Ot.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?l:0)+h,y=i.charProcOperatorList[p.operatorListId];if(!y){Y(`Type3 character "${p.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=p,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(y),this.restore()),b=B.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||rt(this.ctx),n={createCanvasGraphics:r=>new Ns(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new po(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=B.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=B.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=nf(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,Ce(e),Dt.SHADING);const i=Ce(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,c]=B.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,h,l-o,c-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){st("Should not call beginInlineImage")}beginImageData(){st("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=rt(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(rt(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||Mn("TODO: Support non-isolated groups."),t.knockout&&Y("Knockout groups not supported.");const s=rt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=B.getAxialAlignedBoundingBox(t.bbox,rt(e));const n=[0,0,e.canvas.width,e.canvas.height];i=B.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),o=Math.floor(i[1]),h=Math.max(Math.ceil(i[2])-r,1),l=Math.max(Math.ceil(i[3])-o,1);this.current.startNewPathAndClipBox([0,0,h,l]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,h,l),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()),bi(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=rt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=B.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(),jn(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],o=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=o;const[h,l]=B.singularValueDecompose2dScale(rt(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(h,0,0,-l,0,o*l),jn(this.ctx)}else jn(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new al(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=lf(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=rt(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let c=0,u=r.length;c<u;c+=2){const d=B.transform(h,[e,s,i,n,r[c],r[c+1]]),[f,g]=B.applyTransform([0,0],d);o.drawImage(l.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:h,transform:l}=n,c=this.cachedCanvases.getCanvas("maskCanvas",o,h),u=c.context;u.save();const d=this.getObject(r,n);ll(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,Ce(e),Dt.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),Nn(e,c.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){Y("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){Y("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,c=i.length;l<c;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!Pt){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;hl(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,Ce(i));i.imageSmoothingEnabled=cl(rt(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,h=this.cachedCanvases.getCanvas("inlineImage",n,r).context;hl(h,t),i=this.applyTransferMapsToCanvas(h)}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===ul?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=rt(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const c=h*t;r=o=c<1?1/c:1}else if(t===0)r=1/h,o=1/l;else{const c=h*t,u=l*t;r=c<1?1/c:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/h,o=l/h;else{const u=t*h;r=c>u?c/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const a in fe)Ns.prototype[a]!==void 0&&(Ns.prototype[fe[a]]=Ns.prototype[a]);class vi{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 ff{#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 Qr(this.#t)}has(t){return this.#t.has(t)}}const js=Symbol("INTERNAL");class gf{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&Qt.DISPLAY),this.#e=!!(t&Qt.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!==js&&st("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class pf{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=Qt.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 gf(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(js,!1);for(const s of t.on)this.#e.get(s)._setVisible(js,!0);for(const s of t.off)this.#e.get(s)._setVisible(js,!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 Y(`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 Mn("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(Y(`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 Y(`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 Y(`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 Y(`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 Y(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return Y(`Unknown optional content policy ${t.policy}.`),!0}return Y(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){Y(`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(js,!1,!0);i._setVisible(js,!!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?Qr(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Uh;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class mf{constructor(t,{disableRange:e=!1,disableStream:s=!1}){yt(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 h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,l)=>{this._onReceiveData({begin:h,chunk:l})}),t.addProgressListener((h,l)=>{this._onProgress({loaded:h,total:l})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});yt(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(){yt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new bf(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new vf(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 bf{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=no(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 vf{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 yf(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let c=o(e);return c=unescape(c),c=h(c),c=l(c),n(c)}if(e=r(a),e){const c=l(e);return n(c)}if(e=s("filename","i").exec(a),e){e=e[1];let c=o(e);return c=l(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=On(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=h(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 h(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 l(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 dl(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 Bn(a){try{return new URL(a).origin}catch{}return null}function fl({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 gl(a){const t=a.get("Content-Disposition");if(t){let e=yf(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(no(e))return e}return null}function Hn(a,t){return a===404||a===0&&t.startsWith("file:")?new ui('Missing PDF "'+t+'".'):new Pn(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function pl(a){return a===200||a===206}function ml(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function bl(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(Y(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class vl{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=dl(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return yt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new _f(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new wf(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 _f{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,ml(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=Bn(n.url),!pl(n.status))throw Hn(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=fl({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=gl(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new $e("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:bl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class wf{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,ml(n,this._withCredentials,this._abortController)).then(o=>{const h=Bn(o.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!pl(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:bl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const mo=200,bo=206;function xf(a){const t=a.response;return typeof t!="string"?t:On(t).buffer}class Sf{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=dl(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=bo):i.expectedStatus=mo,e.responseType="arraybuffer",yt(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||mo;if(!(n===mo&&s.expectedStatus===bo)&&n!==s.expectedStatus){s.onError(i.status);return}const o=xf(i);if(n===bo){const h=i.getResponseHeader("Content-Range"),l=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);l?s.onDone({begin:parseInt(l[1],10),chunk:o}):(Y('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 Cf{constructor(t){this._source=t,this._manager=new Sf(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 yt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Af(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Tf(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 Af{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=Bn(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[h,...l]=o.split(": ");return[h,l.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=fl({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=gl(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 Tf{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=Bn(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 Ef=/^[a-z][a-z0-9\-+.]+:/i;function kf(a){if(Ef.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class Mf{constructor(t){this.source=t,this.url=kf(t.url),yt(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return yt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Pf(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Of(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 Pf{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 ui(`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 $e("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Of{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 Df=1e5,$t=30,Rf=.8;class Ht{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#h=0;#a=0;#c=null;#l=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(h){h.enqueue(t),h.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#l=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.#h=n,Ht.#O(),fs(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}=Bt.platform;return $(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,fs(this.#l,{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 $e("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>Df){Y("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=B.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 h=Math.hypot(i[2],i[3]),l=h*Ht.#L(o,this.#r);let c,u;n===0?(c=i[4],u=i[5]-l):(c=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const d="calc(var(--scale-factor)*",f=e.style;this.#e===this.#l?(f.left=`${(100*c/this.#a).toFixed(2)}%`,f.top=`${(100*u/this.#h).toFixed(2)}%`):(f.left=`${d}${c.toFixed(2)}px)`,f.top=`${d}${u.toFixed(2)}px)`),f.fontSize=`${d}${(Ht.#S*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,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:h,fontSize:l}=s;Ht.#T(i,l*this.#u,o);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${h*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=$t,this.#T(i,$t,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,$t,$t),i.strokeText("g",0,0);let h=i.getImageData(0,0,$t,$t).data;o=0;for(let c=h.length-1-3;c>=0;c-=4)if(h[c]>0){o=Math.ceil(c/4/$t);break}i.clearRect(0,0,$t,$t),i.strokeText("A",0,$t),h=i.getImageData(0,0,$t,$t).data,r=0;for(let c=0,u=h.length;c<u;c+=4)if(h[c]>0){r=$t-Math.floor(c/4/$t);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):Rf;return this.#_.set(t,l),l}}class yi{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(yi.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 h of n.children)i(h)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Lf=65536,Ff=100,If=5e3,Nf=Pt?Kd:Yd,jf=Pt?Jd:Jh,Bf=Pt?qd:$d,Hf=Pt?Zd:tl;function zf(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new vo,{docId:e}=t,s=a.url?Gf(a.url):null,i=a.data?Vf(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof _l?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:Lf;let c=a.worker instanceof Bs?a.worker:null;const u=a.verbosity,d=typeof a.docBaseUrl=="string"&&!Rn(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,g=a.cMapPacked!==!1,p=a.CMapReaderFactory||jf,b=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,m=a.StandardFontDataFactory||Hf,v=a.stopAtErrors!==!0,y=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,_=a.isEvalSupported!==!1,S=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Pt,A=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Pt&&(Bt.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,E=typeof a.disableFontFace=="boolean"?a.disableFontFace:Pt,O=a.fontExtraProperties===!0,N=a.enableXfa===!0,D=a.ownerDocument||globalThis.document,L=a.disableRange===!0,M=a.disableStream===!0,P=a.disableAutoFetch===!0,j=a.pdfBug===!0,k=a.CanvasFactory||Nf,R=a.FilterFactory||Bf,G=a.enableHWA===!0,at=h?h.length:a.length??NaN,ct=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Pt&&!E,At=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:p===Jh&&m===tl&&f&&b&&fi(f,document.baseURI)&&fi(b,document.baseURI),wt=null;Ad(u);const nt={canvasFactory:new k({ownerDocument:D,enableHWA:G}),filterFactory:new R({docId:e,ownerDocument:D}),cMapReaderFactory:At?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:At?null:new m({baseUrl:b})};if(!c){const ut={verbosity:u,port:vi.workerPort};c=ut.port?Bs.fromPort(ut):new Bs(ut),t._worker=c}const Vt={docId:e,apiVersion:"4.10.38",data:i,password:o,disableAutoFetch:P,rangeChunkSize:l,length:at,docBaseUrl:d,enableXfa:N,evaluatorOptions:{maxImageSize:y,disableFontFace:E,ignoreErrors:v,isEvalSupported:_,isOffscreenCanvasSupported:S,isImageDecoderSupported:A,canvasMaxAreaInBytes:T,fontExtraProperties:O,useSystemFonts:ct,cMapUrl:At?f:null,standardFontDataUrl:At?b:null}},Ee={disableFontFace:E,fontExtraProperties:O,ownerDocument:D,pdfBug:j,styleElement:wt,loadingParams:{disableAutoFetch:P,enableXfa:N}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const ut=c.messageHandler.sendWithPromise("GetDocRequest",Vt,i?[i.buffer]:null);let Q;if(h)Q=new mf(h,{disableRange:L,disableStream:M});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Je;if(Pt)if(fi(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`.");Je=vl}else Je=Mf;else Je=fi(s)?vl:Cf;Q=new Je({url:s,length:at,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:L,disableStream:M})}return ut.then(Je=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const Vs=new mi(e,Je,c.port),ke=new Yf(Vs,t,Q,Ee,nt);t._transport=ke,Vs.send("Ready",null)})}).catch(t._capability.reject),t}function Gf(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(Pt&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Vf(a){if(Pt&&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 On(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 yl(a){return typeof a=="object"&&Number.isInteger(a?.num)&&a.num>=0&&Number.isInteger(a?.gen)&&a.gen>=0}class vo{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${vo.#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 _l{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){st("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 $(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 Wf{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new Vh:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new wl,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new di({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return $(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=Ue.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=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&Qt.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=_=>{p.renderTasks.delete(v),(this._maybeCleanupAfterRender||b)&&(this.#e=!0),this.#s(!b),_?(v.capability.reject(_),this._abortOperatorList({intentState:p,reason:_ instanceof Error?_:new Error(_)})):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:h,operatorList:p.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:l});(p.renderTasks||=new Set).add(v);const y=v.task;return Promise.all([p.displayReadyCapability.promise,o]).then(([_,S])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(S.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:_,optionalContentConfig:S}),v.operatorListChanged()}).catch(m),y}getOperatorList({intent:t="display",annotationMode:e=Ue.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let o=this._intentStates.get(r.cacheKey);o||(o=Object.create(null),this._intentStates.set(r.cacheKey,o));let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(h),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=>yi.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:l}){if(l){s(o);return}o.lang??=h.lang,Object.assign(o.styles,h.styles),o.items.push(...h.items),n()},i)}const r=e.getReader(),o={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),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 Vh),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)},If),!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,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),l=this._intentStates.get(e);l.streamReader=h;const c=()=>{h.read().then(({value:u,done:d})=>{if(d){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,l),c())},u=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const d of l.renderTasks)d.operatorListChanged();this.#s(!0)}if(l.displayReadyCapability)l.displayReadyCapability.reject(u);else if(l.opListReadCapability)l.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 io){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 $e(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 Uf{#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){Y("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 ot=class ot{constructor({name:t=null,port:e=null,verbosity:s=Td()}={}){Xs(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(pe(ot,vs)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(pe(ot,vs)||Si(ot,vs,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 mi("main","worker",t),this._messageHandler.on("ready",function(){}),Xn(this,zs,Un).call(this)}_initialize(){if(pe(ot,bs)||pe(ot,Gs,Yn)){this._setupFakeWorker();return}let{workerSrc:t}=ot;try{ot._isSameOrigin(window.location.href,t)||(t=ot._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new mi("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,Xn(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{Mn("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){pe(ot,bs)||(Y("Setting up fake worker."),Si(ot,bs,!0)),ot._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Uf;this._port=e;const s=`fake${zl(ot,Vn)._++}`,i=new mi(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new mi(s,s+"_worker",e),Xn(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,pe(ot,vs)?.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=pe(this,vs)?.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 ot(t)}static get workerSrc(){if(vi.workerSrc)return vi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return $(this,"_setupFakeWorkerGlobal",(async()=>pe(this,Gs,Yn)?pe(this,Gs,Yn):(await import(this.workerSrc)).WorkerMessageHandler)())}};Vn=new WeakMap,bs=new WeakMap,vs=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}},Xs(ot,Gs),Xs(ot,Vn,0),Xs(ot,bs,!1),Xs(ot,vs),Pt&&(Si(ot,bs,!0),vi.workerSrc||="./pdf.worker.mjs"),ot._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},ot._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let Bs=ot;class Yf{#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 wl,this.fontLoader=new Wd({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 $(this,"annotationStorage",new co)}getRenderingIntent(t,e=Ue.ENABLE,s=null,i=!1,n=!1){let r=Qt.DISPLAY,o=lo;switch(t){case"any":r=Qt.ANY;break;case"display":break;case"print":r=Qt.PRINT;break;default:Y(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Qt.PRINT&&s instanceof Yh?s:this.annotationStorage;switch(e){case Ue.DISABLE:r+=Qt.ANNOTATIONS_DISABLE;break;case Ue.ENABLE:break;case Ue.ENABLE_FORMS:r+=Qt.ANNOTATIONS_FORMS;break;case Ue.ENABLE_STORAGE:r+=Qt.ANNOTATIONS_STORAGE,o=h.serializable;break;default:Y(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Qt.IS_EDITING),n&&(r+=Qt.OPLIST);const{ids:l,hash:c}=h.modifiedIds,u=[r,o.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}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 $e("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)=>{yt(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}yt(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)=>{yt(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}yt(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(Ut(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw Ut(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:h}=this._params;if("error"in n){const d=n.error;Y(`Error during font loading: ${d}`),this.commonObjs.resolve(s,d);break}const l=h&&globalThis.FontInspector?.enabled?(d,f)=>globalThis.FontInspector.fontAdded(d,f):null,c=new Ud(n,{disableFontFace:r,fontExtraProperties:o,inspectFont:l});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;yt(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>wd&&(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&&Y("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 Wf(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return yl(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 pf(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 ff(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(!yl(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const _i=Symbol("INITIAL_DATA");class wl{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:_i}}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===_i)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!==_i}delete(t){const e=this.#t[t];return!e||e.data===_i?!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!==_i&&(yield[t,e])}}}class $f{#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:h,filterFactory:l,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=h,this.filterFactory=l,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 $f(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 io(`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 qf="4.10.38",Kf="f9bea397f";function xl(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function wi(a){return Math.max(0,Math.min(255,255*a))}class Sl{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=wi(t),[t,t,t]}static G_HTML([t]){const e=xl(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(wi)}static RGB_HTML(t){return`#${t.map(xl).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[wi(1-Math.min(1,t+i)),wi(1-Math.min(1,s+i)),wi(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 Jf{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){st("Abstract method `_createSVG` called.")}}class yo extends Jf{_createSVG(t){return document.createElementNS(Be,t)}}class Cl{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",o=>{i.setValue(e,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const o of s.children)o.attributes.value===r.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const h=o.target.options,l=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,o=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,l]of Object.entries(r))if(l!=null)switch(h){case"class":l.length&&t.setAttribute(h,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,l)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const o=n!=="richText",h=t.div;if(h.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=u}o&&h.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),o&&yi.shouldBuildText(i.name)&&l.push(u)}return{textDivs:l}}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);l.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&&yi.shouldBuildText(p)&&l.push(m),b.append(m)}}for(const u of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))u.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const xi=1e3,Zf=9,gs=new WeakSet;function Ke(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class Qf{static create(t){switch(t.data.annotationType){case St.LINK:return new Al(t);case St.TEXT:return new tg(t);case St.WIDGET:switch(t.data.fieldType){case"Tx":return new eg(t);case"Btn":return t.data.radioButton?new Tl(t):t.data.checkBox?new ig(t):new ng(t);case"Ch":return new rg(t);case"Sig":return new sg(t)}return new ps(t);case St.POPUP:return new _o(t);case St.FREETEXT:return new El(t);case St.LINE:return new ag(t);case St.SQUARE:return new hg(t);case St.CIRCLE:return new lg(t);case St.POLYLINE:return new kl(t);case St.CARET:return new ug(t);case St.INK:return new wo(t);case St.POLYGON:return new cg(t);case St.HIGHLIGHT:return new Ml(t);case St.UNDERLINE:return new dg(t);case St.SQUIGGLY:return new fg(t);case St.STRIKEOUT:return new gg(t);case St.STAMP:return new Pl(t);case St.FILEATTACHMENT:return new pg(t);default:return new pt(t)}}}class pt{#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 pt._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:h}}}}=this;s?.splice(0,4,...t);const{width:l,height:c}=Ke(t);e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*l/n}%`,e.height=`${100*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 ps||(n.tabIndex=xi);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 _o){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:o,height:h}=Ke(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 Tl){const v=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=v}switch(e.borderStyle.style){case ci.SOLID:r.borderStyle="solid";break;case ci.DASHED:r.borderStyle="dashed";break;case ci.BEVELED:Y("Unimplemented border style: beveled");break;case ci.INSET:Y("Unimplemented border style: inset");break;case ci.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=B.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const l=B.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*(l[0]-d)/c}%`,r.top=`${100*(l[1]-f)/u}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*o/c}%`,r.height=`${100*h/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}=Ke(this.data.rect);let o,h;t%180===0?(o=100*n/s,h=100*r/i):(o=100*r/s,h=100*n/i),e.style.width=`${o}%`,e.style.height=`${h}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],o=n.slice(1);i.target.style[s]=Sl[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:Sl[`${r}_rgb`](o)})};return $(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 h=i-e,l=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],y=t[p+2],_=t[p+3],S=c.createElement("rect"),A=(y-e)/h,T=(n-v)/l,E=(m-y)/h,O=(v-_)/l;S.setAttribute("x",A),S.setAttribute("y",T),S.setAttribute("width",E),S.setAttribute("height",O),f.append(S),o?.push(`<rect vector-effect="non-scaling-stroke" x="${A}" y="${T}" width="${E}" height="${O}"/>`)}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 _o({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(){st("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:o}of i){if(n===-1||r===e)continue;const h=typeof o=="string"?o:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!gs.has(l)){Y(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&gs.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 Al extends pt{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){Y('_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 h=this.annotationStorage,l=[];for(const c of o){const{id:u}=c;switch(l.push(u),c.type){case"text":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;h.setValue(u,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}default:continue}const d=document.querySelector(`[data-element-id="${u}"]`);if(d){if(!gs.has(d)){Y(`_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:l,name:"ResetForm"}}),!1}}}class tg extends pt{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 ps extends pt{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Bt.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":B.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Zf,n=t.style;let r;const o=2,h=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o),c=Math.round(l/(Kr*i))||1,u=l/c;r=Math.min(i,h(u/Kr))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/Kr))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=B.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 eg extends ps{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(`
|
|
506
|
+
`)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,""));const h={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),gs.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=xi,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"),h.formattedValue=null}),s.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue??"";s.value=h.userValue=u,h.formattedValue=null});let l=c=>{const{formattedValue:u}=h;u!=null&&(c.target.value=u),c.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",u=>{if(h.focused)return;const{target:d}=u;h.userValue&&(d.value=h.userValue),h.lastCommittedValue=d.value,h.commitKey=1,this.data.actions?.Focus||(h.focused=!0)}),s.addEventListener("updatefromsandbox",u=>{this.showElementAndHideCanvas(u.target);const d={value(f){h.userValue=f.detail.value??"",t.setValue(e,{value:h.userValue.toString()}),f.target.value=h.userValue},formattedValue(f){const{formattedValue:g}=f.detail;h.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=h.userValue;!b||b.length<=g||(b=b.slice(0,g),p.value=h.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=>{h.commitKey=1;let d=-1;if(u.key==="Escape"?d=0:u.key==="Enter"&&!this.data.multiLine?d=2:u.key==="Tab"&&(h.commitKey=3),d===-1)return;const{value:f}=u.target;h.lastCommittedValue!==f&&(h.lastCommittedValue=f,h.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=l;l=null,s.addEventListener("blur",u=>{if(!h.focused||!u.relatedTarget)return;this.data.actions?.Blur||(h.focused=!1);const{value:d}=u.target;h.userValue=d,h.lastCommittedValue!==d&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:d,willCommit:!0,commitKey:h.commitKey,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}),c(u)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",u=>{h.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 y=g.substring(0,p).match(/\w*[^\w]*$/);y&&(m-=y[0].length);break}case"deleteWordForward":{const y=g.substring(p).match(/^[^\w]*\w*/);y&&(v+=y[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,h,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],u=>u.target.value)}if(l&&s.addEventListener("blur",l),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 sg extends ps{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class ig extends ps{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 gs.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=xi,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s)){const c=h&&l.exportValue===e.exportValue;l.domElement&&(l.domElement.checked=c),t.setValue(l.id,{value:c})}t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue||"Off";r.target.checked=o===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const o={value(h){h.target.checked=h.detail.value!=="Off",t.setValue(s,{value:h.target.checked})}};this._dispatchEventFromSandbox(o,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Tl extends ps{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(gs.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=xi,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s))t.setValue(l.id,{value:!1});t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue;r.target.checked=o!=null&&o===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",o=>{const h={value:l=>{const c=r===l.detail.value;for(const u of this._getElementsByName(l.target.name)){const d=c&&u.id===s;u.domElement&&(u.domElement.checked=d),t.setValue(u.id,{value:d})}}};this._dispatchEventFromSandbox(h,o)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class ng extends Al{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 rg extends ps{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");gs.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=xi;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 h=o(!1);const l=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)}),h=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:l(d)}),h=o(!1)},clear(d){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),h=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:l(d)}),h=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:l(d)}),h=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)}),h=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:h,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 _o extends pt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:pt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new og({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=>`${so}${s}`).join(",")),this.container}}class og{#t=this.#E.bind(this);#e=this.#T.bind(this);#s=this.#k.bind(this);#i=this.#x.bind(this);#r=null;#n=null;#h=null;#a=null;#c=null;#l=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:h,rect:l,parentRect:c,open:u}){this.#n=t,this.#p=i,this.#h=r,this.#m=o,this.#l=h,this.#r=e,this.#g=l,this.#d=c,this.#c=s,this.#a=Xh.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=B.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=B.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)Cl.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(this.#h);t.append(n)}this.#n.append(t)}get#v(){const t=this.#m,e=this.#h;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(`
|
|
507
|
+
`))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.#h,richText:this.#m},t&&(this.#o=null),e&&(this.#m=this.#A(e),this.#h=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#b&&({contentsObj:this.#h,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.#l;let r=!!this.#d,o=r?this.#d:this.#g;for(const g of this.#c)if(!o||B.intersect(g.data.rect,o)!==null){o=g.data.rect,r=!0;break}const h=B.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=h[0]+c,d=h[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 El extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=U.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 ag extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=Ke(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 hg extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=Ke(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 lg extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=Ke(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 kl extends pt{#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}=Ke(t),o=this.svgFactory.create(n,r,!0);let h=[];for(let c=0,u=e.length;c<u;c+=2){const d=e[c]-t[0],f=t[3]-e[c+1];h.push(`${d},${f}`)}h=h.join(" ");const l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",h),l.setAttribute("stroke-width",s.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class cg extends kl{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class ug extends pt{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 wo extends pt{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?U.HIGHLIGHT:U.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:h}=this.#s(e,t),l=this.svgFactory.create(o,h,!0),c=this.#t=this.svgFactory.createElement("svg:g");l.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(l),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:h}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${o} ${h}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ml extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=U.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class dg extends pt{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 fg extends pt{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 gg extends pt{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 Pl extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=U.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 pg extends pt{#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}=Bt.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 mg{#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=`${so}${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;fs(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 yo,annotationStorage:t.annotationStorage||new co,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===St.POPUP;if(o){const c=i.get(r.id);if(!c)continue;n.elements=c}else{const{width:c,height:u}=Ke(r.rect);if(c<=0||u<=0)continue}n.data=r;const h=Qf.create(n);if(!h.isRenderable)continue;if(!o&&r.popupRef){const c=i.get(r.popupRef);c?c.push(h):i.set(r.popupRef,[h])}const l=h.render();r.hidden&&(l.style.visibility="hidden"),await this.#r(l,r.id),h._isEditable&&(this.#s.set(h.data.id,h),this._annotationEditorUIManager?.renderAnnotationElement(h))}this.#n()}update({viewport:t}){const e=this.div;this.viewport=t,fs(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 Ct extends H{#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=Ct.prototype,e=n=>n.isEmpty(),s=qe.TRANSLATE_SMALL,i=qe.TRANSLATE_BIG;return $(this,"_keyboardManager",new pi([[["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=U.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||Ct._defaultColor||H._defaultLineColor,this.#r=t.fontSize||Ct._defaultFontSize}static initialize(t,e){H.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case q.FREETEXT_SIZE:Ct._defaultFontSize=e;break;case q.FREETEXT_COLOR:Ct._defaultColor=e;break}}updateParams(t,e){switch(t){case q.FREETEXT_SIZE:this.#n(e);break;case q.FREETEXT_COLOR:this.#h(e);break}}static get defaultPropertiesToUpdate(){return[[q.FREETEXT_SIZE,Ct._defaultFontSize],[q.FREETEXT_COLOR,Ct._defaultColor||H._defaultLineColor]]}get propertiesToUpdate(){return[[q.FREETEXT_SIZE,this.#r],[q.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:q.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#h(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:q.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Ct._internalPadding*t,-(Ct._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(U.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(Ct.#l(s)),e=s);return t.join(`
|
|
508
|
+
`)}#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){Ct._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),Ln(this,this.div,["dblclick","keydown"]),this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:r}=this._initialData;let[o,h]=this.getInitialTranslation();[o,h]=this.pageTranslationToScreen(o,h);const[l,c]=this.pageDimensions,[u,d]=this.pageTranslation;let f,g;switch(this.rotation){case 0:f=t+(r[0]-u)/l,g=e+this.height-(r[1]-d)/c;break;case 90:f=t+(r[0]-u)/l,g=e-(r[1]-d)/c,[o,h]=[h,-o];break;case 180:f=t-this.width+(r[0]-u)/l,g=e-(r[1]-d)/c,[o,h]=[-o,-h];break;case 270:f=t+(r[0]-u-this.height*c)/l,g=e+(r[1]-d-this.width*l)/c,[o,h]=[-h,o];break}this.setAt(f*i,g*n,o,h)}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#l(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=Ct.#f(e.getData("text")||"").replaceAll(zn,`
|
|
509
509
|
`);if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes(`
|
|
510
|
-
`)){r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:o,startOffset:h}=r,l=[],c=[];if(o.nodeType===Node.TEXT_NODE){const f=o.parentElement;if(c.push(o.nodeValue.slice(h).replaceAll(
|
|
510
|
+
`)){r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:o,startOffset:h}=r,l=[],c=[];if(o.nodeType===Node.TEXT_NODE){const f=o.parentElement;if(c.push(o.nodeValue.slice(h).replaceAll(zn,"")),f!==this.editorDiv){let g=l;for(const p of this.editorDiv.childNodes){if(p===f){g=c;continue}g.push(Ct.#l(p))}}l.push(o.nodeValue.slice(0,h).replaceAll(zn,""))}else if(o===this.editorDiv){let f=l,g=0;for(const p of this.editorDiv.childNodes)g++===h&&(f=c),f.push(Ct.#l(p))}this.#e=`${l.join(`
|
|
511
511
|
`)}${i}${c.join(`
|
|
512
|
-
`)}`,this.#
|
|
513
|
-
`)){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#
|
|
514
|
-
`),position:
|
|
515
|
-
`)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i={rect:this.getPDFRect()};return i.popup=this.hasEditedComment?this.comment:{text:this.#e},t.updateEdited(i),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class N{static PRECISION=1e-4;toSVGPath(){tt("Abstract method `toSVGPath` must be implemented.")}get box(){tt("Abstract getter `box` must be implemented.")}serialize(t,e){tt("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o]*i,r[o+1]=s+t[o+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o+1]*i,r[o+1]=s+t[o]*n;return r}static _translate(t,e,s,i){i||=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 Ss{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#o;#a;#h;#l;#u;#c;#f=[];static#p=8;static#g=2;static#d=Ss.#p+Ss.#g;constructor({x:t,y:e},s,i,n,r,o=0){this.#t=s,this.#c=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=o,this.#l=Ss.#p*i,this.#h=Ss.#d*i,this.#u=i,this.#f.push(t,e)}isEmpty(){return isNaN(this.#n[8])}#m(){const t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#o+(t[0]-e[0])/2-s)/n,(this.#a+(t[1]-e[1])/2-i)/r,(this.#o+(e[0]-t[0])/2-s)/n,(this.#a+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#o=t,this.#a=e;const[s,i,n,r]=this.#t;let[o,h,l,c]=this.#n.subarray(8,12);const d=t-l,u=e-c,f=Math.hypot(d,u);if(f<this.#h)return!1;const g=f-this.#l,p=g/f,y=p*d,m=p*u;let b=o,v=h;o=l,h=c,l+=y,c+=m,this.#f?.push(t,e);const _=-m/g,w=y/g,x=_*this.#c,T=w*this.#c;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([l+x,c+T],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([l-x,c-T],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([o+x,h+T],2),this.#r.push(NaN,NaN,NaN,NaN,(o+x-s)/n,(h+T-i)/r),this.#n.set([o-x,h-T],14),this.#e.push(NaN,NaN,NaN,NaN,(o-x-s)/n,(h-T-i)/r)),this.#n.set([b,v,o,h,l,c],6),!this.isEmpty()):(this.#n.set([b,v,o,h,l,c],6),Math.abs(Math.atan2(v-h,b-o)-Math.atan2(m,y))<Math.PI/2?([o,h,l,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+c)/2-i)/r),[o,h,b,v]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((b+o)/2-s)/n,((v+h)/2-i)/r),!0):([b,v,o,h,l,c]=this.#n.subarray(0,6),this.#r.push(((b+5*o)/6-s)/n,((v+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),[l,c,o,h,b,v]=this.#n.subarray(12,18),this.#e.push(((b+5*o)/6-s)/n,((v+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#v();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#w(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.#y(s),s.join(" ")}#v(){const[t,e,s,i]=this.#t,[n,r,o,h]=this.#m();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} ${h} L${(this.#n[16]-t)/s} ${(this.#n[17]-e)/i} L${(this.#n[14]-t)/s} ${(this.#n[15]-e)/i} Z`}#y(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#w(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),o=this.#n.subarray(16,18),[h,l,c,d]=this.#m();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${c} ${d} L${(o[0]-e)/i} ${(o[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new nc(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,o]=this.#t,h=new Float32Array((this.#f?.length??0)+2);for(let d=0,u=h.length-2;d<u;d+=2)h[d]=(this.#f[d]-i)/r,h[d+1]=(this.#f[d+1]-n)/o;if(h[h.length-2]=(this.#o-i)/r,h[h.length-1]=(this.#a-n)/o,isNaN(s[6])&&!this.isEmpty())return this.#x(h);const l=new Float32Array(this.#r.length+24+this.#e.length);let c=t.length;for(let d=0;d<c;d+=2){if(isNaN(t[d])){l[d]=l[d+1]=NaN;continue}l[d]=t[d],l[d+1]=t[d+1]}c=this.#S(l,c);for(let d=e.length-6;d>=6;d-=6)for(let u=0;u<6;u+=2){if(isNaN(e[d+u])){l[c]=l[c+1]=NaN,c+=2;continue}l[c]=e[d+u],l[c+1]=e[d+u+1],c+=2}return this.#b(l,c),this.newFreeDrawOutline(l,h,this.#t,this.#u,this.#s,this.#i)}#x(t){const e=this.#n,[s,i,n,r]=this.#t,[o,h,l,c]=this.#m(),d=new Float32Array(36);return d.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,l,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(d,t,this.#t,this.#u,this.#s,this.#i)}#b(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#S(t,e){const s=this.#n.subarray(4,6),i=this.#n.subarray(16,18),[n,r,o,h]=this.#t,[l,c,d,u]=this.#m();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24}}class nc extends N{#t;#e=new Float32Array(4);#s;#i;#r;#n;#o;constructor(t,e,s,i,n,r){super(),this.#o=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,h,l,c]=this.#e;for(let d=0,u=t.length;d<u;d+=2)t[d]=(t[d]-o)/l,t[d+1]=(t[d+1]-h)/c;for(let d=0,u=e.length;d<u;d+=2)e[d]=(e[d]-o)/l,e[d+1]=(e[d+1]-h)/c}toSVGPath(){const t=[`M${this.#o[4]} ${this.#o[5]}`];for(let e=6,s=this.#o.length;e<s;e+=6){if(isNaN(this.#o[e])){t.push(`L${this.#o[e+4]} ${this.#o[e+5]}`);continue}t.push(`C${this.#o[e]} ${this.#o[e+1]} ${this.#o[e+2]} ${this.#o[e+3]} ${this.#o[e+4]} ${this.#o[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,o=i-e;let h,l;switch(n){case 0:h=N._rescale(this.#o,t,i,r,-o),l=N._rescale(this.#r,t,i,r,-o);break;case 90:h=N._rescaleAndSwap(this.#o,t,e,r,o),l=N._rescaleAndSwap(this.#r,t,e,r,o);break;case 180:h=N._rescale(this.#o,s,e,-r,o),l=N._rescale(this.#r,s,e,-r,o);break;case 270:h=N._rescaleAndSwap(this.#o,s,i,-r,-o),l=N._rescaleAndSwap(this.#r,s,i,-r,-o);break}return{outline:Array.from(h),points:[Array.from(l)]}}#a(t){const e=this.#o;let s=e[4],i=e[5];const n=[s,i,s,i];let r=s,o=i;const h=t?Math.max:Math.min;for(let c=6,d=e.length;c<d;c+=6){const u=e[c+4],f=e[c+5];if(isNaN(e[c]))j.pointBoundingBox(u,f,n),o<f?(r=u,o=f):o===f&&(r=h(r,u));else{const g=[1/0,1/0,-1/0,-1/0];j.bezierBoundingBox(s,i,...e.slice(c,c+6),g),j.rectBoundingBox(...g,n),o<g[3]?(r=g[2],o=g[3]):o===g[3]&&(r=h(r,g[2]))}s=u,i=f}const l=this.#e;l[0]=n[0]-this.#s,l[1]=n[1]-this.#s,l[2]=n[2]-n[0]+2*this.#s,l[3]=n[3]-n[1]+2*this.#s,this.lastPoint=[r,o]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new Ss(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[o,h,l,c]=this.#t,d=n*l,u=r*c,f=s*l+o,g=i*c+h,p=this.newOutliner({x:this.#r[0]*d+f,y:this.#r[1]*u+g},this.#t,this.#n,t,this.#i,e??this.#s);for(let y=2;y<this.#r.length;y+=2)p.add({x:this.#r[y]*d+f,y:this.#r[y+1]*u+g});return p.getOutlines()}}class zo{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){const n=[1/0,1/0,-1/0,-1/0],r=10**-4;for(const{x:f,y:g,width:p,height:y}of t){const m=Math.floor((f-e)/r)*r,b=Math.ceil((f+p+e)/r)*r,v=Math.floor((g-e)/r)*r,_=Math.ceil((g+y+e)/r)*r,w=[m,v,_,!0],x=[b,v,_,!1];this.#s.push(w,x),j.rectBoundingBox(m,v,b,_,n)}const o=n[2]-n[0]+2*s,h=n[3]-n[1]+2*s,l=n[0]-s,c=n[1]-s,d=this.#s.at(i?-1:-2),u=[d[0],d[2]];for(const f of this.#s){const[g,p,y]=f;f[0]=(g-l)/o,f[1]=(p-c)/h,f[2]=(y-c)/h}this.#t=new Float32Array([l,c,o,h]),this.#e=u}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.#h(e)),this.#o(e)):(this.#a(e),t.push(...this.#h(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[o,h,l]=r;e.push([o,h,r],[o,l,r])}e.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=e.length;r<o;r+=2){const h=e[r][2],l=e[r+1][2];h.push(l),l.push(h),s.add(h),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,l,c,d]=r;s.delete(r);let u=o,f=h;for(n=[o,l],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(d))g=d;else break;s.delete(g),[o,h,l,c,d]=g,u!==o&&(n.push(u,f,o,f===h?h:l),u=o),f=f===h?l:h}n.push(u,f)}return new Hg(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}#o([,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}}}#h(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#n(i);for(let o=0;o<r;o++){const[h,l]=this.#i[o];for(let c=0,d=n.length;c<d;c++){const[,u,f]=n[c];if(!(l<=u||f<=h)){if(u>=h){if(f>l)n[c][1]=l;else{if(d===1)return[];n.splice(c,1),c--,d--}continue}n[c][2]=h,f>l&&n.push([e,l,f])}}}return n}}class Hg 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,h=i-e;for(const l of this.#e){const c=new Array(l.length);for(let d=0;d<l.length;d+=2)c[d]=t+l[d]*o,c[d+1]=i-l[d+1]*h;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class Go extends Ss{newFreeDrawOutline(t,e,s,i,n,r){return new zg(t,e,s,i,n,r)}}class zg extends nc{newOutliner(t,e,s,i,n,r=0){return new Go(t,e,s,i,n,r)}}class mt extends z{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#o=null;#a=0;#h=null;#l=null;#u=null;#c=!1;#f=null;#p;#g=null;#d="";#m;#v="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=V.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=mt.prototype;return Y(this,"_keyboardManager",new Ai([[["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||mt._defaultColor,this.#m=t.thickness||mt._defaultThickness,this.#p=t.opacity||mt._defaultOpacity,this.#s=t.boxes||null,this.#v=t.methodOfCreation||"",this.#d=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#c=!0,this.#w(t),this.#T()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#o=t.focusNode,this.#a=t.focusOffset,this.#y(),this.#T(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#c?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#m,methodOfCreation:this.#v}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}get commentColor(){return this.color}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#y(){const t=new zo(this.#s,.001);this.#l=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;const e=new zo(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]}#w({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#l=t;const i=1.5;if(this.#n=t.getNewOutline(this.#m/2+i,.0025),e>=0)this.#u=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.#u,{bbox:mt.#C(this.#l.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:mt.#C(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,o,h]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=o,this.height=h;break;case 90:{const[c,d]=this.parentDimensions;this.x=r,this.y=1-n,this.width=o*d/c,this.height=h*c/d;break}case 180:this.x=1-n,this.y=1-r,this.width=o,this.height=h;break;case 270:{const[c,d]=this.parentDimensions;this.x=1-r,this.y=n,this.width=o*d/c,this.height=h*c/d;break}}const{lastPoint:l}=this.#n;this.#f=[(l[0]-n)/o,(l[1]-r)/h]}static initialize(t,e){z.initialize(t,e),mt._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case $.HIGHLIGHT_COLOR:mt._defaultColor=e;break;case $.HIGHLIGHT_THICKNESS:mt._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case $.HIGHLIGHT_COLOR:this.#x(e);break;case $.HIGHLIGHT_THICKNESS:this.#b(e);break}}static get defaultPropertiesToUpdate(){return[[$.HIGHLIGHT_COLOR,mt._defaultColor],[$.HIGHLIGHT_THICKNESS,mt._defaultThickness]]}get propertiesToUpdate(){return[[$.HIGHLIGHT_COLOR,this.color||mt._defaultColor],[$.HIGHLIGHT_THICKNESS,this.#m||mt._defaultThickness],[$.HIGHLIGHT_FREE,this.#c]]}#x(t){const e=(n,r)=>{this.color=n,this.#p=r,this.parent?.drawLayer.updateProperties(this.#u,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#p;this.addCommands({cmd:e.bind(this,t,mt._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:$.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#b(t){const e=this.#m,s=i=>{this.#m=i,this.#S(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:$.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",this.#r=new ce({editor:this})]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#M())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#M())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#k(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#T(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#k():t&&(this.#T(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#S(t){if(!this.#c)return;this.#w({highlightOutlines:this.#l.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#k(){this.#u===null||!this.parent||(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#T(t=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#l.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#p},rootClass:{highlight:!0,free:this.#c},path:{d:this.#l.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#c},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#c),this.#h&&(this.#h.style.clipPath=this.#i))}static#C([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.#c?(t=(t-this.rotation+360)%360,s=mt.#C(this.#l.box,t)):s=mt.#C([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#u,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:mt.#C(this.#n.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#d&&(t.setAttribute("aria-label",this.#d),t.setAttribute("role","mark")),this.#c?t.classList.add("free"):this.div.addEventListener("keydown",this.#O.bind(this),{signal:this._uiManager._signal});const e=this.#h=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),ml(this,this.#h,["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}})}#O(t){mt._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#E(!0);break;case 1:case 3:this.#E(!1);break}}#E(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#o,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.#c||this.#E(!1))}get _mustFixPosition(){return!this.#c}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#u,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#M(){return this.#c?this.rotation:0}#F(){if(this.#c)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:h,y:l,width:c,height:d}of n){const u=h*t+s,f=(1-l)*e+i;r[o]=r[o+4]=u,r[o+1]=r[o+3]=f,r[o+2]=r[o+6]=u+c*t,r[o+5]=r[o+7]=f-d*e,o+=8}return r}#L(t){return this.#l.serialize(t,this.#M())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:o,width:h,height:l}=s.getBoundingClientRect(),c=new AbortController,d=t.combinedSignal(c),u=f=>{c.abort(),this.#I(t,f)};window.addEventListener("blur",u,{signal:d}),window.addEventListener("pointerup",u,{signal:d}),window.addEventListener("pointerdown",wt,{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",ae,{signal:d}),s.addEventListener("pointermove",this.#R.bind(this,t),{signal:d}),this._freeHighlight=new Go({x:i,y:n},[r,o,h,l],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#R(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#I(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 sc){const{data:{quadPoints:g,rect:p,rotation:y,id:m,color:b,opacity:v,popupRef:_,contentsObj:w},parent:{page:{pageNumber:x}}}=t;i=t={annotationType:V.HIGHLIGHT,color:Array.from(b),opacity:v,quadPoints:g,boxes:null,pageIndex:x-1,rect:p.slice(0),rotation:y,annotationElementId:m,id:m,deleted:!1,popupRef:_,comment:w?.str||null}}else if(t instanceof jo){const{data:{inkLists:g,rect:p,rotation:y,id:m,color:b,borderStyle:{rawWidth:v},popupRef:_,contentsObj:w},parent:{page:{pageNumber:x}}}=t;i=t={annotationType:V.HIGHLIGHT,color:Array.from(b),thickness:v,inkLists:g,boxes:null,pageIndex:x-1,rect:p.slice(0),rotation:y,annotationElementId:m,id:m,deleted:!1,popupRef:_,comment:w?.str||null}}const{color:n,quadPoints:r,inkLists:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=j.makeHexColor(...n),l.#p=h||1,o&&(l.#m=t.thickness),l._initialData=i,t.comment&&l.setCommentData(t.comment);const[c,d]=l.pageDimensions,[u,f]=l.pageTranslation;if(r){const g=l.#s=[];for(let p=0;p<r.length;p+=8)g.push({x:(r[p]-u)/c,y:1-(r[p+1]-f)/d,width:(r[p+2]-r[p])/c,height:(r[p+1]-r[p+5])/d});l.#y(),l.#T(),l.rotate(l.rotation)}else if(o){l.#c=!0;const g=o[0],p={x:g[0]-u,y:d-(g[1]-f)},y=new Go(p,[0,0,c,d],1,l.#m/2,!0,.001);for(let v=0,_=g.length;v<_;v+=2)p.x=g[v]-u,p.y=d-(g[v+1]-f),y.add(p);const{id:m,clipPathId:b}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:y.toSVGPath()}},!0,!0);l.#w({highlightOutlines:y.getOutlines(),highlightId:m,clipPathId:b}),l.#T(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getPDFRect(),s=z._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i={annotationType:V.HIGHLIGHT,color:s,opacity:this.#p,thickness:this.#m,quadPoints:this.#F(),outlines:this.#L(e),pageIndex:this.pageIndex,rect:e,rotation:this.#M(),structTreeParentId:this._structTreeParentId};return this.addComment(i),this.annotationElementId&&!this.#P(i)?null:(i.id=this.annotationElementId,i)}#P(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const e={rect:this.getPDFRect()};return this.hasEditedComment&&(e.popup=this.comment),t.updateEdited(e),null}static canCreateNewEmptyEditor(){return!1}}class rc{#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))e.startsWith("_")||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(){tt("Not implemented")}}class G extends z{#t=null;#e;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#o=null;static#a=null;static#h=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,this._addOutlines(t)}_addOutlines(t){t.drawOutlines&&(this.#l(t),this.#f())}#l({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#u(t,this.parent),this.#d(t.box)}#u(t,e){const{id:s}=e.drawLayer.draw(G._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){tt("Not implemented")}static get typesMap(){tt("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&&(G.#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 h=this.#t.updateProperty(e,o);h&&this.#d(h),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties()),t===this.colorType&&this._colorPicker?.update(o)};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,G._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#m()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,G._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#g()),{bbox:this.#m()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#m()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,G._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#m()}))}_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.#c(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#d(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#c()):t&&(this._uiManager.addShouldRescale(this),this.#f(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#c(){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.#u(this.#t,t)}}#p([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]}}#d(t){if([this.x,this.y,this.width,this.height]=this.#p(t),this.div){this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}this._onResized()}#m(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[o,h]}=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/h),i*(h/o),s*(o/h)];case 5:return[1-e,t,s*(o/h),i*(h/o)];case 6:return[1-t-i*(h/o),1-e,i*(h/o),s*(o/h)];case 7:return[e-s*(o/h),1-t-i*(h/o),s*(o/h),i*(h/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*(h/o),e,i*(h/o),s*(o/h)];case 13:return[1-e-s*(o/h),t-i*(h/o),s*(o/h),i*(h/o)];case 14:return[1-t,1-e-s*(o/h),i*(h/o),s*(o/h)];case 15:return[e,1-t,s*(o/h),i*(h/o)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,G._mergeSVGProperties({bbox:this.#m()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#d(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const s=super.render();s.classList.add("draw");const i=document.createElement("div");s.append(i),i.setAttribute("aria-hidden","true"),i.className="internal";const[n,r]=this.parentDimensions;return this.setDims(this.width*n,this.height*r),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),s}static createDrawerInstance(t,e,s,i,n){tt("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:o,pointerId:h,pointerType:l}=i;if(G.#o&&G.#o!==l)return;const{viewport:{rotation:c}}=t,{width:d,height:u}=n.getBoundingClientRect(),f=G.#i=new AbortController,g=t.combinedSignal(f);if(G.#n||=h,G.#o??=l,window.addEventListener("pointerup",p=>{G.#n===p.pointerId?this._endDraw(p):G.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{G.#n===p.pointerId?this._currentParent.endDrawingSession():G.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{G.#o===p.pointerType&&((G.#a||=new Set).add(p.pointerId),G.#s.isCancellable()&&(G.#s.removeLastElement(),G.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",ae,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===G.#h&&wt(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),G.#s){t.drawLayer.updateProperties(this._currentDrawId,G.#s.startNew(r,o,d,u,c));return}e.updateUIForDefaultProperties(this),G.#s=this.createDrawerInstance(r,o,d,u,c),G.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(G.#r.toSVGProperties(),G.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(G.#h=-1,!G.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(G.#n===i){if(G.#a?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,G.#s.add(e,s)),G.#h=t.timeStamp,wt(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,G.#s=null,G.#r=null,G.#o=null,G.#h=NaN),G.#i&&(G.#i.abort(),G.#i=null,G.#n=NaN,G.#a=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,G.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=G.#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:$.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack($.DRAW_STEP),!G.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:G.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:G.#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){tt("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=e.viewport,h=this.deserializeDraw(r,o,i,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,s);return l.createDrawingOptions(t),l.#l({drawOutlines:h}),l.#f(),l.onScaleChanging(),l.rotate(),l}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.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class Gg{#t=new Float64Array(6);#e;#s;#i;#r;#n;#o="";#a=0;#h=new Ri;#l;#u;constructor(t,e,s,i,n,r){this.#l=s,this.#u=i,this.#i=n,this.#r=r,[t,e]=this.#c(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)}#c(t,e){return N._normalizePoint(t,e,this.#l,this.#u,this.#i)}isEmpty(){return!this.#s||this.#s.length===0}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#c(t,e);const[s,i,n,r]=this.#t.subarray(2,6),o=t-n,h=e-r;return Math.hypot(this.#l*o,this.#u*h)<=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.#l=s,this.#u=i,this.#i=n,[t,e]=this.#c(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.#h.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#h.removeLastElement();this.#s.pop(),this.#o="";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.#o}}}toSVGPath(){const t=N.svgRound(this.#e[4]),e=N.svgRound(this.#e[5]);if(this.#n.length===2)return this.#o=`${this.#o} M ${t} ${e} Z`,this.#o;if(this.#n.length<=6){const i=this.#o.lastIndexOf("M");this.#o=`${this.#o.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.#o=`${this.#o} L ${i} ${n}`,this.#a=12,this.#o}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,h,l,c,d]=this.#e.slice(i,i+6).map(N.svgRound);s.push(`C${r} ${o} ${h} ${l} ${c} ${d}`)}return this.#o+=s.join(" "),this.#a=this.#e.length,this.#o}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.#h.build(this.#s,t,e,s,this.#i,this.#r,i),this.#t=null,this.#e=null,this.#s=null,this.#o=null,this.#h}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class Ri extends N{#t;#e=0;#s;#i;#r;#n;#o;#a;#h;build(t,e,s,i,n,r,o){this.#r=e,this.#n=s,this.#o=i,this.#a=n,this.#h=r,this.#s=o??0,this.#i=t,this.#c()}get thickness(){return this.#h}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&&isNaN(e[6])){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,h,l,c]=e.subarray(s,s+6).map(N.svgRound);t.push(`C${n} ${r} ${o} ${h} ${l} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],o=[],[h,l,c,d]=this.#u();let u,f,g,p,y,m,b,v,_;switch(this.#a){case 0:_=N._rescale,u=t,f=e+i,g=s,p=-i,y=t+h*s,m=e+(1-l-d)*i,b=t+(h+c)*s,v=e+(1-l)*i;break;case 90:_=N._rescaleAndSwap,u=t,f=e,g=s,p=i,y=t+l*s,m=e+h*i,b=t+(l+d)*s,v=e+(h+c)*i;break;case 180:_=N._rescale,u=t+s,f=e,g=-s,p=i,y=t+(1-h-c)*s,m=e+l*i,b=t+(1-h)*s,v=e+(l+d)*i;break;case 270:_=N._rescaleAndSwap,u=t+s,f=e+i,g=-s,p=-i,y=t+(1-l-d)*s,m=e+(1-h-c)*i,b=t+(1-l)*s,v=e+(1-h)*i;break}for(const{line:w,points:x}of this.#i)r.push(_(w,u,f,g,p,n?new Array(w.length):null)),o.push(_(x,u,f,g,p,n?new Array(x.length):null));return{lines:r,points:o,rect:[y,m,b,v]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:o},rotation:h,thickness:l}){const c=[];let d,u,f,g,p;switch(h){case 0:p=N._rescale,d=-t/s,u=e/i+1,f=1/s,g=-1/i;break;case 90:p=N._rescaleAndSwap,d=-e/i,u=-t/s,f=1/i,g=1/s;break;case 180:p=N._rescale,d=t/s+1,u=-e/i,f=-1/s,g=1/i;break;case 270:p=N._rescaleAndSwap,d=e/i+1,u=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of o){const b=m.length;if(b===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(b===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1],NaN,NaN,NaN,NaN,m[2],m[3]]));continue}const v=new Float32Array(3*(b-2));r.push(v);let[_,w,x,T]=m.subarray(0,4);v.set([NaN,NaN,NaN,NaN,_,w],0);for(let A=4;A<b;A+=2){const k=m[A],R=m[A+1];v.set(N.createBezierPoints(_,w,x,T,k,R),(A-2)*3),[_,w,x,T]=[x,T,k,R]}}}for(let m=0,b=r.length;m<b;m++)c.push({line:p(r[m].map(v=>v??NaN),d,u,f,g),points:p(o[m].map(v=>v??NaN),d,u,f,g)});const y=new this.prototype.constructor;return y.build(c,s,i,1,h,l,n),y}#l(t=this.#h){const e=this.#s+t/2*this.#o;return this.#a%180===0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#u(){const[t,e,s,i]=this.#t,[n,r]=this.#l(0);return[t+n,e+r,s-2*n,i-2*r]}#c(){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,h=i.length;o<h;o+=6)j.pointBoundingBox(i[o],i[o+1],t);continue}let n=i[4],r=i[5];for(let o=6,h=i.length;o<h;o+=6){const[l,c,d,u,f,g]=i.subarray(o,o+6);j.bezierBoundingBox(n,r,l,c,d,u,f,g,t),n=f,r=g}}const[e,s]=this.#l();t[0]=zt(t[0]-e,0,1),t[1]=zt(t[1]-s,0,1),t[2]=zt(t[2]+e,0,1),t[3]=zt(t[3]+s,0,1),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.#l();this.#h=t;const[i,n]=this.#l(),[r,o]=[i-e,n-s],h=this.#t;return h[0]-=r,h[1]-=o,h[2]+=2*r,h[3]+=2*o,h}updateParentDimensions([t,e],s){const[i,n]=this.#l();this.#r=t,this.#n=e,this.#o=s;const[r,o]=this.#l(),h=r-i,l=o-n,c=this.#t;return c[0]-=h,c[1]-=l,c[2]+=2*h,c[3]+=2*l,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,h=0;switch(this.#e){case 90:i=e/t,n=-t/e,o=t;break;case 180:s=-1,r=-1,o=t,h=e;break;case 270:i=-e/t,n=t/e,h=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${N.svgRound(o)} ${N.svgRound(h)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#l(),[o,h,l,c]=this.#t;if(Math.abs(l-n)<=N.PRECISION||Math.abs(c-r)<=N.PRECISION){const p=t+s/2-(o+l/2),y=e+i/2-(h+c/2);return{path:{"transform-origin":`${N.svgRound(t)} ${N.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${y})`}}}const d=(s-2*n)/(l-2*n),u=(i-2*r)/(c-2*r),f=l/s,g=c/i;return{path:{"transform-origin":`${N.svgRound(o)} ${N.svgRound(h)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${N.svgRound(n)} ${N.svgRound(r)}) scale(${d} ${u}) translate(${N.svgRound(-n)} ${N.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#l(),o=this.#t,[h,l,c,d]=o;if(o[0]=t,o[1]=e,o[2]=s,o[3]=i,Math.abs(c-n)<=N.PRECISION||Math.abs(d-r)<=N.PRECISION){const y=t+s/2-(h+c/2),m=e+i/2-(l+d/2);for(const{line:b,points:v}of this.#i)N._translate(b,y,m,b),N._translate(v,y,m,v);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${N.svgRound(t)} ${N.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const u=(s-2*n)/(c-2*n),f=(i-2*r)/(d-2*r),g=-u*(h+n)+t+n,p=-f*(l+r)+e+r;if(u!==1||f!==1||g!==0||p!==0)for(const{line:y,points:m}of this.#i)N._rescale(y,g,p,u,f,y),N._rescale(m,g,p,u,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],h=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:l,points:c}of this.#i)N._translate(l,o,h,l),N._translate(c,o,h,c);else{const l=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:d,points:u}of this.#i)N._rescale(d,o,h,l,c,d),N._rescale(u,o,h,l,c,u);r[2]*=l,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 nr extends rc{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:z._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._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new nr(this._viewParameters);return t.updateAll(this),t}}class Vo extends G{static _type="ink";static _editorType=V.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){z.initialize(t,e),this._defaultDrawingOptions=new nr(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return Y(this,"typesMap",new Map([[$.INK_THICKNESS,"stroke-width"],[$.INK_COLOR,"stroke"],[$.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new Gg(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return Ri.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof jo){const{data:{inkLists:r,rect:o,rotation:h,id:l,color:c,opacity:d,borderStyle:{rawWidth:u},popupRef:f,contentsObj:g},parent:{page:{pageNumber:p}}}=t;i=t={annotationType:V.INK,color:Array.from(c),thickness:u,opacity:d,paths:{points:r},boxes:null,pageIndex:p-1,rect:o.slice(0),rotation:h,annotationElementId:l,id:l,deleted:!1,popupRef:f,comment:g?.str||null}}const n=await super.deserialize(t,e,s);return n._initialData=i,t.comment&&n.setCommentData(t.comment),n}get toolbarButtons(){return this._colorPicker||=new Oi(this),[["colorPicker",this._colorPicker]]}get colorType(){return $.INK_COLOR}get colorValue(){return this._drawingOptions.stroke}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=Vo.getDefaultDrawingOptions({stroke:j.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,h={annotationType:V.INK,color:z._colorManager.convert(n),opacity:r,thickness:o,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return this.addComment(h),t?(h.isCopy=!0,h):this.annotationElementId&&!this.#t(h)?null:(h.id=this.annotationElementId,h)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((r,o)=>r!==e[o])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:s}=this.serializeDraw(!1),i={rect:s,thickness:this._drawingOptions["stroke-width"],points:e};return this.hasEditedComment&&(i.popup=this.comment),t.updateEdited(i),null}}class Wo extends Ri{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}const rr=8,Fi=3;class Qs{static#t={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#e(t,e,s,i){return s-=t,i-=e,s===0?i>0?0:4:s===1?i+6:2-i}static#s=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#i(t,e,s,i,n,r,o){const h=this.#e(s,i,n,r);for(let l=0;l<8;l++){const c=(-l+h-o+16)%8,d=this.#s[2*c],u=this.#s[2*c+1];if(t[(s+d)*e+(i+u)]!==0)return c}return-1}static#r(t,e,s,i,n,r,o){const h=this.#e(s,i,n,r);for(let l=0;l<8;l++){const c=(l+h+o+16)%8,d=this.#s[2*c],u=this.#s[2*c+1];if(t[(s+d)*e+(i+u)]!==0)return c}return-1}static#n(t,e,s,i){const n=t.length,r=new Int32Array(n);for(let c=0;c<n;c++)r[c]=t[c]<=i?1:0;for(let c=1;c<s-1;c++)r[c*e]=r[c*e+e-1]=0;for(let c=0;c<e;c++)r[c]=r[e*s-1-c]=0;let o=1,h;const l=[];for(let c=1;c<s-1;c++){h=1;for(let d=1;d<e-1;d++){const u=c*e+d,f=r[u];if(f===0)continue;let g=c,p=d;if(f===1&&r[u-1]===0)o+=1,p-=1;else if(f>=1&&r[u+1]===0)o+=1,p+=1,f>1&&(h=f);else{f!==1&&(h=Math.abs(f));continue}const y=[d,c],m=p===d+1,b={isHole:m,points:y,id:o,parent:0};l.push(b);let v;for(const D of l)if(D.id===h){v=D;break}v?v.isHole?b.parent=m?v.parent:h:b.parent=m?h:v.parent:b.parent=m?h:0;const _=this.#i(r,e,c,d,g,p,0);if(_===-1){r[u]=-o,r[u]!==1&&(h=Math.abs(r[u]));continue}let w=this.#s[2*_],x=this.#s[2*_+1];const T=c+w,A=d+x;g=T,p=A;let k=c,R=d;for(;;){const D=this.#r(r,e,k,R,g,p,1);w=this.#s[2*D],x=this.#s[2*D+1];const F=k+w,M=R+x;y.push(M,F);const P=k*e+R;if(r[P+1]===0?r[P]=-o:r[P]===1&&(r[P]=o),F===c&&M===d&&k===T&&R===A){r[u]!==1&&(h=Math.abs(r[u]));break}else g=k,p=R,k=F,R=M}}}return l}static#o(t,e,s,i){if(s-e<=4){for(let T=e;T<s-2;T+=2)i.push(t[T],t[T+1]);return}const n=t[e],r=t[e+1],o=t[s-4]-n,h=t[s-3]-r,l=Math.hypot(o,h),c=o/l,d=h/l,u=c*r-d*n,f=h/o,g=1/l,p=Math.atan(f),y=Math.cos(p),m=Math.sin(p),b=g*(Math.abs(y)+Math.abs(m)),v=g*(1-b+b**2),_=Math.max(Math.atan(Math.abs(m+y)*v),Math.atan(Math.abs(m-y)*v));let w=0,x=e;for(let T=e+2;T<s-2;T+=2){const A=Math.abs(u-c*t[T+1]+d*t[T]);A>w&&(x=T,w=A)}w>(l*_)**2?(this.#o(t,e,x+2,i),this.#o(t,x,s,i)):i.push(n,r)}static#a(t){const e=[],s=t.length;return this.#o(t,0,s,e),e.push(t[s-2],t[s-1]),e.length<=4?null:e}static#h(t,e,s,i,n,r){const o=new Float32Array(r**2),h=-2*i**2,l=r>>1;for(let p=0;p<r;p++){const y=(p-l)**2;for(let m=0;m<r;m++)o[p*r+m]=Math.exp((y+(m-l)**2)/h)}const c=new Float32Array(256),d=-2*n**2;for(let p=0;p<256;p++)c[p]=Math.exp(p**2/d);const u=t.length,f=new Uint8Array(u),g=new Uint32Array(256);for(let p=0;p<s;p++)for(let y=0;y<e;y++){const m=p*e+y,b=t[m];let v=0,_=0;for(let x=0;x<r;x++){const T=p+x-l;if(!(T<0||T>=s))for(let A=0;A<r;A++){const k=y+A-l;if(k<0||k>=e)continue;const R=t[T*e+k],D=o[x*r+A]*c[Math.abs(R-b)];v+=R*D,_+=D}}const w=f[m]=Math.round(v/_);g[w]++}return[f,g]}static#l(t){const e=new Uint32Array(256);for(const s of t)e[s]++;return e}static#u(t){const e=t.length,s=new Uint8ClampedArray(e>>2);let i=-1/0,n=1/0;for(let o=0,h=s.length;o<h;o++){const l=s[o]=t[o<<2];i=Math.max(i,l),n=Math.min(n,l)}const r=255/(i-n);for(let o=0,h=s.length;o<h;o++)s[o]=(s[o]-n)*r;return s}static#c(t){let e,s=-1/0,i=-1/0;const n=t.findIndex(h=>h!==0);let r=n,o=n;for(e=n;e<256;e++){const h=t[e];h>s&&(e-r>i&&(i=e-r,o=e-1),s=h,r=e)}for(e=o-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#f(t){const e=t,{width:s,height:i}=t,{maxDim:n}=this.#t;let r=s,o=i;if(s>n||i>n){let u=s,f=i,g=Math.log2(Math.max(s,i)/n);const p=Math.floor(g);g=g===p?p-1:p;for(let m=0;m<g;m++){r=Math.ceil(u/2),o=Math.ceil(f/2);const b=new OffscreenCanvas(r,o);b.getContext("2d").drawImage(t,0,0,u,f,0,0,r,o),u=r,f=o,t!==e&&t.close(),t=b.transferToImageBitmap()}const y=Math.min(n/r,n/o);r=Math.round(r*y),o=Math.round(o*y)}const l=new OffscreenCanvas(r,o).getContext("2d",{willReadFrequently:!0});l.fillStyle="white",l.fillRect(0,0,r,o),l.filter="grayscale(1)",l.drawImage(t,0,0,t.width,t.height,0,0,r,o);const c=l.getImageData(0,0,r,o).data;return[this.#u(c),r,o]}static extractContoursFromText(t,{fontFamily:e,fontStyle:s,fontWeight:i},n,r,o,h){let l=new OffscreenCanvas(1,1),c=l.getContext("2d",{alpha:!1});const d=200,u=c.font=`${s} ${i} ${d}px ${e}`,{actualBoundingBoxLeft:f,actualBoundingBoxRight:g,actualBoundingBoxAscent:p,actualBoundingBoxDescent:y,fontBoundingBoxAscent:m,fontBoundingBoxDescent:b,width:v}=c.measureText(t),_=1.5,w=Math.ceil(Math.max(Math.abs(f)+Math.abs(g)||0,v)*_),x=Math.ceil(Math.max(Math.abs(p)+Math.abs(y)||d,Math.abs(m)+Math.abs(b)||d)*_);l=new OffscreenCanvas(w,x),c=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),c.font=u,c.filter="grayscale(1)",c.fillStyle="white",c.fillRect(0,0,w,x),c.fillStyle="black",c.fillText(t,w*(_-1)/2,x*(3-_)/2);const T=this.#u(c.getImageData(0,0,w,x).data),A=this.#l(T),k=this.#c(A),R=this.#n(T,w,x,k);return this.processDrawnLines({lines:{curves:R,width:w,height:x},pageWidth:n,pageHeight:r,rotation:o,innerMargin:h,mustSmooth:!0,areContours:!0})}static process(t,e,s,i,n){const[r,o,h]=this.#f(t),[l,c]=this.#h(r,o,h,Math.hypot(o,h)*this.#t.sigmaSFactor,this.#t.sigmaR,this.#t.kernelSize),d=this.#c(c),u=this.#n(l,o,h,d);return this.processDrawnLines({lines:{curves:u,width:o,height:h},pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:r,areContours:o}){i%180!==0&&([e,s]=[s,e]);const{curves:h,width:l,height:c}=t,d=t.thickness??0,u=[],f=Math.min(e/l,s/c),g=f/e,p=f/s,y=[];for(const{points:b}of h){const v=r?this.#a(b):b;if(!v)continue;y.push(v);const _=v.length,w=new Float32Array(_),x=new Float32Array(3*(_===2?2:_-2));if(u.push({line:x,points:w}),_===2){w[0]=v[0]*g,w[1]=v[1]*p,x.set([NaN,NaN,NaN,NaN,w[0],w[1]],0);continue}let[T,A,k,R]=v;T*=g,A*=p,k*=g,R*=p,w.set([T,A,k,R],0),x.set([NaN,NaN,NaN,NaN,T,A],0);for(let D=4;D<_;D+=2){const F=w[D]=v[D]*g,M=w[D+1]=v[D+1]*p;x.set(N.createBezierPoints(T,A,k,R,F,M),(D-2)*3),[T,A,k,R]=[k,R,F,M]}}if(u.length===0)return null;const m=o?new Wo:new Ri;return m.build(u,e,s,1,i,o?0:d,n),{outline:m,newCurves:y,areContours:o,thickness:d,width:l,height:c}}static async compressSignature({outlines:t,areContours:e,thickness:s,width:i,height:n}){let r=1/0,o=-1/0,h=0;for(const v of t){h+=v.length;for(let _=2,w=v.length;_<w;_++){const x=v[_]-v[_-2];r=Math.min(r,x),o=Math.max(o,x)}}let l;r>=-128&&o<=127?l=Int8Array:r>=-32768&&o<=32767?l=Int16Array:l=Int32Array;const c=t.length,d=rr+Fi*c,u=new Uint32Array(d);let f=0;u[f++]=d*Uint32Array.BYTES_PER_ELEMENT+(h-2*c)*l.BYTES_PER_ELEMENT,u[f++]=0,u[f++]=i,u[f++]=n,u[f++]=e?0:1,u[f++]=Math.max(0,Math.floor(s??0)),u[f++]=c,u[f++]=l.BYTES_PER_ELEMENT;for(const v of t)u[f++]=v.length-2,u[f++]=v[0],u[f++]=v[1];const g=new CompressionStream("deflate-raw"),p=g.writable.getWriter();await p.ready,p.write(u);const y=l.prototype.constructor;for(const v of t){const _=new y(v.length-2);for(let w=2,x=v.length;w<x;w++)_[w-2]=v[w]-v[w-2];p.write(_)}p.close();const m=await new Response(g.readable).arrayBuffer(),b=new Uint8Array(m);return gl(b)}static async decompressSignature(t){try{const e=df(t),{readable:s,writable:i}=new DecompressionStream("deflate-raw"),n=i.getWriter();await n.ready,n.write(e).then(async()=>{await n.ready,await n.close()}).catch(()=>{});let r=null,o=0;for await(const v of s)r||=new Uint8Array(new Uint32Array(v.buffer,0,4)[0]),r.set(v,o),o+=v.length;const h=new Uint32Array(r.buffer,0,r.length>>2),l=h[1];if(l!==0)throw new Error(`Invalid version: ${l}`);const c=h[2],d=h[3],u=h[4]===0,f=h[5],g=h[6],p=h[7],y=[],m=(rr+Fi*g)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(p){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(r.buffer,m);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(r.buffer,m);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(r.buffer,m);break}o=0;for(let v=0;v<g;v++){const _=h[Fi*v+rr],w=new Float32Array(_+2);y.push(w);for(let x=0;x<Fi-1;x++)w[x]=h[Fi*v+rr+x+1];for(let x=0;x<_;x++)w[x+2]=w[x]+b[o++]}return{areContours:u,thickness:f,outlines:y,width:c,height:d}}catch(e){return W(`decompressSignature: ${e}`),null}}}class Uo extends rc{constructor(){super(),super.updateProperties({fill:z._defaultLineColor,"stroke-width":0})}clone(){const t=new Uo;return t.updateAll(this),t}}class Xo extends nr{constructor(t){super(t),super.updateProperties({stroke:z._defaultLineColor,"stroke-width":1})}clone(){const t=new Xo(this._viewParameters);return t.updateAll(this),t}}class Oe extends G{#t=!1;#e=null;#s=null;#i=null;static _type="signature";static _editorType=V.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#s=t.signatureData||null,this.#e=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){z.initialize(t,e),this._defaultDrawingOptions=new Uo,this._defaultDrawnSignatureOptions=new Xo(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return Y(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#e}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){this._drawId!==null&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:s}=this;if(s&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),this._drawId===null)if(this.#s){const{lines:i,mustSmooth:n,areContours:r,description:o,uuid:h,heightInPage:l}=this.#s,{rawDims:{pageWidth:c,pageHeight:d},rotation:u}=this.parent.viewport,f=Qs.processDrawnLines({lines:i,pageWidth:c,pageHeight:d,rotation:u,innerMargin:Oe._INNER_MARGIN,mustSmooth:n,areContours:r});this.addSignature(f,l,o,h)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#e||""}));return s&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#i=t,this.addEditToolbar()}getUuid(){return this.#i}get description(){return this.#e}set description(t){this.#e=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:s,width:i,height:n}=this.#s,r=Math.max(i,n),o=Qs.processDrawnLines({lines:{curves:t.map(h=>({points:h})),thickness:s,width:i,height:n},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e});return{areContours:e,outline:o.outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,s,i){const{x:n,y:r}=this,{outline:o}=this.#s=t;this.#t=o instanceof Wo,this.description=s;let h;this.#t?h=Oe.getDefaultDrawingOptions():(h=Oe._defaultDrawnSignatureOptions.clone(),h.updateProperties({"stroke-width":o.thickness})),this._addOutlines({drawOutlines:o,drawingOptions:h});const[l,c]=this.parentDimensions,[,d]=this.pageDimensions;let u=e/d;u=u>=1?.5:u,this.width*=u/this.height,this.width>=1&&(u*=.9/this.width,this.width=.9),this.height=u,this.setDims(l*this.width,c*this.height),this.x=n,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(i),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!i,hasDescription:!!s}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return Qs.process(t,e,s,i,Oe._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:s,pageHeight:i},rotation:n}=this.parent.viewport;return Qs.extractContoursFromText(t,e,s,i,n,Oe._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return Qs.processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:Oe._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=Oe.getDefaultDrawingOptions():(this._drawingOptions=Oe._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:s,rect:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,r={annotationType:V.SIGNATURE,isSignature:!0,areContours:this.#t,color:[0,0,0],thickness:this.#t?0:n,pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return this.addComment(r),t?(r.paths={lines:e,points:s},r.uuid=this.#i,r.isCopy=!0):r.lines=e,this.#e&&(r.accessibilityData={type:"Figure",alt:this.#e}),r}static deserializeDraw(t,e,s,i,n,r){return r.areContours?Wo.deserialize(t,e,s,i,n,r):Ri.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){const i=await super.deserialize(t,e,s);return i.#t=t.areContours,i.description=t.accessibilityData?.alt||"",i.#i=t.uuid,i}}class Vg extends z{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#o=null;#a=!1;#h=null;#l=!1;#u=!1;static _type="stamp";static _editorType=V.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){z.initialize(t,e)}static isHandlingMimeForPasting(t){return xo.includes(t)}static paste(t,e){e.pasteEditor({mode:V.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}}#c(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#l=t.isSvg),t.file&&(this.#n=t.file.name),this.#g()}#f(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#o){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this.addEditToolbar().then(()=>{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 h=o.output;return await this.setGuessedAltText(h),e&&!this.hasAltTextData()&&(this.altTextData={alt:h,decorative:!1}),h}#p(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#c(s,!0)).finally(()=>this.#f());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.#c(i)).finally(()=>this.#f());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.#c(i)).finally(()=>this.#f());return}const t=document.createElement("input");t.type="file",t.accept=xo.join(",");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.#c(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#f()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#o?.remove(),this.#o=null,this.#h&&(clearTimeout(this.#h),this.#h=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#p();return}super.rebuild(),this.div!==null&&(this.#e&&this.#o===null&&this.#p(),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||this.#a)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#a||(this.#t?this.#g():this.#p()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:s,bitmap:i}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),s&&this._uiManager.imageManager.isValidId(s)&&(this.#e=s,i&&(this.#t=i),this.#a=!1,this.#g())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#h!==null&&clearTimeout(this.#h);const t=200;this.#h=setTimeout(()=>{this.#h=null,this.#m()},t)}#g(){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,h]=this.parentDimensions;this.setDims(e*o/i,s*h/n),this._uiManager.enableWaiting(!1);const l=this.#o=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),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.#u||(this.parent.addUndoableEditor(this),this.#u=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&this.div.setAttribute("aria-description",this.#n),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new Me;let o=this.#t,h=i,l=n,c=null;if(e){if(i>e||n>e){const x=Math.min(e/i,e/n);h=Math.floor(i*x),l=Math.floor(n*x)}c=document.createElement("canvas");const u=c.width=Math.ceil(h*r.sx),f=c.height=Math.ceil(l*r.sy);this.#l||(o=this.#d(u,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",y="#cfcfd8";this._uiManager.hcmFilter!=="none"?y="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",y="#42414d");const m=15,b=m*r.sx,v=m*r.sy,_=new OffscreenCanvas(b*2,v*2),w=_.getContext("2d");w.fillStyle=p,w.fillRect(0,0,b*2,v*2),w.fillStyle=y,w.fillRect(0,0,b,v),w.fillRect(b,v,b,v),g.fillStyle=g.createPattern(_,"repeat"),g.fillRect(0,0,u,f),g.drawImage(o,0,0,o.width,o.height,0,0,u,f)}let d=null;if(s){let u,f;if(r.symmetric&&o.width<t&&o.height<t)u=o.width,f=o.height;else if(o=this.#t,i>t||n>t){const y=Math.min(t/i,t/n);u=Math.floor(i*y),f=Math.floor(n*y),this.#l||(o=this.#d(u,f))}const p=new OffscreenCanvas(u,f).getContext("2d",{willReadFrequently:!0});p.drawImage(o,0,0,o.width,o.height,0,0,u,f),d={width:u,height:f,data:p.getImageData(0,0,u,f).data}}return{canvas:c,width:h,height:l,imageData:d}}#d(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 h=n,l=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,h,l,0,0,n,r),o=c.transferToImageBitmap()}return o}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new Me,r=Math.ceil(s*t*n.sx),o=Math.ceil(i*e*n.sy),h=this.#o;if(!h||h.width===r&&h.height===o)return;h.width=r,h.height=o;const l=this.#l?this.#t:this.#d(r,o),c=h.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,o)}#v(t){if(t){if(this.#l){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.#l){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*Xs.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*Xs.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,n=!1;if(t instanceof ic){const{data:{rect:p,rotation:y,id:m,structParent:b,popupRef:v,contentsObj:_},container:w,parent:{page:{pageNumber:x}},canvas:T}=t;let A,k;T?(delete t.canvas,{id:A,bitmap:k}=s.imageManager.getFromCanvas(w.id,T),T.remove()):(n=!0,t._hasNoCanvas=!0);const R=(await e._structTree.getAriaAttributes(`${bo}${m}`))?.get("aria-label")||"";i=t={annotationType:V.STAMP,bitmapId:A,bitmap:k,pageIndex:x-1,rect:p.slice(0),rotation:y,annotationElementId:m,id:m,deleted:!1,accessibilityData:{decorative:!1,altText:R},isSvg:!1,structParent:b,popupRef:v,comment:_?.str||null}}const r=await super.deserialize(t,e,s),{rect:o,bitmap:h,bitmapUrl:l,bitmapId:c,isSvg:d,accessibilityData:u}=t;n?(s.addMissingCanvas(t.id,r),r.#a=!0):c&&s.imageManager.isValidId(c)?(r.#e=c,h&&(r.#t=h)):r.#i=l,r.#l=d;const[f,g]=r.pageDimensions;return r.width=(o[2]-o[0])/f,r.height=(o[3]-o[1])/g,u&&(r.altTextData=u),r._initialData=i,t.comment&&r.setCommentData(t.comment),r.#u=!!i,r}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:V.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,isSvg:this.#l,structTreeParentId:this._structTreeParentId};if(this.addComment(s),t)return s.bitmapUrl=this.#v(!0),s.accessibilityData=this.serializeAltText(!0),s.isCopy=!0,s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const o=this.#y(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.#l?(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.#v(!1);else if(this.#l){const o=e.stamps.get(this.#e);r>o.area&&(o.area=r,o.serialized.bitmap.close(),o.serialized.bitmap=this.#v(!1))}return s}#y(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const e={rect:this.getPDFRect()};return this.hasEditedComment&&(e.popup=this.comment),t.updateEdited(e),null}}class Ye{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#o=!1;#a=!1;#h=!1;#l=null;#u=null;#c=null;#f=null;#p=null;#g=-1;#d;static _initialized=!1;static#m=new Map([Ct,Vo,Vg,mt,Oe].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:c}){const d=[...Ye.#m.values()];if(!Ye._initialized){Ye._initialized=!0;for(const u of d)u.initialize(c,t)}t.registerEditorTypes(d),this.#d=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=l,this.#c=h,this.drawLayer=o,this._structTree=i,this.#d.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#d.getMode()===V.NONE}updateToolbar(t){this.#d.updateToolbar(t)}updateMode(t=this.#d.getMode()){switch(this.#b(),t){case V.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case V.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case V.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 Ye.#m.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#c?.div}setEditingState(t){this.#d.setEditingState(t)}addCommands(t){this.#d.addCommands(t)}cleanUndoStack(t){this.#d.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.#h=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.#p?.abort(),this.#p=null;const t=new Set;for(const s of this.#n.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#d.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s){this.#h=!1;return}const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#d.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#h=!1}disable(){if(this.#a=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.#c&&!this.#p){this.#p=new AbortController;const i=this.#d.combinedSignal(this.#p);this.#c.div.addEventListener("pointerdown",n=>{const{clientX:o,clientY:h,timeStamp:l}=n,c=this.#g;if(l-c>500){this.#g=l;return}this.#g=-1;const{classList:d}=this.div;d.toggle("getElements",!0);const u=document.elementsFromPoint(o,h);if(d.toggle("getElements",!1),!this.div.contains(u[0]))return;let f;const g=new RegExp(`^${al}[0-9]+$`);for(const y of u)if(g.test(y.id)){f=y.id;break}if(!f)return;const p=this.#n.get(f);p?.annotationElementId===null&&(n.stopPropagation(),n.preventDefault(),p.dblclick())},{signal:i,capture:!0})}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.#d.isDeletedAnnotationElement(r)){n.updateEdited({deleted:!0});continue}let o=e.get(r);if(o){o.resetAnnotationElement(n),o.show(!1),n.show();continue}o=t.get(r),o&&(this.#d.addChangedExistingAnnotation(o),o.renderAnnotationElement(n)&&o.show(!1)),n.show()}}this.#b(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of Ye.#m.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.#d.getActive()!==t&&this.#d.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#c?.div&&!this.#f){this.#f=new AbortController;const t=this.#d.combinedSignal(this.#f);this.#c.div.addEventListener("pointerdown",this.#v.bind(this),{signal:t}),this.#c.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#c?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#c.div.classList.remove("highlighting"))}#v(t){this.#d.unselectAll();const{target:e}=t;if(e===this.#c.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#c.div.contains(e)){const{isMac:s}=Tt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#d.showAllEditors("highlight",!0,!0),this.#c.div.classList.add("free"),this.toggleDrawing(),mt.startHighlighting(this,this.#d.direction==="ltr",{target:this.#c.div,x:t.x,y:t.y}),this.#c.div.addEventListener("pointerup",()=>{this.#c.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#d._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#d.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.#d.isDeletedAnnotationElement(e)&&this.#d.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#a&&t.annotationElementId&&this.#d.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#d.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#d.addDeletedAnnotationElement(t.annotationElementId),z.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.#d.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#h),this.#d.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.#d._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.#d.getId()}get#y(){return Ye.#m.get(this.#d.getMode())}combinedSignal(t){return this.#d.combinedSignal(t)}#w(t){const e=this.#y;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#y?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#d.updateMode(t.mode);const{offsetX:s,offsetY:i}=this.#x(),n=this.getNextId(),r=this.#w({parent:this,id:n,x:s,y:i,uiManager:this.#d,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await Ye.#m.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#d)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#w({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#d,isCentered:e,...s});return n&&this.add(n),n}#x(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),o=Math.min(window.innerWidth,t+s),h=Math.min(window.innerHeight,e+i),l=(n+o)/2-t,c=(r+h)/2-e,[d,u]=this.viewport.rotation%180===0?[l,c]:[c,l];return{offsetX:d,offsetY:u}}addNewEditor(t={}){this.createAndAddNewEditor(this.#x(),!0,t)}setSelected(t){this.#d.setSelected(t)}toggleSelected(t){this.#d.toggleSelected(t)}unselect(t){this.#d.unselect(t)}pointerup(t){const{isMac:e}=Tt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div||!this.#o||(this.#o=!1,this.#y?.isDrawer&&this.#y.supportMultipleDrawings))return;if(!this.#e){this.#e=!0;return}const s=this.#d.getMode();if(s===V.STAMP||s===V.SIGNATURE){this.#d.unselectAll();return}this.createAndAddNewEditor(t,!1)}pointerdown(t){if(this.#d.getMode()===V.HIGHLIGHT&&this.enableTextSelection(),this.#o){this.#o=!1;return}const{isMac:e}=Tt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#o=!0,this.#y?.isDrawer){this.startDrawingSession(t);return}const s=this.#d.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#l){this.#y.startDrawing(this,this.#d,!1,t);return}this.#d.setCurrentDrawingSession(this),this.#l=new AbortController;const e=this.#d.combinedSignal(this.#l);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#u=null,this.commitOrRemove())},{signal:e}),this.#y.startDrawing(this,this.#d,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#u=e);return}this.#u&&setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(t=!1){return this.#l?(this.#d.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#u=null,this.#y.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#d.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#y.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#d.getActive()?.parent===this&&(this.#d.commitOrRemove(),this.#d.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.#d.removeLayer(this)}#b(){for(const t of this.#n.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,_s(this.div,t);for(const e of this.#d.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#d.commitOrRemove(),this.#b();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,_s(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.#d.viewParameters.realScale}}class kt{#t=null;#e=new Map;#s=new Map;static#i=0;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#e.size>0)for(const e of this.#e.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return Y(this,"_svgFactory",new sr)}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=kt._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#o(t,e){const s=kt._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=kt._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=kt.#i++,n=this.#n(),r=kt._svgFactory.createElement("defs");n.append(r);const o=kt._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#s.set(i,o);const l=s?this.#o(r,h):null,c=kt._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${h}`),this.updateProperties(n,t),this.#e.set(i,n),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,e){const s=kt.#i++,i=this.#n(),n=kt._svgFactory.createElement("defs");i.append(n);const r=kt._svgFactory.createElement("path");n.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke");let h;if(e){const d=kt._svgFactory.createElement("mask");n.append(d),h=`mask_p${this.pageIndex}_${s}`,d.setAttribute("id",h),d.setAttribute("maskUnits","objectBoundingBox");const u=kt._svgFactory.createElement("rect");d.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const f=kt._svgFactory.createElement("use");d.append(f),f.setAttribute("href",`#${o}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const l=kt._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${o}`),h&&l.setAttribute("mask",`url(#${h})`);const c=l.cloneNode();return i.append(c),l.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#e.set(s,i),s}finalizeDraw(t,e){this.#s.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.#e.get(t):t;if(o){if(s&&this.#a(o,s),i&&kt.#r(o,i),n){const{classList:h}=o;for(const[l,c]of Object.entries(n))h.toggle(l,c)}if(r){const l=o.firstChild.firstChild;this.#a(l,r)}}}updateParent(t,e){if(e===this)return;const s=this.#e.get(t);s&&(e.#t.append(s),this.#e.delete(t),e.#e.set(t,s))}remove(t){this.#s.delete(t),this.#t!==null&&(this.#e.get(t).remove(),this.#e.delete(t))}destroy(){this.#t=null;for(const t of this.#e.values())t.remove();this.#e.clear(),this.#s.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner:zo},globalThis.pdfjsLib={AbortException:es,AnnotationEditorLayer:Ye,AnnotationEditorParamsType:$,AnnotationEditorType:V,AnnotationEditorUIManager:ss,AnnotationLayer:Ho,AnnotationMode:ts,AnnotationType:vt,build:_g,ColorPicker:ce,createValidAbsoluteUrl:hl,DOMSVGFactory:sr,DrawLayer:kt,FeatureTest:Tt,fetchData:wi,getDocument:Xl,getFilenameFromUrl:uf,getPdfFilenameFromUrl:ff,getRGB:Yn,getUuid:fl,getXfaPageViewport:pf,GlobalWorkerOptions:Ks,ImageKind:Hn,InvalidPDFException:po,isDataScheme:Xn,isPdfFile:_o,isValidExplicitDest:Tf,MathClamp:zt,noContextMenu:ae,normalizeUnicode:lf,OPS:vi,OutputScale:Me,PasswordResponses:Qu,PDFDataRangeTransport:Yl,PDFDateString:wo,PDFWorker:Pi,PermissionFlag:Zu,PixelsPerInch:Xs,RenderingCancelledException:vo,ResponseException:Un,setLayerDimensions:_s,shadow:Y,SignatureExtractor:Qs,stopEvent:wt,SupportedImageMimeTypes:xo,TextLayer:Gt,TouchManager:qn,updateUrlHash:ll,Util:j,VerbosityLevel:zn,version:$l,XfaLayer:Jl};let oc=null;function Wg(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function Ug(){const a=oc??Wg();return oc=a,a/72}function Xg(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 Yg(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)})}ac()||(Ks.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${$l}/pdf.worker.min.mjs`);function ac(){try{return typeof OffscreenCanvas<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function"}catch{return!1}}async function $g({page:a,data:t,scale:e,password:s},i){const n=Ug()/window.devicePixelRatio,r=await Yg(t);if(ac()){const o=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/pdfjs.worker-CJ2MeDJc.js").href:new URL("assets/pdfjs.worker-CJ2MeDJc.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:ut&&ut.tagName.toUpperCase()==="SCRIPT"&&ut.src||new URL("pdf-canvas.umd.js",document.baseURI).href),{type:"module"});return o.postMessage({data:r,password:s,id:i,page:a,units:n,scale:e}),await new Promise(l=>{o.addEventListener("message",c=>{if(c.data.status!=="success")return;const{bitmap:d,width:u,height:f,pages:g}=c.data;if(d){const p=document.createElement("canvas"),y=p.getContext("bitmaprenderer");p.width=u,p.height=f,y?.transferFromImageBitmap(d),l({pages:g,canvas:p})}else l({pages:g,canvas:null})})})}else{const o=await Xl({data:r,password:s}).promise,h=o.numPages;if(!i)return{canvas:null,pages:h};const l=await o.getPage(a),c=l.getViewport({scale:e}),d=document.createElement("canvas"),u={canvas:d,viewport:c,transform:[n,0,0,n,0,0]};return d.width=Math.floor(c.width*n),d.height=Math.floor(c.height*n),l.render(u).promise.then(()=>({canvas:d,pages:h}))}}const Vt=new Map;function qg(a){const t=new Qr(a);return Vt.set(a,t),t}function Kg(a){const t=Date.now();return{PDFId:`${a.name}-${t}`,name:a.name.replace(/.pdf/,""),updateDate:t,data:a}}async function Jg({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await zu(a),n=s.filter(o=>o!==null),r=nu.groupSVGElements(n,i);return n.forEach(o=>{o.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function Zg(a,t){if(!Vt.get(a))return;const s=1/3,i=rp(t,s);lc(a,i,s)}async function Qg(a,t){const e=Date.now(),i={PDFId:`${a.name}-${e}`,name:a.name.replace(/.png|.jpg|.jpeg/,""),updateDate:e,data:a};return t&&hc(t,{data:a}),{...i,pages:1}}async function hc(a,{data:t,scale:e=.5}){if(!Vt.get(a))return;const i=URL.createObjectURL(t),n=await Ot.fromURL(i);n.scale(e),lc(a,n,e),URL.revokeObjectURL(i)}function lc(a,t,e){const s=Vt.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function tp(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function ep(a,t,e){!e||!a||(e.scale(1/t),tp(a,e))}function sp(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 ip(a){const t=Vt.get(a);t&&(t.discardActiveObject(),t.renderAll())}function np(a){const t=Vt.get(a);t&&(t.clear(),Vt.delete(a))}function rp(a,t){return new Ot(a,{scaleX:t,scaleY:t})}function Yo(a,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:o}=a,h=t.x*r*i,l=t.y*o*n;a.set({left:e-h,top:s-l})}function cc(a,t,e){const s=a.type;return{"application/pdf":op,"image/png":uc,"image/jpeg":uc}[s]?.(a,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function op(a,t,e){const s=Kg(a),i=await dc({page:1,data:a,scale:.8,password:t},e);return{...s,pages:i}}function dc(a,t){return $g(a,t).then(({canvas:e,pages:s})=>(e&&t&&Zg(t,e),s))}async function uc(a,t,e){return await Qg(a,e)}function ap(a,t){const e=Vt.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 hp(a,t){const e=Vt.get(a);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(xc);i instanceof te?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),Yo(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function lp(a){const t=Vt.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 fc(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{};let h=null,l=null,c=1,d={...wc};function u(){if(!t||Vt.has(t))return;const M=qg(t);return M.on("selection:created",P=>{if(r?.(P),P.selected.length<=1)return;const B=M.getActiveObject();B&&(l=B,e?.value&&l.set(e.value),l._cornerSize=l.cornerSize,w(c))}),M.on("selection:cleared",P=>{o?.(P),T(M)}),s&&M.on("mouse:down",s),i&&M.on("mouse:move",i),n&&M.on("mouse:up",n),M}function f(M,P){return cc(M,P,t)}function g(M){return dc(M,t)}function p({data:M,scale:P=.5}){return hc(t,{data:M,scale:P})}async function y(M,P,B){const O=Vt.get(t);if(!O)return;const L=await Ot.fromURL(M,{},{...cr,...P});Yo(L,B),O.add(L),b(O,L),O.setActiveObject(L)}function m(M,P,B){const O=Vt.get(t);if(!O)return;const L=new Pt(M,{...vc,...P});Yo(L,B),O.add(L),b(O,L),O.setActiveObject(L)}function b(M,P){P.on("selected",B=>v({canvas:M,target:B.target})),P.on("modified",B=>v({canvas:M,target:B.target})),P.on("scaling",()=>T(M)),P.on("moving",()=>T(M)),P.on("rotating",()=>T(M)),P._cornerSize=P._cornerSize??P.cornerSize}async function v({canvas:M,target:P,stroke:B=d.stroke,uuid:O=Date.now()}){if(M.getActiveObjects().length>1||h?.stroke===`${B}-${O}`)return;const H=await Jg(d,O,B);T(M),h=H,l=P,_(M,P,O),w(c,!0),H&&M.add(H)}function _(M,P,B){h&&(h.on("selected",()=>{M.remove(P),T(M)}),h.on("mouseover",()=>{v({canvas:M,target:P,stroke:d.hoverStroke,uuid:B})}),h.on("mouseout",()=>{v({canvas:M,target:P,stroke:d.stroke,uuid:B})}))}function w(M,P=!1){const B=Vt.get(t);c=M,B&&(sp(l,M),ep(l,M,h),!P&&B.renderAll())}function x(M){if(!M)return;d={...d,...M};const P=Vt.get(t);!h||!l||!P||v({target:l,canvas:P})}function T(M){l=null,h&&(M.remove(h),h=null)}function A(){ip(t)}function k(){np(t)}function R(M){ap(t,M)}function D(){return hp(t,b)}function F(){lp(t)}return{createCanvas:u,loadFile:f,specifyPage:g,renderImage:p,addFabric:y,addTextFabric:m,clearActive:A,deleteCanvas:k,scaleFabric:w,setCloseSvgOptions:x,setActiveFabric:R,copyActiveFabric:D,deleteActiveFabric:F}}function cp(a){let t=0;const e=Xg(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});X.onMounted(()=>{window.addEventListener("resize",e)}),X.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const dp=X.defineComponent({__name:"pdf-canvas",props:{file:{},page:{default:1},canvasId:{default:"PDF-canvas"},fileZoom:{default:1},fileScale:{default:1},canvasScale:{default:1},canvasClass:{default:""},isDrop:{type:Boolean,default:!1},password:{},dropTextOptions:{},dropImageOptions:{},selectionOptions:{},closeSvgOptions:{},manualReload:{type:Boolean},onDestroy:{type:Function,default:X.onBeforeUnmount}},emits:["loaded","reload","pointerDown","pointerMove","pointerUp","selectionCreated","selectionCleared"],setup(a,{expose:t,emit:e}){const s=a,i=e,{onDestroy:n}=s,r=X.ref(null),o=`${s.canvasId}-${s.page-1}`,h=X.computed(()=>s.fileZoom*s.canvasScale),l=X.computed(()=>({..._c,...s.selectionOptions})),{createCanvas:c,specifyPage:d,addFabric:u,addTextFabric:f,renderImage:g,clearActive:p,deleteCanvas:y,scaleFabric:m,setActiveFabric:b,setCloseSvgOptions:v,copyActiveFabric:_,deleteActiveFabric:w}=fc({id:o,selectionOptions:l,pointerDown:D=>i("pointerDown",D),pointerMove:D=>i("pointerMove",D),pointerUp:D=>i("pointerUp",D),selectionCreated:D=>i("selectionCreated",D),selectionCleared:D=>i("selectionCleared",D)});x(),cp(R);async function x(){const{file:D,page:F,fileScale:M}=s;globalThis.requestAnimationFrame(async()=>{if(await X.nextTick(),c(),D.data?.type.startsWith("image/")){g({data:D.data,scale:M/3}),i("loaded");return}const P=D.canvas?.[F-1]??D.data;P&&await d({page:F,data:P,scale:M,password:s.password}),i("loaded")})}function T(D){if(!s.isDrop||!D.dataTransfer)return;const{dataTransfer:F,offsetX:M,offsetY:P}=D,B=F.getData("text/plain"),O=F.getData("text/uri-list"),L=F.getData("custom/offset"),H=L?JSON.parse(L):null,Z={top:P,left:M},ct={x:H?.offsetX??0,y:H?.offsetY??0};O?A(O,Z,ct):B&&k(B,Z,ct)}function A(D,F,M){u(D,{...s.dropImageOptions,...F},M)}function k(D,F,M){f(D,{...s.dropTextOptions,...F},M)}function R(){s.manualReload||x(),i("reload")}return X.watch([()=>s.fileScale,()=>s.page,()=>s.file,()=>s.password],R),X.watch(h,D=>m(D),{immediate:!0}),X.watch(()=>s.closeSvgOptions,v,{immediate:!0}),n(y),t({reload:x,addImage:A,addText:k,clearActive:p,deleteCanvas:y,setActiveFabric:b,copyActiveFabric:_,deleteActiveFabric:w,canvasRef:r}),(D,F)=>(X.openBlock(),X.createElementBlock("div",{style:X.normalizeStyle({transform:`scale(${h.value})`}),onDragover:F[0]||(F[0]=X.withModifiers(()=>{},["prevent"])),onDragenter:F[1]||(F[1]=X.withModifiers(()=>{},["prevent"])),onDrop:X.withModifiers(T,["stop","prevent"])},[X.createElementVNode("canvas",{id:o,ref_key:"canvasRef",ref:r,class:X.normalizeClass(a.canvasClass)},null,2)],36))}});K.default=dp,K.loadFile=cc,K.useFabric=fc,Object.defineProperties(K,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
512
|
+
`)}`,this.#d();const u=new Range;let d=l.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(`
|
|
513
|
+
`)){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 El){const{data:{defaultAppearanceData:{fontSize:r,fontColor:o},rect:h,rotation:l,id:c,popupRef:u},textContent:d,textPosition:f,parent:{page:{pageNumber:g}}}=t;if(!d||d.length===0)return null;i=t={annotationType:U.FREETEXT,color:Array.from(o),fontSize:r,value:d.join(`
|
|
514
|
+
`),position:f,pageIndex:g-1,rect:h.slice(0),rotation:l,id:c,deleted:!1,popupRef:u}}const n=await super.deserialize(t,e,s);return n.#r=t.fontSize,n.#t=B.makeHexColor(...t.color),n.#e=Ct.#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=Ct._internalPadding*this.parentScale,s=this.getRect(e,e),i=H._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#t),n={annotationType:U.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(`
|
|
515
|
+
`)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=Ct._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class I{static PRECISION=1e-4;toSVGPath(){st("Abstract method `toSVGPath` must be implemented.")}get box(){st("Abstract getter `box` must be implemented.")}serialize(t,e){st("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o]*i,r[o+1]=s+t[o+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o+1]*i,r[o+1]=s+t[o]*n;return r}static _translate(t,e,s,i){i||=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 ms{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#h;#a;#c;#l;#d;#u;#f=[];static#o=8;static#g=2;static#m=ms.#o+ms.#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.#l=ms.#o*i,this.#c=ms.#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.#h+(t[0]-e[0])/2-s)/n,(this.#a+(t[1]-e[1])/2-i)/r,(this.#h+(e[0]-t[0])/2-s)/n,(this.#a+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#h=t,this.#a=e;const[s,i,n,r]=this.#t;let[o,h,l,c]=this.#n.subarray(8,12);const u=t-l,d=e-c,f=Math.hypot(u,d);if(f<this.#c)return!1;const g=f-this.#l,p=g/f,b=p*u,m=p*d;let v=o,y=h;o=l,h=c,l+=b,c+=m,this.#f?.push(t,e);const _=-m/g,S=b/g,A=_*this.#u,T=S*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([l+A,c+T],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([l-A,c-T],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([o+A,h+T],2),this.#r.push(NaN,NaN,NaN,NaN,(o+A-s)/n,(h+T-i)/r),this.#n.set([o-A,h-T],14),this.#e.push(NaN,NaN,NaN,NaN,(o-A-s)/n,(h-T-i)/r)),this.#n.set([v,y,o,h,l,c],6),!this.isEmpty()):(this.#n.set([v,y,o,h,l,c],6),Math.abs(Math.atan2(y-h,v-o)-Math.atan2(m,b))<Math.PI/2?([o,h,l,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+c)/2-i)/r),[o,h,v,y]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((v+o)/2-s)/n,((y+h)/2-i)/r),!0):([v,y,o,h,l,c]=this.#n.subarray(0,6),this.#r.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),[l,c,o,h,v,y]=this.#n.subarray(12,18),this.#e.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+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,h]=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} ${h} 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),[h,l,c,u]=this.#p();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${c} ${u} L${(o[0]-e)/i} ${(o[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Ol(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,o]=this.#t,h=new Float32Array((this.#f?.length??0)+2);for(let u=0,d=h.length-2;u<d;u+=2)h[u]=(this.#f[u]-i)/r,h[u+1]=(this.#f[u+1]-n)/o;if(h[h.length-2]=(this.#h-i)/r,h[h.length-1]=(this.#a-n)/o,isNaN(s[6])&&!this.isEmpty())return this.#w(h);const l=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])){l[u]=l[u+1]=NaN;continue}l[u]=t[u],l[u+1]=t[u+1]}c=this.#A(l,c);for(let u=e.length-6;u>=6;u-=6)for(let d=0;d<6;d+=2){if(isNaN(e[u+d])){l[c]=l[c+1]=NaN,c+=2;continue}l[c]=e[u+d],l[c+1]=e[u+d+1],c+=2}return this.#S(l,c),this.newFreeDrawOutline(l,h,this.#t,this.#d,this.#s,this.#i)}#w(t){const e=this.#n,[s,i,n,r]=this.#t,[o,h,l,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,h,NaN,NaN,NaN,NaN,l,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,h]=this.#t,[l,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24}}class Ol extends I{#t;#e=new Float32Array(4);#s;#i;#r;#n;#h;constructor(t,e,s,i,n,r){super(),this.#h=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,h,l,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-o)/l,t[u+1]=(t[u+1]-h)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-o)/l,e[u+1]=(e[u+1]-h)/c}toSVGPath(){const t=[`M${this.#h[4]} ${this.#h[5]}`];for(let e=6,s=this.#h.length;e<s;e+=6){if(isNaN(this.#h[e])){t.push(`L${this.#h[e+4]} ${this.#h[e+5]}`);continue}t.push(`C${this.#h[e]} ${this.#h[e+1]} ${this.#h[e+2]} ${this.#h[e+3]} ${this.#h[e+4]} ${this.#h[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,o=i-e;let h,l;switch(n){case 0:h=I._rescale(this.#h,t,i,r,-o),l=I._rescale(this.#r,t,i,r,-o);break;case 90:h=I._rescaleAndSwap(this.#h,t,e,r,o),l=I._rescaleAndSwap(this.#r,t,e,r,o);break;case 180:h=I._rescale(this.#h,s,e,-r,o),l=I._rescale(this.#r,s,e,-r,o);break;case 270:h=I._rescaleAndSwap(this.#h,s,i,-r,-o),l=I._rescaleAndSwap(this.#r,s,i,-r,-o);break}return{outline:Array.from(h),points:[Array.from(l)]}}#a(t){const e=this.#h;let s=e[4],i=e[5],n=s,r=i,o=s,h=i,l=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]),h=Math.max(h,e[f+5]),c<e[f+5]?(l=e[f+4],c=e[f+5]):c===e[f+5]&&(l=u(l,e[f+4]));else{const p=B.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]),h=Math.max(h,p[3]),c<p[3]?(l=p[2],c=p[3]):c===p[3]&&(l=u(l,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]=h-r+2*this.#s,this.lastPoint=[l,c]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new ms(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[o,h,l,c]=this.#t,u=n*l,d=r*c,f=s*l+o,g=i*c+h,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 xo{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,o=1/0,h=-1/0;const l=10**-4;for(const{x:b,y:m,width:v,height:y}of t){const _=Math.floor((b-e)/l)*l,S=Math.ceil((b+v+e)/l)*l,A=Math.floor((m-e)/l)*l,T=Math.ceil((m+y+e)/l)*l,E=[_,A,T,!0],O=[S,A,T,!1];this.#s.push(E,O),n=Math.min(n,_),r=Math.max(r,S),o=Math.min(o,A),h=Math.max(h,T)}const c=r-n+2*s,u=h-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,y]=b;b[0]=(m-d)/c,b[1]=(v-f)/u,b[2]=(y-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.#h(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,h,l]=r;e.push([o,h,r],[o,l,r])}e.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=e.length;r<o;r+=2){const h=e[r][2],l=e[r+1][2];h.push(l),l.push(h),s.add(h),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,l,c,u]=r;s.delete(r);let d=o,f=h;for(n=[o,l],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[o,h,l,c,u]=g,d!==o&&(n.push(d,f,o,f===h?h:l),d=o),f=f===h?l:h}n.push(d,f)}return new bg(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}#h([,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[h,l]=this.#i[o];for(let c=0,u=n.length;c<u;c++){const[,d,f]=n[c];if(!(l<=d||f<=h)){if(d>=h){if(f>l)n[c][1]=l;else{if(u===1)return[];n.splice(c,1),c--,u--}continue}n[c][2]=h,f>l&&n.push([e,l,f])}}}return n}}class bg extends I{#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,h=i-e;for(const l of this.#e){const c=new Array(l.length);for(let u=0;u<l.length;u+=2)c[u]=t+l[u]*o,c[u+1]=i-l[u+1]*h;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class So extends ms{newFreeDrawOutline(t,e,s,i,n,r){return new vg(t,e,s,i,n,r)}}class vg extends Ol{newOutliner(t,e,s,i,n,r=0){return new So(t,e,s,i,n,r)}}class ne{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#h=null;#a;#c=null;#l=null;#d;static#u=null;static get _keyboardManager(){return $(this,"_keyboardManager",new pi([[["Escape","mac+Escape"],ne.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ne.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ne.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ne.prototype._moveToPrevious],[["Home","mac+Home"],ne.prototype._moveToBeginning],[["End","mac+End"],ne.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=q.HIGHLIGHT_COLOR,this.#h=t):(this.#n=!0,this.#d=q.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||e,this.#a=this.#l._eventBus,this.#s=t?.color||this.#l?.highlightColors.values().next().value||"#FFFF98",ne.#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.#l._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.#l._signal;t.addEventListener("contextmenu",ge,{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.#l.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",ne.#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){ne._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.#l.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.#h?.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.#l.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 mt extends H{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#h=null;#a=0;#c=null;#l=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=U.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=mt.prototype;return $(this,"_keyboardManager",new pi([[["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||mt._defaultColor,this.#p=t.thickness||mt._defaultThickness,this.#o=t.opacity||mt._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.#h=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 xo(this.#s,.001);this.#l=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;const e=new xo(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.#l=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:mt.#x(this.#l.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:mt.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,o,h]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=o,this.height=h;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=o*u/c,this.height=h*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=o,this.height=h;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=o*u/c,this.height=h*c/u;break}}const{lastPoint:l}=this.#n;this.#f=[(l[0]-n)/o,(l[1]-r)/h]}static initialize(t,e){H.initialize(t,e),mt._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case q.HIGHLIGHT_DEFAULT_COLOR:mt._defaultColor=e;break;case q.HIGHLIGHT_THICKNESS:mt._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case q.HIGHLIGHT_COLOR:this.#w(e);break;case q.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[q.HIGHLIGHT_DEFAULT_COLOR,mt._defaultColor],[q.HIGHLIGHT_THICKNESS,mt._defaultThickness]]}get propertiesToUpdate(){return[[q.HIGHLIGHT_COLOR,this.color||mt._defaultColor],[q.HIGHLIGHT_THICKNESS,this.#p||mt._defaultThickness],[q.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,mt._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(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:q.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 ne({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.#l.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.#l.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#o},rootClass:{highlight:!0,free:this.#u},path:{d:this.#l.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=mt.#x(this.#l.box,t)):s=mt.#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:mt.#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),Ln(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){mt._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.#h,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:h,y:l,width:c,height:u}of n){const d=h*t+s,f=(1-l)*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.#l.serialize(t,this.#O())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:o,width:h,height:l}=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",te,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",ge,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new So({x:i,y:n},[r,o,h,l],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 Ml){const{data:{quadPoints:g,rect:p,rotation:b,id:m,color:v,opacity:y,popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:U.HIGHLIGHT,color:Array.from(v),opacity:y,quadPoints:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}else if(t instanceof wo){const{data:{inkLists:g,rect:p,rotation:b,id:m,color:v,borderStyle:{rawWidth:y},popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:U.HIGHLIGHT,color:Array.from(v),thickness:y,inkLists:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}const{color:n,quadPoints:r,inkLists:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=B.makeHexColor(...n),l.#o=h||1,o&&(l.#p=t.thickness),l.annotationElementId=t.id||null,l._initialData=i;const[c,u]=l.pageDimensions,[d,f]=l.pageTranslation;if(r){const g=l.#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});l.#_(),l.#M(),l.rotate(l.rotation)}else if(o){l.#u=!0;const g=o[0],p={x:g[0]-d,y:u-(g[1]-f)},b=new So(p,[0,0,c,u],1,l.#p/2,!0,.001);for(let y=0,_=g.length;y<_;y+=2)p.x=g[y]-d,p.y=u-(g[y+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:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:b.toSVGPath()}},!0,!0);l.#v({highlightOutlines:b.getOutlines(),highlightId:m,clipPathId:v}),l.#M()}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=H._colorManager.convert(this.color),i={annotationType:U.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 yg{#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(){st("Not implemented")}}class z extends H{#t=null;#e;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#h=null;static#a=null;static#c=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,t.drawOutlines&&(this.#l(t),this.#f())}#l({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(z._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){st("Not implemented")}static get typesMap(){st("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&&(z.#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 h=this.#t.updateProperty(e,o);h&&this.#m(h),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,z._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,z._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,z._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,h]}=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/h),i*(h/o),s*(o/h)];case 5:return[1-e,t,s*(o/h),i*(h/o)];case 6:return[1-t-i*(h/o),1-e,i*(h/o),s*(o/h)];case 7:return[e-s*(o/h),1-t-i*(h/o),s*(o/h),i*(h/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*(h/o),e,i*(h/o),s*(o/h)];case 13:return[1-e-s*(o/h),t-i*(h/o),s*(o/h),i*(h/o)];case 14:return[1-t,1-e-s*(o/h),i*(h/o),s*(o/h)];case 15:return[e,1-t,s*(o/h),i*(h/o)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,z._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){st("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:o,pointerId:h,pointerType:l}=i;if(z.#h&&z.#h!==l)return;const{viewport:{rotation:c}}=t,{width:u,height:d}=n.getBoundingClientRect(),f=z.#i=new AbortController,g=t.combinedSignal(f);if(z.#n||=h,z.#h??=l,window.addEventListener("pointerup",p=>{z.#n===p.pointerId?this._endDraw(p):z.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{z.#n===p.pointerId?this._currentParent.endDrawingSession():z.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{z.#h===p.pointerType&&((z.#a||=new Set).add(p.pointerId),z.#s.isCancellable()&&(z.#s.removeLastElement(),z.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",ge,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===z.#c&&te(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),z.#s){t.drawLayer.updateProperties(this._currentDrawId,z.#s.startNew(r,o,u,d,c));return}e.updateUIForDefaultProperties(this),z.#s=this.createDrawerInstance(r,o,u,d,c),z.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(z.#r.toSVGProperties(),z.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(z.#c=-1,!z.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(z.#n===i){if(z.#a?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,z.#s.add(e,s)),z.#c=t.timeStamp,te(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,z.#s=null,z.#r=null,z.#h=null,z.#c=NaN),z.#i&&(z.#i.abort(),z.#i=null,z.#n=NaN,z.#a=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t&&e.drawLayer.updateProperties(this._currentDrawId,z.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=z.#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:q.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(q.DRAW_STEP),!z.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:z.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:z.#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){st("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=e.viewport,h=this.deserializeDraw(r,o,i,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,s);return l.createDrawingOptions(t),l.#l({drawOutlines:h}),l.#f(),l.onScaleChanging(),l.rotate(),l}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 _g{#t=new Float64Array(6);#e;#s;#i;#r;#n;#h="";#a=0;#c=new Gn;#l;#d;constructor(t,e,s,i,n,r){this.#l=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 I._normalizePoint(t,e,this.#l,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,h=e-r;return Math.hypot(this.#l*o,this.#d*h)<=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(...I.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.#l=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.#h="";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.#h}}}toSVGPath(){const t=I.svgRound(this.#e[4]),e=I.svgRound(this.#e[5]);if(this.#n.length===2)return this.#h=`${this.#h} M ${t} ${e} Z`,this.#h;if(this.#n.length<=6){const i=this.#h.lastIndexOf("M");this.#h=`${this.#h.slice(0,i)} M ${t} ${e}`,this.#a=6}if(this.#n.length===4){const i=I.svgRound(this.#e[10]),n=I.svgRound(this.#e[11]);return this.#h=`${this.#h} L ${i} ${n}`,this.#a=12,this.#h}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,h,l,c,u]=this.#e.slice(i,i+6).map(I.svgRound);s.push(`C${r} ${o} ${h} ${l} ${c} ${u}`)}return this.#h+=s.join(" "),this.#a=this.#e.length,this.#h}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.#h=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class Gn extends I{#t;#e=0;#s;#i;#r;#n;#h;#a;#c;build(t,e,s,i,n,r,o){this.#r=e,this.#n=s,this.#h=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${I.svgRound(e[4])} ${I.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${I.svgRound(e[10])} ${I.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,o,h,l,c]=e.subarray(s,s+6).map(I.svgRound);t.push(`C${n} ${r} ${o} ${h} ${l} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],o=[],[h,l,c,u]=this.#d();let d,f,g,p,b,m,v,y,_;switch(this.#a){case 0:_=I._rescale,d=t,f=e+i,g=s,p=-i,b=t+h*s,m=e+(1-l-u)*i,v=t+(h+c)*s,y=e+(1-l)*i;break;case 90:_=I._rescaleAndSwap,d=t,f=e,g=s,p=i,b=t+l*s,m=e+h*i,v=t+(l+u)*s,y=e+(h+c)*i;break;case 180:_=I._rescale,d=t+s,f=e,g=-s,p=i,b=t+(1-h-c)*s,m=e+l*i,v=t+(1-h)*s,y=e+(l+u)*i;break;case 270:_=I._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,b=t+(1-l-u)*s,m=e+(1-h-c)*i,v=t+(1-l)*s,y=e+(1-h)*i;break}for(const{line:S,points:A}of this.#i)r.push(_(S,d,f,g,p,n?new Array(S.length):null)),o.push(_(A,d,f,g,p,n?new Array(A.length):null));return{lines:r,points:o,rect:[b,m,v,y]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:o},rotation:h,thickness:l}){const c=[];let u,d,f,g,p;switch(h){case 0:p=I._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=I._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=I._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=I._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 y=new Float32Array(3*(v-2));r.push(y);let[_,S,A,T]=m.subarray(0,4);y.set([NaN,NaN,NaN,NaN,_,S],0);for(let E=4;E<v;E+=2){const O=m[E],N=m[E+1];y.set(I.createBezierPoints(_,S,A,T,O,N),(E-2)*3),[_,S,A,T]=[A,T,O,N]}}}for(let m=0,v=r.length;m<v;m++)c.push({line:p(r[m].map(y=>y??NaN),u,d,f,g),points:p(o[m].map(y=>y??NaN),u,d,f,g)});const b=new Gn;return b.build(c,s,i,1,h,l,n),b}#l(t=this.#c){const e=this.#s+t/2*this.#h;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.#l(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,h=i.length;o<h;o+=6){const[l,c]=i.subarray(o,o+2);t[0]=Math.min(t[0],l),t[1]=Math.min(t[1],c),t[2]=Math.max(t[2],l),t[3]=Math.max(t[3],c)}continue}let n=i[4],r=i[5];for(let o=6,h=i.length;o<h;o+=6){const[l,c,u,d,f,g]=i.subarray(o,o+6);B.bezierBoundingBox(n,r,l,c,u,d,f,g,t),n=f,r=g}}const[e,s]=this.#l();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.#l();this.#c=t;const[i,n]=this.#l(),[r,o]=[i-e,n-s],h=this.#t;return h[0]-=r,h[1]-=o,h[2]+=2*r,h[3]+=2*o,h}updateParentDimensions([t,e],s){const[i,n]=this.#l();this.#r=t,this.#n=e,this.#h=s;const[r,o]=this.#l(),h=r-i,l=o-n,c=this.#t;return c[0]-=h,c[1]-=l,c[2]+=2*h,c[3]+=2*l,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(I.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,o=0,h=0;switch(this.#e){case 90:i=e/t,n=-t/e,o=t;break;case 180:s=-1,r=-1,o=t,h=e;break;case 270:i=-e/t,n=t/e,h=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${I.svgRound(o)} ${I.svgRound(h)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#l(),[o,h,l,c]=this.#t;if(Math.abs(l-n)<=I.PRECISION||Math.abs(c-r)<=I.PRECISION){const p=t+s/2-(o+l/2),b=e+i/2-(h+c/2);return{path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${b})`}}}const u=(s-2*n)/(l-2*n),d=(i-2*r)/(c-2*r),f=l/s,g=c/i;return{path:{"transform-origin":`${I.svgRound(o)} ${I.svgRound(h)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${I.svgRound(n)} ${I.svgRound(r)}) scale(${u} ${d}) translate(${I.svgRound(-n)} ${I.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#l(),o=this.#t,[h,l,c,u]=o;if(o[0]=t,o[1]=e,o[2]=s,o[3]=i,Math.abs(c-n)<=I.PRECISION||Math.abs(u-r)<=I.PRECISION){const b=t+s/2-(h+c/2),m=e+i/2-(l+u/2);for(const{line:v,points:y}of this.#i)I._translate(v,b,m,v),I._translate(y,b,m,y);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.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*(h+n)+t+n,p=-f*(l+r)+e+r;if(d!==1||f!==1||g!==0||p!==0)for(const{line:b,points:m}of this.#i)I._rescale(b,g,p,d,f,b),I._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,o=t-r[0],h=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:l,points:c}of this.#i)I._translate(l,o,h,l),I._translate(c,o,h,c);else{const l=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:u,points:d}of this.#i)I._rescale(u,o,h,l,c,u),I._rescale(d,o,h,l,c,d);r[2]*=l,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${I.svgRound(t[0])} ${I.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Co extends yg{#t;constructor(t){super(),this.#t=t,super.updateProperties({fill:"none",stroke:H._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 Co(this.#t);return t.updateAll(this),t}}class Ao extends z{static _type="ink";static _editorType=U.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){H.initialize(t,e),this._defaultDrawingOptions=new Co(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return $(this,"typesMap",new Map([[q.INK_THICKNESS,"stroke-width"],[q.INK_COLOR,"stroke"],[q.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new _g(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 wo){const{data:{inkLists:r,rect:o,rotation:h,id:l,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:U.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:o.slice(0),rotation:h,id:l,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=Ao.getDefaultDrawingOptions({stroke:B.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,h={annotationType:U.INK,color:H._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?h:this.annotationElementId&&!this.#t(h)?null:(h.id=this.annotationElementId,h)}#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 To extends H{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#h=null;#a=null;#c=!1;#l=!1;static _type="stamp";static _editorType=U.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile}static initialize(t,e){H.initialize(t,e)}static get supportedTypes(){return $(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return $(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(U.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.#h){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 h=o.output;return await this.setGuessedAltText(h),e&&!this.hasAltTextData()&&(this.altTextData={alt:h,decorative:!1}),h}#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=To.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.#h?.remove(),this.#h=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.#h===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,h]=this.parentDimensions;this.setDims(e*o/i,s*h/n),this._uiManager.enableWaiting(!1);const l=this.#h=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),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.#l||(this.parent.addUndoableEditor(this),this.#l=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&l.setAttribute("aria-label",this.#n)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new oo;let o=this.#t,h=i,l=n,c=null;if(e){if(i>e||n>e){const A=Math.min(e/i,e/n);h=Math.floor(i*A),l=Math.floor(n*A)}c=document.createElement("canvas");const d=c.width=Math.ceil(h*r.sx),f=c.height=Math.ceil(l*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,y=m*r.sy,_=new OffscreenCanvas(v*2,y*2),S=_.getContext("2d");S.fillStyle=p,S.fillRect(0,0,v*2,y*2),S.fillStyle=b,S.fillRect(0,0,v,y),S.fillRect(v,y,v,y),g.fillStyle=g.createPattern(_,"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:h,height:l,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 h=n,l=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,h,l,0,0,n,r),o=c.transferToImageBitmap()}return o}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new oo,r=Math.ceil(s*t*n.sx),o=Math.ceil(i*e*n.sy),h=this.#h;if(!h||h.width===r&&h.height===o)return;h.width=r,h.height=o;const l=this.#c?this.#t:this.#g(r,o),c=h.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,o)}getImageForAltText(){return this.#h}#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*Is.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*Is.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 Pl){const{data:{rect:g,rotation:p,id:b,structParent:m,popupRef:v},container:y,parent:{page:{pageNumber:_}}}=t,S=y.querySelector("canvas"),A=s.imageManager.getFromCanvas(y.id,S);S.remove();const T=(await e._structTree.getAriaAttributes(`${so}${b}`))?.get("aria-label")||"";i=t={annotationType:U.STAMP,bitmapId:A.id,bitmap:A.bitmap,pageIndex:_-1,rect:g.slice(0),rotation:p,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:T},isSvg:!1,structParent:m,popupRef:v}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:o,bitmapUrl:h,bitmapId:l,isSvg:c,accessibilityData:u}=t;l&&s.imageManager.isValidId(l)?(n.#e=l,o&&(n.#t=o)):n.#i=h,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.#l=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:U.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 He{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#h=!1;#a=!1;#c=!1;#l=null;#d=null;#u=null;#f=null;#o;static _initialized=!1;static#g=new Map([Ct,Ao,To,mt].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:c}){const u=[...He.#g.values()];if(!He._initialized){He._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=l,this.#u=h,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()===U.NONE}updateToolbar(t){this.#o.updateToolbar(t)}updateMode(t=this.#o.getMode()){switch(this.#v(),t){case U.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case U.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case U.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 He.#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 He.#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}=Bt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#o.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),mt.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),H.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 He.#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 He.#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),h=Math.min(window.innerHeight,e+i),l=(n+o)/2-t,c=(r+h)/2-e,[u,d]=this.viewport.rotation%180===0?[l,c]:[c,l];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}=Bt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#h&&(this.#h=!1,!(this.#p?.isDrawer&&this.#p.supportMultipleDrawings))){if(!this.#e){this.#e=!0;return}if(this.#o.getMode()===U.STAMP){this.#o.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#o.getMode()===U.HIGHLIGHT&&this.enableTextSelection(),this.#h){this.#h=!1;return}const{isMac:e}=Bt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#h=!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.#l){this.#p.startDrawing(this,this.#o,!1,t);return}this.#o.setCurrentDrawingSession(this),this.#l=new AbortController;const e=this.#o.combinedSignal(this.#l);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.#l?(this.#o.setCurrentDrawingSession(null),this.#l.abort(),this.#l=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.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&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,fs(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,fs(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 $(this,"_svgFactory",new yo)}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}#h(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 h=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,o);const l=s?this.#h(r,h):null,c=zt._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${h}`),this.updateProperties(n,t),this.#s.set(i,n),{id:i,clipPathId:`url(#${l})`}}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 h;if(e){const u=zt._svgFactory.createElement("mask");n.append(u),h=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",h),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 l=zt._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${o}`),h&&l.setAttribute("mask",`url(#${h})`);const c=l.cloneNode();return i.append(c),l.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:h}=o;for(const[l,c]of Object.entries(n))h.toggle(l,c)}if(r){const l=o.firstChild.firstChild;this.#a(l,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:xo},V.AbortException,V.AnnotationEditorLayer,V.AnnotationEditorParamsType,V.AnnotationEditorType,V.AnnotationEditorUIManager,V.AnnotationLayer,V.AnnotationMode,V.ColorPicker,V.DOMSVGFactory,V.DrawLayer,V.FeatureTest;var wg=V.GlobalWorkerOptions;V.ImageKind,V.InvalidPDFException,V.MissingPDFException,V.OPS,V.OutputScale,V.PDFDataRangeTransport,V.PDFDateString,V.PDFWorker,V.PasswordResponses,V.PermissionFlag,V.PixelsPerInch,V.RenderingCancelledException,V.TextLayer,V.TouchManager,V.UnexpectedResponseException,V.Util,V.VerbosityLevel,V.XfaLayer,V.build,V.createValidAbsoluteUrl,V.fetchData;var xg=V.getDocument;V.getFilenameFromUrl,V.getPdfFilenameFromUrl,V.getXfaPageViewport,V.isDataScheme,V.isPdfFile,V.noContextMenu,V.normalizeUnicode,V.setLayerDimensions,V.shadow,V.stopEvent;var Sg=V.version;let Dl=null;function Cg(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function Ag(){const a=Dl??Cg();return Dl=a,a/72}function Tg(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 Eg(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)})}Rl()||(wg.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Sg}/pdf.worker.min.mjs`);function Rl(){try{return typeof OffscreenCanvas<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function"}catch{return!1}}async function kg({page:a,data:t,scale:e,password:s},i){const n=Ag()/window.devicePixelRatio,r=await Eg(t);if(Rl()){const o=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/pdfjs.worker-DawqtvLM.js").href:new URL("assets/pdfjs.worker-DawqtvLM.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:dt&&dt.tagName.toUpperCase()==="SCRIPT"&&dt.src||new URL("pdf-canvas.umd.js",document.baseURI).href),{type:"module"});return o.postMessage({data:r,password:s,id:i,page:a,units:n,scale:e}),await new Promise(l=>{o.addEventListener("message",c=>{if(c.data.status!=="success")return;const{bitmap:u,width:d,height:f,pages:g}=c.data;if(u){const p=document.createElement("canvas"),b=p.getContext("bitmaprenderer");p.width=d,p.height=f,b?.transferFromImageBitmap(u),l({pages:g,canvas:p})}else l({pages:g,canvas:null})})})}else{const o=await xg({data:r,password:s}).promise,h=o.numPages;if(!i)return{canvas:null,pages:h};const l=await o.getPage(a),c=l.getViewport({scale:e}),u=document.createElement("canvas"),f={canvasContext:u.getContext("2d"),viewport:c,transform:[n,0,0,n,0,0]};return u.width=Math.floor(c.width*n),u.height=Math.floor(c.height*n),l.render(f).promise.then(()=>({canvas:u,pages:h}))}}const Gt=new Map;function Mg(a){const t=new Nr(a);return Gt.set(a,t),t}function Pg(a){const t=Date.now();return{PDFId:`${a.name}-${t}`,name:a.name.replace(/.pdf/,""),updateDate:t,data:a}}async function Og({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await cd(a),n=s.filter(o=>o!==null),r=Eu.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=Bg(t,s);Fl(a,i,s)}async function Rg(a,t){const e=Date.now(),i={PDFId:`${a.name}-${e}`,name:a.name.replace(/.png|.jpg|.jpeg/,""),updateDate:e,data:a};return t&&Ll(t,{data:a}),{...i,pages:1}}async function Ll(a,{data:t,scale:e=.5}){if(!Gt.get(a))return;const i=URL.createObjectURL(t),n=await Mt.fromURL(i);n.scale(e),Fl(a,n,e),URL.revokeObjectURL(i)}function Fl(a,t,e){const s=Gt.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function Lg(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function Fg(a,t,e){!e||!a||(e.scale(1/t),Lg(a,e))}function Ig(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 Ng(a){const t=Gt.get(a);t&&(t.discardActiveObject(),t.renderAll())}function jg(a){const t=Gt.get(a);t&&(t.clear(),Gt.delete(a))}function Bg(a,t){return new Mt(a,{scaleX:t,scaleY:t})}function Eo(a,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:o}=a,h=t.x*r*i,l=t.y*o*n;a.set({left:e-h,top:s-l})}function Il(a,t,e){const s=a.type;return{"application/pdf":Hg,"image/png":jl,"image/jpeg":jl}[s]?.(a,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function Hg(a,t,e){const s=Pg(a),i=await Nl({page:1,data:a,scale:.8,password:t},e);return{...s,pages:i}}function Nl(a,t){return kg(a,t).then(({canvas:e,pages:s})=>(e&&t&&Dg(t,e),s))}async function jl(a,t,e){return await Rg(a,e)}function zg(a,t){const e=Gt.get(a);if(!e)return;const s=e.getActiveObject();s&&(s instanceof Jt?s.forEachObject(i=>{i.set(t)}):s.set(t),e.renderAll())}async function Gg(a,t){const e=Gt.get(a);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(Wl);i instanceof Jt?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),Eo(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function Vg(a){const t=Gt.get(a);if(!t)return;const e=t.getActiveObject();e&&(e instanceof Jt?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Bl(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{};let h=null,l=null,c=1,u={...Xl};function d(){if(!t||Gt.has(t))return;const M=Mg(t);return M.on("selection:created",P=>{if(r?.(P),P.selected.length<=1)return;const j=M.getActiveObject();j&&(l=j,e?.value&&l.set(e.value),l._cornerSize=l.cornerSize,S(c))}),M.on("selection:cleared",P=>{o?.(P),T(M)}),s&&M.on("mouse:down",s),i&&M.on("mouse:move",i),n&&M.on("mouse:up",n),M}function f(M,P){return Il(M,P,t)}function g(M){return Nl(M,t)}function p({data:M,scale:P=.5}){return Ll(t,{data:M,scale:P})}async function b(M,P,j){const k=Gt.get(t);if(!k)return;const R=await Mt.fromURL(M,{},{...$n,...P});Eo(R,j),k.add(R),v(k,R),k.setActiveObject(R)}function m(M,P,j){const k=Gt.get(t);if(!k)return;const R=new kt(M,{...Gl,...P});Eo(R,j),k.add(R),v(k,R),k.setActiveObject(R)}function v(M,P){P.on("selected",j=>y({canvas:M,target:j.target})),P.on("modified",j=>y({canvas:M,target:j.target})),P.on("scaling",()=>T(M)),P.on("moving",()=>T(M)),P.on("rotating",()=>T(M)),P._cornerSize=P._cornerSize??P.cornerSize}async function y({canvas:M,target:P,stroke:j=u.stroke,uuid:k=Date.now()}){if(M.getActiveObjects().length>1||h?.stroke===`${j}-${k}`)return;const G=await Og(u,k,j);T(M),h=G,l=P,_(M,P,k),S(c,!0),G&&M.add(G)}function _(M,P,j){h&&(h.on("selected",()=>{M.remove(P),T(M)}),h.on("mouseover",()=>{y({canvas:M,target:P,stroke:u.hoverStroke,uuid:j})}),h.on("mouseout",()=>{y({canvas:M,target:P,stroke:u.stroke,uuid:j})}))}function S(M,P=!1){const j=Gt.get(t);c=M,j&&(Ig(l,M),Fg(l,M,h),!P&&j.renderAll())}function A(M){if(!M)return;u={...u,...M};const P=Gt.get(t);!h||!l||!P||y({target:l,canvas:P})}function T(M){l=null,h&&(M.remove(h),h=null)}function E(){Ng(t)}function O(){jg(t)}function N(M){zg(t,M)}function D(){return Gg(t,v)}function L(){Vg(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:b,addTextFabric:m,clearActive:E,deleteCanvas:O,scaleFabric:S,setCloseSvgOptions:A,setActiveFabric:N,copyActiveFabric:D,deleteActiveFabric:L}}function Xg(a){let t=0;const e=Tg(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});W.onMounted(()=>{window.addEventListener("resize",e)}),W.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const Wg=W.defineComponent({__name:"pdf-canvas",props:{file:{},page:{default:1},canvasId:{default:"PDF-canvas"},fileZoom:{default:1},fileScale:{default:1},canvasScale:{default:1},canvasClass:{default:""},isDrop:{type:Boolean,default:!1},password:{},dropTextOptions:{},dropImageOptions:{},selectionOptions:{},closeSvgOptions:{},manualReload:{type:Boolean},onDestroy:{type:Function,default:W.onBeforeUnmount}},emits:["loaded","reload","pointerDown","pointerMove","pointerUp","selectionCreated","selectionCleared"],setup(a,{expose:t,emit:e}){const s=a,i=e,{onDestroy:n}=s,r=W.ref(null),o=`${s.canvasId}-${s.page-1}`,h=W.computed(()=>s.fileZoom*s.canvasScale),l=W.computed(()=>({...Vl,...s.selectionOptions})),{createCanvas:c,specifyPage:u,addFabric:d,addTextFabric:f,renderImage:g,clearActive:p,deleteCanvas:b,scaleFabric:m,setActiveFabric:v,setCloseSvgOptions:y,copyActiveFabric:_,deleteActiveFabric:S}=Bl({id:o,selectionOptions:l,pointerDown:D=>i("pointerDown",D),pointerMove:D=>i("pointerMove",D),pointerUp:D=>i("pointerUp",D),selectionCreated:D=>i("selectionCreated",D),selectionCleared:D=>i("selectionCleared",D)});A(),Xg(N);async function A(){const{file:D,page:L,fileScale:M}=s;globalThis.requestAnimationFrame(async()=>{if(await W.nextTick(),c(),D.data?.type.startsWith("image/")||D.canvas){const{canvas:P}=D,j=P?7:3,k=P?.length?P[L-1]:D.data;k&&g({data:k,scale:M/j}),i("loaded");return}D.data&&await u({page:L,data:D.data,scale:M,password:s.password}),i("loaded")})}function T(D){if(!s.isDrop||!D.dataTransfer)return;const{dataTransfer:L,offsetX:M,offsetY:P}=D,j=L.getData("text/plain"),k=L.getData("text/uri-list"),R=L.getData("custom/offset"),G=R?JSON.parse(R):null,at={top:P,left:M},ct={x:G?.offsetX??0,y:G?.offsetY??0};k?E(k,at,ct):j&&O(j,at,ct)}function E(D,L,M){d(D,{...s.dropImageOptions,...L},M)}function O(D,L,M){f(D,{...s.dropTextOptions,...L},M)}function N(){s.manualReload||A(),i("reload")}return W.watch([()=>s.fileScale,()=>s.page,()=>s.file,()=>s.password],N),W.watch(h,D=>m(D),{immediate:!0}),W.watch(()=>s.closeSvgOptions,y,{immediate:!0}),n(b),t({reload:A,addImage:E,addText:O,clearActive:p,deleteCanvas:b,setActiveFabric:v,copyActiveFabric:_,deleteActiveFabric:S,canvasRef:r}),(D,L)=>(W.openBlock(),W.createElementBlock("div",{style:W.normalizeStyle({transform:`scale(${h.value})`}),onDragover:L[0]||(L[0]=W.withModifiers(()=>{},["prevent"])),onDragenter:L[1]||(L[1]=W.withModifiers(()=>{},["prevent"])),onDrop:W.withModifiers(T,["stop","prevent"])},[W.createElementVNode("canvas",{id:o,ref_key:"canvasRef",ref:r,class:W.normalizeClass(a.canvasClass)},null,2)],36))}});J.default=Wg,J.loadFile=Il,J.useFabric=Bl,Object.defineProperties(J,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|